@orbitdb/core
Version:
Distributed p2p database on IPFS
36,078 lines • 1.29 MB
JavaScript
var OrbitDB;
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ "./node_modules/abstract-level/abstract-chained-batch.js":
/*!***************************************************************!*\
!*** ./node_modules/abstract-level/abstract-chained-batch.js ***!
\***************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
const { fromCallback } = __webpack_require__(/*! catering */ "./node_modules/catering/index.js")
const ModuleError = __webpack_require__(/*! module-error */ "./node_modules/module-error/index.js")
const { getCallback, getOptions } = __webpack_require__(/*! ./lib/common */ "./node_modules/abstract-level/lib/common.js")
const kPromise = Symbol('promise')
const kStatus = Symbol('status')
const kOperations = Symbol('operations')
const kFinishClose = Symbol('finishClose')
const kCloseCallbacks = Symbol('closeCallbacks')
class AbstractChainedBatch {
constructor (db) {
if (typeof db !== 'object' || db === null) {
const hint = db === null ? 'null' : typeof db
throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)
}
this[kOperations] = []
this[kCloseCallbacks] = []
this[kStatus] = 'open'
this[kFinishClose] = this[kFinishClose].bind(this)
this.db = db
this.db.attachResource(this)
this.nextTick = db.nextTick
}
get length () {
return this[kOperations].length
}
put (key, value, options) {
if (this[kStatus] !== 'open') {
throw new ModuleError('Batch is not open: cannot call put() after write() or close()', {
code: 'LEVEL_BATCH_NOT_OPEN'
})
}
const err = this.db._checkKey(key) || this.db._checkValue(value)
if (err) throw err
const db = options && options.sublevel != null ? options.sublevel : this.db
const original = options
const keyEncoding = db.keyEncoding(options && options.keyEncoding)
const valueEncoding = db.valueEncoding(options && options.valueEncoding)
const keyFormat = keyEncoding.format
// Forward encoding options
options = { ...options, keyEncoding: keyFormat, valueEncoding: valueEncoding.format }
// Prevent double prefixing
if (db !== this.db) {
options.sublevel = null
}
const mappedKey = db.prefixKey(keyEncoding.encode(key), keyFormat)
const mappedValue = valueEncoding.encode(value)
this._put(mappedKey, mappedValue, options)
this[kOperations].push({ ...original, type: 'put', key, value })
return this
}
_put (key, value, options) {}
del (key, options) {
if (this[kStatus] !== 'open') {
throw new ModuleError('Batch is not open: cannot call del() after write() or close()', {
code: 'LEVEL_BATCH_NOT_OPEN'
})
}
const err = this.db._checkKey(key)
if (err) throw err
const db = options && options.sublevel != null ? options.sublevel : this.db
const original = options
const keyEncoding = db.keyEncoding(options && options.keyEncoding)
const keyFormat = keyEncoding.format
// Forward encoding options
options = { ...options, keyEncoding: keyFormat }
// Prevent double prefixing
if (db !== this.db) {
options.sublevel = null
}
this._del(db.prefixKey(keyEncoding.encode(key), keyFormat), options)
this[kOperations].push({ ...original, type: 'del', key })
return this
}
_del (key, options) {}
clear () {
if (this[kStatus] !== 'open') {
throw new ModuleError('Batch is not open: cannot call clear() after write() or close()', {
code: 'LEVEL_BATCH_NOT_OPEN'
})
}
this._clear()
this[kOperations] = []
return this
}
_clear () {}
write (options, callback) {
callback = getCallback(options, callback)
callback = fromCallback(callback, kPromise)
options = getOptions(options)
if (this[kStatus] !== 'open') {
this.nextTick(callback, new ModuleError('Batch is not open: cannot call write() after write() or close()', {
code: 'LEVEL_BATCH_NOT_OPEN'
}))
} else if (this.length === 0) {
this.close(callback)
} else {
this[kStatus] = 'writing'
this._write(options, (err) => {
this[kStatus] = 'closing'
this[kCloseCallbacks].push(() => callback(err))
// Emit after setting 'closing' status, because event may trigger a
// db close which in turn triggers (idempotently) closing this batch.
if (!err) this.db.emit('batch', this[kOperations])
this._close(this[kFinishClose])
})
}
return callback[kPromise]
}
_write (options, callback) {}
close (callback) {
callback = fromCallback(callback, kPromise)
if (this[kStatus] === 'closing') {
this[kCloseCallbacks].push(callback)
} else if (this[kStatus] === 'closed') {
this.nextTick(callback)
} else {
this[kCloseCallbacks].push(callback)
if (this[kStatus] !== 'writing') {
this[kStatus] = 'closing'
this._close(this[kFinishClose])
}
}
return callback[kPromise]
}
_close (callback) {
this.nextTick(callback)
}
[kFinishClose] () {
this[kStatus] = 'closed'
this.db.detachResource(this)
const callbacks = this[kCloseCallbacks]
this[kCloseCallbacks] = []
for (const cb of callbacks) {
cb()
}
}
}
exports.AbstractChainedBatch = AbstractChainedBatch
/***/ }),
/***/ "./node_modules/abstract-level/abstract-iterator.js":
/*!**********************************************************!*\
!*** ./node_modules/abstract-level/abstract-iterator.js ***!
\**********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
const { fromCallback } = __webpack_require__(/*! catering */ "./node_modules/catering/index.js")
const ModuleError = __webpack_require__(/*! module-error */ "./node_modules/module-error/index.js")
const { getOptions, getCallback } = __webpack_require__(/*! ./lib/common */ "./node_modules/abstract-level/lib/common.js")
const kPromise = Symbol('promise')
const kCallback = Symbol('callback')
const kWorking = Symbol('working')
const kHandleOne = Symbol('handleOne')
const kHandleMany = Symbol('handleMany')
const kAutoClose = Symbol('autoClose')
const kFinishWork = Symbol('finishWork')
const kReturnMany = Symbol('returnMany')
const kClosing = Symbol('closing')
const kHandleClose = Symbol('handleClose')
const kClosed = Symbol('closed')
const kCloseCallbacks = Symbol('closeCallbacks')
const kKeyEncoding = Symbol('keyEncoding')
const kValueEncoding = Symbol('valueEncoding')
const kAbortOnClose = Symbol('abortOnClose')
const kLegacy = Symbol('legacy')
const kKeys = Symbol('keys')
const kValues = Symbol('values')
const kLimit = Symbol('limit')
const kCount = Symbol('count')
const emptyOptions = Object.freeze({})
const noop = () => {}
let warnedEnd = false
// This class is an internal utility for common functionality between AbstractIterator,
// AbstractKeyIterator and AbstractValueIterator. It's not exported.
class CommonIterator {
constructor (db, options, legacy) {
if (typeof db !== 'object' || db === null) {
const hint = db === null ? 'null' : typeof db
throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)
}
if (typeof options !== 'object' || options === null) {
throw new TypeError('The second argument must be an options object')
}
this[kClosed] = false
this[kCloseCallbacks] = []
this[kWorking] = false
this[kClosing] = false
this[kAutoClose] = false
this[kCallback] = null
this[kHandleOne] = this[kHandleOne].bind(this)
this[kHandleMany] = this[kHandleMany].bind(this)
this[kHandleClose] = this[kHandleClose].bind(this)
this[kKeyEncoding] = options[kKeyEncoding]
this[kValueEncoding] = options[kValueEncoding]
this[kLegacy] = legacy
this[kLimit] = Number.isInteger(options.limit) && options.limit >= 0 ? options.limit : Infinity
this[kCount] = 0
// Undocumented option to abort pending work on close(). Used by the
// many-level module as a temporary solution to a blocked close().
// TODO (next major): consider making this the default behavior. Native
// implementations should have their own logic to safely close iterators.
this[kAbortOnClose] = !!options.abortOnClose
this.db = db
this.db.attachResource(this)
this.nextTick = db.nextTick
}
get count () {
return this[kCount]
}
get limit () {
return this[kLimit]
}
next (callback) {
let promise
if (callback === undefined) {
promise = new Promise((resolve, reject) => {
callback = (err, key, value) => {
if (err) reject(err)
else if (!this[kLegacy]) resolve(key)
else if (key === undefined && value === undefined) resolve()
else resolve([key, value])
}
})
} else if (typeof callback !== 'function') {
throw new TypeError('Callback must be a function')
}
if (this[kClosing]) {
this.nextTick(callback, new ModuleError('Iterator is not open: cannot call next() after close()', {
code: 'LEVEL_ITERATOR_NOT_OPEN'
}))
} else if (this[kWorking]) {
this.nextTick(callback, new ModuleError('Iterator is busy: cannot call next() until previous call has completed', {
code: 'LEVEL_ITERATOR_BUSY'
}))
} else {
this[kWorking] = true
this[kCallback] = callback
if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleOne], null)
else this._next(this[kHandleOne])
}
return promise
}
_next (callback) {
this.nextTick(callback)
}
nextv (size, options, callback) {
callback = getCallback(options, callback)
callback = fromCallback(callback, kPromise)
options = getOptions(options, emptyOptions)
if (!Number.isInteger(size)) {
this.nextTick(callback, new TypeError("The first argument 'size' must be an integer"))
return callback[kPromise]
}
if (this[kClosing]) {
this.nextTick(callback, new ModuleError('Iterator is not open: cannot call nextv() after close()', {
code: 'LEVEL_ITERATOR_NOT_OPEN'
}))
} else if (this[kWorking]) {
this.nextTick(callback, new ModuleError('Iterator is busy: cannot call nextv() until previous call has completed', {
code: 'LEVEL_ITERATOR_BUSY'
}))
} else {
if (size < 1) size = 1
if (this[kLimit] < Infinity) size = Math.min(size, this[kLimit] - this[kCount])
this[kWorking] = true
this[kCallback] = callback
if (size <= 0) this.nextTick(this[kHandleMany], null, [])
else this._nextv(size, options, this[kHandleMany])
}
return callback[kPromise]
}
_nextv (size, options, callback) {
const acc = []
const onnext = (err, key, value) => {
if (err) {
return callback(err)
} else if (this[kLegacy] ? key === undefined && value === undefined : key === undefined) {
return callback(null, acc)
}
acc.push(this[kLegacy] ? [key, value] : key)
if (acc.length === size) {
callback(null, acc)
} else {
this._next(onnext)
}
}
this._next(onnext)
}
all (options, callback) {
callback = getCallback(options, callback)
callback = fromCallback(callback, kPromise)
options = getOptions(options, emptyOptions)
if (this[kClosing]) {
this.nextTick(callback, new ModuleError('Iterator is not open: cannot call all() after close()', {
code: 'LEVEL_ITERATOR_NOT_OPEN'
}))
} else if (this[kWorking]) {
this.nextTick(callback, new ModuleError('Iterator is busy: cannot call all() until previous call has completed', {
code: 'LEVEL_ITERATOR_BUSY'
}))
} else {
this[kWorking] = true
this[kCallback] = callback
this[kAutoClose] = true
if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleMany], null, [])
else this._all(options, this[kHandleMany])
}
return callback[kPromise]
}
_all (options, callback) {
// Must count here because we're directly calling _nextv()
let count = this[kCount]
const acc = []
const nextv = () => {
// Not configurable, because implementations should optimize _all().
const size = this[kLimit] < Infinity ? Math.min(1e3, this[kLimit] - count) : 1e3
if (size <= 0) {
this.nextTick(callback, null, acc)
} else {
this._nextv(size, emptyOptions, onnextv)
}
}
const onnextv = (err, items) => {
if (err) {
callback(err)
} else if (items.length === 0) {
callback(null, acc)
} else {
acc.push.apply(acc, items)
count += items.length
nextv()
}
}
nextv()
}
[kFinishWork] () {
const cb = this[kCallback]
// Callback will be null if work was aborted on close
if (this[kAbortOnClose] && cb === null) return noop
this[kWorking] = false
this[kCallback] = null
if (this[kClosing]) this._close(this[kHandleClose])
return cb
}
[kReturnMany] (cb, err, items) {
if (this[kAutoClose]) {
this.close(cb.bind(null, err, items))
} else {
cb(err, items)
}
}
seek (target, options) {
options = getOptions(options, emptyOptions)
if (this[kClosing]) {
// Don't throw here, to be kind to implementations that wrap
// another db and don't necessarily control when the db is closed
} else if (this[kWorking]) {
throw new ModuleError('Iterator is busy: cannot call seek() until next() has completed', {
code: 'LEVEL_ITERATOR_BUSY'
})
} else {
const keyEncoding = this.db.keyEncoding(options.keyEncoding || this[kKeyEncoding])
const keyFormat = keyEncoding.format
if (options.keyEncoding !== keyFormat) {
options = { ...options, keyEncoding: keyFormat }
}
const mapped = this.db.prefixKey(keyEncoding.encode(target), keyFormat)
this._seek(mapped, options)
}
}
_seek (target, options) {
throw new ModuleError('Iterator does not support seek()', {
code: 'LEVEL_NOT_SUPPORTED'
})
}
close (callback) {
callback = fromCallback(callback, kPromise)
if (this[kClosed]) {
this.nextTick(callback)
} else if (this[kClosing]) {
this[kCloseCallbacks].push(callback)
} else {
this[kClosing] = true
this[kCloseCallbacks].push(callback)
if (!this[kWorking]) {
this._close(this[kHandleClose])
} else if (this[kAbortOnClose]) {
// Don't wait for work to finish. Subsequently ignore the result.
const cb = this[kFinishWork]()
cb(new ModuleError('Aborted on iterator close()', {
code: 'LEVEL_ITERATOR_NOT_OPEN'
}))
}
}
return callback[kPromise]
}
_close (callback) {
this.nextTick(callback)
}
[kHandleClose] () {
this[kClosed] = true
this.db.detachResource(this)
const callbacks = this[kCloseCallbacks]
this[kCloseCallbacks] = []
for (const cb of callbacks) {
cb()
}
}
async * [Symbol.asyncIterator] () {
try {
let item
while ((item = (await this.next())) !== undefined) {
yield item
}
} finally {
if (!this[kClosed]) await this.close()
}
}
}
// For backwards compatibility this class is not (yet) called AbstractEntryIterator.
class AbstractIterator extends CommonIterator {
constructor (db, options) {
super(db, options, true)
this[kKeys] = options.keys !== false
this[kValues] = options.values !== false
}
[kHandleOne] (err, key, value) {
const cb = this[kFinishWork]()
if (err) return cb(err)
try {
key = this[kKeys] && key !== undefined ? this[kKeyEncoding].decode(key) : undefined
value = this[kValues] && value !== undefined ? this[kValueEncoding].decode(value) : undefined
} catch (err) {
return cb(new IteratorDecodeError('entry', err))
}
if (!(key === undefined && value === undefined)) {
this[kCount]++
}
cb(null, key, value)
}
[kHandleMany] (err, entries) {
const cb = this[kFinishWork]()
if (err) return this[kReturnMany](cb, err)
try {
for (const entry of entries) {
const key = entry[0]
const value = entry[1]
entry[0] = this[kKeys] && key !== undefined ? this[kKeyEncoding].decode(key) : undefined
entry[1] = this[kValues] && value !== undefined ? this[kValueEncoding].decode(value) : undefined
}
} catch (err) {
return this[kReturnMany](cb, new IteratorDecodeError('entries', err))
}
this[kCount] += entries.length
this[kReturnMany](cb, null, entries)
}
end (callback) {
if (!warnedEnd && typeof console !== 'undefined') {
warnedEnd = true
console.warn(new ModuleError(
'The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version',
{ code: 'LEVEL_LEGACY' }
))
}
return this.close(callback)
}
}
class AbstractKeyIterator extends CommonIterator {
constructor (db, options) {
super(db, options, false)
}
[kHandleOne] (err, key) {
const cb = this[kFinishWork]()
if (err) return cb(err)
try {
key = key !== undefined ? this[kKeyEncoding].decode(key) : undefined
} catch (err) {
return cb(new IteratorDecodeError('key', err))
}
if (key !== undefined) this[kCount]++
cb(null, key)
}
[kHandleMany] (err, keys) {
const cb = this[kFinishWork]()
if (err) return this[kReturnMany](cb, err)
try {
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
keys[i] = key !== undefined ? this[kKeyEncoding].decode(key) : undefined
}
} catch (err) {
return this[kReturnMany](cb, new IteratorDecodeError('keys', err))
}
this[kCount] += keys.length
this[kReturnMany](cb, null, keys)
}
}
class AbstractValueIterator extends CommonIterator {
constructor (db, options) {
super(db, options, false)
}
[kHandleOne] (err, value) {
const cb = this[kFinishWork]()
if (err) return cb(err)
try {
value = value !== undefined ? this[kValueEncoding].decode(value) : undefined
} catch (err) {
return cb(new IteratorDecodeError('value', err))
}
if (value !== undefined) this[kCount]++
cb(null, value)
}
[kHandleMany] (err, values) {
const cb = this[kFinishWork]()
if (err) return this[kReturnMany](cb, err)
try {
for (let i = 0; i < values.length; i++) {
const value = values[i]
values[i] = value !== undefined ? this[kValueEncoding].decode(value) : undefined
}
} catch (err) {
return this[kReturnMany](cb, new IteratorDecodeError('values', err))
}
this[kCount] += values.length
this[kReturnMany](cb, null, values)
}
}
// Internal utility, not typed or exported
class IteratorDecodeError extends ModuleError {
constructor (subject, cause) {
super(`Iterator could not decode ${subject}`, {
code: 'LEVEL_DECODE_ERROR',
cause
})
}
}
// To help migrating to abstract-level
for (const k of ['_ended property', '_nexting property', '_end method']) {
Object.defineProperty(AbstractIterator.prototype, k.split(' ')[0], {
get () { throw new ModuleError(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) },
set () { throw new ModuleError(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) }
})
}
// Exposed so that AbstractLevel can set these options
AbstractIterator.keyEncoding = kKeyEncoding
AbstractIterator.valueEncoding = kValueEncoding
exports.AbstractIterator = AbstractIterator
exports.AbstractKeyIterator = AbstractKeyIterator
exports.AbstractValueIterator = AbstractValueIterator
/***/ }),
/***/ "./node_modules/abstract-level/abstract-level.js":
/*!*******************************************************!*\
!*** ./node_modules/abstract-level/abstract-level.js ***!
\*******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
const { supports } = __webpack_require__(/*! level-supports */ "./node_modules/level-supports/index.js")
const { Transcoder } = __webpack_require__(/*! level-transcoder */ "./node_modules/level-transcoder/index.js")
const { EventEmitter } = __webpack_require__(/*! events */ "./node_modules/events/events.js")
const { fromCallback } = __webpack_require__(/*! catering */ "./node_modules/catering/index.js")
const ModuleError = __webpack_require__(/*! module-error */ "./node_modules/module-error/index.js")
const { AbstractIterator } = __webpack_require__(/*! ./abstract-iterator */ "./node_modules/abstract-level/abstract-iterator.js")
const { DefaultKeyIterator, DefaultValueIterator } = __webpack_require__(/*! ./lib/default-kv-iterator */ "./node_modules/abstract-level/lib/default-kv-iterator.js")
const { DeferredIterator, DeferredKeyIterator, DeferredValueIterator } = __webpack_require__(/*! ./lib/deferred-iterator */ "./node_modules/abstract-level/lib/deferred-iterator.js")
const { DefaultChainedBatch } = __webpack_require__(/*! ./lib/default-chained-batch */ "./node_modules/abstract-level/lib/default-chained-batch.js")
const { getCallback, getOptions } = __webpack_require__(/*! ./lib/common */ "./node_modules/abstract-level/lib/common.js")
const rangeOptions = __webpack_require__(/*! ./lib/range-options */ "./node_modules/abstract-level/lib/range-options.js")
const kPromise = Symbol('promise')
const kLanded = Symbol('landed')
const kResources = Symbol('resources')
const kCloseResources = Symbol('closeResources')
const kOperations = Symbol('operations')
const kUndefer = Symbol('undefer')
const kDeferOpen = Symbol('deferOpen')
const kOptions = Symbol('options')
const kStatus = Symbol('status')
const kDefaultOptions = Symbol('defaultOptions')
const kTranscoder = Symbol('transcoder')
const kKeyEncoding = Symbol('keyEncoding')
const kValueEncoding = Symbol('valueEncoding')
const noop = () => {}
class AbstractLevel extends EventEmitter {
constructor (manifest, options) {
super()
if (typeof manifest !== 'object' || manifest === null) {
throw new TypeError("The first argument 'manifest' must be an object")
}
options = getOptions(options)
const { keyEncoding, valueEncoding, passive, ...forward } = options
this[kResources] = new Set()
this[kOperations] = []
this[kDeferOpen] = true
this[kOptions] = forward
this[kStatus] = 'opening'
this.supports = supports(manifest, {
status: true,
promises: true,
clear: true,
getMany: true,
deferredOpen: true,
// TODO (next major): add seek
snapshots: manifest.snapshots !== false,
permanence: manifest.permanence !== false,
// TODO: remove from level-supports because it's always supported
keyIterator: true,
valueIterator: true,
iteratorNextv: true,
iteratorAll: true,
encodings: manifest.encodings || {},
events: Object.assign({}, manifest.events, {
opening: true,
open: true,
closing: true,
closed: true,
put: true,
del: true,
batch: true,
clear: true
})
})
this[kTranscoder] = new Transcoder(formats(this))
this[kKeyEncoding] = this[kTranscoder].encoding(keyEncoding || 'utf8')
this[kValueEncoding] = this[kTranscoder].encoding(valueEncoding || 'utf8')
// Add custom and transcoder encodings to manifest
for (const encoding of this[kTranscoder].encodings()) {
if (!this.supports.encodings[encoding.commonName]) {
this.supports.encodings[encoding.commonName] = true
}
}
this[kDefaultOptions] = {
empty: Object.freeze({}),
entry: Object.freeze({
keyEncoding: this[kKeyEncoding].commonName,
valueEncoding: this[kValueEncoding].commonName
}),
key: Object.freeze({
keyEncoding: this[kKeyEncoding].commonName
})
}
// Let subclass finish its constructor
this.nextTick(() => {
if (this[kDeferOpen]) {
this.open({ passive: false }, noop)
}
})
}
get status () {
return this[kStatus]
}
keyEncoding (encoding) {
return this[kTranscoder].encoding(encoding != null ? encoding : this[kKeyEncoding])
}
valueEncoding (encoding) {
return this[kTranscoder].encoding(encoding != null ? encoding : this[kValueEncoding])
}
open (options, callback) {
callback = getCallback(options, callback)
callback = fromCallback(callback, kPromise)
options = { ...this[kOptions], ...getOptions(options) }
options.createIfMissing = options.createIfMissing !== false
options.errorIfExists = !!options.errorIfExists
const maybeOpened = (err) => {
if (this[kStatus] === 'closing' || this[kStatus] === 'opening') {
// Wait until pending state changes are done
this.once(kLanded, err ? () => maybeOpened(err) : maybeOpened)
} else if (this[kStatus] !== 'open') {
callback(new ModuleError('Database is not open', {
code: 'LEVEL_DATABASE_NOT_OPEN',
cause: err
}))
} else {
callback()
}
}
if (options.passive) {
if (this[kStatus] === 'opening') {
this.once(kLanded, maybeOpened)
} else {
this.nextTick(maybeOpened)
}
} else if (this[kStatus] === 'closed' || this[kDeferOpen]) {
this[kDeferOpen] = false
this[kStatus] = 'opening'
this.emit('opening')
this._open(options, (err) => {
if (err) {
this[kStatus] = 'closed'
// Resources must be safe to close in any db state
this[kCloseResources](() => {
this.emit(kLanded)
maybeOpened(err)
})
this[kUndefer]()
return
}
this[kStatus] = 'open'
this[kUndefer]()
this.emit(kLanded)
// Only emit public event if pending state changes are done
if (this[kStatus] === 'open') this.emit('open')
// TODO (next major): remove this alias
if (this[kStatus] === 'open') this.emit('ready')
maybeOpened()
})
} else if (this[kStatus] === 'open') {
this.nextTick(maybeOpened)
} else {
this.once(kLanded, () => this.open(options, callback))
}
return callback[kPromise]
}
_open (options, callback) {
this.nextTick(callback)
}
close (callback) {
callback = fromCallback(callback, kPromise)
const maybeClosed = (err) => {
if (this[kStatus] === 'opening' || this[kStatus] === 'closing') {
// Wait until pending state changes are done
this.once(kLanded, err ? maybeClosed(err) : maybeClosed)
} else if (this[kStatus] !== 'closed') {
callback(new ModuleError('Database is not closed', {
code: 'LEVEL_DATABASE_NOT_CLOSED',
cause: err
}))
} else {
callback()
}
}
if (this[kStatus] === 'open') {
this[kStatus] = 'closing'
this.emit('closing')
const cancel = (err) => {
this[kStatus] = 'open'
this[kUndefer]()
this.emit(kLanded)
maybeClosed(err)
}
this[kCloseResources](() => {
this._close((err) => {
if (err) return cancel(err)
this[kStatus] = 'closed'
this[kUndefer]()
this.emit(kLanded)
// Only emit public event if pending state changes are done
if (this[kStatus] === 'closed') this.emit('closed')
maybeClosed()
})
})
} else if (this[kStatus] === 'closed') {
this.nextTick(maybeClosed)
} else {
this.once(kLanded, () => this.close(callback))
}
return callback[kPromise]
}
[kCloseResources] (callback) {
if (this[kResources].size === 0) {
return this.nextTick(callback)
}
let pending = this[kResources].size
let sync = true
const next = () => {
if (--pending === 0) {
// We don't have tests for generic resources, so dezalgo
if (sync) this.nextTick(callback)
else callback()
}
}
// In parallel so that all resources know they are closed
for (const resource of this[kResources]) {
resource.close(next)
}
sync = false
this[kResources].clear()
}
_close (callback) {
this.nextTick(callback)
}
get (key, options, callback) {
callback = getCallback(options, callback)
callback = fromCallback(callback, kPromise)
options = getOptions(options, this[kDefaultOptions].entry)
if (this[kStatus] === 'opening') {
this.defer(() => this.get(key, options, callback))
return callback[kPromise]
}
if (maybeError(this, callback)) {
return callback[kPromise]
}
const err = this._checkKey(key)
if (err) {
this.nextTick(callback, err)
return callback[kPromise]
}
const keyEncoding = this.keyEncoding(options.keyEncoding)
const valueEncoding = this.valueEncoding(options.valueEncoding)
const keyFormat = keyEncoding.format
const valueFormat = valueEncoding.format
// Forward encoding options to the underlying store
if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {
// Avoid spread operator because of https://bugs.chromium.org/p/chromium/issues/detail?id=1204540
options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })
}
this._get(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err, value) => {
if (err) {
// Normalize not found error for backwards compatibility with abstract-leveldown and level(up)
if (err.code === 'LEVEL_NOT_FOUND' || err.notFound || /NotFound/i.test(err)) {
if (!err.code) err.code = 'LEVEL_NOT_FOUND' // Preferred way going forward
if (!err.notFound) err.notFound = true // Same as level-errors
if (!err.status) err.status = 404 // Same as level-errors
}
return callback(err)
}
try {
value = valueEncoding.decode(value)
} catch (err) {
return callback(new ModuleError('Could not decode value', {
code: 'LEVEL_DECODE_ERROR',
cause: err
}))
}
callback(null, value)
})
return callback[kPromise]
}
_get (key, options, callback) {
this.nextTick(callback, new Error('NotFound'))
}
getMany (keys, options, callback) {
callback = getCallback(options, callback)
callback = fromCallback(callback, kPromise)
options = getOptions(options, this[kDefaultOptions].entry)
if (this[kStatus] === 'opening') {
this.defer(() => this.getMany(keys, options, callback))
return callback[kPromise]
}
if (maybeError(this, callback)) {
return callback[kPromise]
}
if (!Array.isArray(keys)) {
this.nextTick(callback, new TypeError("The first argument 'keys' must be an array"))
return callback[kPromise]
}
if (keys.length === 0) {
this.nextTick(callback, null, [])
return callback[kPromise]
}
const keyEncoding = this.keyEncoding(options.keyEncoding)
const valueEncoding = this.valueEncoding(options.valueEncoding)
const keyFormat = keyEncoding.format
const valueFormat = valueEncoding.format
// Forward encoding options
if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {
options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })
}
const mappedKeys = new Array(keys.length)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const err = this._checkKey(key)
if (err) {
this.nextTick(callback, err)
return callback[kPromise]
}
mappedKeys[i] = this.prefixKey(keyEncoding.encode(key), keyFormat)
}
this._getMany(mappedKeys, options, (err, values) => {
if (err) return callback(err)
try {
for (let i = 0; i < values.length; i++) {
if (values[i] !== undefined) {
values[i] = valueEncoding.decode(values[i])
}
}
} catch (err) {
return callback(new ModuleError(`Could not decode one or more of ${values.length} value(s)`, {
code: 'LEVEL_DECODE_ERROR',
cause: err
}))
}
callback(null, values)
})
return callback[kPromise]
}
_getMany (keys, options, callback) {
this.nextTick(callback, null, new Array(keys.length).fill(undefined))
}
put (key, value, options, callback) {
callback = getCallback(options, callback)
callback = fromCallback(callback, kPromise)
options = getOptions(options, this[kDefaultOptions].entry)
if (this[kStatus] === 'opening') {
this.defer(() => this.put(key, value, options, callback))
return callback[kPromise]
}
if (maybeError(this, callback)) {
return callback[kPromise]
}
const err = this._checkKey(key) || this._checkValue(value)
if (err) {
this.nextTick(callback, err)
return callback[kPromise]
}
const keyEncoding = this.keyEncoding(options.keyEncoding)
const valueEncoding = this.valueEncoding(options.valueEncoding)
const keyFormat = keyEncoding.format
const valueFormat = valueEncoding.format
// Forward encoding options
if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {
options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })
}
const mappedKey = this.prefixKey(keyEncoding.encode(key), keyFormat)
const mappedValue = valueEncoding.encode(value)
this._put(mappedKey, mappedValue, options, (err) => {
if (err) return callback(err)
this.emit('put', key, value)
callback()
})
return callback[kPromise]
}
_put (key, value, options, callback) {
this.nextTick(callback)
}
del (key, options, callback) {
callback = getCallback(options, callback)
callback = fromCallback(callback, kPromise)
options = getOptions(options, this[kDefaultOptions].key)
if (this[kStatus] === 'opening') {
this.defer(() => this.del(key, options, callback))
return callback[kPromise]
}
if (maybeError(this, callback)) {
return callback[kPromise]
}
const err = this._checkKey(key)
if (err) {
this.nextTick(callback, err)
return callback[kPromise]
}
const keyEncoding = this.keyEncoding(options.keyEncoding)
const keyFormat = keyEncoding.format
// Forward encoding options
if (options.keyEncoding !== keyFormat) {
options = Object.assign({}, options, { keyEncoding: keyFormat })
}
this._del(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err) => {
if (err) return callback(err)
this.emit('del', key)
callback()
})
return callback[kPromise]
}
_del (key, options, callback) {
this.nextTick(callback)
}
batch (operations, options, callback) {
if (!arguments.length) {
if (this[kStatus] === 'opening') return new DefaultChainedBatch(this)
if (this[kStatus] !== 'open') {
throw new ModuleError('Database is not open', {
code: 'LEVEL_DATABASE_NOT_OPEN'
})
}
return this._chainedBatch()
}
if (typeof operations === 'function') callback = operations
else callback = getCallback(options, callback)
callback = fromCallback(callback, kPromise)
options = getOptions(options, this[kDefaultOptions].empty)
if (this[kStatus] === 'opening') {
this.defer(() => this.batch(operations, options, callback))
return callback[kPromise]
}
if (maybeError(this, callback)) {
return callback[kPromise]
}
if (!Array.isArray(operations)) {
this.nextTick(callback, new TypeError("The first argument 'operations' must be an array"))
return callback[kPromise]
}
if (operations.length === 0) {
this.nextTick(callback)
return callback[kPromise]
}
const mapped = new Array(operations.length)
const { keyEncoding: ke, valueEncoding: ve, ...forward } = options
for (let i = 0; i < operations.length; i++) {
if (typeof operations[i] !== 'object' || operations[i] === null) {
this.nextTick(callback, new TypeError('A batch operation must be an object'))
return callback[kPromise]
}
const op = Object.assign({}, operations[i])
if (op.type !== 'put' && op.type !== 'del') {
this.nextTick(callback, new TypeError("A batch operation must have a type property that is 'put' or 'del'"))
return callback[kPromise]
}
const err = this._checkKey(op.key)
if (err) {
this.nextTick(callback, err)
return callback[kPromise]
}
const db = op.sublevel != null ? op.sublevel : this
const keyEncoding = db.keyEncoding(op.keyEncoding || ke)
const keyFormat = keyEncoding.format
op.key = db.prefixKey(keyEncoding.encode(op.key), keyFormat)
op.keyEncoding = keyFormat
if (op.type === 'put') {
const valueErr = this._checkValue(op.value)
if (valueErr) {
this.nextTick(callback, valueErr)
return callback[kPromise]
}
const valueEncoding = db.valueEncoding(op.valueEncoding || ve)
op.value = valueEncoding.encode(op.value)
op.valueEncoding = valueEncoding.format
}
// Prevent double prefixing
if (db !== this) {
op.sublevel = null
}
mapped[i] = op
}
this._batch(mapped, forward, (err) => {
if (err) return callback(err)
this.emit('batch', operations)
callback()
})
return callback[kPromise]
}
_batch (operations, options, callback) {
this.nextTick(callback)
}
sublevel (name, options) {
return this._sublevel(name, AbstractSublevel.defaults(options))
}
_sublevel (name, options) {
return new AbstractSublevel(this, name, options)
}
prefixKey (key, keyFormat) {
return key
}
clear (options, callback) {
callback = getCallback(options, callback)
callback = fromCallback(callback, kPromise)
options = getOptions(options, this[kDefaultOptions].empty)
if (this[kStatus] === 'opening') {
this.defer(() => this.clear(options, callback))
return callback[kPromise]
}
if (maybeError(this, callback)) {
return callback[kPromise]
}
const original = options
const keyEncoding = this.keyEncoding(options.keyEncoding)
options = rangeOptions(options, keyEncoding)
options.keyEncoding = keyEncoding.format
if (options.limit === 0) {
this.nextTick(callback)
} else {
this._clear(options, (err) => {
if (err) return callback(err)
this.emit('clear', original)
callback()
})
}
return callback[kPromise]
}
_clear (options, callback) {
this.nextTick(callback)
}
iterator (options) {
const keyEncoding = this.keyEncoding(options && options.keyEncoding)
const valueEncoding = this.valueEncoding(options && options.valueEncoding)
options = rangeOptions(options, keyEncoding)
options.keys = options.keys !== false
options.values = options.values !== false
// We need the original encoding options in AbstractIterator in order to decode data
options[AbstractIterator.keyEncoding] = keyEncoding
options[AbstractIterator.valueEncoding] = valueEncoding
// Forward encoding options to private API
options.keyEncoding = keyEncoding.format
options.valueEncoding = valueEncoding.format
if (this[kStatus] === 'opening') {
return new DeferredIterator(this, options)
} else if (this[kStatus] !== 'open') {
throw new ModuleError('Database is not open', {
code: 'LEVEL_DATABASE_NOT_OPEN'
})
}
return this._iterator(options)
}
_iterator (options) {
return new AbstractIterator(this, options)
}
keys (options) {
// Also include valueEncoding (though unused) because we may fallback to _iterator()
const keyEncoding = this.keyEncoding(options && options.keyEncoding)
const valueEncoding = this.valueEncoding(options && options.valueEncoding)
options = rangeOptions(options, keyEncoding)
// We need the original encoding options in AbstractKeyIterator in order to decode data
options[AbstractIterator.keyEncoding] = keyEncoding
options[AbstractIterator.valueEncoding] = valueEncoding
// Forward encoding options to private API
options.keyEncoding = keyEncoding.format
options.valueEncoding = valueEncoding.format
if (this[kStatus] === 'opening') {
return new DeferredKeyIterator(this, options)
} else if (this[kStatus] !== 'open') {
throw new ModuleError('Database is not open', {
code: 'LEVEL_DATABASE_NOT_OPEN'
})
}
return this._keys(options)
}
_keys (options) {
return new DefaultKeyIterator(this, options)
}
values (options) {
const keyEncoding = this.keyEncoding(options && options.keyEncoding)
const valueEncoding = this.valueEncoding(options && options.valueEncoding)
options = rangeOptions(options, keyEncoding)
// We need the original encoding options in AbstractValueIterator in order to decode data
options[AbstractIterator.keyEncoding] = keyEncoding
options[AbstractIterator.valueEncoding] = valueEncoding
// Forward encoding options to private API
options.keyEncoding = keyEncoding.format
options.valueEncoding = valueEncoding.format
if (this[kStatus] === 'opening') {
return new DeferredValueIterator(this, options)
} else if (this[kStatus] !== 'open') {
throw new ModuleError('Database is not open', {
code: 'LEVEL_DATABASE_NOT_OPEN'
})
}
return this._values(options)
}
_values (options) {
return new DefaultValueIterator(this, options)
}
defer (fn) {
if (typeof fn !== 'function') {
throw new TypeError('The first argument must be a function')
}
this[kOperations].push(fn)
}
[kUndefer] () {
if (this[kOperations].length === 0) {
return
}
const operations = this[kOperations]
this[kOperations] = []
for (const op of operations) {
op()
}
}
// TODO: docs and types
attachResource (resource) {
if (typeof resource !== 'object' || resource === null ||
typeof resource.close !== 'function') {
throw new TypeError('The first argument must be a resource object')
}
this[kResources].add(resource)
}
// TODO: docs and types
detachResource (resource) {
this[kResources].delete(resource)
}
_chainedBatch () {
return new DefaultChainedBatch(this)
}
_checkKey (key) {
if (key === null || key === undefined) {
return new ModuleError('Key cannot be null or undefined', {
code: 'LEVEL_INVALID_KEY'
})
}
}
_checkValue (value) {
if (value === null || value === undefined) {
return new ModuleError('Value cannot be null or undefined', {
code: 'LEVEL_INVALID_VALUE'
})
}
}
}
// Expose browser-compatible nextTick for dependents
// TODO: after we drop node 10, also use queueMicrotask in node
AbstractLevel.prototype.nextTick = __webpack_require__(/*! ./lib/next-tick */ "./node_modules/abstract-level/lib/next-tick-browser.js")
const { AbstractSublevel } = __webpack_require__(/*! ./lib/abstract-sublevel */ "./node_modules/abstract-level/lib/abstract-sublevel.js")({ AbstractLevel })
exports.AbstractLevel = AbstractLevel
exports.AbstractSublevel = AbstractSublevel
const maybeError = function (db, callback) {
if (db[kStatus] !== 'open') {
db.nextTick(callback, new ModuleError('Database is not open', {
code: 'LEVEL_DATABASE_NOT_OPEN'
}))
return true
}
return false
}
const formats = function (db) {
return Object.keys(db.supports.encodings)
.filter(k => !!db.supports.encodings[k])
}
/***/ }),
/***/ "./node_modules/abstract-level/index.js":
/*!**********************************************!*\
!*** ./node_modules/abstract-level/index.js ***!
\**********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
exports.AbstractLevel = __webpack_require__(/*! ./abstract-level */ "./node_modules/abstract-level/abstract-level.js").AbstractLevel
exports.AbstractSublevel = __webpack_require__(/*! ./abstract-level */ "./node_modules/abstract-level/abstract-level.js").AbstractSublevel
exports.AbstractIterator = __webpack_require__(/*! ./abstract-iterator */ "./node_modules/abstract-level/abstract-iterator.js").AbstractIterator
exports.AbstractKeyIterator = __webpack_require__(/*! ./abstract-iterator */ "./node_modules/abstract-level/abstract-iterator.js").AbstractKeyIterator
exports.AbstractValueIterator = __webpack_require__(/*! ./abstract-iterator */ "./node_modules/abstract-level/abstract-iterator.js").AbstractValueIterator
exports.AbstractChainedBatch = __webpack_require__(/*! ./abstract-chained-batch */ "./node_modules/abstract-level/abstract-chained-batch.js").AbstractChainedBatch
/***/ }),
/***/ "./node_modules/abstract-level/lib/abstract-sublevel-iterator.js":
/*!***********************************************************************!*\
!*** ./node_modules/abstract-level/lib/abstract-sublevel-iterator.js ***!
\***********************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
const { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = __webpack_require__(/*! ../abstract-iterator */ "./node_modules/abstract-level/abstract-iterator.js")
const kUnfix = Symbol('unfix')
const kIterator = Symbol('iterator')
const kHandleOne = Symbol('handleOne')
const kHandleMany = Symbol('handleMany')
const kCallback = Symbol('callback')
// TODO: unfix natively if db supports it
class AbstractSublevelIterator extends AbstractIterator {
constructor (db, options, iterator, unfix) {
super(db, options)
this[kIterator] = iterator
this[kUnfix] = unfix
this[kHandleOne] = this[kHandleOne].bind(this)
this[kHandleMany] = this[kHandleMany].bind(this)
this[kCallback] = null
}
[kHandleOne] (err, key, value) {
const callback = this[kCallback]
if (err) return callback(err)
if (key !== undefined) key = this[kUnfix](key)
callback(err, key, value)
}
[kHandleMany] (err, entries) {
const callback = this[kCallback]
if (err) return callback(err)
for (const entry of entries) {
const key = entry[0]
if (key !== undefined) entry[0] = this[kUnfix](key)
}
callback(err, entries)
}
}
class AbstractSublevelKeyIterator extends AbstractKeyIterator {
constructor (db, options, iterator, unfix) {
super(db, options)
this[kIterator] = iterator
this[kUnfix] = unfix
this[kHandleOne] = this[kHandleOne].bind(this)
this[kHandleMany] = this[kHandleMany].bind(this)
this[kCallback] = null
}
[kHandleOne] (err, key) {
const callback = this[kCallback]
if (err) return callback(err)
if (key !== undefined) key = this[kUnfix](key)
callback(err, key)
}
[kHandleMany] (err, keys) {
const callback = this[kCallback]
if (err) return callback(err)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
if (key !== undefined) keys[i] = this[kUnfix](key)
}
callback(err, keys)
}
}
class AbstractSublevelValueIterator extends AbstractValueIterator {
constructor (db, options, iterator) {
super(db, options)
this[kIterator] = iterator
}
}
for (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator]) {
Iterator.prototype._next = function (callback) {
this[kCallback] = callback
this[kIterator].next(this[kHandleOne])
}
Iterator.prototype._nextv = function (size, options, callback) {
this[kCallback] = callback
this[kIterator].nextv(size, options, this[kHandleMany])
}
Iterator.prototype._all = function (options, callback) {
this[kCallback] = callback
this[kIterator].all(options, this[kHandleMany])
}
}
for (const Iterator of [AbstractSublevelValueIterator]) {
Iterator.prototype._next = function (callback) {
this[kIterator].next(callback)
}
Iterator.prototype._nextv = function (size, options, callback) {
this[kIterator].nextv(size, options, callback)
}
Iterator.prototype._all = function (options, callback) {
this[kIterator].all(options, callback)
}
}
for (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator, AbstractSublevelValueIterator]) {
Iterator.prototype._seek = function (target, options) {
this[kIterator].seek(target, options)
}
Iterator.prototype._close = function (callback) {
this[kIterator].close(callback)
}
}
exports.AbstractSublevelIterator = AbstractSublevelIterator
exports.AbstractSublevelKeyIterator = AbstractSublevelKeyIterator
exports.AbstractSublevelValueIterator = AbstractSublevelValueIterator
/***/ }),
/***/ "./node_modules/abstract-level/lib/abstract-sublevel.js":
/*!**************************************************************!*\
!*** ./node_modules/abstract-level/lib/abstract-sublevel.js ***!
\**************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
const ModuleError = __webpack_require__(/*! module-error */ "./node_modules/module-error/index.js")
const { Buffer } = __webpack_require__(/*! buffer */ "./node_modules/buffer/index.js") || {}
const {
AbstractSublevelIterator,
AbstractSublevelKeyIterator,
AbstractSublevelValueIterator
} = __webpack_require__(/*! ./abstract-sublevel-iterator */ "./node_modules/abstract-level/lib/abstract-sublevel-iterator.js")
const kPrefix = Symbol('prefix')
const kUpperBound = Symbol('upperBound')
const kPrefixRange = Symbol('prefixRange')
const kParent = Symbol('parent')
const kUnfix = Symbol('unfix')
const textEncoder = new TextEncoder()
const defaults = { separator: '!' }
// Wrapped to avoid circular dependency
module.exports = function ({ AbstractLevel }) {
class AbstractSublevel extends AbstractLevel {
static defaults (options) {
// To help migrating from subleveldown to abstract-level
if (typeof options === 'string') {
throw new ModuleError('The subleveldown string shorthand for { separator } has been removed', {
code: 'LEVEL_LEGACY'
})
} else if (options && options.open) {
throw new ModuleError('The subleveldown open option has been removed', {
code: 'LEVEL_LEGACY'
})
}
if (options == null) {
return defaults
} else if (!options.separator) {
return { ...options, separator: '!' }
} else {
return options
}
}
// TODO: add autoClose option, which if true, does parent.attachResource(this)
constructor (db, name, options) {
// Don't forward AbstractSublevel options to AbstractLevel
const { separator, manifest, ...forward } = AbstractSublevel.defaults(options)
name = trim(name, separator)
// Reserve one character between separator and name to give us an upper bound
const reserved = separator.charCodeAt(0) + 1
const parent = db[kParent] || db
// Keys should sort like ['!a!', '!a!!a!', '!a"', '!aa!', '!b!'].
// Use ASCII for consistent length between string, Buffer and Uint8Array
if (!textEncoder.encode(name).every(x => x > reserved && x < 127)) {
throw new ModuleError(`Prefix must use bytes > ${reserved} < ${127}`, {
code: 'LEVEL_INVALID_PREFIX'
})
}
super(mergeManifests(parent, manifest), forward)
const prefix = (db.prefix || '') + separator + name + separator
const upperBound = prefix.slice(0, -1) + String.fromCharCode(reserved)
this[kParent] = parent
this[kPrefix] = new MultiFormat(prefix)
this[kUpperBound] = new MultiFormat(upperBound)
this[kUnfix] = new Unfixer()
this.nextTick = parent.nextTick
}
prefixKey (key, keyFormat) {
if (keyFormat === 'utf8') {
return this[kPrefix].utf8 + key
} else if (key.byteLength === 0) {
// Fast path for empty key (no copy)
return this[kPrefix][keyFormat]
} else if (keyFormat === 'view') {
const view = this[kPrefix].view
const result = new Uint8Array(view.byteLength + key.byteLength)
result.set(view, 0)
result.set(key, view.byteLength)
return result
} else {
const buffer = this[kPrefix].buffer
return Buffer.concat([buffer, key], buffer.byteLength + key.byteLength)
}
}
// Not exposed for now.
[kPrefixRange] (range, keyFormat) {
if (range.gte !== undefined) {
range.gte = this.prefixKey(range.gte, keyFormat)
} else if (range.gt !== undefined) {
range.gt = this.prefixKey(range.gt, keyFormat)
} else {
range.gte = this[kPrefix][keyFormat]
}
if (range.lte !== undefined) {
range.lte = this.prefixKey(range.lte, keyFormat)
} else if (range.lt !== undefined) {
range.lt = this.prefixKey(range.lt, keyFormat)
} else {
range.lte = this[kUpperBound][keyFormat]
}
}
get prefix () {
return this[kPrefix].utf8
}
get db () {
return this[kParent]
}
_open (options, callback) {
// The parent db must open itself or be (re)opened by the user because
// a sublevel should not initiate state changes on the rest of the db.
this[kParent].open({ passive: true }, callback)
}
_put (key, value, options, callback) {
this[kParent].put(key, value, options, callback)
}
_get (key, options, callback) {
this[kParent].get(key, options, callback)
}
_getMany (keys, options, callback) {
this[kParent].getMany(keys, options, callback)
}
_del (key, options, callback) {
this[kParent].del(key, options, callback)
}
_batch (operations, options, callback) {
this[kParent].batch(operations, options, callback)
}
_clear (options, callback) {
// TODO (refactor): move to AbstractLevel
this[kPrefixRange](options, options.keyEncoding)
this[kParent].clear(options, callback)
}
_iterator (options) {
// TODO (refactor): move to AbstractLevel
this[kPrefixRange](options, options.keyEncoding)
const iterator = this[kParent].iterator(options)
const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding)
return new AbstractSublevelIterator(this, options, iterator, unfix)
}
_keys (options) {
this[kPrefixRange](options, options.keyEncoding)
const iterator = this[kParent].keys(options)
const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding)
return new AbstractSublevelKeyIterator(this, options, iterator, unfix)
}
_values (options) {
this[kPrefixRange](options, options.keyEncoding)
const iterator = this[kParent].values(options)
return new AbstractSublevelValueIterator(this, options, iterator)
}
}
return { AbstractSublevel }
}
const mergeManifests = function (parent, manifest) {
return {
// Inherit manifest of parent db
...parent.supports,
// Disable unsupported features
createIfMissing: false,
errorIfExists: false,
// Unset additional events because we're not forwarding them
events: {},
// Unset additional methods (like approximateSize) which we can't support here unless
// the AbstractSublevel class is overridden by an implementation of `abstract-level`.
additionalMethods: {},
// Inherit manifest of custom AbstractSublevel subclass. Such a class is not
// allowed to override encodings.
...manifest,
encodings: {
utf8: supportsEncoding(parent, 'utf8'),
buffer: supportsEncoding(parent, 'buffer'),
view: supportsEncoding(parent, 'view')
}
}
}
const supportsEncoding = function (parent, encoding) {
// Prefer a non-transcoded encoding for optimal performance
return parent.supports.encodings[encoding]
? parent.keyEncoding(encoding).name === encoding
: false
}
class MultiFormat {
constructor (key) {
this.utf8 = key
this.view = textEncoder.encode(key)
this.buffer = Buffer ? Buffer.from(this.view.buffer, 0, this.view.byteLength) : {}
}
}
class Unfixer {
constructor () {
this.cache = new Map()
}
get (prefixLength, keyFormat) {
let unfix = this.cache.get(keyFormat)
if (unfix === undefined) {
if (keyFormat === 'view') {
unfix = function (prefixLength, key) {
// Avoid Uint8Array#slice() because it copies
return key.subarray(prefixLength)
}.bind(null, prefixLength)
} else {
unfix = function (prefixLength, key) {
// Avoid Buffer#subarray() because it's slow
return key.slice(prefixLength)
}.bind(null, prefixLength)
}
this.cache.set(keyFormat, unfix)
}
return unfix
}
}
const trim = function (str, char) {
let start = 0
let end = str.length
while (start < end && str[start] === char) start++
while (end > start && str[end - 1] === char) end--
return str.slice(start, end)
}
/***/ }),
/***/ "./node_modules/abstract-level/lib/common.js":
/*!***************************************************!*\
!*** ./node_modules/abstract-level/lib/common.js ***!
\***************************************************/
/***/ ((__unused_webpack_module, exports) => {
"use strict";
exports.getCallback = function (options, callback) {
return typeof options === 'function' ? options : callback
}
exports.getOptions = function (options, def) {
if (typeof options === 'object' && options !== null) {
return options
}
if (def !== undefined) {
return def
}
return {}
}
/***/ }),
/***/ "./node_modules/abstract-level/lib/default-chained-batch.js":
/*!******************************************************************!*\
!*** ./node_modules/abstract-level/lib/default-chained-batch.js ***!
\******************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
const { AbstractChainedBatch } = __webpack_require__(/*! ../abstract-chained-batch */ "./node_modules/abstract-level/abstract-chained-batch.js")
const ModuleError = __webpack_require__(/*! module-error */ "./node_modules/module-error/index.js")
const kEncoded = Symbol('encoded')
// Functional default for chained batch, with support of deferred open
class DefaultChainedBatch extends AbstractChainedBatch {
constructor (db) {
super(db)
this[kEncoded] = []
}
_put (key, value, options) {
this[kEncoded].push({ ...options, type: 'put', key, value })
}
_del (key, options) {
this[kEncoded].push({ ...options, type: 'del', key })
}
_clear () {
this[kEncoded] = []
}
// Assumes this[kEncoded] cannot change after write()
_write (options, callback) {
if (this.db.status === 'opening') {
this.db.defer(() => this._write(options, callback))
} else if (this.db.status === 'open') {
if (this[kEncoded].length === 0) this.nextTick(callback)
else this.db._batch(this[kEncoded], options, callback)
} else {
this.nextTick(callback, new ModuleError('Batch is not open: cannot call write() after write() or close()', {
code: 'LEVEL_BATCH_NOT_OPEN'
}))
}
}
}
exports.DefaultChainedBatch = DefaultChainedBatch
/***/ }),
/***/ "./node_modules/abstract-level/lib/default-kv-iterator.js":
/*!****************************************************************!*\
!*** ./node_modules/abstract-level/lib/default-kv-iterator.js ***!
\****************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
const { AbstractKeyIterator, AbstractValueIterator } = __webpack_require__(/*! ../abstract-iterator */ "./node_modules/abstract-level/abstract-iterator.js")
const kIterator = Symbol('iterator')
const kCallback = Symbol('callback')
const kHandleOne = Symbol('handleOne')
const kHandleMany = Symbol('handleMany')
class DefaultKeyIterator extends AbstractKeyIterator {
constructor (db, options) {
super(db, options)
this[kIterator] = db.iterator({ ...options, keys: true, values: false })
this[kHandleOne] = this[kHandleOne].bind(this)
this[kHandleMany] = this[kHandleMany].bind(this)
}
}
class DefaultValueIterator extends AbstractValueIterator {
constructor (db, options) {
super(db, options)
this[kIterator] = db.iterator({ ...options, keys: false, values: true })
this[kHandleOne] = this[kHandleOne].bind(this)
this[kHandleMany] = this[kHandleMany].bind(this)
}
}
for (const Iterator of [DefaultKeyIterator, DefaultValueIterator]) {
const keys = Iterator === DefaultKeyIterator
const mapEntry = keys ? (entry) => entry[0] : (entry) => entry[1]
Iterator.prototype._next = function (callback) {
this[kCallback] = callback
this[kIterator].next(this[kHandleOne])
}
Iterator.prototype[kHandleOne] = function (err, key, value) {
const callback = this[kCallback]
if (err) callback(err)
else callback(null, keys ? key : value)
}
Iterator.prototype._nextv = function (size, options, callback) {
this[kCallback] = callback
this[kIterator].nextv(size, options, this[kHandleMany])
}
Iterator.prototype._all = function (options, callback) {
this[kCallback] = callback
this[kIterator].all(options, this[kHandleMany])
}
Iterator.prototype[kHandleMany] = function (err, entries) {
const callback = this[kCallback]
if (err) callback(err)
else callback(null, entries.map(mapEntry))
}
Iterator.prototype._seek = function (target, options) {
this[kIterator].seek(target, options)
}
Iterator.prototype._close = function (callback) {
this[kIterator].close(callback)
}
}
// Internal utilities, should be typed as AbstractKeyIterator and AbstractValueIterator
exports.DefaultKeyIterator = DefaultKeyIterator
exports.DefaultValueIterator = DefaultValueIterator
/***/ }),
/***/ "./node_modules/abstract-level/lib/deferred-iterator.js":
/*!**************************************************************!*\
!*** ./node_modules/abstract-level/lib/deferred-iterator.js ***!
\**************************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
const { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = __webpack_require__(/*! ../abstract-iterator */ "./node_modules/abstract-level/abstract-iterator.js")
const ModuleError = __webpack_require__(/*! module-error */ "./node_modules/module-error/index.js")
const kNut = Symbol('nut')
const kUndefer = Symbol('undefer')
const kFactory = Symbol('factory')
class DeferredIterator extends AbstractIterator {
constructor (db, options) {
super(db, options)
this[kNut] = null
this[kFactory] = () => db.iterator(options)
this.db.defer(() => this[kUndefer]())
}
}
class DeferredKeyIterator extends AbstractKeyIterator {
constructor (db, options) {
super(db, options)
this[kNut] = null
this[kFactory] = () => db.keys(options)
this.db.defer(() => this[kUndefer]())
}
}
class DeferredValueIterator extends AbstractValueIterator {
constructor (db, options) {
super(db, options)
this[kNut] = null
this[kFactory] = () => db.values(options)
this.db.defer(() => this[kUndefer]())
}
}
for (const Iterator of [DeferredIterator, DeferredKeyIterator, DeferredValueIterator]) {
Iterator.prototype[kUndefer] = function () {
if (this.db.status === 'open') {
this[kNut] = this[kFactory]()
}
}
Iterator.prototype._next = function (callback) {
if (this[kNut] !== null) {
this[kNut].next(callback)
} else if (this.db.status === 'opening') {
this.db.defer(() => this._next(callback))
} else {
this.nextTick(callback, new ModuleError('Iterator is not open: cannot call next() after close()', {
code: 'LEVEL_ITERATOR_NOT_OPEN'
}))
}
}
Iterator.prototype._nextv = function (size, options, callback) {
if (this[kNut] !== null) {
this[kNut].nextv(size, options, callback)
} else if (this.db.status === 'opening') {
this.db.defer(() => this._nextv(size, options, callback))
} else {
this.nextTick(callback, new ModuleError('Iterator is not open: cannot call nextv() after close()', {
code: 'LEVEL_ITERATOR_NOT_OPEN'
}))
}
}
Iterator.prototype._all = function (options, callback) {
if (this[kNut] !== null) {
this[kNut].all(callback)
} else if (this.db.status === 'opening') {
this.db.defer(() => this._all(options, callback))
} else {
this.nextTick(callback, new ModuleError('Iterator is not open: cannot call all() after close()', {
code: 'LEVEL_ITERATOR_NOT_OPEN'
}))
}
}
Iterator.prototype._seek = function (target, options) {
if (this[kNut] !== null) {
// TODO: explain why we need _seek() rather than seek() here
this[kNut]._seek(target, options)
} else if (this.db.status === 'opening') {
this.db.defer(() => this._seek(target, options))
}
}
Iterator.prototype._close = function (callback) {
if (this[kNut] !== null) {
this[kNut].close(callback)
} else if (this.db.status === 'opening') {
this.db.defer(() => this._close(callback))
} else {
this.nextTick(callback)
}
}
}
exports.DeferredIterator = DeferredIterator
exports.DeferredKeyIterator = DeferredKeyIterator
exports.DeferredValueIterator = DeferredValueIterator
/***/ }),
/***/ "./node_modules/abstract-level/lib/next-tick-browser.js":
/*!**************************************************************!*\
!*** ./node_modules/abstract-level/lib/next-tick-browser.js ***!
\**************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
const queueMicrotask = __webpack_require__(/*! queue-microtask */ "./node_modules/queue-microtask/index.js")
module.exports = function (fn, ...args) {
if (args.length === 0) {
queueMicrotask(fn)
} else {
queueMicrotask(() => fn(...args))
}
}
/***/ }),
/***/ "./node_modules/abstract-level/lib/range-options.js":
/*!**********************************************************!*\
!*** ./node_modules/abstract-level/lib/range-options.js ***!
\**********************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
const ModuleError = __webpack_require__(/*! module-error */ "./node_modules/module-error/index.js")
const hasOwnProperty = Object.prototype.hasOwnProperty
const rangeOptions = new Set(['lt', 'lte', 'gt', 'gte'])
module.exports = function (options, keyEncoding) {
const result = {}
for (const k in options) {
if (!hasOwnProperty.call(options, k)) continue
if (k === 'keyEncoding' || k === 'valueEncoding') continue
if (k === 'start' || k === 'end') {
throw new ModuleError(`The legacy range option '${k}' has been removed`, {
code: 'LEVEL_LEGACY'
})
} else if (k === 'encoding') {
// To help migrating to abstract-level
throw new ModuleError("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead", {
code: 'LEVEL_LEGACY'
})
}
if (rangeOptions.has(k)) {
// Note that we don't reject nullish and empty options here. While
// those types are invalid as keys, they are valid as range options.
result[k] = keyEncoding.encode(options[k])
} else {
result[k] = options[k]
}
}
result.reverse = !!result.reverse
result.limit = Number.isInteger(result.limit) && result.limit >= 0 ? result.limit : -1
return result
}
/***/ }),
/***/ "./node_modules/asn1js/build/index.es.js":
/*!***********************************************!*\
!*** ./node_modules/asn1js/build/index.es.js ***!
\***********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Any: () => (/* binding */ Any),
/* harmony export */ BaseBlock: () => (/* binding */ BaseBlock),
/* harmony export */ BaseStringBlock: () => (/* binding */ BaseStringBlock),
/* harmony export */ BitString: () => (/* binding */ BitString),
/* harmony export */ BmpString: () => (/* binding */ BmpString),
/* harmony export */ Boolean: () => (/* binding */ Boolean),
/* harmony export */ CharacterString: () => (/* binding */ CharacterString),
/* harmony export */ Choice: () => (/* binding */ Choice),
/* harmony export */ Constructed: () => (/* binding */ Constructed),
/* harmony export */ DATE: () => (/* binding */ DATE),
/* harmony export */ DateTime: () => (/* binding */ DateTime),
/* harmony export */ Duration: () => (/* binding */ Duration),
/* harmony export */ EndOfContent: () => (/* binding */ EndOfContent),
/* harmony export */ Enumerated: () => (/* binding */ Enumerated),
/* harmony export */ GeneralString: () => (/* binding */ GeneralString),
/* harmony export */ GeneralizedTime: () => (/* binding */ GeneralizedTime),
/* harmony export */ GraphicString: () => (/* binding */ GraphicString),
/* harmony export */ HexBlock: () => (/* binding */ HexBlock),
/* harmony export */ IA5String: () => (/* binding */ IA5String),
/* harmony export */ Integer: () => (/* binding */ Integer),
/* harmony export */ Null: () => (/* binding */ Null),
/* harmony export */ NumericString: () => (/* binding */ NumericString),
/* harmony export */ ObjectIdentifier: () => (/* binding */ ObjectIdentifier),
/* harmony export */ OctetString: () => (/* binding */ OctetString),
/* harmony export */ Primitive: () => (/* binding */ Primitive),
/* harmony export */ PrintableString: () => (/* binding */ PrintableString),
/* harmony export */ RawData: () => (/* binding */ RawData),
/* harmony export */ RelativeObjectIdentifier: () => (/* binding */ RelativeObjectIdentifier),
/* harmony export */ Repeated: () => (/* binding */ Repeated),
/* harmony export */ Sequence: () => (/* binding */ Sequence),
/* harmony export */ Set: () => (/* binding */ Set),
/* harmony export */ TIME: () => (/* binding */ TIME),
/* harmony export */ TeletexString: () => (/* binding */ TeletexString),
/* harmony export */ TimeOfDay: () => (/* binding */ TimeOfDay),
/* harmony export */ UTCTime: () => (/* binding */ UTCTime),
/* harmony export */ UniversalString: () => (/* binding */ UniversalString),
/* harmony export */ Utf8String: () => (/* binding */ Utf8String),
/* harmony export */ ValueBlock: () => (/* binding */ ValueBlock),
/* harmony export */ VideotexString: () => (/* binding */ VideotexString),
/* harmony export */ ViewWriter: () => (/* binding */ ViewWriter),
/* harmony export */ VisibleString: () => (/* binding */ VisibleString),
/* harmony export */ compareSchema: () => (/* binding */ compareSchema),
/* harmony export */ fromBER: () => (/* binding */ fromBER),
/* harmony export */ verifySchema: () => (/* binding */ verifySchema)
/* harmony export */ });
/* harmony import */ var pvtsutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! pvtsutils */ "./node_modules/pvtsutils/build/index.js");
/* harmony import */ var pvutils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! pvutils */ "./node_modules/pvutils/build/utils.es.js");
/*!
* Copyright (c) 2014, GMO GlobalSign
* Copyright (c) 2015-2022, Peculiar Ventures
* All rights reserved.
*
* Author 2014-2019, Yury Strozhevsky
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
function assertBigInt() {
if (typeof BigInt === "undefined") {
throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.");
}
}
function concat(buffers) {
let outputLength = 0;
let prevLength = 0;
for (let i = 0; i < buffers.length; i++) {
const buffer = buffers[i];
outputLength += buffer.byteLength;
}
const retView = new Uint8Array(outputLength);
for (let i = 0; i < buffers.length; i++) {
const buffer = buffers[i];
retView.set(new Uint8Array(buffer), prevLength);
prevLength += buffer.byteLength;
}
return retView.buffer;
}
function checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {
if (!(inputBuffer instanceof Uint8Array)) {
baseBlock.error = "Wrong parameter: inputBuffer must be 'Uint8Array'";
return false;
}
if (!inputBuffer.byteLength) {
baseBlock.error = "Wrong parameter: inputBuffer has zero length";
return false;
}
if (inputOffset < 0) {
baseBlock.error = "Wrong parameter: inputOffset less than zero";
return false;
}
if (inputLength < 0) {
baseBlock.error = "Wrong parameter: inputLength less than zero";
return false;
}
if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {
baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)";
return false;
}
return true;
}
class ViewWriter {
constructor() {
this.items = [];
}
write(buf) {
this.items.push(buf);
}
final() {
return concat(this.items);
}
}
const powers2 = [new Uint8Array([1])];
const digitsString = "0123456789";
const NAME = "name";
const VALUE_HEX_VIEW = "valueHexView";
const IS_HEX_ONLY = "isHexOnly";
const ID_BLOCK = "idBlock";
const TAG_CLASS = "tagClass";
const TAG_NUMBER = "tagNumber";
const IS_CONSTRUCTED = "isConstructed";
const FROM_BER = "fromBER";
const TO_BER = "toBER";
const LOCAL = "local";
const EMPTY_STRING = "";
const EMPTY_BUFFER = new ArrayBuffer(0);
const EMPTY_VIEW = new Uint8Array(0);
const END_OF_CONTENT_NAME = "EndOfContent";
const OCTET_STRING_NAME = "OCTET STRING";
const BIT_STRING_NAME = "BIT STRING";
function HexBlock(BaseClass) {
var _a;
return _a = class Some extends BaseClass {
constructor(...args) {
var _a;
super(...args);
const params = args[0] || {};
this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false;
this.valueHexView = params.valueHex ? pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;
}
get valueHex() {
return this.valueHexView.slice().buffer;
}
set valueHex(value) {
this.valueHexView = new Uint8Array(value);
}
fromBER(inputBuffer, inputOffset, inputLength) {
const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;
if (!checkBufferParams(this, view, inputOffset, inputLength)) {
return -1;
}
const endLength = inputOffset + inputLength;
this.valueHexView = view.subarray(inputOffset, endLength);
if (!this.valueHexView.length) {
this.warnings.push("Zero buffer length");
return inputOffset;
}
this.blockLength = inputLength;
return endLength;
}
toBER(sizeOnly = false) {
if (!this.isHexOnly) {
this.error = "Flag 'isHexOnly' is not set, abort";
return EMPTY_BUFFER;
}
if (sizeOnly) {
return new ArrayBuffer(this.valueHexView.byteLength);
}
return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength)
? this.valueHexView.buffer
: this.valueHexView.slice().buffer;
}
toJSON() {
return {
...super.toJSON(),
isHexOnly: this.isHexOnly,
valueHex: pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.ToHex(this.valueHexView),
};
}
},
_a.NAME = "hexBlock",
_a;
}
class LocalBaseBlock {
constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) {
this.blockLength = blockLength;
this.error = error;
this.warnings = warnings;
this.valueBeforeDecodeView = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(valueBeforeDecode);
}
static blockName() {
return this.NAME;
}
get valueBeforeDecode() {
return this.valueBeforeDecodeView.slice().buffer;
}
set valueBeforeDecode(value) {
this.valueBeforeDecodeView = new Uint8Array(value);
}
toJSON() {
return {
blockName: this.constructor.NAME,
blockLength: this.blockLength,
error: this.error,
warnings: this.warnings,
valueBeforeDecode: pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.ToHex(this.valueBeforeDecodeView),
};
}
}
LocalBaseBlock.NAME = "baseBlock";
class ValueBlock extends LocalBaseBlock {
fromBER(inputBuffer, inputOffset, inputLength) {
throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
}
toBER(sizeOnly, writer) {
throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
}
}
ValueBlock.NAME = "valueBlock";
class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) {
constructor({ idBlock = {}, } = {}) {
var _a, _b, _c, _d;
super();
if (idBlock) {
this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false;
this.valueHexView = idBlock.valueHex ? pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(idBlock.valueHex) : EMPTY_VIEW;
this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;
this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;
this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false;
}
else {
this.tagClass = -1;
this.tagNumber = -1;
this.isConstructed = false;
}
}
toBER(sizeOnly = false) {
let firstOctet = 0;
switch (this.tagClass) {
case 1:
firstOctet |= 0x00;
break;
case 2:
firstOctet |= 0x40;
break;
case 3:
firstOctet |= 0x80;
break;
case 4:
firstOctet |= 0xC0;
break;
default:
this.error = "Unknown tag class";
return EMPTY_BUFFER;
}
if (this.isConstructed)
firstOctet |= 0x20;
if (this.tagNumber < 31 && !this.isHexOnly) {
const retView = new Uint8Array(1);
if (!sizeOnly) {
let number = this.tagNumber;
number &= 0x1F;
firstOctet |= number;
retView[0] = firstOctet;
}
return retView.buffer;
}
if (!this.isHexOnly) {
const encodedBuf = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilToBase(this.tagNumber, 7);
const encodedView = new Uint8Array(encodedBuf);
const size = encodedBuf.byteLength;
const retView = new Uint8Array(size + 1);
retView[0] = (firstOctet | 0x1F);
if (!sizeOnly) {
for (let i = 0; i < (size - 1); i++)
retView[i + 1] = encodedView[i] | 0x80;
retView[size] = encodedView[size - 1];
}
return retView.buffer;
}
const retView = new Uint8Array(this.valueHexView.byteLength + 1);
retView[0] = (firstOctet | 0x1F);
if (!sizeOnly) {
const curView = this.valueHexView;
for (let i = 0; i < (curView.length - 1); i++)
retView[i + 1] = curView[i] | 0x80;
retView[this.valueHexView.byteLength] = curView[curView.length - 1];
}
return retView.buffer;
}
fromBER(inputBuffer, inputOffset, inputLength) {
const inputView = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
return -1;
}
const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
if (intBuffer.length === 0) {
this.error = "Zero buffer length";
return -1;
}
const tagClassMask = intBuffer[0] & 0xC0;
switch (tagClassMask) {
case 0x00:
this.tagClass = (1);
break;
case 0x40:
this.tagClass = (2);
break;
case 0x80:
this.tagClass = (3);
break;
case 0xC0:
this.tagClass = (4);
break;
default:
this.error = "Unknown tag class";
return -1;
}
this.isConstructed = (intBuffer[0] & 0x20) === 0x20;
this.isHexOnly = false;
const tagNumberMask = intBuffer[0] & 0x1F;
if (tagNumberMask !== 0x1F) {
this.tagNumber = (tagNumberMask);
this.blockLength = 1;
}
else {
let count = 1;
let intTagNumberBuffer = this.valueHexView = new Uint8Array(255);
let tagNumberBufferMaxLength = 255;
while (intBuffer[count] & 0x80) {
intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;
count++;
if (count >= intBuffer.length) {
this.error = "End of input reached before message was fully decoded";
return -1;
}
if (count === tagNumberBufferMaxLength) {
tagNumberBufferMaxLength += 255;
const tempBufferView = new Uint8Array(tagNumberBufferMaxLength);
for (let i = 0; i < intTagNumberBuffer.length; i++)
tempBufferView[i] = intTagNumberBuffer[i];
intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength);
}
}
this.blockLength = (count + 1);
intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;
const tempBufferView = new Uint8Array(count);
for (let i = 0; i < count; i++)
tempBufferView[i] = intTagNumberBuffer[i];
intTagNumberBuffer = this.valueHexView = new Uint8Array(count);
intTagNumberBuffer.set(tempBufferView);
if (this.blockLength <= 9)
this.tagNumber = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilFromBase(intTagNumberBuffer, 7);
else {
this.isHexOnly = true;
this.warnings.push("Tag too long, represented as hex-coded");
}
}
if (((this.tagClass === 1)) &&
(this.isConstructed)) {
switch (this.tagNumber) {
case 1:
case 2:
case 5:
case 6:
case 9:
case 13:
case 14:
case 23:
case 24:
case 31:
case 32:
case 33:
case 34:
this.error = "Constructed encoding used for primitive type";
return -1;
}
}
return (inputOffset + this.blockLength);
}
toJSON() {
return {
...super.toJSON(),
tagClass: this.tagClass,
tagNumber: this.tagNumber,
isConstructed: this.isConstructed,
};
}
}
LocalIdentificationBlock.NAME = "identificationBlock";
class LocalLengthBlock extends LocalBaseBlock {
constructor({ lenBlock = {}, } = {}) {
var _a, _b, _c;
super();
this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false;
this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;
this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0;
}
fromBER(inputBuffer, inputOffset, inputLength) {
const view = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, view, inputOffset, inputLength)) {
return -1;
}
const intBuffer = view.subarray(inputOffset, inputOffset + inputLength);
if (intBuffer.length === 0) {
this.error = "Zero buffer length";
return -1;
}
if (intBuffer[0] === 0xFF) {
this.error = "Length block 0xFF is reserved by standard";
return -1;
}
this.isIndefiniteForm = intBuffer[0] === 0x80;
if (this.isIndefiniteForm) {
this.blockLength = 1;
return (inputOffset + this.blockLength);
}
this.longFormUsed = !!(intBuffer[0] & 0x80);
if (this.longFormUsed === false) {
this.length = (intBuffer[0]);
this.blockLength = 1;
return (inputOffset + this.blockLength);
}
const count = intBuffer[0] & 0x7F;
if (count > 8) {
this.error = "Too big integer";
return -1;
}
if ((count + 1) > intBuffer.length) {
this.error = "End of input reached before message was fully decoded";
return -1;
}
const lenOffset = inputOffset + 1;
const lengthBufferView = view.subarray(lenOffset, lenOffset + count);
if (lengthBufferView[count - 1] === 0x00)
this.warnings.push("Needlessly long encoded length");
this.length = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilFromBase(lengthBufferView, 8);
if (this.longFormUsed && (this.length <= 127))
this.warnings.push("Unnecessary usage of long length form");
this.blockLength = count + 1;
return (inputOffset + this.blockLength);
}
toBER(sizeOnly = false) {
let retBuf;
let retView;
if (this.length > 127)
this.longFormUsed = true;
if (this.isIndefiniteForm) {
retBuf = new ArrayBuffer(1);
if (sizeOnly === false) {
retView = new Uint8Array(retBuf);
retView[0] = 0x80;
}
return retBuf;
}
if (this.longFormUsed) {
const encodedBuf = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilToBase(this.length, 8);
if (encodedBuf.byteLength > 127) {
this.error = "Too big length";
return (EMPTY_BUFFER);
}
retBuf = new ArrayBuffer(encodedBuf.byteLength + 1);
if (sizeOnly)
return retBuf;
const encodedView = new Uint8Array(encodedBuf);
retView = new Uint8Array(retBuf);
retView[0] = encodedBuf.byteLength | 0x80;
for (let i = 0; i < encodedBuf.byteLength; i++)
retView[i + 1] = encodedView[i];
return retBuf;
}
retBuf = new ArrayBuffer(1);
if (sizeOnly === false) {
retView = new Uint8Array(retBuf);
retView[0] = this.length;
}
return retBuf;
}
toJSON() {
return {
...super.toJSON(),
isIndefiniteForm: this.isIndefiniteForm,
longFormUsed: this.longFormUsed,
length: this.length,
};
}
}
LocalLengthBlock.NAME = "lengthBlock";
const typeStore = {};
class BaseBlock extends LocalBaseBlock {
constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) {
super(parameters);
this.name = name;
this.optional = optional;
if (primitiveSchema) {
this.primitiveSchema = primitiveSchema;
}
this.idBlock = new LocalIdentificationBlock(parameters);
this.lenBlock = new LocalLengthBlock(parameters);
this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters);
}
fromBER(inputBuffer, inputOffset, inputLength) {
const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);
if (resultOffset === -1) {
this.error = this.valueBlock.error;
return resultOffset;
}
if (!this.idBlock.error.length)
this.blockLength += this.idBlock.blockLength;
if (!this.lenBlock.error.length)
this.blockLength += this.lenBlock.blockLength;
if (!this.valueBlock.error.length)
this.blockLength += this.valueBlock.blockLength;
return resultOffset;
}
toBER(sizeOnly, writer) {
const _writer = writer || new ViewWriter();
if (!writer) {
prepareIndefiniteForm(this);
}
const idBlockBuf = this.idBlock.toBER(sizeOnly);
_writer.write(idBlockBuf);
if (this.lenBlock.isIndefiniteForm) {
_writer.write(new Uint8Array([0x80]).buffer);
this.valueBlock.toBER(sizeOnly, _writer);
_writer.write(new ArrayBuffer(2));
}
else {
const valueBlockBuf = this.valueBlock.toBER(sizeOnly);
this.lenBlock.length = valueBlockBuf.byteLength;
const lenBlockBuf = this.lenBlock.toBER(sizeOnly);
_writer.write(lenBlockBuf);
_writer.write(valueBlockBuf);
}
if (!writer) {
return _writer.final();
}
return EMPTY_BUFFER;
}
toJSON() {
const object = {
...super.toJSON(),
idBlock: this.idBlock.toJSON(),
lenBlock: this.lenBlock.toJSON(),
valueBlock: this.valueBlock.toJSON(),
name: this.name,
optional: this.optional,
};
if (this.primitiveSchema)
object.primitiveSchema = this.primitiveSchema.toJSON();
return object;
}
toString(encoding = "ascii") {
if (encoding === "ascii") {
return this.onAsciiEncoding();
}
return pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.ToHex(this.toBER());
}
onAsciiEncoding() {
return `${this.constructor.NAME} : ${pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`;
}
isEqual(other) {
if (this === other) {
return true;
}
if (!(other instanceof this.constructor)) {
return false;
}
const thisRaw = this.toBER();
const otherRaw = other.toBER();
return pvutils__WEBPACK_IMPORTED_MODULE_1__.isEqualBuffer(thisRaw, otherRaw);
}
}
BaseBlock.NAME = "BaseBlock";
function prepareIndefiniteForm(baseBlock) {
if (baseBlock instanceof typeStore.Constructed) {
for (const value of baseBlock.valueBlock.value) {
if (prepareIndefiniteForm(value)) {
baseBlock.lenBlock.isIndefiniteForm = true;
}
}
}
return !!baseBlock.lenBlock.isIndefiniteForm;
}
class BaseStringBlock extends BaseBlock {
constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {
super(parameters, stringValueBlockType);
if (value) {
this.fromString(value);
}
}
getValue() {
return this.valueBlock.value;
}
setValue(value) {
this.valueBlock.value = value;
}
fromBER(inputBuffer, inputOffset, inputLength) {
const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);
if (resultOffset === -1) {
this.error = this.valueBlock.error;
return resultOffset;
}
this.fromBuffer(this.valueBlock.valueHexView);
if (!this.idBlock.error.length)
this.blockLength += this.idBlock.blockLength;
if (!this.lenBlock.error.length)
this.blockLength += this.lenBlock.blockLength;
if (!this.valueBlock.error.length)
this.blockLength += this.valueBlock.blockLength;
return resultOffset;
}
onAsciiEncoding() {
return `${this.constructor.NAME} : '${this.valueBlock.value}'`;
}
}
BaseStringBlock.NAME = "BaseStringBlock";
class LocalPrimitiveValueBlock extends HexBlock(ValueBlock) {
constructor({ isHexOnly = true, ...parameters } = {}) {
super(parameters);
this.isHexOnly = isHexOnly;
}
}
LocalPrimitiveValueBlock.NAME = "PrimitiveValueBlock";
var _a$w;
class Primitive extends BaseBlock {
constructor(parameters = {}) {
super(parameters, LocalPrimitiveValueBlock);
this.idBlock.isConstructed = false;
}
}
_a$w = Primitive;
(() => {
typeStore.Primitive = _a$w;
})();
Primitive.NAME = "PRIMITIVE";
function localChangeType(inputObject, newType) {
if (inputObject instanceof newType) {
return inputObject;
}
const newObject = new newType();
newObject.idBlock = inputObject.idBlock;
newObject.lenBlock = inputObject.lenBlock;
newObject.warnings = inputObject.warnings;
newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView;
return newObject;
}
function localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) {
const incomingOffset = inputOffset;
let returnObject = new BaseBlock({}, ValueBlock);
const baseBlock = new LocalBaseBlock();
if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) {
returnObject.error = baseBlock.error;
return {
offset: -1,
result: returnObject
};
}
const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength);
if (!intBuffer.length) {
returnObject.error = "Zero buffer length";
return {
offset: -1,
result: returnObject
};
}
let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength);
if (returnObject.idBlock.warnings.length) {
returnObject.warnings.concat(returnObject.idBlock.warnings);
}
if (resultOffset === -1) {
returnObject.error = returnObject.idBlock.error;
return {
offset: -1,
result: returnObject
};
}
inputOffset = resultOffset;
inputLength -= returnObject.idBlock.blockLength;
resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength);
if (returnObject.lenBlock.warnings.length) {
returnObject.warnings.concat(returnObject.lenBlock.warnings);
}
if (resultOffset === -1) {
returnObject.error = returnObject.lenBlock.error;
return {
offset: -1,
result: returnObject
};
}
inputOffset = resultOffset;
inputLength -= returnObject.lenBlock.blockLength;
if (!returnObject.idBlock.isConstructed &&
returnObject.lenBlock.isIndefiniteForm) {
returnObject.error = "Indefinite length form used for primitive encoding form";
return {
offset: -1,
result: returnObject
};
}
let newASN1Type = BaseBlock;
switch (returnObject.idBlock.tagClass) {
case 1:
if ((returnObject.idBlock.tagNumber >= 37) &&
(returnObject.idBlock.isHexOnly === false)) {
returnObject.error = "UNIVERSAL 37 and upper tags are reserved by ASN.1 standard";
return {
offset: -1,
result: returnObject
};
}
switch (returnObject.idBlock.tagNumber) {
case 0:
if ((returnObject.idBlock.isConstructed) &&
(returnObject.lenBlock.length > 0)) {
returnObject.error = "Type [UNIVERSAL 0] is reserved";
return {
offset: -1,
result: returnObject
};
}
newASN1Type = typeStore.EndOfContent;
break;
case 1:
newASN1Type = typeStore.Boolean;
break;
case 2:
newASN1Type = typeStore.Integer;
break;
case 3:
newASN1Type = typeStore.BitString;
break;
case 4:
newASN1Type = typeStore.OctetString;
break;
case 5:
newASN1Type = typeStore.Null;
break;
case 6:
newASN1Type = typeStore.ObjectIdentifier;
break;
case 10:
newASN1Type = typeStore.Enumerated;
break;
case 12:
newASN1Type = typeStore.Utf8String;
break;
case 13:
newASN1Type = typeStore.RelativeObjectIdentifier;
break;
case 14:
newASN1Type = typeStore.TIME;
break;
case 15:
returnObject.error = "[UNIVERSAL 15] is reserved by ASN.1 standard";
return {
offset: -1,
result: returnObject
};
case 16:
newASN1Type = typeStore.Sequence;
break;
case 17:
newASN1Type = typeStore.Set;
break;
case 18:
newASN1Type = typeStore.NumericString;
break;
case 19:
newASN1Type = typeStore.PrintableString;
break;
case 20:
newASN1Type = typeStore.TeletexString;
break;
case 21:
newASN1Type = typeStore.VideotexString;
break;
case 22:
newASN1Type = typeStore.IA5String;
break;
case 23:
newASN1Type = typeStore.UTCTime;
break;
case 24:
newASN1Type = typeStore.GeneralizedTime;
break;
case 25:
newASN1Type = typeStore.GraphicString;
break;
case 26:
newASN1Type = typeStore.VisibleString;
break;
case 27:
newASN1Type = typeStore.GeneralString;
break;
case 28:
newASN1Type = typeStore.UniversalString;
break;
case 29:
newASN1Type = typeStore.CharacterString;
break;
case 30:
newASN1Type = typeStore.BmpString;
break;
case 31:
newASN1Type = typeStore.DATE;
break;
case 32:
newASN1Type = typeStore.TimeOfDay;
break;
case 33:
newASN1Type = typeStore.DateTime;
break;
case 34:
newASN1Type = typeStore.Duration;
break;
default: {
const newObject = returnObject.idBlock.isConstructed
? new typeStore.Constructed()
: new typeStore.Primitive();
newObject.idBlock = returnObject.idBlock;
newObject.lenBlock = returnObject.lenBlock;
newObject.warnings = returnObject.warnings;
returnObject = newObject;
}
}
break;
case 2:
case 3:
case 4:
default: {
newASN1Type = returnObject.idBlock.isConstructed
? typeStore.Constructed
: typeStore.Primitive;
}
}
returnObject = localChangeType(returnObject, newASN1Type);
resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length);
returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength);
return {
offset: resultOffset,
result: returnObject
};
}
function fromBER(inputBuffer) {
if (!inputBuffer.byteLength) {
const result = new BaseBlock({}, ValueBlock);
result.error = "Input buffer has zero length";
return {
offset: -1,
result
};
}
return localFromBER(pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength);
}
function checkLen(indefiniteLength, length) {
if (indefiniteLength) {
return 1;
}
return length;
}
class LocalConstructedValueBlock extends ValueBlock {
constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) {
super(parameters);
this.value = value;
this.isIndefiniteForm = isIndefiniteForm;
}
fromBER(inputBuffer, inputOffset, inputLength) {
const view = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, view, inputOffset, inputLength)) {
return -1;
}
this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength);
if (this.valueBeforeDecodeView.length === 0) {
this.warnings.push("Zero buffer length");
return inputOffset;
}
let currentOffset = inputOffset;
while (checkLen(this.isIndefiniteForm, inputLength) > 0) {
const returnObject = localFromBER(view, currentOffset, inputLength);
if (returnObject.offset === -1) {
this.error = returnObject.result.error;
this.warnings.concat(returnObject.result.warnings);
return -1;
}
currentOffset = returnObject.offset;
this.blockLength += returnObject.result.blockLength;
inputLength -= returnObject.result.blockLength;
this.value.push(returnObject.result);
if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) {
break;
}
}
if (this.isIndefiniteForm) {
if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) {
this.value.pop();
}
else {
this.warnings.push("No EndOfContent block encoded");
}
}
return currentOffset;
}
toBER(sizeOnly, writer) {
const _writer = writer || new ViewWriter();
for (let i = 0; i < this.value.length; i++) {
this.value[i].toBER(sizeOnly, _writer);
}
if (!writer) {
return _writer.final();
}
return EMPTY_BUFFER;
}
toJSON() {
const object = {
...super.toJSON(),
isIndefiniteForm: this.isIndefiniteForm,
value: [],
};
for (const value of this.value) {
object.value.push(value.toJSON());
}
return object;
}
}
LocalConstructedValueBlock.NAME = "ConstructedValueBlock";
var _a$v;
class Constructed extends BaseBlock {
constructor(parameters = {}) {
super(parameters, LocalConstructedValueBlock);
this.idBlock.isConstructed = true;
}
fromBER(inputBuffer, inputOffset, inputLength) {
this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;
const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);
if (resultOffset === -1) {
this.error = this.valueBlock.error;
return resultOffset;
}
if (!this.idBlock.error.length)
this.blockLength += this.idBlock.blockLength;
if (!this.lenBlock.error.length)
this.blockLength += this.lenBlock.blockLength;
if (!this.valueBlock.error.length)
this.blockLength += this.valueBlock.blockLength;
return resultOffset;
}
onAsciiEncoding() {
const values = [];
for (const value of this.valueBlock.value) {
values.push(value.toString("ascii").split("\n").map(o => ` ${o}`).join("\n"));
}
const blockName = this.idBlock.tagClass === 3
? `[${this.idBlock.tagNumber}]`
: this.constructor.NAME;
return values.length
? `${blockName} :\n${values.join("\n")}`
: `${blockName} :`;
}
}
_a$v = Constructed;
(() => {
typeStore.Constructed = _a$v;
})();
Constructed.NAME = "CONSTRUCTED";
class LocalEndOfContentValueBlock extends ValueBlock {
fromBER(inputBuffer, inputOffset, inputLength) {
return inputOffset;
}
toBER(sizeOnly) {
return EMPTY_BUFFER;
}
}
LocalEndOfContentValueBlock.override = "EndOfContentValueBlock";
var _a$u;
class EndOfContent extends BaseBlock {
constructor(parameters = {}) {
super(parameters, LocalEndOfContentValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 0;
}
}
_a$u = EndOfContent;
(() => {
typeStore.EndOfContent = _a$u;
})();
EndOfContent.NAME = END_OF_CONTENT_NAME;
var _a$t;
class Null extends BaseBlock {
constructor(parameters = {}) {
super(parameters, ValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 5;
}
fromBER(inputBuffer, inputOffset, inputLength) {
if (this.lenBlock.length > 0)
this.warnings.push("Non-zero length of value block for Null type");
if (!this.idBlock.error.length)
this.blockLength += this.idBlock.blockLength;
if (!this.lenBlock.error.length)
this.blockLength += this.lenBlock.blockLength;
this.blockLength += inputLength;
if ((inputOffset + inputLength) > inputBuffer.byteLength) {
this.error = "End of input reached before message was fully decoded (inconsistent offset and length values)";
return -1;
}
return (inputOffset + inputLength);
}
toBER(sizeOnly, writer) {
const retBuf = new ArrayBuffer(2);
if (!sizeOnly) {
const retView = new Uint8Array(retBuf);
retView[0] = 0x05;
retView[1] = 0x00;
}
if (writer) {
writer.write(retBuf);
}
return retBuf;
}
onAsciiEncoding() {
return `${this.constructor.NAME}`;
}
}
_a$t = Null;
(() => {
typeStore.Null = _a$t;
})();
Null.NAME = "NULL";
class LocalBooleanValueBlock extends HexBlock(ValueBlock) {
constructor({ value, ...parameters } = {}) {
super(parameters);
if (parameters.valueHex) {
this.valueHexView = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(parameters.valueHex);
}
else {
this.valueHexView = new Uint8Array(1);
}
if (value) {
this.value = value;
}
}
get value() {
for (const octet of this.valueHexView) {
if (octet > 0) {
return true;
}
}
return false;
}
set value(value) {
this.valueHexView[0] = value ? 0xFF : 0x00;
}
fromBER(inputBuffer, inputOffset, inputLength) {
const inputView = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
return -1;
}
this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength);
if (inputLength > 1)
this.warnings.push("Boolean value encoded in more then 1 octet");
this.isHexOnly = true;
pvutils__WEBPACK_IMPORTED_MODULE_1__.utilDecodeTC.call(this);
this.blockLength = inputLength;
return (inputOffset + inputLength);
}
toBER() {
return this.valueHexView.slice();
}
toJSON() {
return {
...super.toJSON(),
value: this.value,
};
}
}
LocalBooleanValueBlock.NAME = "BooleanValueBlock";
var _a$s;
class Boolean extends BaseBlock {
constructor(parameters = {}) {
super(parameters, LocalBooleanValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 1;
}
getValue() {
return this.valueBlock.value;
}
setValue(value) {
this.valueBlock.value = value;
}
onAsciiEncoding() {
return `${this.constructor.NAME} : ${this.getValue}`;
}
}
_a$s = Boolean;
(() => {
typeStore.Boolean = _a$s;
})();
Boolean.NAME = "BOOLEAN";
class LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) {
constructor({ isConstructed = false, ...parameters } = {}) {
super(parameters);
this.isConstructed = isConstructed;
}
fromBER(inputBuffer, inputOffset, inputLength) {
let resultOffset = 0;
if (this.isConstructed) {
this.isHexOnly = false;
resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);
if (resultOffset === -1)
return resultOffset;
for (let i = 0; i < this.value.length; i++) {
const currentBlockName = this.value[i].constructor.NAME;
if (currentBlockName === END_OF_CONTENT_NAME) {
if (this.isIndefiniteForm)
break;
else {
this.error = "EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only";
return -1;
}
}
if (currentBlockName !== OCTET_STRING_NAME) {
this.error = "OCTET STRING may consists of OCTET STRINGs only";
return -1;
}
}
}
else {
this.isHexOnly = true;
resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);
this.blockLength = inputLength;
}
return resultOffset;
}
toBER(sizeOnly, writer) {
if (this.isConstructed)
return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);
return sizeOnly
? new ArrayBuffer(this.valueHexView.byteLength)
: this.valueHexView.slice().buffer;
}
toJSON() {
return {
...super.toJSON(),
isConstructed: this.isConstructed,
};
}
}
LocalOctetStringValueBlock.NAME = "OctetStringValueBlock";
var _a$r;
class OctetString extends BaseBlock {
constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
var _b, _c;
(_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));
super({
idBlock: {
isConstructed: parameters.isConstructed,
...idBlock,
},
lenBlock: {
...lenBlock,
isIndefiniteForm: !!parameters.isIndefiniteForm,
},
...parameters,
}, LocalOctetStringValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 4;
}
fromBER(inputBuffer, inputOffset, inputLength) {
this.valueBlock.isConstructed = this.idBlock.isConstructed;
this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;
if (inputLength === 0) {
if (this.idBlock.error.length === 0)
this.blockLength += this.idBlock.blockLength;
if (this.lenBlock.error.length === 0)
this.blockLength += this.lenBlock.blockLength;
return inputOffset;
}
if (!this.valueBlock.isConstructed) {
const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;
const buf = view.subarray(inputOffset, inputOffset + inputLength);
try {
if (buf.byteLength) {
const asn = localFromBER(buf, 0, buf.byteLength);
if (asn.offset !== -1 && asn.offset === inputLength) {
this.valueBlock.value = [asn.result];
}
}
}
catch (e) {
}
}
return super.fromBER(inputBuffer, inputOffset, inputLength);
}
onAsciiEncoding() {
if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {
return Constructed.prototype.onAsciiEncoding.call(this);
}
return `${this.constructor.NAME} : ${pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.ToHex(this.valueBlock.valueHexView)}`;
}
getValue() {
if (!this.idBlock.isConstructed) {
return this.valueBlock.valueHexView.slice().buffer;
}
const array = [];
for (const content of this.valueBlock.value) {
if (content instanceof OctetString) {
array.push(content.valueBlock.valueHexView);
}
}
return pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.concat(array);
}
}
_a$r = OctetString;
(() => {
typeStore.OctetString = _a$r;
})();
OctetString.NAME = OCTET_STRING_NAME;
class LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) {
constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) {
super(parameters);
this.unusedBits = unusedBits;
this.isConstructed = isConstructed;
this.blockLength = this.valueHexView.byteLength;
}
fromBER(inputBuffer, inputOffset, inputLength) {
if (!inputLength) {
return inputOffset;
}
let resultOffset = -1;
if (this.isConstructed) {
resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);
if (resultOffset === -1)
return resultOffset;
for (const value of this.value) {
const currentBlockName = value.constructor.NAME;
if (currentBlockName === END_OF_CONTENT_NAME) {
if (this.isIndefiniteForm)
break;
else {
this.error = "EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only";
return -1;
}
}
if (currentBlockName !== BIT_STRING_NAME) {
this.error = "BIT STRING may consists of BIT STRINGs only";
return -1;
}
const valueBlock = value.valueBlock;
if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) {
this.error = "Using of \"unused bits\" inside constructive BIT STRING allowed for least one only";
return -1;
}
this.unusedBits = valueBlock.unusedBits;
}
return resultOffset;
}
const inputView = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
return -1;
}
const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
this.unusedBits = intBuffer[0];
if (this.unusedBits > 7) {
this.error = "Unused bits for BitString must be in range 0-7";
return -1;
}
if (!this.unusedBits) {
const buf = intBuffer.subarray(1);
try {
if (buf.byteLength) {
const asn = localFromBER(buf, 0, buf.byteLength);
if (asn.offset !== -1 && asn.offset === (inputLength - 1)) {
this.value = [asn.result];
}
}
}
catch (e) {
}
}
this.valueHexView = intBuffer.subarray(1);
this.blockLength = intBuffer.length;
return (inputOffset + inputLength);
}
toBER(sizeOnly, writer) {
if (this.isConstructed) {
return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);
}
if (sizeOnly) {
return new ArrayBuffer(this.valueHexView.byteLength + 1);
}
if (!this.valueHexView.byteLength) {
return EMPTY_BUFFER;
}
const retView = new Uint8Array(this.valueHexView.length + 1);
retView[0] = this.unusedBits;
retView.set(this.valueHexView, 1);
return retView.buffer;
}
toJSON() {
return {
...super.toJSON(),
unusedBits: this.unusedBits,
isConstructed: this.isConstructed,
};
}
}
LocalBitStringValueBlock.NAME = "BitStringValueBlock";
var _a$q;
class BitString extends BaseBlock {
constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
var _b, _c;
(_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));
super({
idBlock: {
isConstructed: parameters.isConstructed,
...idBlock,
},
lenBlock: {
...lenBlock,
isIndefiniteForm: !!parameters.isIndefiniteForm,
},
...parameters,
}, LocalBitStringValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 3;
}
fromBER(inputBuffer, inputOffset, inputLength) {
this.valueBlock.isConstructed = this.idBlock.isConstructed;
this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;
return super.fromBER(inputBuffer, inputOffset, inputLength);
}
onAsciiEncoding() {
if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {
return Constructed.prototype.onAsciiEncoding.call(this);
}
else {
const bits = [];
const valueHex = this.valueBlock.valueHexView;
for (const byte of valueHex) {
bits.push(byte.toString(2).padStart(8, "0"));
}
const bitsStr = bits.join("");
return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`;
}
}
}
_a$q = BitString;
(() => {
typeStore.BitString = _a$q;
})();
BitString.NAME = BIT_STRING_NAME;
var _a$p;
function viewAdd(first, second) {
const c = new Uint8Array([0]);
const firstView = new Uint8Array(first);
const secondView = new Uint8Array(second);
let firstViewCopy = firstView.slice(0);
const firstViewCopyLength = firstViewCopy.length - 1;
const secondViewCopy = secondView.slice(0);
const secondViewCopyLength = secondViewCopy.length - 1;
let value = 0;
const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength;
let counter = 0;
for (let i = max; i >= 0; i--, counter++) {
switch (true) {
case (counter < secondViewCopy.length):
value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0];
break;
default:
value = firstViewCopy[firstViewCopyLength - counter] + c[0];
}
c[0] = value / 10;
switch (true) {
case (counter >= firstViewCopy.length):
firstViewCopy = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilConcatView(new Uint8Array([value % 10]), firstViewCopy);
break;
default:
firstViewCopy[firstViewCopyLength - counter] = value % 10;
}
}
if (c[0] > 0)
firstViewCopy = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilConcatView(c, firstViewCopy);
return firstViewCopy;
}
function power2(n) {
if (n >= powers2.length) {
for (let p = powers2.length; p <= n; p++) {
const c = new Uint8Array([0]);
let digits = (powers2[p - 1]).slice(0);
for (let i = (digits.length - 1); i >= 0; i--) {
const newValue = new Uint8Array([(digits[i] << 1) + c[0]]);
c[0] = newValue[0] / 10;
digits[i] = newValue[0] % 10;
}
if (c[0] > 0)
digits = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilConcatView(c, digits);
powers2.push(digits);
}
}
return powers2[n];
}
function viewSub(first, second) {
let b = 0;
const firstView = new Uint8Array(first);
const secondView = new Uint8Array(second);
const firstViewCopy = firstView.slice(0);
const firstViewCopyLength = firstViewCopy.length - 1;
const secondViewCopy = secondView.slice(0);
const secondViewCopyLength = secondViewCopy.length - 1;
let value;
let counter = 0;
for (let i = secondViewCopyLength; i >= 0; i--, counter++) {
value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b;
switch (true) {
case (value < 0):
b = 1;
firstViewCopy[firstViewCopyLength - counter] = value + 10;
break;
default:
b = 0;
firstViewCopy[firstViewCopyLength - counter] = value;
}
}
if (b > 0) {
for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) {
value = firstViewCopy[firstViewCopyLength - counter] - b;
if (value < 0) {
b = 1;
firstViewCopy[firstViewCopyLength - counter] = value + 10;
}
else {
b = 0;
firstViewCopy[firstViewCopyLength - counter] = value;
break;
}
}
}
return firstViewCopy.slice();
}
class LocalIntegerValueBlock extends HexBlock(ValueBlock) {
constructor({ value, ...parameters } = {}) {
super(parameters);
this._valueDec = 0;
if (parameters.valueHex) {
this.setValueHex();
}
if (value !== undefined) {
this.valueDec = value;
}
}
setValueHex() {
if (this.valueHexView.length >= 4) {
this.warnings.push("Too big Integer for decoding, hex only");
this.isHexOnly = true;
this._valueDec = 0;
}
else {
this.isHexOnly = false;
if (this.valueHexView.length > 0) {
this._valueDec = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilDecodeTC.call(this);
}
}
}
set valueDec(v) {
this._valueDec = v;
this.isHexOnly = false;
this.valueHexView = new Uint8Array(pvutils__WEBPACK_IMPORTED_MODULE_1__.utilEncodeTC(v));
}
get valueDec() {
return this._valueDec;
}
fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) {
const offset = this.fromBER(inputBuffer, inputOffset, inputLength);
if (offset === -1)
return offset;
const view = this.valueHexView;
if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) {
this.valueHexView = view.subarray(1);
}
else {
if (expectedLength !== 0) {
if (view.length < expectedLength) {
if ((expectedLength - view.length) > 1)
expectedLength = view.length + 1;
this.valueHexView = view.subarray(expectedLength - view.length);
}
}
}
return offset;
}
toDER(sizeOnly = false) {
const view = this.valueHexView;
switch (true) {
case ((view[0] & 0x80) !== 0):
{
const updatedView = new Uint8Array(this.valueHexView.length + 1);
updatedView[0] = 0x00;
updatedView.set(view, 1);
this.valueHexView = updatedView;
}
break;
case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)):
{
this.valueHexView = this.valueHexView.subarray(1);
}
break;
}
return this.toBER(sizeOnly);
}
fromBER(inputBuffer, inputOffset, inputLength) {
const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);
if (resultOffset === -1) {
return resultOffset;
}
this.setValueHex();
return resultOffset;
}
toBER(sizeOnly) {
return sizeOnly
? new ArrayBuffer(this.valueHexView.length)
: this.valueHexView.slice().buffer;
}
toJSON() {
return {
...super.toJSON(),
valueDec: this.valueDec,
};
}
toString() {
const firstBit = (this.valueHexView.length * 8) - 1;
let digits = new Uint8Array((this.valueHexView.length * 8) / 3);
let bitNumber = 0;
let currentByte;
const asn1View = this.valueHexView;
let result = "";
let flag = false;
for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) {
currentByte = asn1View[byteNumber];
for (let i = 0; i < 8; i++) {
if ((currentByte & 1) === 1) {
switch (bitNumber) {
case firstBit:
digits = viewSub(power2(bitNumber), digits);
result = "-";
break;
default:
digits = viewAdd(digits, power2(bitNumber));
}
}
bitNumber++;
currentByte >>= 1;
}
}
for (let i = 0; i < digits.length; i++) {
if (digits[i])
flag = true;
if (flag)
result += digitsString.charAt(digits[i]);
}
if (flag === false)
result += digitsString.charAt(0);
return result;
}
}
_a$p = LocalIntegerValueBlock;
LocalIntegerValueBlock.NAME = "IntegerValueBlock";
(() => {
Object.defineProperty(_a$p.prototype, "valueHex", {
set: function (v) {
this.valueHexView = new Uint8Array(v);
this.setValueHex();
},
get: function () {
return this.valueHexView.slice().buffer;
},
});
})();
var _a$o;
class Integer extends BaseBlock {
constructor(parameters = {}) {
super(parameters, LocalIntegerValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 2;
}
toBigInt() {
assertBigInt();
return BigInt(this.valueBlock.toString());
}
static fromBigInt(value) {
assertBigInt();
const bigIntValue = BigInt(value);
const writer = new ViewWriter();
const hex = bigIntValue.toString(16).replace(/^-/, "");
const view = new Uint8Array(pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.FromHex(hex));
if (bigIntValue < 0) {
const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0));
first[0] |= 0x80;
const firstInt = BigInt(`0x${pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.ToHex(first)}`);
const secondInt = firstInt + bigIntValue;
const second = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.FromHex(secondInt.toString(16)));
second[0] |= 0x80;
writer.write(second);
}
else {
if (view[0] & 0x80) {
writer.write(new Uint8Array([0]));
}
writer.write(view);
}
const res = new Integer({
valueHex: writer.final(),
});
return res;
}
convertToDER() {
const integer = new Integer({ valueHex: this.valueBlock.valueHexView });
integer.valueBlock.toDER();
return integer;
}
convertFromDER() {
return new Integer({
valueHex: this.valueBlock.valueHexView[0] === 0
? this.valueBlock.valueHexView.subarray(1)
: this.valueBlock.valueHexView,
});
}
onAsciiEncoding() {
return `${this.constructor.NAME} : ${this.valueBlock.toString()}`;
}
}
_a$o = Integer;
(() => {
typeStore.Integer = _a$o;
})();
Integer.NAME = "INTEGER";
var _a$n;
class Enumerated extends Integer {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 10;
}
}
_a$n = Enumerated;
(() => {
typeStore.Enumerated = _a$n;
})();
Enumerated.NAME = "ENUMERATED";
class LocalSidValueBlock extends HexBlock(ValueBlock) {
constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) {
super(parameters);
this.valueDec = valueDec;
this.isFirstSid = isFirstSid;
}
fromBER(inputBuffer, inputOffset, inputLength) {
if (!inputLength) {
return inputOffset;
}
const inputView = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
return -1;
}
const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
this.valueHexView = new Uint8Array(inputLength);
for (let i = 0; i < inputLength; i++) {
this.valueHexView[i] = intBuffer[i] & 0x7F;
this.blockLength++;
if ((intBuffer[i] & 0x80) === 0x00)
break;
}
const tempView = new Uint8Array(this.blockLength);
for (let i = 0; i < this.blockLength; i++) {
tempView[i] = this.valueHexView[i];
}
this.valueHexView = tempView;
if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {
this.error = "End of input reached before message was fully decoded";
return -1;
}
if (this.valueHexView[0] === 0x00)
this.warnings.push("Needlessly long format of SID encoding");
if (this.blockLength <= 8)
this.valueDec = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilFromBase(this.valueHexView, 7);
else {
this.isHexOnly = true;
this.warnings.push("Too big SID for decoding, hex only");
}
return (inputOffset + this.blockLength);
}
set valueBigInt(value) {
assertBigInt();
let bits = BigInt(value).toString(2);
while (bits.length % 7) {
bits = "0" + bits;
}
const bytes = new Uint8Array(bits.length / 7);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0);
}
this.fromBER(bytes.buffer, 0, bytes.length);
}
toBER(sizeOnly) {
if (this.isHexOnly) {
if (sizeOnly)
return (new ArrayBuffer(this.valueHexView.byteLength));
const curView = this.valueHexView;
const retView = new Uint8Array(this.blockLength);
for (let i = 0; i < (this.blockLength - 1); i++)
retView[i] = curView[i] | 0x80;
retView[this.blockLength - 1] = curView[this.blockLength - 1];
return retView.buffer;
}
const encodedBuf = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilToBase(this.valueDec, 7);
if (encodedBuf.byteLength === 0) {
this.error = "Error during encoding SID value";
return EMPTY_BUFFER;
}
const retView = new Uint8Array(encodedBuf.byteLength);
if (!sizeOnly) {
const encodedView = new Uint8Array(encodedBuf);
const len = encodedBuf.byteLength - 1;
for (let i = 0; i < len; i++)
retView[i] = encodedView[i] | 0x80;
retView[len] = encodedView[len];
}
return retView;
}
toString() {
let result = "";
if (this.isHexOnly)
result = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.ToHex(this.valueHexView);
else {
if (this.isFirstSid) {
let sidValue = this.valueDec;
if (this.valueDec <= 39)
result = "0.";
else {
if (this.valueDec <= 79) {
result = "1.";
sidValue -= 40;
}
else {
result = "2.";
sidValue -= 80;
}
}
result += sidValue.toString();
}
else
result = this.valueDec.toString();
}
return result;
}
toJSON() {
return {
...super.toJSON(),
valueDec: this.valueDec,
isFirstSid: this.isFirstSid,
};
}
}
LocalSidValueBlock.NAME = "sidBlock";
class LocalObjectIdentifierValueBlock extends ValueBlock {
constructor({ value = EMPTY_STRING, ...parameters } = {}) {
super(parameters);
this.value = [];
if (value) {
this.fromString(value);
}
}
fromBER(inputBuffer, inputOffset, inputLength) {
let resultOffset = inputOffset;
while (inputLength > 0) {
const sidBlock = new LocalSidValueBlock();
resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);
if (resultOffset === -1) {
this.blockLength = 0;
this.error = sidBlock.error;
return resultOffset;
}
if (this.value.length === 0)
sidBlock.isFirstSid = true;
this.blockLength += sidBlock.blockLength;
inputLength -= sidBlock.blockLength;
this.value.push(sidBlock);
}
return resultOffset;
}
toBER(sizeOnly) {
const retBuffers = [];
for (let i = 0; i < this.value.length; i++) {
const valueBuf = this.value[i].toBER(sizeOnly);
if (valueBuf.byteLength === 0) {
this.error = this.value[i].error;
return EMPTY_BUFFER;
}
retBuffers.push(valueBuf);
}
return concat(retBuffers);
}
fromString(string) {
this.value = [];
let pos1 = 0;
let pos2 = 0;
let sid = "";
let flag = false;
do {
pos2 = string.indexOf(".", pos1);
if (pos2 === -1)
sid = string.substring(pos1);
else
sid = string.substring(pos1, pos2);
pos1 = pos2 + 1;
if (flag) {
const sidBlock = this.value[0];
let plus = 0;
switch (sidBlock.valueDec) {
case 0:
break;
case 1:
plus = 40;
break;
case 2:
plus = 80;
break;
default:
this.value = [];
return;
}
const parsedSID = parseInt(sid, 10);
if (isNaN(parsedSID))
return;
sidBlock.valueDec = parsedSID + plus;
flag = false;
}
else {
const sidBlock = new LocalSidValueBlock();
if (sid > Number.MAX_SAFE_INTEGER) {
assertBigInt();
const sidValue = BigInt(sid);
sidBlock.valueBigInt = sidValue;
}
else {
sidBlock.valueDec = parseInt(sid, 10);
if (isNaN(sidBlock.valueDec))
return;
}
if (!this.value.length) {
sidBlock.isFirstSid = true;
flag = true;
}
this.value.push(sidBlock);
}
} while (pos2 !== -1);
}
toString() {
let result = "";
let isHexOnly = false;
for (let i = 0; i < this.value.length; i++) {
isHexOnly = this.value[i].isHexOnly;
let sidStr = this.value[i].toString();
if (i !== 0)
result = `${result}.`;
if (isHexOnly) {
sidStr = `{${sidStr}}`;
if (this.value[i].isFirstSid)
result = `2.{${sidStr} - 80}`;
else
result += sidStr;
}
else
result += sidStr;
}
return result;
}
toJSON() {
const object = {
...super.toJSON(),
value: this.toString(),
sidArray: [],
};
for (let i = 0; i < this.value.length; i++) {
object.sidArray.push(this.value[i].toJSON());
}
return object;
}
}
LocalObjectIdentifierValueBlock.NAME = "ObjectIdentifierValueBlock";
var _a$m;
class ObjectIdentifier extends BaseBlock {
constructor(parameters = {}) {
super(parameters, LocalObjectIdentifierValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 6;
}
getValue() {
return this.valueBlock.toString();
}
setValue(value) {
this.valueBlock.fromString(value);
}
onAsciiEncoding() {
return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
}
toJSON() {
return {
...super.toJSON(),
value: this.getValue(),
};
}
}
_a$m = ObjectIdentifier;
(() => {
typeStore.ObjectIdentifier = _a$m;
})();
ObjectIdentifier.NAME = "OBJECT IDENTIFIER";
class LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) {
constructor({ valueDec = 0, ...parameters } = {}) {
super(parameters);
this.valueDec = valueDec;
}
fromBER(inputBuffer, inputOffset, inputLength) {
if (inputLength === 0)
return inputOffset;
const inputView = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, inputView, inputOffset, inputLength))
return -1;
const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
this.valueHexView = new Uint8Array(inputLength);
for (let i = 0; i < inputLength; i++) {
this.valueHexView[i] = intBuffer[i] & 0x7F;
this.blockLength++;
if ((intBuffer[i] & 0x80) === 0x00)
break;
}
const tempView = new Uint8Array(this.blockLength);
for (let i = 0; i < this.blockLength; i++)
tempView[i] = this.valueHexView[i];
this.valueHexView = tempView;
if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {
this.error = "End of input reached before message was fully decoded";
return -1;
}
if (this.valueHexView[0] === 0x00)
this.warnings.push("Needlessly long format of SID encoding");
if (this.blockLength <= 8)
this.valueDec = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilFromBase(this.valueHexView, 7);
else {
this.isHexOnly = true;
this.warnings.push("Too big SID for decoding, hex only");
}
return (inputOffset + this.blockLength);
}
toBER(sizeOnly) {
if (this.isHexOnly) {
if (sizeOnly)
return (new ArrayBuffer(this.valueHexView.byteLength));
const curView = this.valueHexView;
const retView = new Uint8Array(this.blockLength);
for (let i = 0; i < (this.blockLength - 1); i++)
retView[i] = curView[i] | 0x80;
retView[this.blockLength - 1] = curView[this.blockLength - 1];
return retView.buffer;
}
const encodedBuf = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilToBase(this.valueDec, 7);
if (encodedBuf.byteLength === 0) {
this.error = "Error during encoding SID value";
return EMPTY_BUFFER;
}
const retView = new Uint8Array(encodedBuf.byteLength);
if (!sizeOnly) {
const encodedView = new Uint8Array(encodedBuf);
const len = encodedBuf.byteLength - 1;
for (let i = 0; i < len; i++)
retView[i] = encodedView[i] | 0x80;
retView[len] = encodedView[len];
}
return retView.buffer;
}
toString() {
let result = "";
if (this.isHexOnly)
result = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.ToHex(this.valueHexView);
else {
result = this.valueDec.toString();
}
return result;
}
toJSON() {
return {
...super.toJSON(),
valueDec: this.valueDec,
};
}
}
LocalRelativeSidValueBlock.NAME = "relativeSidBlock";
class LocalRelativeObjectIdentifierValueBlock extends ValueBlock {
constructor({ value = EMPTY_STRING, ...parameters } = {}) {
super(parameters);
this.value = [];
if (value) {
this.fromString(value);
}
}
fromBER(inputBuffer, inputOffset, inputLength) {
let resultOffset = inputOffset;
while (inputLength > 0) {
const sidBlock = new LocalRelativeSidValueBlock();
resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);
if (resultOffset === -1) {
this.blockLength = 0;
this.error = sidBlock.error;
return resultOffset;
}
this.blockLength += sidBlock.blockLength;
inputLength -= sidBlock.blockLength;
this.value.push(sidBlock);
}
return resultOffset;
}
toBER(sizeOnly, writer) {
const retBuffers = [];
for (let i = 0; i < this.value.length; i++) {
const valueBuf = this.value[i].toBER(sizeOnly);
if (valueBuf.byteLength === 0) {
this.error = this.value[i].error;
return EMPTY_BUFFER;
}
retBuffers.push(valueBuf);
}
return concat(retBuffers);
}
fromString(string) {
this.value = [];
let pos1 = 0;
let pos2 = 0;
let sid = "";
do {
pos2 = string.indexOf(".", pos1);
if (pos2 === -1)
sid = string.substring(pos1);
else
sid = string.substring(pos1, pos2);
pos1 = pos2 + 1;
const sidBlock = new LocalRelativeSidValueBlock();
sidBlock.valueDec = parseInt(sid, 10);
if (isNaN(sidBlock.valueDec))
return true;
this.value.push(sidBlock);
} while (pos2 !== -1);
return true;
}
toString() {
let result = "";
let isHexOnly = false;
for (let i = 0; i < this.value.length; i++) {
isHexOnly = this.value[i].isHexOnly;
let sidStr = this.value[i].toString();
if (i !== 0)
result = `${result}.`;
if (isHexOnly) {
sidStr = `{${sidStr}}`;
result += sidStr;
}
else
result += sidStr;
}
return result;
}
toJSON() {
const object = {
...super.toJSON(),
value: this.toString(),
sidArray: [],
};
for (let i = 0; i < this.value.length; i++)
object.sidArray.push(this.value[i].toJSON());
return object;
}
}
LocalRelativeObjectIdentifierValueBlock.NAME = "RelativeObjectIdentifierValueBlock";
var _a$l;
class RelativeObjectIdentifier extends BaseBlock {
constructor(parameters = {}) {
super(parameters, LocalRelativeObjectIdentifierValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 13;
}
getValue() {
return this.valueBlock.toString();
}
setValue(value) {
this.valueBlock.fromString(value);
}
onAsciiEncoding() {
return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
}
toJSON() {
return {
...super.toJSON(),
value: this.getValue(),
};
}
}
_a$l = RelativeObjectIdentifier;
(() => {
typeStore.RelativeObjectIdentifier = _a$l;
})();
RelativeObjectIdentifier.NAME = "RelativeObjectIdentifier";
var _a$k;
class Sequence extends Constructed {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 16;
}
}
_a$k = Sequence;
(() => {
typeStore.Sequence = _a$k;
})();
Sequence.NAME = "SEQUENCE";
var _a$j;
class Set extends Constructed {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 17;
}
}
_a$j = Set;
(() => {
typeStore.Set = _a$j;
})();
Set.NAME = "SET";
class LocalStringValueBlock extends HexBlock(ValueBlock) {
constructor({ ...parameters } = {}) {
super(parameters);
this.isHexOnly = true;
this.value = EMPTY_STRING;
}
toJSON() {
return {
...super.toJSON(),
value: this.value,
};
}
}
LocalStringValueBlock.NAME = "StringValueBlock";
class LocalSimpleStringValueBlock extends LocalStringValueBlock {
}
LocalSimpleStringValueBlock.NAME = "SimpleStringValueBlock";
class LocalSimpleStringBlock extends BaseStringBlock {
constructor({ ...parameters } = {}) {
super(parameters, LocalSimpleStringValueBlock);
}
fromBuffer(inputBuffer) {
this.valueBlock.value = String.fromCharCode.apply(null, pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer));
}
fromString(inputString) {
const strLen = inputString.length;
const view = this.valueBlock.valueHexView = new Uint8Array(strLen);
for (let i = 0; i < strLen; i++)
view[i] = inputString.charCodeAt(i);
this.valueBlock.value = inputString;
}
}
LocalSimpleStringBlock.NAME = "SIMPLE STRING";
class LocalUtf8StringValueBlock extends LocalSimpleStringBlock {
fromBuffer(inputBuffer) {
this.valueBlock.valueHexView = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer);
try {
this.valueBlock.value = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.ToUtf8String(inputBuffer);
}
catch (ex) {
this.warnings.push(`Error during "decodeURIComponent": ${ex}, using raw string`);
this.valueBlock.value = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.ToBinary(inputBuffer);
}
}
fromString(inputString) {
this.valueBlock.valueHexView = new Uint8Array(pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.FromUtf8String(inputString));
this.valueBlock.value = inputString;
}
}
LocalUtf8StringValueBlock.NAME = "Utf8StringValueBlock";
var _a$i;
class Utf8String extends LocalUtf8StringValueBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 12;
}
}
_a$i = Utf8String;
(() => {
typeStore.Utf8String = _a$i;
})();
Utf8String.NAME = "UTF8String";
class LocalBmpStringValueBlock extends LocalSimpleStringBlock {
fromBuffer(inputBuffer) {
this.valueBlock.value = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.ToUtf16String(inputBuffer);
this.valueBlock.valueHexView = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer);
}
fromString(inputString) {
this.valueBlock.value = inputString;
this.valueBlock.valueHexView = new Uint8Array(pvtsutils__WEBPACK_IMPORTED_MODULE_0__.Convert.FromUtf16String(inputString));
}
}
LocalBmpStringValueBlock.NAME = "BmpStringValueBlock";
var _a$h;
class BmpString extends LocalBmpStringValueBlock {
constructor({ ...parameters } = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 30;
}
}
_a$h = BmpString;
(() => {
typeStore.BmpString = _a$h;
})();
BmpString.NAME = "BMPString";
class LocalUniversalStringValueBlock extends LocalSimpleStringBlock {
fromBuffer(inputBuffer) {
const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0);
const valueView = new Uint8Array(copyBuffer);
for (let i = 0; i < valueView.length; i += 4) {
valueView[i] = valueView[i + 3];
valueView[i + 1] = valueView[i + 2];
valueView[i + 2] = 0x00;
valueView[i + 3] = 0x00;
}
this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer));
}
fromString(inputString) {
const strLength = inputString.length;
const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4);
for (let i = 0; i < strLength; i++) {
const codeBuf = pvutils__WEBPACK_IMPORTED_MODULE_1__.utilToBase(inputString.charCodeAt(i), 8);
const codeView = new Uint8Array(codeBuf);
if (codeView.length > 4)
continue;
const dif = 4 - codeView.length;
for (let j = (codeView.length - 1); j >= 0; j--)
valueHexView[i * 4 + j + dif] = codeView[j];
}
this.valueBlock.value = inputString;
}
}
LocalUniversalStringValueBlock.NAME = "UniversalStringValueBlock";
var _a$g;
class UniversalString extends LocalUniversalStringValueBlock {
constructor({ ...parameters } = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 28;
}
}
_a$g = UniversalString;
(() => {
typeStore.UniversalString = _a$g;
})();
UniversalString.NAME = "UniversalString";
var _a$f;
class NumericString extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 18;
}
}
_a$f = NumericString;
(() => {
typeStore.NumericString = _a$f;
})();
NumericString.NAME = "NumericString";
var _a$e;
class PrintableString extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 19;
}
}
_a$e = PrintableString;
(() => {
typeStore.PrintableString = _a$e;
})();
PrintableString.NAME = "PrintableString";
var _a$d;
class TeletexString extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 20;
}
}
_a$d = TeletexString;
(() => {
typeStore.TeletexString = _a$d;
})();
TeletexString.NAME = "TeletexString";
var _a$c;
class VideotexString extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 21;
}
}
_a$c = VideotexString;
(() => {
typeStore.VideotexString = _a$c;
})();
VideotexString.NAME = "VideotexString";
var _a$b;
class IA5String extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 22;
}
}
_a$b = IA5String;
(() => {
typeStore.IA5String = _a$b;
})();
IA5String.NAME = "IA5String";
var _a$a;
class GraphicString extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 25;
}
}
_a$a = GraphicString;
(() => {
typeStore.GraphicString = _a$a;
})();
GraphicString.NAME = "GraphicString";
var _a$9;
class VisibleString extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 26;
}
}
_a$9 = VisibleString;
(() => {
typeStore.VisibleString = _a$9;
})();
VisibleString.NAME = "VisibleString";
var _a$8;
class GeneralString extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 27;
}
}
_a$8 = GeneralString;
(() => {
typeStore.GeneralString = _a$8;
})();
GeneralString.NAME = "GeneralString";
var _a$7;
class CharacterString extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 29;
}
}
_a$7 = CharacterString;
(() => {
typeStore.CharacterString = _a$7;
})();
CharacterString.NAME = "CharacterString";
var _a$6;
class UTCTime extends VisibleString {
constructor({ value, valueDate, ...parameters } = {}) {
super(parameters);
this.year = 0;
this.month = 0;
this.day = 0;
this.hour = 0;
this.minute = 0;
this.second = 0;
if (value) {
this.fromString(value);
this.valueBlock.valueHexView = new Uint8Array(value.length);
for (let i = 0; i < value.length; i++)
this.valueBlock.valueHexView[i] = value.charCodeAt(i);
}
if (valueDate) {
this.fromDate(valueDate);
this.valueBlock.valueHexView = new Uint8Array(this.toBuffer());
}
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 23;
}
fromBuffer(inputBuffer) {
this.fromString(String.fromCharCode.apply(null, pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer)));
}
toBuffer() {
const str = this.toString();
const buffer = new ArrayBuffer(str.length);
const view = new Uint8Array(buffer);
for (let i = 0; i < str.length; i++)
view[i] = str.charCodeAt(i);
return buffer;
}
fromDate(inputDate) {
this.year = inputDate.getUTCFullYear();
this.month = inputDate.getUTCMonth() + 1;
this.day = inputDate.getUTCDate();
this.hour = inputDate.getUTCHours();
this.minute = inputDate.getUTCMinutes();
this.second = inputDate.getUTCSeconds();
}
toDate() {
return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second)));
}
fromString(inputString) {
const parser = /(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig;
const parserArray = parser.exec(inputString);
if (parserArray === null) {
this.error = "Wrong input string for conversion";
return;
}
const year = parseInt(parserArray[1], 10);
if (year >= 50)
this.year = 1900 + year;
else
this.year = 2000 + year;
this.month = parseInt(parserArray[2], 10);
this.day = parseInt(parserArray[3], 10);
this.hour = parseInt(parserArray[4], 10);
this.minute = parseInt(parserArray[5], 10);
this.second = parseInt(parserArray[6], 10);
}
toString(encoding = "iso") {
if (encoding === "iso") {
const outputArray = new Array(7);
outputArray[0] = pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2);
outputArray[1] = pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(this.month, 2);
outputArray[2] = pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(this.day, 2);
outputArray[3] = pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(this.hour, 2);
outputArray[4] = pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(this.minute, 2);
outputArray[5] = pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(this.second, 2);
outputArray[6] = "Z";
return outputArray.join("");
}
return super.toString(encoding);
}
onAsciiEncoding() {
return `${this.constructor.NAME} : ${this.toDate().toISOString()}`;
}
toJSON() {
return {
...super.toJSON(),
year: this.year,
month: this.month,
day: this.day,
hour: this.hour,
minute: this.minute,
second: this.second,
};
}
}
_a$6 = UTCTime;
(() => {
typeStore.UTCTime = _a$6;
})();
UTCTime.NAME = "UTCTime";
var _a$5;
class GeneralizedTime extends UTCTime {
constructor(parameters = {}) {
var _b;
super(parameters);
(_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 24;
}
fromDate(inputDate) {
super.fromDate(inputDate);
this.millisecond = inputDate.getUTCMilliseconds();
}
toDate() {
return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond)));
}
fromString(inputString) {
let isUTC = false;
let timeString = "";
let dateTimeString = "";
let fractionPart = 0;
let parser;
let hourDifference = 0;
let minuteDifference = 0;
if (inputString[inputString.length - 1] === "Z") {
timeString = inputString.substring(0, inputString.length - 1);
isUTC = true;
}
else {
const number = new Number(inputString[inputString.length - 1]);
if (isNaN(number.valueOf()))
throw new Error("Wrong input string for conversion");
timeString = inputString;
}
if (isUTC) {
if (timeString.indexOf("+") !== -1)
throw new Error("Wrong input string for conversion");
if (timeString.indexOf("-") !== -1)
throw new Error("Wrong input string for conversion");
}
else {
let multiplier = 1;
let differencePosition = timeString.indexOf("+");
let differenceString = "";
if (differencePosition === -1) {
differencePosition = timeString.indexOf("-");
multiplier = -1;
}
if (differencePosition !== -1) {
differenceString = timeString.substring(differencePosition + 1);
timeString = timeString.substring(0, differencePosition);
if ((differenceString.length !== 2) && (differenceString.length !== 4))
throw new Error("Wrong input string for conversion");
let number = parseInt(differenceString.substring(0, 2), 10);
if (isNaN(number.valueOf()))
throw new Error("Wrong input string for conversion");
hourDifference = multiplier * number;
if (differenceString.length === 4) {
number = parseInt(differenceString.substring(2, 4), 10);
if (isNaN(number.valueOf()))
throw new Error("Wrong input string for conversion");
minuteDifference = multiplier * number;
}
}
}
let fractionPointPosition = timeString.indexOf(".");
if (fractionPointPosition === -1)
fractionPointPosition = timeString.indexOf(",");
if (fractionPointPosition !== -1) {
const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`);
if (isNaN(fractionPartCheck.valueOf()))
throw new Error("Wrong input string for conversion");
fractionPart = fractionPartCheck.valueOf();
dateTimeString = timeString.substring(0, fractionPointPosition);
}
else
dateTimeString = timeString;
switch (true) {
case (dateTimeString.length === 8):
parser = /(\d{4})(\d{2})(\d{2})/ig;
if (fractionPointPosition !== -1)
throw new Error("Wrong input string for conversion");
break;
case (dateTimeString.length === 10):
parser = /(\d{4})(\d{2})(\d{2})(\d{2})/ig;
if (fractionPointPosition !== -1) {
let fractionResult = 60 * fractionPart;
this.minute = Math.floor(fractionResult);
fractionResult = 60 * (fractionResult - this.minute);
this.second = Math.floor(fractionResult);
fractionResult = 1000 * (fractionResult - this.second);
this.millisecond = Math.floor(fractionResult);
}
break;
case (dateTimeString.length === 12):
parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig;
if (fractionPointPosition !== -1) {
let fractionResult = 60 * fractionPart;
this.second = Math.floor(fractionResult);
fractionResult = 1000 * (fractionResult - this.second);
this.millisecond = Math.floor(fractionResult);
}
break;
case (dateTimeString.length === 14):
parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig;
if (fractionPointPosition !== -1) {
const fractionResult = 1000 * fractionPart;
this.millisecond = Math.floor(fractionResult);
}
break;
default:
throw new Error("Wrong input string for conversion");
}
const parserArray = parser.exec(dateTimeString);
if (parserArray === null)
throw new Error("Wrong input string for conversion");
for (let j = 1; j < parserArray.length; j++) {
switch (j) {
case 1:
this.year = parseInt(parserArray[j], 10);
break;
case 2:
this.month = parseInt(parserArray[j], 10);
break;
case 3:
this.day = parseInt(parserArray[j], 10);
break;
case 4:
this.hour = parseInt(parserArray[j], 10) + hourDifference;
break;
case 5:
this.minute = parseInt(parserArray[j], 10) + minuteDifference;
break;
case 6:
this.second = parseInt(parserArray[j], 10);
break;
default:
throw new Error("Wrong input string for conversion");
}
}
if (isUTC === false) {
const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);
this.year = tempDate.getUTCFullYear();
this.month = tempDate.getUTCMonth();
this.day = tempDate.getUTCDay();
this.hour = tempDate.getUTCHours();
this.minute = tempDate.getUTCMinutes();
this.second = tempDate.getUTCSeconds();
this.millisecond = tempDate.getUTCMilliseconds();
}
}
toString(encoding = "iso") {
if (encoding === "iso") {
const outputArray = [];
outputArray.push(pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(this.year, 4));
outputArray.push(pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(this.month, 2));
outputArray.push(pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(this.day, 2));
outputArray.push(pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(this.hour, 2));
outputArray.push(pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(this.minute, 2));
outputArray.push(pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(this.second, 2));
if (this.millisecond !== 0) {
outputArray.push(".");
outputArray.push(pvutils__WEBPACK_IMPORTED_MODULE_1__.padNumber(this.millisecond, 3));
}
outputArray.push("Z");
return outputArray.join("");
}
return super.toString(encoding);
}
toJSON() {
return {
...super.toJSON(),
millisecond: this.millisecond,
};
}
}
_a$5 = GeneralizedTime;
(() => {
typeStore.GeneralizedTime = _a$5;
})();
GeneralizedTime.NAME = "GeneralizedTime";
var _a$4;
class DATE extends Utf8String {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 31;
}
}
_a$4 = DATE;
(() => {
typeStore.DATE = _a$4;
})();
DATE.NAME = "DATE";
var _a$3;
class TimeOfDay extends Utf8String {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 32;
}
}
_a$3 = TimeOfDay;
(() => {
typeStore.TimeOfDay = _a$3;
})();
TimeOfDay.NAME = "TimeOfDay";
var _a$2;
class DateTime extends Utf8String {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 33;
}
}
_a$2 = DateTime;
(() => {
typeStore.DateTime = _a$2;
})();
DateTime.NAME = "DateTime";
var _a$1;
class Duration extends Utf8String {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 34;
}
}
_a$1 = Duration;
(() => {
typeStore.Duration = _a$1;
})();
Duration.NAME = "Duration";
var _a;
class TIME extends Utf8String {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 14;
}
}
_a = TIME;
(() => {
typeStore.TIME = _a;
})();
TIME.NAME = "TIME";
class Any {
constructor({ name = EMPTY_STRING, optional = false, } = {}) {
this.name = name;
this.optional = optional;
}
}
class Choice extends Any {
constructor({ value = [], ...parameters } = {}) {
super(parameters);
this.value = value;
}
}
class Repeated extends Any {
constructor({ value = new Any(), local = false, ...parameters } = {}) {
super(parameters);
this.value = value;
this.local = local;
}
}
class RawData {
constructor({ data = EMPTY_VIEW } = {}) {
this.dataView = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(data);
}
get data() {
return this.dataView.slice().buffer;
}
set data(value) {
this.dataView = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(value);
}
fromBER(inputBuffer, inputOffset, inputLength) {
const endLength = inputOffset + inputLength;
this.dataView = pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength);
return endLength;
}
toBER(sizeOnly) {
return this.dataView.slice().buffer;
}
}
function compareSchema(root, inputData, inputSchema) {
if (inputSchema instanceof Choice) {
for (let j = 0; j < inputSchema.value.length; j++) {
const result = compareSchema(root, inputData, inputSchema.value[j]);
if (result.verified) {
return {
verified: true,
result: root
};
}
}
{
const _result = {
verified: false,
result: {
error: "Wrong values for Choice type"
},
};
if (inputSchema.hasOwnProperty(NAME))
_result.name = inputSchema.name;
return _result;
}
}
if (inputSchema instanceof Any) {
if (inputSchema.hasOwnProperty(NAME))
root[inputSchema.name] = inputData;
return {
verified: true,
result: root
};
}
if ((root instanceof Object) === false) {
return {
verified: false,
result: { error: "Wrong root object" }
};
}
if ((inputData instanceof Object) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 data" }
};
}
if ((inputSchema instanceof Object) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if ((ID_BLOCK in inputSchema) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if ((FROM_BER in inputSchema.idBlock) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if ((TO_BER in inputSchema.idBlock) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
const encodedId = inputSchema.idBlock.toBER(false);
if (encodedId.byteLength === 0) {
return {
verified: false,
result: { error: "Error encoding idBlock for ASN.1 schema" }
};
}
const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength);
if (decodedOffset === -1) {
return {
verified: false,
result: { error: "Error decoding idBlock for ASN.1 schema" }
};
}
if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) {
return {
verified: false,
result: root
};
}
if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) {
return {
verified: false,
result: root
};
}
if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) {
return {
verified: false,
result: root
};
}
if (!(IS_HEX_ONLY in inputSchema.idBlock)) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) {
return {
verified: false,
result: root
};
}
if (inputSchema.idBlock.isHexOnly) {
if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
const schemaView = inputSchema.idBlock.valueHexView;
const asn1View = inputData.idBlock.valueHexView;
if (schemaView.length !== asn1View.length) {
return {
verified: false,
result: root
};
}
for (let i = 0; i < schemaView.length; i++) {
if (schemaView[i] !== asn1View[1]) {
return {
verified: false,
result: root
};
}
}
}
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name)
root[inputSchema.name] = inputData;
}
if (inputSchema instanceof typeStore.Constructed) {
let admission = 0;
let result = {
verified: false,
result: {
error: "Unknown error",
}
};
let maxLength = inputSchema.valueBlock.value.length;
if (maxLength > 0) {
if (inputSchema.valueBlock.value[0] instanceof Repeated) {
maxLength = inputData.valueBlock.value.length;
}
}
if (maxLength === 0) {
return {
verified: true,
result: root
};
}
if ((inputData.valueBlock.value.length === 0) &&
(inputSchema.valueBlock.value.length !== 0)) {
let _optional = true;
for (let i = 0; i < inputSchema.valueBlock.value.length; i++)
_optional = _optional && (inputSchema.valueBlock.value[i].optional || false);
if (_optional) {
return {
verified: true,
result: root
};
}
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name)
delete root[inputSchema.name];
}
root.error = "Inconsistent object length";
return {
verified: false,
result: root
};
}
for (let i = 0; i < maxLength; i++) {
if ((i - admission) >= inputData.valueBlock.value.length) {
if (inputSchema.valueBlock.value[i].optional === false) {
const _result = {
verified: false,
result: root
};
root.error = "Inconsistent length between ASN.1 data and schema";
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name) {
delete root[inputSchema.name];
_result.name = inputSchema.name;
}
}
return _result;
}
}
else {
if (inputSchema.valueBlock.value[0] instanceof Repeated) {
result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value);
if (result.verified === false) {
if (inputSchema.valueBlock.value[0].optional)
admission++;
else {
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name)
delete root[inputSchema.name];
}
return result;
}
}
if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) {
let arrayRoot = {};
if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local))
arrayRoot = inputData;
else
arrayRoot = root;
if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === "undefined")
arrayRoot[inputSchema.valueBlock.value[0].name] = [];
arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]);
}
}
else {
result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]);
if (result.verified === false) {
if (inputSchema.valueBlock.value[i].optional)
admission++;
else {
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name)
delete root[inputSchema.name];
}
return result;
}
}
}
}
}
if (result.verified === false) {
const _result = {
verified: false,
result: root
};
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name) {
delete root[inputSchema.name];
_result.name = inputSchema.name;
}
}
return _result;
}
return {
verified: true,
result: root
};
}
if (inputSchema.primitiveSchema &&
(VALUE_HEX_VIEW in inputData.valueBlock)) {
const asn1 = localFromBER(inputData.valueBlock.valueHexView);
if (asn1.offset === -1) {
const _result = {
verified: false,
result: asn1.result
};
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name) {
delete root[inputSchema.name];
_result.name = inputSchema.name;
}
}
return _result;
}
return compareSchema(root, asn1.result, inputSchema.primitiveSchema);
}
return {
verified: true,
result: root
};
}
function verifySchema(inputBuffer, inputSchema) {
if ((inputSchema instanceof Object) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema type" }
};
}
const asn1 = localFromBER(pvtsutils__WEBPACK_IMPORTED_MODULE_0__.BufferSourceConverter.toUint8Array(inputBuffer));
if (asn1.offset === -1) {
return {
verified: false,
result: asn1.result
};
}
return compareSchema(asn1.result, asn1.result, inputSchema);
}
/***/ }),
/***/ "./node_modules/base64-js/index.js":
/*!*****************************************!*\
!*** ./node_modules/base64-js/index.js ***!
\*****************************************/
/***/ ((__unused_webpack_module, exports) => {
"use strict";
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
/***/ }),
/***/ "./node_modules/browser-level/index.js":
/*!*********************************************!*\
!*** ./node_modules/browser-level/index.js ***!
\*********************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/* global indexedDB */
const { AbstractLevel } = __webpack_require__(/*! abstract-level */ "./node_modules/abstract-level/index.js")
const ModuleError = __webpack_require__(/*! module-error */ "./node_modules/module-error/index.js")
const parallel = __webpack_require__(/*! run-parallel-limit */ "./node_modules/run-parallel-limit/index.js")
const { fromCallback } = __webpack_require__(/*! catering */ "./node_modules/catering/index.js")
const { Iterator } = __webpack_require__(/*! ./iterator */ "./node_modules/browser-level/iterator.js")
const deserialize = __webpack_require__(/*! ./util/deserialize */ "./node_modules/browser-level/util/deserialize.js")
const clear = __webpack_require__(/*! ./util/clear */ "./node_modules/browser-level/util/clear.js")
const createKeyRange = __webpack_require__(/*! ./util/key-range */ "./node_modules/browser-level/util/key-range.js")
// Keep as-is for compatibility with existing level-js databases
const DEFAULT_PREFIX = 'level-js-'
const kIDB = Symbol('idb')
const kNamePrefix = Symbol('namePrefix')
const kLocation = Symbol('location')
const kVersion = Symbol('version')
const kStore = Symbol('store')
const kOnComplete = Symbol('onComplete')
const kPromise = Symbol('promise')
class BrowserLevel extends AbstractLevel {
constructor (location, options, _) {
// To help migrating to abstract-level
if (typeof options === 'function' || typeof _ === 'function') {
throw new ModuleError('The levelup-style callback argument has been removed', {
code: 'LEVEL_LEGACY'
})
}
const { prefix, version, ...forward } = options || {}
super({
encodings: { view: true },
snapshots: false,
createIfMissing: false,
errorIfExists: false,
seek: true
}, forward)
if (typeof location !== 'string') {
throw new Error('constructor requires a location string argument')
}
// TODO (next major): remove default prefix
this[kLocation] = location
this[kNamePrefix] = prefix == null ? DEFAULT_PREFIX : prefix
this[kVersion] = parseInt(version || 1, 10)
this[kIDB] = null
}
get location () {
return this[kLocation]
}
get namePrefix () {
return this[kNamePrefix]
}
get version () {
return this[kVersion]
}
// Exposed for backwards compat and unit tests
get db () {
return this[kIDB]
}
get type () {
return 'browser-level'
}
_open (options, callback) {
const req = indexedDB.open(this[kNamePrefix] + this[kLocation], this[kVersion])
req.onerror = function () {
callback(req.error || new Error('unknown error'))
}
req.onsuccess = () => {
this[kIDB] = req.result
callback()
}
req.onupgradeneeded = (ev) => {
const db = ev.target.result
if (!db.objectStoreNames.contains(this[kLocation])) {
db.createObjectStore(this[kLocation])
}
}
}
[kStore] (mode) {
const transaction = this[kIDB].transaction([this[kLocation]], mode)
return transaction.objectStore(this[kLocation])
}
[kOnComplete] (request, callback) {
const transaction = request.transaction
// Take advantage of the fact that a non-canceled request error aborts
// the transaction. I.e. no need to listen for "request.onerror".
transaction.onabort = function () {
callback(transaction.error || new Error('aborted by user'))
}
transaction.oncomplete = function () {
callback(null, request.result)
}
}
_get (key, options, callback) {
const store = this[kStore]('readonly')
let req
try {
req = store.get(key)
} catch (err) {
return this.nextTick(callback, err)
}
this[kOnComplete](req, function (err, value) {
if (err) return callback(err)
if (value === undefined) {
return callback(new ModuleError('Entry not found', {
code: 'LEVEL_NOT_FOUND'
}))
}
callback(null, deserialize(value))
})
}
_getMany (keys, options, callback) {
const store = this[kStore]('readonly')
const tasks = keys.map((key) => (next) => {
let request
try {
request = store.get(key)
} catch (err) {
return next(err)
}
request.onsuccess = () => {
const value = request.result
next(null, value === undefined ? value : deserialize(value))
}
request.onerror = (ev) => {
ev.stopPropagation()
next(request.error)
}
})
parallel(tasks, 16, callback)
}
_del (key, options, callback) {
const store = this[kStore]('readwrite')
let req
try {
req = store.delete(key)
} catch (err) {
return this.nextTick(callback, err)
}
this[kOnComplete](req, callback)
}
_put (key, value, options, callback) {
const store = this[kStore]('readwrite')
let req
try {
// Will throw a DataError or DataCloneError if the environment
// does not support serializing the key or value respectively.
req = store.put(value, key)
} catch (err) {
return this.nextTick(callback, err)
}
this[kOnComplete](req, callback)
}
// TODO: implement key and value iterators
_iterator (options) {
return new Iterator(this, this[kLocation], options)
}
_batch (operations, options, callback) {
const store = this[kStore]('readwrite')
const transaction = store.transaction
let index = 0
let error
transaction.onabort = function () {
callback(error || transaction.error || new Error('aborted by user'))
}
transaction.oncomplete = function () {
callback()
}
// Wait for a request to complete before making the next, saving CPU.
function loop () {
const op = operations[index++]
const key = op.key
let req
try {
req = op.type === 'del' ? store.delete(key) : store.put(op.value, key)
} catch (err) {
error = err
transaction.abort()
return
}
if (index < operations.length) {
req.onsuccess = loop
} else if (typeof transaction.commit === 'function') {
// Commit now instead of waiting for auto-commit
transaction.commit()
}
}
loop()
}
_clear (options, callback) {
let keyRange
let req
try {
keyRange = createKeyRange(options)
} catch (e) {
// The lower key is greater than the upper key.
// IndexedDB throws an error, but we'll just do nothing.
return this.nextTick(callback)
}
if (options.limit >= 0) {
// IDBObjectStore#delete(range) doesn't have such an option.
// Fall back to cursor-based implementation.
return clear(this, this[kLocation], keyRange, options, callback)
}
try {
const store = this[kStore]('readwrite')
req = keyRange ? store.delete(keyRange) : store.clear()
} catch (err) {
return this.nextTick(callback, err)
}
this[kOnComplete](req, callback)
}
_close (callback) {
this[kIDB].close()
this.nextTick(callback)
}
}
BrowserLevel.destroy = function (location, prefix, callback) {
if (typeof prefix === 'function') {
callback = prefix
prefix = DEFAULT_PREFIX
}
callback = fromCallback(callback, kPromise)
const request = indexedDB.deleteDatabase(prefix + location)
request.onsuccess = function () {
callback()
}
request.onerror = function (err) {
callback(err)
}
return callback[kPromise]
}
exports.BrowserLevel = BrowserLevel
/***/ }),
/***/ "./node_modules/browser-level/iterator.js":
/*!************************************************!*\
!*** ./node_modules/browser-level/iterator.js ***!
\************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
const { AbstractIterator } = __webpack_require__(/*! abstract-level */ "./node_modules/abstract-level/index.js")
const createKeyRange = __webpack_require__(/*! ./util/key-range */ "./node_modules/browser-level/util/key-range.js")
const deserialize = __webpack_require__(/*! ./util/deserialize */ "./node_modules/browser-level/util/deserialize.js")
const kCache = Symbol('cache')
const kFinished = Symbol('finished')
const kOptions = Symbol('options')
const kCurrentOptions = Symbol('currentOptions')
const kPosition = Symbol('position')
const kLocation = Symbol('location')
const kFirst = Symbol('first')
const emptyOptions = {}
class Iterator extends AbstractIterator {
constructor (db, location, options) {
super(db, options)
this[kCache] = []
this[kFinished] = this.limit === 0
this[kOptions] = options
this[kCurrentOptions] = { ...options }
this[kPosition] = undefined
this[kLocation] = location
this[kFirst] = true
}
// Note: if called by _all() then size can be Infinity. This is an internal
// detail; by design AbstractIterator.nextv() does not support Infinity.
_nextv (size, options, callback) {
this[kFirst] = false
if (this[kFinished]) {
return this.nextTick(callback, null, [])
} else if (this[kCache].length > 0) {
// TODO: mixing next and nextv is not covered by test suite
size = Math.min(size, this[kCache].length)
return this.nextTick(callback, null, this[kCache].splice(0, size))
}
// Adjust range by what we already visited
if (this[kPosition] !== undefined) {
if (this[kOptions].reverse) {
this[kCurrentOptions].lt = this[kPosition]
this[kCurrentOptions].lte = undefined
} else {
this[kCurrentOptions].gt = this[kPosition]
this[kCurrentOptions].gte = undefined
}
}
let keyRange
try {
keyRange = createKeyRange(this[kCurrentOptions])
} catch (_) {
// The lower key is greater than the upper key.
// IndexedDB throws an error, but we'll just return 0 results.
this[kFinished] = true
return this.nextTick(callback, null, [])
}
const transaction = this.db.db.transaction([this[kLocation]], 'readonly')
const store = transaction.objectStore(this[kLocation])
const entries = []
if (!this[kOptions].reverse) {
let keys
let values
const complete = () => {
// Wait for both requests to complete
if (keys === undefined || values === undefined) return
const length = Math.max(keys.length, values.length)
if (length === 0 || size === Infinity) {
this[kFinished] = true
} else {
this[kPosition] = keys[length - 1]
}
// Resize
entries.length = length
// Merge keys and values
for (let i = 0; i < length; i++) {
const key = keys[i]
const value = values[i]
entries[i] = [
this[kOptions].keys && key !== undefined ? deserialize(key) : undefined,
this[kOptions].values && value !== undefined ? deserialize(value) : undefined
]
}
maybeCommit(transaction)
}
// If keys were not requested and size is Infinity, we don't have to keep
// track of position and can thus skip getting keys.
if (this[kOptions].keys || size < Infinity) {
store.getAllKeys(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {
keys = ev.target.result
complete()
}
} else {
keys = []
this.nextTick(complete)
}
if (this[kOptions].values) {
store.getAll(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {
values = ev.target.result
complete()
}
} else {
values = []
this.nextTick(complete)
}
} else {
// Can't use getAll() in reverse, so use a slower cursor that yields one item at a time
// TODO: test if all target browsers support openKeyCursor
const method = !this[kOptions].values && store.openKeyCursor ? 'openKeyCursor' : 'openCursor'
store[method](keyRange, 'prev').onsuccess = (ev) => {
const cursor = ev.target.result
if (cursor) {
const { key, value } = cursor
this[kPosition] = key
entries.push([
this[kOptions].keys && key !== undefined ? deserialize(key) : undefined,
this[kOptions].values && value !== undefined ? deserialize(value) : undefined
])
if (entries.length < size) {
cursor.continue()
} else {
maybeCommit(transaction)
}
} else {
this[kFinished] = true
}
}
}
// If an error occurs (on the request), the transaction will abort.
transaction.onabort = () => {
callback(transaction.error || new Error('aborted by user'))
callback = null
}
transaction.oncomplete = () => {
callback(null, entries)
callback = null
}
}
_next (callback) {
if (this[kCache].length > 0) {
const [key, value] = this[kCache].shift()
this.nextTick(callback, null, key, value)
} else if (this[kFinished]) {
this.nextTick(callback)
} else {
let size = Math.min(100, this.limit - this.count)
if (this[kFirst]) {
// It's common to only want one entry initially or after a seek()
this[kFirst] = false
size = 1
}
this._nextv(size, emptyOptions, (err, entries) => {
if (err) return callback(err)
this[kCache] = entries
this._next(callback)
})
}
}
_all (options, callback) {
this[kFirst] = false
// TODO: mixing next and all is not covered by test suite
const cache = this[kCache].splice(0, this[kCache].length)
const size = this.limit - this.count - cache.length
if (size <= 0) {
return this.nextTick(callback, null, cache)
}
this._nextv(size, emptyOptions, (err, entries) => {
if (err) return callback(err)
if (cache.length > 0) entries = cache.concat(entries)
callback(null, entries)
})
}
_seek (target, options) {
this[kFirst] = true
this[kCache] = []
this[kFinished] = false
this[kPosition] = undefined
// TODO: not covered by test suite
this[kCurrentOptions] = { ...this[kOptions] }
let keyRange
try {
keyRange = createKeyRange(this[kOptions])
} catch (_) {
this[kFinished] = true
return
}
if (keyRange !== null && !keyRange.includes(target)) {
this[kFinished] = true
} else if (this[kOptions].reverse) {
this[kCurrentOptions].lte = target
} else {
this[kCurrentOptions].gte = target
}
}
}
exports.Iterator = Iterator
function maybeCommit (transaction) {
// Commit (meaning close) now instead of waiting for auto-commit
if (typeof transaction.commit === 'function') {
transaction.commit()
}
}
/***/ }),
/***/ "./node_modules/browser-level/util/clear.js":
/*!**************************************************!*\
!*** ./node_modules/browser-level/util/clear.js ***!
\**************************************************/
/***/ ((module) => {
"use strict";
module.exports = function clear (db, location, keyRange, options, callback) {
if (options.limit === 0) return db.nextTick(callback)
const transaction = db.db.transaction([location], 'readwrite')
const store = transaction.objectStore(location)
let count = 0
transaction.oncomplete = function () {
callback()
}
transaction.onabort = function () {
callback(transaction.error || new Error('aborted by user'))
}
// A key cursor is faster (skips reading values) but not supported by IE
// TODO: we no longer support IE. Test others
const method = store.openKeyCursor ? 'openKeyCursor' : 'openCursor'
const direction = options.reverse ? 'prev' : 'next'
store[method](keyRange, direction).onsuccess = function (ev) {
const cursor = ev.target.result
if (cursor) {
// Wait for a request to complete before continuing, saving CPU.
store.delete(cursor.key).onsuccess = function () {
if (options.limit <= 0 || ++count < options.limit) {
cursor.continue()
}
}
}
}
}
/***/ }),
/***/ "./node_modules/browser-level/util/deserialize.js":
/*!********************************************************!*\
!*** ./node_modules/browser-level/util/deserialize.js ***!
\********************************************************/
/***/ ((module) => {
"use strict";
const textEncoder = new TextEncoder()
module.exports = function (data) {
if (data instanceof Uint8Array) {
return data
} else if (data instanceof ArrayBuffer) {
return new Uint8Array(data)
} else {
// Non-binary data stored with an old version (level-js < 5.0.0)
return textEncoder.encode(data)
}
}
/***/ }),
/***/ "./node_modules/browser-level/util/key-range.js":
/*!******************************************************!*\
!*** ./node_modules/browser-level/util/key-range.js ***!
\******************************************************/
/***/ ((module) => {
"use strict";
/* global IDBKeyRange */
module.exports = function createKeyRange (options) {
const lower = options.gte !== undefined ? options.gte : options.gt !== undefined ? options.gt : undefined
const upper = options.lte !== undefined ? options.lte : options.lt !== undefined ? options.lt : undefined
const lowerExclusive = options.gte === undefined
const upperExclusive = options.lte === undefined
if (lower !== undefined && upper !== undefined) {
return IDBKeyRange.bound(lower, upper, lowerExclusive, upperExclusive)
} else if (lower !== undefined) {
return IDBKeyRange.lowerBound(lower, lowerExclusive)
} else if (upper !== undefined) {
return IDBKeyRange.upperBound(upper, upperExclusive)
} else {
return null
}
}
/***/ }),
/***/ "./node_modules/buffer/index.js":
/*!**************************************!*\
!*** ./node_modules/buffer/index.js ***!
\**************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
const base64 = __webpack_require__(/*! base64-js */ "./node_modules/base64-js/index.js")
const ieee754 = __webpack_require__(/*! ieee754 */ "./node_modules/ieee754/index.js")
const customInspectSymbol =
(typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
: null
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
const K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
const arr = new Uint8Array(1)
const proto = { foo: function () { return 42 } }
Object.setPrototypeOf(proto, Uint8Array.prototype)
Object.setPrototypeOf(arr, proto)
return arr.foo() === 42
} catch (e) {
return false
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.buffer
}
})
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.byteOffset
}
})
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"')
}
// Return an augmented `Uint8Array` instance
const buf = new Uint8Array(length)
Object.setPrototypeOf(buf, Buffer.prototype)
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
if (ArrayBuffer.isView(value)) {
return fromArrayView(value)
}
if (value == null) {
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
if (isInstance(value, ArrayBuffer) ||
(value && isInstance(value.buffer, ArrayBuffer))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof SharedArrayBuffer !== 'undefined' &&
(isInstance(value, SharedArrayBuffer) ||
(value && isInstance(value.buffer, SharedArrayBuffer)))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'number') {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
)
}
const valueOf = value.valueOf && value.valueOf()
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length)
}
const b = fromObject(value)
if (b) return b
if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)
}
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
Object.setPrototypeOf(Buffer, Uint8Array)
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number')
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpreted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
const length = byteLength(string, encoding) | 0
let buf = createBuffer(length)
const actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
const length = array.length < 0 ? 0 : checked(array.length) | 0
const buf = createBuffer(length)
for (let i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayView (arrayView) {
if (isInstance(arrayView, Uint8Array)) {
const copy = new Uint8Array(arrayView)
return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
}
return fromArrayLike(arrayView)
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds')
}
let buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
Object.setPrototypeOf(buf, Buffer.prototype)
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
const len = checked(obj.length) | 0
const buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true &&
b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}
Buffer.compare = function compare (a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
)
}
if (a === b) return 0
let x = a.length
let y = b.length
for (let i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
let i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
const buffer = Buffer.allocUnsafe(length)
let pos = 0
for (i = 0; i < list.length; ++i) {
let buf = list[i]
if (isInstance(buf, Uint8Array)) {
if (pos + buf.length > buffer.length) {
if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
buf.copy(buffer, pos)
} else {
Uint8Array.prototype.set.call(
buffer,
buf,
pos
)
}
} else if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
} else {
buf.copy(buffer, pos)
}
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
throw new TypeError(
'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
'Received type ' + typeof string
)
}
const len = string.length
const mustMatch = (arguments.length > 2 && arguments[2] === true)
if (!mustMatch && len === 0) return 0
// Use a for loop to avoid recursion
let loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) {
return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
}
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
let loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coercion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
const i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
const len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (let i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
const len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (let i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
const len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (let i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
const length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.toLocaleString = Buffer.prototype.toString
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
let str = ''
const max = exports.INSPECT_MAX_BYTES
str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
if (this.length > max) str += ' ... '
return '<Buffer ' + str + '>'
}
if (customInspectSymbol) {
Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array)) {
target = Buffer.from(target, target.offset, target.byteLength)
}
if (!Buffer.isBuffer(target)) {
throw new TypeError(
'The "target" argument must be one of type Buffer or Uint8Array. ' +
'Received type ' + (typeof target)
)
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
let x = thisEnd - thisStart
let y = end - start
const len = Math.min(x, y)
const thisCopy = this.slice(thisStart, thisEnd)
const targetCopy = target.slice(start, end)
for (let i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
let indexSize = 1
let arrLength = arr.length
let valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
let i
if (dir) {
let foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
let found = true
for (let j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
const remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
const strLen = string.length
if (length > strLen / 2) {
length = strLen / 2
}
let i
for (i = 0; i < length; ++i) {
const parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
const remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
let loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
case 'latin1':
case 'binary':
return asciiWrite(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
const res = []
let i = start
while (i < end) {
const firstByte = buf[i]
let codePoint = null
let bytesPerSequence = (firstByte > 0xEF)
? 4
: (firstByte > 0xDF)
? 3
: (firstByte > 0xBF)
? 2
: 1
if (i + bytesPerSequence <= end) {
let secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
const len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
let res = ''
let i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
let ret = ''
end = Math.min(buf.length, end)
for (let i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
let ret = ''
end = Math.min(buf.length, end)
for (let i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
const len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
let out = ''
for (let i = start; i < end; ++i) {
out += hexSliceLookupTable[buf[i]]
}
return out
}
function utf16leSlice (buf, start, end) {
const bytes = buf.slice(start, end)
let res = ''
// If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
for (let i = 0; i < bytes.length - 1; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
const len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
const newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
Object.setPrototypeOf(newBuf, Buffer.prototype)
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUintLE =
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
let val = this[offset]
let mul = 1
let i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUintBE =
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
let val = this[offset + --byteLength]
let mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUint8 =
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUint16LE =
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUint16BE =
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUint32LE =
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUint32BE =
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {
offset = offset >>> 0
validateNumber(offset, 'offset')
const first = this[offset]
const last = this[offset + 7]
if (first === undefined || last === undefined) {
boundsError(offset, this.length - 8)
}
const lo = first +
this[++offset] * 2 ** 8 +
this[++offset] * 2 ** 16 +
this[++offset] * 2 ** 24
const hi = this[++offset] +
this[++offset] * 2 ** 8 +
this[++offset] * 2 ** 16 +
last * 2 ** 24
return BigInt(lo) + (BigInt(hi) << BigInt(32))
})
Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {
offset = offset >>> 0
validateNumber(offset, 'offset')
const first = this[offset]
const last = this[offset + 7]
if (first === undefined || last === undefined) {
boundsError(offset, this.length - 8)
}
const hi = first * 2 ** 24 +
this[++offset] * 2 ** 16 +
this[++offset] * 2 ** 8 +
this[++offset]
const lo = this[++offset] * 2 ** 24 +
this[++offset] * 2 ** 16 +
this[++offset] * 2 ** 8 +
last
return (BigInt(hi) << BigInt(32)) + BigInt(lo)
})
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
let val = this[offset]
let mul = 1
let i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
let i = byteLength
let mul = 1
let val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
const val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
const val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {
offset = offset >>> 0
validateNumber(offset, 'offset')
const first = this[offset]
const last = this[offset + 7]
if (first === undefined || last === undefined) {
boundsError(offset, this.length - 8)
}
const val = this[offset + 4] +
this[offset + 5] * 2 ** 8 +
this[offset + 6] * 2 ** 16 +
(last << 24) // Overflow
return (BigInt(val) << BigInt(32)) +
BigInt(first +
this[++offset] * 2 ** 8 +
this[++offset] * 2 ** 16 +
this[++offset] * 2 ** 24)
})
Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {
offset = offset >>> 0
validateNumber(offset, 'offset')
const first = this[offset]
const last = this[offset + 7]
if (first === undefined || last === undefined) {
boundsError(offset, this.length - 8)
}
const val = (first << 24) + // Overflow
this[++offset] * 2 ** 16 +
this[++offset] * 2 ** 8 +
this[++offset]
return (BigInt(val) << BigInt(32)) +
BigInt(this[++offset] * 2 ** 24 +
this[++offset] * 2 ** 16 +
this[++offset] * 2 ** 8 +
last)
})
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUintLE =
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
const maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
let mul = 1
let i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUintBE =
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
const maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
let i = byteLength - 1
let mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUint8 =
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUint16LE =
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUint16BE =
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUint32LE =
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUint32BE =
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function wrtBigUInt64LE (buf, value, offset, min, max) {
checkIntBI(value, min, max, buf, offset, 7)
let lo = Number(value & BigInt(0xffffffff))
buf[offset++] = lo
lo = lo >> 8
buf[offset++] = lo
lo = lo >> 8
buf[offset++] = lo
lo = lo >> 8
buf[offset++] = lo
let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))
buf[offset++] = hi
hi = hi >> 8
buf[offset++] = hi
hi = hi >> 8
buf[offset++] = hi
hi = hi >> 8
buf[offset++] = hi
return offset
}
function wrtBigUInt64BE (buf, value, offset, min, max) {
checkIntBI(value, min, max, buf, offset, 7)
let lo = Number(value & BigInt(0xffffffff))
buf[offset + 7] = lo
lo = lo >> 8
buf[offset + 6] = lo
lo = lo >> 8
buf[offset + 5] = lo
lo = lo >> 8
buf[offset + 4] = lo
let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))
buf[offset + 3] = hi
hi = hi >> 8
buf[offset + 2] = hi
hi = hi >> 8
buf[offset + 1] = hi
hi = hi >> 8
buf[offset] = hi
return offset + 8
}
Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {
return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))
})
Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {
return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))
})
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
const limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
let i = 0
let mul = 1
let sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
const limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
let i = byteLength - 1
let mul = 1
let sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {
return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))
})
Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {
return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))
})
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
const len = end - start
if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end)
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, end),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
if (val.length === 1) {
const code = val.charCodeAt(0)
if ((encoding === 'utf8' && code < 128) ||
encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code
}
}
} else if (typeof val === 'number') {
val = val & 255
} else if (typeof val === 'boolean') {
val = Number(val)
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
let i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
const bytes = Buffer.isBuffer(val)
? val
: Buffer.from(val, encoding)
const len = bytes.length
if (len === 0) {
throw new TypeError('The value "' + val +
'" is invalid for argument "value"')
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// CUSTOM ERRORS
// =============
// Simplified versions from Node, changed for Buffer-only usage
const errors = {}
function E (sym, getMessage, Base) {
errors[sym] = class NodeError extends Base {
constructor () {
super()
Object.defineProperty(this, 'message', {
value: getMessage.apply(this, arguments),
writable: true,
configurable: true
})
// Add the error code to the name to include it in the stack trace.
this.name = `${this.name} [${sym}]`
// Access the stack to generate the error message including the error code
// from the name.
this.stack // eslint-disable-line no-unused-expressions
// Reset the name to the actual name.
delete this.name
}
get code () {
return sym
}
set code (value) {
Object.defineProperty(this, 'code', {
configurable: true,
enumerable: true,
value,
writable: true
})
}
toString () {
return `${this.name} [${sym}]: ${this.message}`
}
}
}
E('ERR_BUFFER_OUT_OF_BOUNDS',
function (name) {
if (name) {
return `${name} is outside of buffer bounds`
}
return 'Attempt to access memory outside buffer bounds'
}, RangeError)
E('ERR_INVALID_ARG_TYPE',
function (name, actual) {
return `The "${name}" argument must be of type number. Received type ${typeof actual}`
}, TypeError)
E('ERR_OUT_OF_RANGE',
function (str, range, input) {
let msg = `The value of "${str}" is out of range.`
let received = input
if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
received = addNumericalSeparator(String(input))
} else if (typeof input === 'bigint') {
received = String(input)
if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
received = addNumericalSeparator(received)
}
received += 'n'
}
msg += ` It must be ${range}. Received ${received}`
return msg
}, RangeError)
function addNumericalSeparator (val) {
let res = ''
let i = val.length
const start = val[0] === '-' ? 1 : 0
for (; i >= start + 4; i -= 3) {
res = `_${val.slice(i - 3, i)}${res}`
}
return `${val.slice(0, i)}${res}`
}
// CHECK FUNCTIONS
// ===============
function checkBounds (buf, offset, byteLength) {
validateNumber(offset, 'offset')
if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {
boundsError(offset, buf.length - (byteLength + 1))
}
}
function checkIntBI (value, min, max, buf, offset, byteLength) {
if (value > max || value < min) {
const n = typeof min === 'bigint' ? 'n' : ''
let range
if (byteLength > 3) {
if (min === 0 || min === BigInt(0)) {
range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`
} else {
range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +
`${(byteLength + 1) * 8 - 1}${n}`
}
} else {
range = `>= ${min}${n} and <= ${max}${n}`
}
throw new errors.ERR_OUT_OF_RANGE('value', range, value)
}
checkBounds(buf, offset, byteLength)
}
function validateNumber (value, name) {
if (typeof value !== 'number') {
throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)
}
}
function boundsError (value, length, type) {
if (Math.floor(value) !== value) {
validateNumber(value, type)
throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)
}
if (length < 0) {
throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()
}
throw new errors.ERR_OUT_OF_RANGE(type || 'offset',
`>= ${type ? 1 : 0} and <= ${length}`,
value)
}
// HELPER FUNCTIONS
// ================
const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function utf8ToBytes (string, units) {
units = units || Infinity
let codePoint
const length = string.length
let leadSurrogate = null
const bytes = []
for (let i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
const byteArray = []
for (let i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
let c, hi, lo
const byteArray = []
for (let i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
let i
for (i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
return obj instanceof type ||
(obj != null && obj.constructor != null && obj.constructor.name != null &&
obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
// For IE11 support
return obj !== obj // eslint-disable-line no-self-compare
}
// Create lookup table for `toString('hex')`
// See: https://github.com/feross/buffer/issues/219
const hexSliceLookupTable = (function () {
const alphabet = '0123456789abcdef'
const table = new Array(256)
for (let i = 0; i < 16; ++i) {
const i16 = i * 16
for (let j = 0; j < 16; ++j) {
table[i16 + j] = alphabet[i] + alphabet[j]
}
}
return table
})()
// Return not function with Error if BigInt not supported
function defineBigIntMethod (fn) {
return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn
}
function BufferBigIntNotDefined () {
throw new Error('BigInt not supported')
}
/***/ }),
/***/ "./node_modules/catering/index.js":
/*!****************************************!*\
!*** ./node_modules/catering/index.js ***!
\****************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
var nextTick = __webpack_require__(/*! ./next-tick */ "./node_modules/catering/next-tick-browser.js")
exports.fromCallback = function (callback, symbol) {
if (callback === undefined) {
var promise = new Promise(function (resolve, reject) {
callback = function (err, res) {
if (err) reject(err)
else resolve(res)
}
})
callback[symbol !== undefined ? symbol : 'promise'] = promise
} else if (typeof callback !== 'function') {
throw new TypeError('Callback must be a function')
}
return callback
}
exports.fromPromise = function (promise, callback) {
if (callback === undefined) return promise
promise
.then(function (res) { nextTick(() => callback(null, res)) })
.catch(function (err) { nextTick(() => callback(err)) })
}
/***/ }),
/***/ "./node_modules/catering/next-tick-browser.js":
/*!****************************************************!*\
!*** ./node_modules/catering/next-tick-browser.js ***!
\****************************************************/
/***/ ((module) => {
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
/***/ }),
/***/ "./node_modules/eventemitter3/index.js":
/*!*********************************************!*\
!*** ./node_modules/eventemitter3/index.js ***!
\*********************************************/
/***/ ((module) => {
"use strict";
var has = Object.prototype.hasOwnProperty
, prefix = '~';
/**
* Constructor to create a storage for our `EE` objects.
* An `Events` instance is a plain object whose properties are event names.
*
* @constructor
* @private
*/
function Events() {}
//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
if (Object.create) {
Events.prototype = Object.create(null);
//
// This hack is needed because the `__proto__` property is still inherited in
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
//
if (!new Events().__proto__) prefix = false;
}
/**
* Representation of a single event listener.
*
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
* @constructor
* @private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Add a listener for a given event.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} once Specify if the listener is a one-time listener.
* @returns {EventEmitter}
* @private
*/
function addListener(emitter, event, fn, context, once) {
if (typeof fn !== 'function') {
throw new TypeError('The listener must be a function');
}
var listener = new EE(fn, context || emitter, once)
, evt = prefix ? prefix + event : event;
if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
else emitter._events[evt] = [emitter._events[evt], listener];
return emitter;
}
/**
* Clear event by name.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} evt The Event name.
* @private
*/
function clearEvent(emitter, evt) {
if (--emitter._eventsCount === 0) emitter._events = new Events();
else delete emitter._events[evt];
}
/**
* Minimal `EventEmitter` interface that is molded against the Node.js
* `EventEmitter` interface.
*
* @constructor
* @public
*/
function EventEmitter() {
this._events = new Events();
this._eventsCount = 0;
}
/**
* Return an array listing the events for which the emitter has registered
* listeners.
*
* @returns {Array}
* @public
*/
EventEmitter.prototype.eventNames = function eventNames() {
var names = []
, events
, name;
if (this._eventsCount === 0) return names;
for (name in (events = this._events)) {
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events));
}
return names;
};
/**
* Return the listeners registered for a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Array} The registered listeners.
* @public
*/
EventEmitter.prototype.listeners = function listeners(event) {
var evt = prefix ? prefix + event : event
, handlers = this._events[evt];
if (!handlers) return [];
if (handlers.fn) return [handlers.fn];
for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
ee[i] = handlers[i].fn;
}
return ee;
};
/**
* Return the number of listeners listening to a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Number} The number of listeners.
* @public
*/
EventEmitter.prototype.listenerCount = function listenerCount(event) {
var evt = prefix ? prefix + event : event
, listeners = this._events[evt];
if (!listeners) return 0;
if (listeners.fn) return 1;
return listeners.length;
};
/**
* Calls each of the listeners registered for a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Boolean} `true` if the event had listeners, else `false`.
* @public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
/**
* Add a listener for a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
return addListener(this, event, fn, context, false);
};
/**
* Add a one-time listener for a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
return addListener(this, event, fn, context, true);
};
/**
* Remove the listeners of a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn Only remove the listeners that match this function.
* @param {*} context Only remove the listeners that have this context.
* @param {Boolean} once Only remove one-time listeners.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
clearEvent(this, evt);
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (
listeners.fn === fn &&
(!once || listeners.once) &&
(!context || listeners.context === context)
) {
clearEvent(this, evt);
}
} else {
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
if (
listeners[i].fn !== fn ||
(once && !listeners[i].once) ||
(context && listeners[i].context !== context)
) {
events.push(listeners[i]);
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
else clearEvent(this, evt);
}
return this;
};
/**
* Remove all listeners, or those of the specified event.
*
* @param {(String|Symbol)} [event] The event name.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) clearEvent(this, evt);
} else {
this._events = new Events();
this._eventsCount = 0;
}
return this;
};
//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
//
// Expose the prefix.
//
EventEmitter.prefixed = prefix;
//
// Allow `EventEmitter` to be imported as module namespace.
//
EventEmitter.EventEmitter = EventEmitter;
//
// Expose the module.
//
if (true) {
module.exports = EventEmitter;
}
/***/ }),
/***/ "./node_modules/events/events.js":
/*!***************************************!*\
!*** ./node_modules/events/events.js ***!
\***************************************/
/***/ ((module) => {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
// EventTarget does not have `error` event semantics like Node
// EventEmitters, we do not listen for `error` events here.
emitter.addEventListener(name, function wrapListener(arg) {
// IE does not have builtin `{ once: true }` support so we
// have to do it manually.
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
/***/ }),
/***/ "./node_modules/ieee754/index.js":
/*!***************************************!*\
!*** ./node_modules/ieee754/index.js ***!
\***************************************/
/***/ ((__unused_webpack_module, exports) => {
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
/***/ }),
/***/ "./node_modules/inherits/inherits_browser.js":
/*!***************************************************!*\
!*** ./node_modules/inherits/inherits_browser.js ***!
\***************************************************/
/***/ ((module) => {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
/***/ }),
/***/ "./node_modules/level-supports/index.js":
/*!**********************************************!*\
!*** ./node_modules/level-supports/index.js ***!
\**********************************************/
/***/ ((__unused_webpack_module, exports) => {
"use strict";
exports.supports = function supports (...manifests) {
const manifest = manifests.reduce((acc, m) => Object.assign(acc, m), {})
return Object.assign(manifest, {
snapshots: manifest.snapshots || false,
permanence: manifest.permanence || false,
seek: manifest.seek || false,
clear: manifest.clear || false,
getMany: manifest.getMany || false,
keyIterator: manifest.keyIterator || false,
valueIterator: manifest.valueIterator || false,
iteratorNextv: manifest.iteratorNextv || false,
iteratorAll: manifest.iteratorAll || false,
status: manifest.status || false,
createIfMissing: manifest.createIfMissing || false,
errorIfExists: manifest.errorIfExists || false,
deferredOpen: manifest.deferredOpen || false,
promises: manifest.promises || false,
streams: manifest.streams || false,
encodings: Object.assign({}, manifest.encodings),
events: Object.assign({}, manifest.events),
additionalMethods: Object.assign({}, manifest.additionalMethods)
})
}
/***/ }),
/***/ "./node_modules/level-transcoder/index.js":
/*!************************************************!*\
!*** ./node_modules/level-transcoder/index.js ***!
\************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
const ModuleError = __webpack_require__(/*! module-error */ "./node_modules/module-error/index.js")
const encodings = __webpack_require__(/*! ./lib/encodings */ "./node_modules/level-transcoder/lib/encodings.js")
const { Encoding } = __webpack_require__(/*! ./lib/encoding */ "./node_modules/level-transcoder/lib/encoding.js")
const { BufferFormat, ViewFormat, UTF8Format } = __webpack_require__(/*! ./lib/formats */ "./node_modules/level-transcoder/lib/formats.js")
const kFormats = Symbol('formats')
const kEncodings = Symbol('encodings')
const validFormats = new Set(['buffer', 'view', 'utf8'])
/** @template T */
class Transcoder {
/**
* @param {Array<'buffer'|'view'|'utf8'>} formats
*/
constructor (formats) {
if (!Array.isArray(formats)) {
throw new TypeError("The first argument 'formats' must be an array")
} else if (!formats.every(f => validFormats.has(f))) {
// Note: we only only support aliases in key- and valueEncoding options (where we already did)
throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")
}
/** @type {Map<string|MixedEncoding<any, any, any>, Encoding<any, any, any>>} */
this[kEncodings] = new Map()
this[kFormats] = new Set(formats)
// Register encodings (done early in order to populate encodings())
for (const k in encodings) {
try {
this.encoding(k)
} catch (err) {
/* istanbul ignore if: assertion */
if (err.code !== 'LEVEL_ENCODING_NOT_SUPPORTED') throw err
}
}
}
/**
* @returns {Array<Encoding<any,T,any>>}
*/
encodings () {
return Array.from(new Set(this[kEncodings].values()))
}
/**
* @param {string|MixedEncoding<any, any, any>} encoding
* @returns {Encoding<any, T, any>}
*/
encoding (encoding) {
let resolved = this[kEncodings].get(encoding)
if (resolved === undefined) {
if (typeof encoding === 'string' && encoding !== '') {
resolved = lookup[encoding]
if (!resolved) {
throw new ModuleError(`Encoding '${encoding}' is not found`, {
code: 'LEVEL_ENCODING_NOT_FOUND'
})
}
} else if (typeof encoding !== 'object' || encoding === null) {
throw new TypeError("First argument 'encoding' must be a string or object")
} else {
resolved = from(encoding)
}
const { name, format } = resolved
if (!this[kFormats].has(format)) {
if (this[kFormats].has('view')) {
resolved = resolved.createViewTranscoder()
} else if (this[kFormats].has('buffer')) {
resolved = resolved.createBufferTranscoder()
} else if (this[kFormats].has('utf8')) {
resolved = resolved.createUTF8Transcoder()
} else {
throw new ModuleError(`Encoding '${name}' cannot be transcoded`, {
code: 'LEVEL_ENCODING_NOT_SUPPORTED'
})
}
}
for (const k of [encoding, name, resolved.name, resolved.commonName]) {
this[kEncodings].set(k, resolved)
}
}
return resolved
}
}
exports.Transcoder = Transcoder
/**
* @param {MixedEncoding<any, any, any>} options
* @returns {Encoding<any, any, any>}
*/
function from (options) {
if (options instanceof Encoding) {
return options
}
// Loosely typed for ecosystem compatibility
const maybeType = 'type' in options && typeof options.type === 'string' ? options.type : undefined
const name = options.name || maybeType || `anonymous-${anonymousCount++}`
switch (detectFormat(options)) {
case 'view': return new ViewFormat({ ...options, name })
case 'utf8': return new UTF8Format({ ...options, name })
case 'buffer': return new BufferFormat({ ...options, name })
default: {
throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")
}
}
}
/**
* If format is not provided, fallback to detecting `level-codec`
* or `multiformats` encodings, else assume a format of buffer.
* @param {MixedEncoding<any, any, any>} options
* @returns {string}
*/
function detectFormat (options) {
if ('format' in options && options.format !== undefined) {
return options.format
} else if ('buffer' in options && typeof options.buffer === 'boolean') {
return options.buffer ? 'buffer' : 'utf8' // level-codec
} else if ('code' in options && Number.isInteger(options.code)) {
return 'view' // multiformats
} else {
return 'buffer'
}
}
/**
* @typedef {import('./lib/encoding').MixedEncoding<TIn,TFormat,TOut>} MixedEncoding
* @template TIn, TFormat, TOut
*/
/**
* @type {Object.<string, Encoding<any, any, any>>}
*/
const aliases = {
binary: encodings.buffer,
'utf-8': encodings.utf8
}
/**
* @type {Object.<string, Encoding<any, any, any>>}
*/
const lookup = {
...encodings,
...aliases
}
let anonymousCount = 0
/***/ }),
/***/ "./node_modules/level-transcoder/lib/encoding.js":
/*!*******************************************************!*\
!*** ./node_modules/level-transcoder/lib/encoding.js ***!
\*******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
const ModuleError = __webpack_require__(/*! module-error */ "./node_modules/module-error/index.js")
const formats = new Set(['buffer', 'view', 'utf8'])
/**
* @template TIn, TFormat, TOut
* @abstract
*/
class Encoding {
/**
* @param {IEncoding<TIn,TFormat,TOut>} options
*/
constructor (options) {
/** @type {(data: TIn) => TFormat} */
this.encode = options.encode || this.encode
/** @type {(data: TFormat) => TOut} */
this.decode = options.decode || this.decode
/** @type {string} */
this.name = options.name || this.name
/** @type {string} */
this.format = options.format || this.format
if (typeof this.encode !== 'function') {
throw new TypeError("The 'encode' property must be a function")
}
if (typeof this.decode !== 'function') {
throw new TypeError("The 'decode' property must be a function")
}
this.encode = this.encode.bind(this)
this.decode = this.decode.bind(this)
if (typeof this.name !== 'string' || this.name === '') {
throw new TypeError("The 'name' property must be a string")
}
if (typeof this.format !== 'string' || !formats.has(this.format)) {
throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'")
}
if (options.createViewTranscoder) {
this.createViewTranscoder = options.createViewTranscoder
}
if (options.createBufferTranscoder) {
this.createBufferTranscoder = options.createBufferTranscoder
}
if (options.createUTF8Transcoder) {
this.createUTF8Transcoder = options.createUTF8Transcoder
}
}
get commonName () {
return /** @type {string} */ (this.name.split('+')[0])
}
/** @return {BufferFormat<TIn,TOut>} */
createBufferTranscoder () {
throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'buffer'`, {
code: 'LEVEL_ENCODING_NOT_SUPPORTED'
})
}
/** @return {ViewFormat<TIn,TOut>} */
createViewTranscoder () {
throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'view'`, {
code: 'LEVEL_ENCODING_NOT_SUPPORTED'
})
}
/** @return {UTF8Format<TIn,TOut>} */
createUTF8Transcoder () {
throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'utf8'`, {
code: 'LEVEL_ENCODING_NOT_SUPPORTED'
})
}
}
exports.Encoding = Encoding
/**
* @typedef {import('./encoding').IEncoding<TIn,TFormat,TOut>} IEncoding
* @template TIn, TFormat, TOut
*/
/**
* @typedef {import('./formats').BufferFormat<TIn,TOut>} BufferFormat
* @template TIn, TOut
*/
/**
* @typedef {import('./formats').ViewFormat<TIn,TOut>} ViewFormat
* @template TIn, TOut
*/
/**
* @typedef {import('./formats').UTF8Format<TIn,TOut>} UTF8Format
* @template TIn, TOut
*/
/***/ }),
/***/ "./node_modules/level-transcoder/lib/encodings.js":
/*!********************************************************!*\
!*** ./node_modules/level-transcoder/lib/encodings.js ***!
\********************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
const { Buffer } = __webpack_require__(/*! buffer */ "./node_modules/buffer/index.js") || { Buffer: { isBuffer: () => false } }
const { textEncoder, textDecoder } = __webpack_require__(/*! ./text-endec */ "./node_modules/level-transcoder/lib/text-endec.js")()
const { BufferFormat, ViewFormat, UTF8Format } = __webpack_require__(/*! ./formats */ "./node_modules/level-transcoder/lib/formats.js")
/** @type {<T>(v: T) => v} */
const identity = (v) => v
/**
* @type {typeof import('./encodings').utf8}
*/
exports.utf8 = new UTF8Format({
encode: function (data) {
// On node 16.9.1 buffer.toString() is 5x faster than TextDecoder
return Buffer.isBuffer(data)
? data.toString('utf8')
: ArrayBuffer.isView(data)
? textDecoder.decode(data)
: String(data)
},
decode: identity,
name: 'utf8',
createViewTranscoder () {
return new ViewFormat({
encode: function (data) {
return ArrayBuffer.isView(data) ? data : textEncoder.encode(data)
},
decode: function (data) {
return textDecoder.decode(data)
},
name: `${this.name}+view`
})
},
createBufferTranscoder () {
return new BufferFormat({
encode: function (data) {
return Buffer.isBuffer(data)
? data
: ArrayBuffer.isView(data)
? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
: Buffer.from(String(data), 'utf8')
},
decode: function (data) {
return data.toString('utf8')
},
name: `${this.name}+buffer`
})
}
})
/**
* @type {typeof import('./encodings').json}
*/
exports.json = new UTF8Format({
encode: JSON.stringify,
decode: JSON.parse,
name: 'json'
})
/**
* @type {typeof import('./encodings').buffer}
*/
exports.buffer = new BufferFormat({
encode: function (data) {
return Buffer.isBuffer(data)
? data
: ArrayBuffer.isView(data)
? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
: Buffer.from(String(data), 'utf8')
},
decode: identity,
name: 'buffer',
createViewTranscoder () {
return new ViewFormat({
encode: function (data) {
return ArrayBuffer.isView(data) ? data : Buffer.from(String(data), 'utf8')
},
decode: function (data) {
return Buffer.from(data.buffer, data.byteOffset, data.byteLength)
},
name: `${this.name}+view`
})
}
})
/**
* @type {typeof import('./encodings').view}
*/
exports.view = new ViewFormat({
encode: function (data) {
return ArrayBuffer.isView(data) ? data : textEncoder.encode(data)
},
decode: identity,
name: 'view',
createBufferTranscoder () {
return new BufferFormat({
encode: function (data) {
return Buffer.isBuffer(data)
? data
: ArrayBuffer.isView(data)
? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
: Buffer.from(String(data), 'utf8')
},
decode: identity,
name: `${this.name}+buffer`
})
}
})
/**
* @type {typeof import('./encodings').hex}
*/
exports.hex = new BufferFormat({
encode: function (data) {
return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'hex')
},
decode: function (buffer) {
return buffer.toString('hex')
},
name: 'hex'
})
/**
* @type {typeof import('./encodings').base64}
*/
exports.base64 = new BufferFormat({
encode: function (data) {
return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'base64')
},
decode: function (buffer) {
return buffer.toString('base64')
},
name: 'base64'
})
/***/ }),
/***/ "./node_modules/level-transcoder/lib/formats.js":
/*!******************************************************!*\
!*** ./node_modules/level-transcoder/lib/formats.js ***!
\******************************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
const { Buffer } = __webpack_require__(/*! buffer */ "./node_modules/buffer/index.js") || {}
const { Encoding } = __webpack_require__(/*! ./encoding */ "./node_modules/level-transcoder/lib/encoding.js")
const textEndec = __webpack_require__(/*! ./text-endec */ "./node_modules/level-transcoder/lib/text-endec.js")
/**
* @template TIn, TOut
* @extends {Encoding<TIn,Buffer,TOut>}
*/
class BufferFormat extends Encoding {
/**
* @param {Omit<IEncoding<TIn, Buffer, TOut>, 'format'>} options
*/
constructor (options) {
super({ ...options, format: 'buffer' })
}
/** @override */
createViewTranscoder () {
return new ViewFormat({
encode: this.encode, // Buffer is a view (UInt8Array)
decode: (data) => this.decode(
Buffer.from(data.buffer, data.byteOffset, data.byteLength)
),
name: `${this.name}+view`
})
}
/** @override */
createBufferTranscoder () {
return this
}
}
/**
* @extends {Encoding<TIn,Uint8Array,TOut>}
* @template TIn, TOut
*/
class ViewFormat extends Encoding {
/**
* @param {Omit<IEncoding<TIn, Uint8Array, TOut>, 'format'>} options
*/
constructor (options) {
super({ ...options, format: 'view' })
}
/** @override */
createBufferTranscoder () {
return new BufferFormat({
encode: (data) => {
const view = this.encode(data)
return Buffer.from(view.buffer, view.byteOffset, view.byteLength)
},
decode: this.decode, // Buffer is a view (UInt8Array)
name: `${this.name}+buffer`
})
}
/** @override */
createViewTranscoder () {
return this
}
}
/**
* @extends {Encoding<TIn,string,TOut>}
* @template TIn, TOut
*/
class UTF8Format extends Encoding {
/**
* @param {Omit<IEncoding<TIn, string, TOut>, 'format'>} options
*/
constructor (options) {
super({ ...options, format: 'utf8' })
}
/** @override */
createBufferTranscoder () {
return new BufferFormat({
encode: (data) => Buffer.from(this.encode(data), 'utf8'),
decode: (data) => this.decode(data.toString('utf8')),
name: `${this.name}+buffer`
})
}
/** @override */
createViewTranscoder () {
const { textEncoder, textDecoder } = textEndec()
return new ViewFormat({
encode: (data) => textEncoder.encode(this.encode(data)),
decode: (data) => this.decode(textDecoder.decode(data)),
name: `${this.name}+view`
})
}
/** @override */
createUTF8Transcoder () {
return this
}
}
exports.BufferFormat = BufferFormat
exports.ViewFormat = ViewFormat
exports.UTF8Format = UTF8Format
/**
* @typedef {import('./encoding').IEncoding<TIn,TFormat,TOut>} IEncoding
* @template TIn, TFormat, TOut
*/
/***/ }),
/***/ "./node_modules/level-transcoder/lib/text-endec.js":
/*!*********************************************************!*\
!*** ./node_modules/level-transcoder/lib/text-endec.js ***!
\*********************************************************/
/***/ ((module) => {
"use strict";
/** @type {{ textEncoder: TextEncoder, textDecoder: TextDecoder }|null} */
let lazy = null
/**
* Get semi-global instances of TextEncoder and TextDecoder.
* @returns {{ textEncoder: TextEncoder, textDecoder: TextDecoder }}
*/
module.exports = function () {
if (lazy === null) {
lazy = {
textEncoder: new TextEncoder(),
textDecoder: new TextDecoder()
}
}
return lazy
}
/***/ }),
/***/ "./node_modules/level/browser.js":
/*!***************************************!*\
!*** ./node_modules/level/browser.js ***!
\***************************************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
exports.Level = __webpack_require__(/*! browser-level */ "./node_modules/browser-level/index.js").BrowserLevel
/***/ }),
/***/ "./node_modules/lru/index.js":
/*!***********************************!*\
!*** ./node_modules/lru/index.js ***!
\***********************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
var events = __webpack_require__(/*! events */ "./node_modules/events/events.js")
var inherits = __webpack_require__(/*! inherits */ "./node_modules/inherits/inherits_browser.js")
module.exports = LRU
function LRU (opts) {
if (!(this instanceof LRU)) return new LRU(opts)
if (typeof opts === 'number') opts = {max: opts}
if (!opts) opts = {}
events.EventEmitter.call(this)
this.cache = {}
this.head = this.tail = null
this.length = 0
this.max = opts.max || 1000
this.maxAge = opts.maxAge || 0
}
inherits(LRU, events.EventEmitter)
Object.defineProperty(LRU.prototype, 'keys', {
get: function () { return Object.keys(this.cache) }
})
LRU.prototype.clear = function () {
this.cache = {}
this.head = this.tail = null
this.length = 0
}
LRU.prototype.remove = function (key) {
if (typeof key !== 'string') key = '' + key
if (!this.cache.hasOwnProperty(key)) return
var element = this.cache[key]
delete this.cache[key]
this._unlink(key, element.prev, element.next)
return element.value
}
LRU.prototype._unlink = function (key, prev, next) {
this.length--
if (this.length === 0) {
this.head = this.tail = null
} else {
if (this.head === key) {
this.head = prev
this.cache[this.head].next = null
} else if (this.tail === key) {
this.tail = next
this.cache[this.tail].prev = null
} else {
this.cache[prev].next = next
this.cache[next].prev = prev
}
}
}
LRU.prototype.peek = function (key) {
if (!this.cache.hasOwnProperty(key)) return
var element = this.cache[key]
if (!this._checkAge(key, element)) return
return element.value
}
LRU.prototype.set = function (key, value) {
if (typeof key !== 'string') key = '' + key
var element
if (this.cache.hasOwnProperty(key)) {
element = this.cache[key]
element.value = value
if (this.maxAge) element.modified = Date.now()
// If it's already the head, there's nothing more to do:
if (key === this.head) return value
this._unlink(key, element.prev, element.next)
} else {
element = {value: value, modified: 0, next: null, prev: null}
if (this.maxAge) element.modified = Date.now()
this.cache[key] = element
// Eviction is only possible if the key didn't already exist:
if (this.length === this.max) this.evict()
}
this.length++
element.next = null
element.prev = this.head
if (this.head) this.cache[this.head].next = key
this.head = key
if (!this.tail) this.tail = key
return value
}
LRU.prototype._checkAge = function (key, element) {
if (this.maxAge && (Date.now() - element.modified) > this.maxAge) {
this.remove(key)
this.emit('evict', {key: key, value: element.value})
return false
}
return true
}
LRU.prototype.get = function (key) {
if (typeof key !== 'string') key = '' + key
if (!this.cache.hasOwnProperty(key)) return
var element = this.cache[key]
if (!this._checkAge(key, element)) return
if (this.head !== key) {
if (key === this.tail) {
this.tail = element.next
this.cache[this.tail].prev = null
} else {
// Set prev.next -> element.next:
this.cache[element.prev].next = element.next
}
// Set element.next.prev -> element.prev:
this.cache[element.next].prev = element.prev
// Element is the new head
this.cache[this.head].next = key
element.prev = this.head
element.next = null
this.head = key
}
return element.value
}
LRU.prototype.evict = function () {
if (!this.tail) return
var key = this.tail
var value = this.remove(this.tail)
this.emit('evict', {key: key, value: value})
}
/***/ }),
/***/ "./node_modules/module-error/index.js":
/*!********************************************!*\
!*** ./node_modules/module-error/index.js ***!
\********************************************/
/***/ ((module) => {
"use strict";
module.exports = class ModuleError extends Error {
/**
* @param {string} message Error message
* @param {{ code?: string, cause?: Error, expected?: boolean, transient?: boolean }} [options]
*/
constructor (message, options) {
super(message || '')
if (typeof options === 'object' && options !== null) {
if (options.code) this.code = String(options.code)
if (options.expected) this.expected = true
if (options.transient) this.transient = true
if (options.cause) this.cause = options.cause
}
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor)
}
}
}
/***/ }),
/***/ "./node_modules/pvtsutils/build/index.js":
/*!***********************************************!*\
!*** ./node_modules/pvtsutils/build/index.js ***!
\***********************************************/
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/*!
* MIT License
*
* Copyright (c) 2017-2022 Peculiar Ventures, LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
const ARRAY_BUFFER_NAME = "[object ArrayBuffer]";
class BufferSourceConverter {
static isArrayBuffer(data) {
return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;
}
static toArrayBuffer(data) {
if (this.isArrayBuffer(data)) {
return data;
}
if (data.byteLength === data.buffer.byteLength) {
return data.buffer;
}
if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
return data.buffer;
}
return this.toUint8Array(data.buffer)
.slice(data.byteOffset, data.byteOffset + data.byteLength)
.buffer;
}
static toUint8Array(data) {
return this.toView(data, Uint8Array);
}
static toView(data, type) {
if (data.constructor === type) {
return data;
}
if (this.isArrayBuffer(data)) {
return new type(data);
}
if (this.isArrayBufferView(data)) {
return new type(data.buffer, data.byteOffset, data.byteLength);
}
throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
}
static isBufferSource(data) {
return this.isArrayBufferView(data)
|| this.isArrayBuffer(data);
}
static isArrayBufferView(data) {
return ArrayBuffer.isView(data)
|| (data && this.isArrayBuffer(data.buffer));
}
static isEqual(a, b) {
const aView = BufferSourceConverter.toUint8Array(a);
const bView = BufferSourceConverter.toUint8Array(b);
if (aView.length !== bView.byteLength) {
return false;
}
for (let i = 0; i < aView.length; i++) {
if (aView[i] !== bView[i]) {
return false;
}
}
return true;
}
static concat(...args) {
let buffers;
if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {
buffers = args[0];
}
else if (Array.isArray(args[0]) && args[1] instanceof Function) {
buffers = args[0];
}
else {
if (args[args.length - 1] instanceof Function) {
buffers = args.slice(0, args.length - 1);
}
else {
buffers = args;
}
}
let size = 0;
for (const buffer of buffers) {
size += buffer.byteLength;
}
const res = new Uint8Array(size);
let offset = 0;
for (const buffer of buffers) {
const view = this.toUint8Array(buffer);
res.set(view, offset);
offset += view.length;
}
if (args[args.length - 1] instanceof Function) {
return this.toView(res, args[args.length - 1]);
}
return res.buffer;
}
}
const STRING_TYPE = "string";
const HEX_REGEX = /^[0-9a-f]+$/i;
const BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
const BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;
class Utf8Converter {
static fromString(text) {
const s = unescape(encodeURIComponent(text));
const uintArray = new Uint8Array(s.length);
for (let i = 0; i < s.length; i++) {
uintArray[i] = s.charCodeAt(i);
}
return uintArray.buffer;
}
static toString(buffer) {
const buf = BufferSourceConverter.toUint8Array(buffer);
let encodedString = "";
for (let i = 0; i < buf.length; i++) {
encodedString += String.fromCharCode(buf[i]);
}
const decodedString = decodeURIComponent(escape(encodedString));
return decodedString;
}
}
class Utf16Converter {
static toString(buffer, littleEndian = false) {
const arrayBuffer = BufferSourceConverter.toArrayBuffer(buffer);
const dataView = new DataView(arrayBuffer);
let res = "";
for (let i = 0; i < arrayBuffer.byteLength; i += 2) {
const code = dataView.getUint16(i, littleEndian);
res += String.fromCharCode(code);
}
return res;
}
static fromString(text, littleEndian = false) {
const res = new ArrayBuffer(text.length * 2);
const dataView = new DataView(res);
for (let i = 0; i < text.length; i++) {
dataView.setUint16(i * 2, text.charCodeAt(i), littleEndian);
}
return res;
}
}
class Convert {
static isHex(data) {
return typeof data === STRING_TYPE
&& HEX_REGEX.test(data);
}
static isBase64(data) {
return typeof data === STRING_TYPE
&& BASE64_REGEX.test(data);
}
static isBase64Url(data) {
return typeof data === STRING_TYPE
&& BASE64URL_REGEX.test(data);
}
static ToString(buffer, enc = "utf8") {
const buf = BufferSourceConverter.toUint8Array(buffer);
switch (enc.toLowerCase()) {
case "utf8":
return this.ToUtf8String(buf);
case "binary":
return this.ToBinary(buf);
case "hex":
return this.ToHex(buf);
case "base64":
return this.ToBase64(buf);
case "base64url":
return this.ToBase64Url(buf);
case "utf16le":
return Utf16Converter.toString(buf, true);
case "utf16":
case "utf16be":
return Utf16Converter.toString(buf);
default:
throw new Error(`Unknown type of encoding '${enc}'`);
}
}
static FromString(str, enc = "utf8") {
if (!str) {
return new ArrayBuffer(0);
}
switch (enc.toLowerCase()) {
case "utf8":
return this.FromUtf8String(str);
case "binary":
return this.FromBinary(str);
case "hex":
return this.FromHex(str);
case "base64":
return this.FromBase64(str);
case "base64url":
return this.FromBase64Url(str);
case "utf16le":
return Utf16Converter.fromString(str, true);
case "utf16":
case "utf16be":
return Utf16Converter.fromString(str);
default:
throw new Error(`Unknown type of encoding '${enc}'`);
}
}
static ToBase64(buffer) {
const buf = BufferSourceConverter.toUint8Array(buffer);
if (typeof btoa !== "undefined") {
const binary = this.ToString(buf, "binary");
return btoa(binary);
}
else {
return Buffer.from(buf).toString("base64");
}
}
static FromBase64(base64) {
const formatted = this.formatString(base64);
if (!formatted) {
return new ArrayBuffer(0);
}
if (!Convert.isBase64(formatted)) {
throw new TypeError("Argument 'base64Text' is not Base64 encoded");
}
if (typeof atob !== "undefined") {
return this.FromBinary(atob(formatted));
}
else {
return new Uint8Array(Buffer.from(formatted, "base64")).buffer;
}
}
static FromBase64Url(base64url) {
const formatted = this.formatString(base64url);
if (!formatted) {
return new ArrayBuffer(0);
}
if (!Convert.isBase64Url(formatted)) {
throw new TypeError("Argument 'base64url' is not Base64Url encoded");
}
return this.FromBase64(this.Base64Padding(formatted.replace(/\-/g, "+").replace(/\_/g, "/")));
}
static ToBase64Url(data) {
return this.ToBase64(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/\=/g, "");
}
static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) {
switch (encoding) {
case "ascii":
return this.FromBinary(text);
case "utf8":
return Utf8Converter.fromString(text);
case "utf16":
case "utf16be":
return Utf16Converter.fromString(text);
case "utf16le":
case "usc2":
return Utf16Converter.fromString(text, true);
default:
throw new Error(`Unknown type of encoding '${encoding}'`);
}
}
static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) {
switch (encoding) {
case "ascii":
return this.ToBinary(buffer);
case "utf8":
return Utf8Converter.toString(buffer);
case "utf16":
case "utf16be":
return Utf16Converter.toString(buffer);
case "utf16le":
case "usc2":
return Utf16Converter.toString(buffer, true);
default:
throw new Error(`Unknown type of encoding '${encoding}'`);
}
}
static FromBinary(text) {
const stringLength = text.length;
const resultView = new Uint8Array(stringLength);
for (let i = 0; i < stringLength; i++) {
resultView[i] = text.charCodeAt(i);
}
return resultView.buffer;
}
static ToBinary(buffer) {
const buf = BufferSourceConverter.toUint8Array(buffer);
let res = "";
for (let i = 0; i < buf.length; i++) {
res += String.fromCharCode(buf[i]);
}
return res;
}
static ToHex(buffer) {
const buf = BufferSourceConverter.toUint8Array(buffer);
let result = "";
const len = buf.length;
for (let i = 0; i < len; i++) {
const byte = buf[i];
if (byte < 16) {
result += "0";
}
result += byte.toString(16);
}
return result;
}
static FromHex(hexString) {
let formatted = this.formatString(hexString);
if (!formatted) {
return new ArrayBuffer(0);
}
if (!Convert.isHex(formatted)) {
throw new TypeError("Argument 'hexString' is not HEX encoded");
}
if (formatted.length % 2) {
formatted = `0${formatted}`;
}
const res = new Uint8Array(formatted.length / 2);
for (let i = 0; i < formatted.length; i = i + 2) {
const c = formatted.slice(i, i + 2);
res[i / 2] = parseInt(c, 16);
}
return res.buffer;
}
static ToUtf16String(buffer, littleEndian = false) {
return Utf16Converter.toString(buffer, littleEndian);
}
static FromUtf16String(text, littleEndian = false) {
return Utf16Converter.fromString(text, littleEndian);
}
static Base64Padding(base64) {
const padCount = 4 - (base64.length % 4);
if (padCount < 4) {
for (let i = 0; i < padCount; i++) {
base64 += "=";
}
}
return base64;
}
static formatString(data) {
return (data === null || data === void 0 ? void 0 : data.replace(/[\n\r\t ]/g, "")) || "";
}
}
Convert.DEFAULT_UTF8_ENCODING = "utf8";
function assign(target, ...sources) {
const res = arguments[0];
for (let i = 1; i < arguments.length; i++) {
const obj = arguments[i];
for (const prop in obj) {
res[prop] = obj[prop];
}
}
return res;
}
function combine(...buf) {
const totalByteLength = buf.map((item) => item.byteLength).reduce((prev, cur) => prev + cur);
const res = new Uint8Array(totalByteLength);
let currentPos = 0;
buf.map((item) => new Uint8Array(item)).forEach((arr) => {
for (const item2 of arr) {
res[currentPos++] = item2;
}
});
return res.buffer;
}
function isEqual(bytes1, bytes2) {
if (!(bytes1 && bytes2)) {
return false;
}
if (bytes1.byteLength !== bytes2.byteLength) {
return false;
}
const b1 = new Uint8Array(bytes1);
const b2 = new Uint8Array(bytes2);
for (let i = 0; i < bytes1.byteLength; i++) {
if (b1[i] !== b2[i]) {
return false;
}
}
return true;
}
exports.BufferSourceConverter = BufferSourceConverter;
exports.Convert = Convert;
exports.assign = assign;
exports.combine = combine;
exports.isEqual = isEqual;
/***/ }),
/***/ "./node_modules/pvutils/build/utils.es.js":
/*!************************************************!*\
!*** ./node_modules/pvutils/build/utils.es.js ***!
\************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ arrayBufferToString: () => (/* binding */ arrayBufferToString),
/* harmony export */ bufferToHexCodes: () => (/* binding */ bufferToHexCodes),
/* harmony export */ checkBufferParams: () => (/* binding */ checkBufferParams),
/* harmony export */ clearProps: () => (/* binding */ clearProps),
/* harmony export */ fromBase64: () => (/* binding */ fromBase64),
/* harmony export */ getParametersValue: () => (/* binding */ getParametersValue),
/* harmony export */ getUTCDate: () => (/* binding */ getUTCDate),
/* harmony export */ isEqualBuffer: () => (/* binding */ isEqualBuffer),
/* harmony export */ nearestPowerOf2: () => (/* binding */ nearestPowerOf2),
/* harmony export */ padNumber: () => (/* binding */ padNumber),
/* harmony export */ stringToArrayBuffer: () => (/* binding */ stringToArrayBuffer),
/* harmony export */ toBase64: () => (/* binding */ toBase64),
/* harmony export */ utilConcatBuf: () => (/* binding */ utilConcatBuf),
/* harmony export */ utilConcatView: () => (/* binding */ utilConcatView),
/* harmony export */ utilDecodeTC: () => (/* binding */ utilDecodeTC),
/* harmony export */ utilEncodeTC: () => (/* binding */ utilEncodeTC),
/* harmony export */ utilFromBase: () => (/* binding */ utilFromBase),
/* harmony export */ utilToBase: () => (/* binding */ utilToBase)
/* harmony export */ });
/*!
Copyright (c) Peculiar Ventures, LLC
*/
function getUTCDate(date) {
return new Date(date.getTime() + (date.getTimezoneOffset() * 60000));
}
function getParametersValue(parameters, name, defaultValue) {
var _a;
if ((parameters instanceof Object) === false) {
return defaultValue;
}
return (_a = parameters[name]) !== null && _a !== void 0 ? _a : defaultValue;
}
function bufferToHexCodes(inputBuffer, inputOffset = 0, inputLength = (inputBuffer.byteLength - inputOffset), insertSpace = false) {
let result = "";
for (const item of (new Uint8Array(inputBuffer, inputOffset, inputLength))) {
const str = item.toString(16).toUpperCase();
if (str.length === 1) {
result += "0";
}
result += str;
if (insertSpace) {
result += " ";
}
}
return result.trim();
}
function checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {
if (!(inputBuffer instanceof ArrayBuffer)) {
baseBlock.error = "Wrong parameter: inputBuffer must be \"ArrayBuffer\"";
return false;
}
if (!inputBuffer.byteLength) {
baseBlock.error = "Wrong parameter: inputBuffer has zero length";
return false;
}
if (inputOffset < 0) {
baseBlock.error = "Wrong parameter: inputOffset less than zero";
return false;
}
if (inputLength < 0) {
baseBlock.error = "Wrong parameter: inputLength less than zero";
return false;
}
if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {
baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)";
return false;
}
return true;
}
function utilFromBase(inputBuffer, inputBase) {
let result = 0;
if (inputBuffer.length === 1) {
return inputBuffer[0];
}
for (let i = (inputBuffer.length - 1); i >= 0; i--) {
result += inputBuffer[(inputBuffer.length - 1) - i] * Math.pow(2, inputBase * i);
}
return result;
}
function utilToBase(value, base, reserved = (-1)) {
const internalReserved = reserved;
let internalValue = value;
let result = 0;
let biggest = Math.pow(2, base);
for (let i = 1; i < 8; i++) {
if (value < biggest) {
let retBuf;
if (internalReserved < 0) {
retBuf = new ArrayBuffer(i);
result = i;
}
else {
if (internalReserved < i) {
return (new ArrayBuffer(0));
}
retBuf = new ArrayBuffer(internalReserved);
result = internalReserved;
}
const retView = new Uint8Array(retBuf);
for (let j = (i - 1); j >= 0; j--) {
const basis = Math.pow(2, j * base);
retView[result - j - 1] = Math.floor(internalValue / basis);
internalValue -= (retView[result - j - 1]) * basis;
}
return retBuf;
}
biggest *= Math.pow(2, base);
}
return new ArrayBuffer(0);
}
function utilConcatBuf(...buffers) {
let outputLength = 0;
let prevLength = 0;
for (const buffer of buffers) {
outputLength += buffer.byteLength;
}
const retBuf = new ArrayBuffer(outputLength);
const retView = new Uint8Array(retBuf);
for (const buffer of buffers) {
retView.set(new Uint8Array(buffer), prevLength);
prevLength += buffer.byteLength;
}
return retBuf;
}
function utilConcatView(...views) {
let outputLength = 0;
let prevLength = 0;
for (const view of views) {
outputLength += view.length;
}
const retBuf = new ArrayBuffer(outputLength);
const retView = new Uint8Array(retBuf);
for (const view of views) {
retView.set(view, prevLength);
prevLength += view.length;
}
return retView;
}
function utilDecodeTC() {
const buf = new Uint8Array(this.valueHex);
if (this.valueHex.byteLength >= 2) {
const condition1 = (buf[0] === 0xFF) && (buf[1] & 0x80);
const condition2 = (buf[0] === 0x00) && ((buf[1] & 0x80) === 0x00);
if (condition1 || condition2) {
this.warnings.push("Needlessly long format");
}
}
const bigIntBuffer = new ArrayBuffer(this.valueHex.byteLength);
const bigIntView = new Uint8Array(bigIntBuffer);
for (let i = 0; i < this.valueHex.byteLength; i++) {
bigIntView[i] = 0;
}
bigIntView[0] = (buf[0] & 0x80);
const bigInt = utilFromBase(bigIntView, 8);
const smallIntBuffer = new ArrayBuffer(this.valueHex.byteLength);
const smallIntView = new Uint8Array(smallIntBuffer);
for (let j = 0; j < this.valueHex.byteLength; j++) {
smallIntView[j] = buf[j];
}
smallIntView[0] &= 0x7F;
const smallInt = utilFromBase(smallIntView, 8);
return (smallInt - bigInt);
}
function utilEncodeTC(value) {
const modValue = (value < 0) ? (value * (-1)) : value;
let bigInt = 128;
for (let i = 1; i < 8; i++) {
if (modValue <= bigInt) {
if (value < 0) {
const smallInt = bigInt - modValue;
const retBuf = utilToBase(smallInt, 8, i);
const retView = new Uint8Array(retBuf);
retView[0] |= 0x80;
return retBuf;
}
let retBuf = utilToBase(modValue, 8, i);
let retView = new Uint8Array(retBuf);
if (retView[0] & 0x80) {
const tempBuf = retBuf.slice(0);
const tempView = new Uint8Array(tempBuf);
retBuf = new ArrayBuffer(retBuf.byteLength + 1);
retView = new Uint8Array(retBuf);
for (let k = 0; k < tempBuf.byteLength; k++) {
retView[k + 1] = tempView[k];
}
retView[0] = 0x00;
}
return retBuf;
}
bigInt *= Math.pow(2, 8);
}
return (new ArrayBuffer(0));
}
function isEqualBuffer(inputBuffer1, inputBuffer2) {
if (inputBuffer1.byteLength !== inputBuffer2.byteLength) {
return false;
}
const view1 = new Uint8Array(inputBuffer1);
const view2 = new Uint8Array(inputBuffer2);
for (let i = 0; i < view1.length; i++) {
if (view1[i] !== view2[i]) {
return false;
}
}
return true;
}
function padNumber(inputNumber, fullLength) {
const str = inputNumber.toString(10);
if (fullLength < str.length) {
return "";
}
const dif = fullLength - str.length;
const padding = new Array(dif);
for (let i = 0; i < dif; i++) {
padding[i] = "0";
}
const paddingString = padding.join("");
return paddingString.concat(str);
}
const base64Template = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
const base64UrlTemplate = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";
function toBase64(input, useUrlTemplate = false, skipPadding = false, skipLeadingZeros = false) {
let i = 0;
let flag1 = 0;
let flag2 = 0;
let output = "";
const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;
if (skipLeadingZeros) {
let nonZeroPosition = 0;
for (let i = 0; i < input.length; i++) {
if (input.charCodeAt(i) !== 0) {
nonZeroPosition = i;
break;
}
}
input = input.slice(nonZeroPosition);
}
while (i < input.length) {
const chr1 = input.charCodeAt(i++);
if (i >= input.length) {
flag1 = 1;
}
const chr2 = input.charCodeAt(i++);
if (i >= input.length) {
flag2 = 1;
}
const chr3 = input.charCodeAt(i++);
const enc1 = chr1 >> 2;
const enc2 = ((chr1 & 0x03) << 4) | (chr2 >> 4);
let enc3 = ((chr2 & 0x0F) << 2) | (chr3 >> 6);
let enc4 = chr3 & 0x3F;
if (flag1 === 1) {
enc3 = enc4 = 64;
}
else {
if (flag2 === 1) {
enc4 = 64;
}
}
if (skipPadding) {
if (enc3 === 64) {
output += `${template.charAt(enc1)}${template.charAt(enc2)}`;
}
else {
if (enc4 === 64) {
output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}`;
}
else {
output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;
}
}
}
else {
output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;
}
}
return output;
}
function fromBase64(input, useUrlTemplate = false, cutTailZeros = false) {
const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;
function indexOf(toSearch) {
for (let i = 0; i < 64; i++) {
if (template.charAt(i) === toSearch)
return i;
}
return 64;
}
function test(incoming) {
return ((incoming === 64) ? 0x00 : incoming);
}
let i = 0;
let output = "";
while (i < input.length) {
const enc1 = indexOf(input.charAt(i++));
const enc2 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));
const enc3 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));
const enc4 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));
const chr1 = (test(enc1) << 2) | (test(enc2) >> 4);
const chr2 = ((test(enc2) & 0x0F) << 4) | (test(enc3) >> 2);
const chr3 = ((test(enc3) & 0x03) << 6) | test(enc4);
output += String.fromCharCode(chr1);
if (enc3 !== 64) {
output += String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output += String.fromCharCode(chr3);
}
}
if (cutTailZeros) {
const outputLength = output.length;
let nonZeroStart = (-1);
for (let i = (outputLength - 1); i >= 0; i--) {
if (output.charCodeAt(i) !== 0) {
nonZeroStart = i;
break;
}
}
if (nonZeroStart !== (-1)) {
output = output.slice(0, nonZeroStart + 1);
}
else {
output = "";
}
}
return output;
}
function arrayBufferToString(buffer) {
let resultString = "";
const view = new Uint8Array(buffer);
for (const element of view) {
resultString += String.fromCharCode(element);
}
return resultString;
}
function stringToArrayBuffer(str) {
const stringLength = str.length;
const resultBuffer = new ArrayBuffer(stringLength);
const resultView = new Uint8Array(resultBuffer);
for (let i = 0; i < stringLength; i++) {
resultView[i] = str.charCodeAt(i);
}
return resultBuffer;
}
const log2 = Math.log(2);
function nearestPowerOf2(length) {
const base = (Math.log(length) / log2);
const floor = Math.floor(base);
const round = Math.round(base);
return ((floor === round) ? floor : round);
}
function clearProps(object, propsArray) {
for (const prop of propsArray) {
delete object[prop];
}
}
/***/ }),
/***/ "./node_modules/queue-microtask/index.js":
/*!***********************************************!*\
!*** ./node_modules/queue-microtask/index.js ***!
\***********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
let promise
module.exports = typeof queueMicrotask === 'function'
? queueMicrotask.bind(typeof window !== 'undefined' ? window : __webpack_require__.g)
// reuse resolved promise, and allocate it lazily
: cb => (promise || (promise = Promise.resolve()))
.then(cb)
.catch(err => setTimeout(() => { throw err }, 0))
/***/ }),
/***/ "./node_modules/retimer/retimer.js":
/*!*****************************************!*\
!*** ./node_modules/retimer/retimer.js ***!
\*****************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
const getTime = __webpack_require__(/*! ./time */ "./node_modules/retimer/time-browser.js")
class Retimer {
constructor (callback, timeout, args) {
const that = this
this._started = getTime()
this._rescheduled = 0
this._scheduled = timeout
this._args = args
this._triggered = false
this._timerWrapper = () => {
if (that._rescheduled > 0) {
that._scheduled = that._rescheduled - (getTime() - that._started)
that._schedule(that._scheduled)
} else {
that._triggered = true
callback.apply(null, that._args)
}
}
this._timer = setTimeout(this._timerWrapper, timeout)
}
reschedule (timeout) {
if (!timeout) {
timeout = this._scheduled
}
const now = getTime()
if ((now + timeout) - (this._started + this._scheduled) < 0) {
clearTimeout(this._timer)
this._schedule(timeout)
} else if (!this._triggered) {
this._started = now
this._rescheduled = timeout
} else {
this._schedule(timeout)
}
}
_schedule (timeout) {
this._triggered = false
this._started = getTime()
this._rescheduled = 0
this._scheduled = timeout
this._timer = setTimeout(this._timerWrapper, timeout)
}
clear () {
clearTimeout(this._timer)
}
}
function retimer () {
if (typeof arguments[0] !== 'function') {
throw new Error('callback needed')
}
if (typeof arguments[1] !== 'number') {
throw new Error('timeout needed')
}
let args
if (arguments.length > 0) {
args = new Array(arguments.length - 2)
/* eslint-disable no-var */
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i + 2]
}
}
return new Retimer(arguments[0], arguments[1], args)
}
module.exports = retimer
/***/ }),
/***/ "./node_modules/retimer/time-browser.js":
/*!**********************************************!*\
!*** ./node_modules/retimer/time-browser.js ***!
\**********************************************/
/***/ ((module) => {
"use strict";
module.exports = function getTime () {
return Date.now()
}
/***/ }),
/***/ "./node_modules/run-parallel-limit/index.js":
/*!**************************************************!*\
!*** ./node_modules/run-parallel-limit/index.js ***!
\**************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
/*! run-parallel-limit. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
module.exports = runParallelLimit
const queueMicrotask = __webpack_require__(/*! queue-microtask */ "./node_modules/queue-microtask/index.js")
function runParallelLimit (tasks, limit, cb) {
if (typeof limit !== 'number') throw new Error('second argument must be a Number')
let results, len, pending, keys, isErrored
let isSync = true
let next
if (Array.isArray(tasks)) {
results = []
pending = len = tasks.length
} else {
keys = Object.keys(tasks)
results = {}
pending = len = keys.length
}
function done (err) {
function end () {
if (cb) cb(err, results)
cb = null
}
if (isSync) queueMicrotask(end)
else end()
}
function each (i, err, result) {
results[i] = result
if (err) isErrored = true
if (--pending === 0 || err) {
done(err)
} else if (!isErrored && next < len) {
let key
if (keys) {
key = keys[next]
next += 1
tasks[key](function (err, result) { each(key, err, result) })
} else {
key = next
next += 1
tasks[key](function (err, result) { each(key, err, result) })
}
}
}
next = limit
if (!pending) {
// empty
done(null)
} else if (keys) {
// object
keys.some(function (key, i) {
tasks[key](function (err, result) { each(key, err, result) })
if (i === limit - 1) return true // early return
return false
})
} else {
// array
tasks.some(function (task, i) {
task(function (err, result) { each(i, err, result) })
if (i === limit - 1) return true // early return
return false
})
}
isSync = false
}
/***/ }),
/***/ "./node_modules/timeout-abort-controller/index.js":
/*!********************************************************!*\
!*** ./node_modules/timeout-abort-controller/index.js ***!
\********************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
const { AbortController } = globalThis
// @ts-expect-error no types
const retimer = __webpack_require__(/*! retimer */ "./node_modules/retimer/retimer.js")
class TimeoutController extends AbortController {
/**
* @constructor
* @param {number} ms milliseconds
*/
constructor (ms) {
super()
this._ms = ms
this._timer = retimer(() => this.abort(), ms)
// Patch for safari not supported extending built in classes
Object.setPrototypeOf(this, TimeoutController.prototype)
}
/**
* Aborts the controller and clears the timer
*/
abort () {
this._timer.clear()
return super.abort()
}
/**
* Clears the timer
*/
clear () {
this._timer.clear()
}
/**
* Resets the timer
*/
reset () {
this._timer.clear()
this._timer = retimer(() => this.abort(), this._ms)
}
}
module.exports = {
TimeoutController
}
/***/ }),
/***/ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bases/base.js":
/*!**************************************************************************************!*\
!*** ./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bases/base.js ***!
\**************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Codec: () => (/* binding */ Codec),
/* harmony export */ baseX: () => (/* binding */ baseX),
/* harmony export */ from: () => (/* binding */ from),
/* harmony export */ or: () => (/* binding */ or),
/* harmony export */ rfc4648: () => (/* binding */ rfc4648)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/vendor/base-x.js");
/**
* Class represents both BaseEncoder and MultibaseEncoder meaning it
* can be used to encode to multibase or base encode without multibase
* prefix.
*/
class Encoder {
name;
prefix;
baseEncode;
constructor(name, prefix, baseEncode) {
this.name = name;
this.prefix = prefix;
this.baseEncode = baseEncode;
}
encode(bytes) {
if (bytes instanceof Uint8Array) {
return `${this.prefix}${this.baseEncode(bytes)}`;
}
else {
throw Error('Unknown type, must be binary type');
}
}
}
/**
* Class represents both BaseDecoder and MultibaseDecoder so it could be used
* to decode multibases (with matching prefix) or just base decode strings
* with corresponding base encoding.
*/
class Decoder {
name;
prefix;
baseDecode;
prefixCodePoint;
constructor(name, prefix, baseDecode) {
this.name = name;
this.prefix = prefix;
/* c8 ignore next 3 */
if (prefix.codePointAt(0) === undefined) {
throw new Error('Invalid prefix character');
}
this.prefixCodePoint = prefix.codePointAt(0);
this.baseDecode = baseDecode;
}
decode(text) {
if (typeof text === 'string') {
if (text.codePointAt(0) !== this.prefixCodePoint) {
throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
}
return this.baseDecode(text.slice(this.prefix.length));
}
else {
throw Error('Can only multibase decode strings');
}
}
or(decoder) {
return or(this, decoder);
}
}
class ComposedDecoder {
decoders;
constructor(decoders) {
this.decoders = decoders;
}
or(decoder) {
return or(this, decoder);
}
decode(input) {
const prefix = input[0];
const decoder = this.decoders[prefix];
if (decoder != null) {
return decoder.decode(input);
}
else {
throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
}
}
}
function or(left, right) {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return new ComposedDecoder({
...(left.decoders ?? { [left.prefix]: left }),
...(right.decoders ?? { [right.prefix]: right })
});
}
class Codec {
name;
prefix;
baseEncode;
baseDecode;
encoder;
decoder;
constructor(name, prefix, baseEncode, baseDecode) {
this.name = name;
this.prefix = prefix;
this.baseEncode = baseEncode;
this.baseDecode = baseDecode;
this.encoder = new Encoder(name, prefix, baseEncode);
this.decoder = new Decoder(name, prefix, baseDecode);
}
encode(input) {
return this.encoder.encode(input);
}
decode(input) {
return this.decoder.decode(input);
}
}
function from({ name, prefix, encode, decode }) {
return new Codec(name, prefix, encode, decode);
}
function baseX({ name, prefix, alphabet }) {
const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__["default"])(alphabet, name);
return from({
prefix,
name,
encode,
decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))
});
}
function decode(string, alphabet, bitsPerChar, name) {
// Build the character lookup table:
const codes = {};
for (let i = 0; i < alphabet.length; ++i) {
codes[alphabet[i]] = i;
}
// Count the padding bytes:
let end = string.length;
while (string[end - 1] === '=') {
--end;
}
// Allocate the output:
const out = new Uint8Array((end * bitsPerChar / 8) | 0);
// Parse the data:
let bits = 0; // Number of bits currently in the buffer
let buffer = 0; // Bits waiting to be written out, MSB first
let written = 0; // Next byte to write
for (let i = 0; i < end; ++i) {
// Read one character from the string:
const value = codes[string[i]];
if (value === undefined) {
throw new SyntaxError(`Non-${name} character`);
}
// Append the bits to the buffer:
buffer = (buffer << bitsPerChar) | value;
bits += bitsPerChar;
// Write out some bits if the buffer has a byte's worth:
if (bits >= 8) {
bits -= 8;
out[written++] = 0xff & (buffer >> bits);
}
}
// Verify that we have received just enough bits:
if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
throw new SyntaxError('Unexpected end of data');
}
return out;
}
function encode(data, alphabet, bitsPerChar) {
const pad = alphabet[alphabet.length - 1] === '=';
const mask = (1 << bitsPerChar) - 1;
let out = '';
let bits = 0; // Number of bits currently in the buffer
let buffer = 0; // Bits waiting to be written out, MSB first
for (let i = 0; i < data.length; ++i) {
// Slurp data into the buffer:
buffer = (buffer << 8) | data[i];
bits += 8;
// Write out as much as we can:
while (bits > bitsPerChar) {
bits -= bitsPerChar;
out += alphabet[mask & (buffer >> bits)];
}
}
// Partial character:
if (bits !== 0) {
out += alphabet[mask & (buffer << (bitsPerChar - bits))];
}
// Add padding characters until we hit a byte boundary:
if (pad) {
while (((out.length * bitsPerChar) & 7) !== 0) {
out += '=';
}
}
return out;
}
/**
* RFC4648 Factory
*/
function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
return from({
prefix,
name,
encode(input) {
return encode(input, alphabet, bitsPerChar);
},
decode(input) {
return decode(input, alphabet, bitsPerChar, name);
}
});
}
//# sourceMappingURL=base.js.map
/***/ }),
/***/ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bases/base32.js":
/*!****************************************************************************************!*\
!*** ./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bases/base32.js ***!
\****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base32: () => (/* binding */ base32),
/* harmony export */ base32hex: () => (/* binding */ base32hex),
/* harmony export */ base32hexpad: () => (/* binding */ base32hexpad),
/* harmony export */ base32hexpadupper: () => (/* binding */ base32hexpadupper),
/* harmony export */ base32hexupper: () => (/* binding */ base32hexupper),
/* harmony export */ base32pad: () => (/* binding */ base32pad),
/* harmony export */ base32padupper: () => (/* binding */ base32padupper),
/* harmony export */ base32upper: () => (/* binding */ base32upper),
/* harmony export */ base32z: () => (/* binding */ base32z)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bases/base.js");
const base32 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'b',
name: 'base32',
alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
bitsPerChar: 5
});
const base32upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'B',
name: 'base32upper',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
bitsPerChar: 5
});
const base32pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'c',
name: 'base32pad',
alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
bitsPerChar: 5
});
const base32padupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'C',
name: 'base32padupper',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
bitsPerChar: 5
});
const base32hex = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'v',
name: 'base32hex',
alphabet: '0123456789abcdefghijklmnopqrstuv',
bitsPerChar: 5
});
const base32hexupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'V',
name: 'base32hexupper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
bitsPerChar: 5
});
const base32hexpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 't',
name: 'base32hexpad',
alphabet: '0123456789abcdefghijklmnopqrstuv=',
bitsPerChar: 5
});
const base32hexpadupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'T',
name: 'base32hexpadupper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
bitsPerChar: 5
});
const base32z = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'h',
name: 'base32z',
alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
bitsPerChar: 5
});
//# sourceMappingURL=base32.js.map
/***/ }),
/***/ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bases/base58.js":
/*!****************************************************************************************!*\
!*** ./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bases/base58.js ***!
\****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base58btc: () => (/* binding */ base58btc),
/* harmony export */ base58flickr: () => (/* binding */ base58flickr)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bases/base.js");
const base58btc = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
name: 'base58btc',
prefix: 'z',
alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
const base58flickr = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
name: 'base58flickr',
prefix: 'Z',
alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.map
/***/ }),
/***/ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bytes.js":
/*!*********************************************************************************!*\
!*** ./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bytes.js ***!
\*********************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ coerce: () => (/* binding */ coerce),
/* harmony export */ empty: () => (/* binding */ empty),
/* harmony export */ equals: () => (/* binding */ equals),
/* harmony export */ fromHex: () => (/* binding */ fromHex),
/* harmony export */ fromString: () => (/* binding */ fromString),
/* harmony export */ isBinary: () => (/* binding */ isBinary),
/* harmony export */ toHex: () => (/* binding */ toHex),
/* harmony export */ toString: () => (/* binding */ toString)
/* harmony export */ });
const empty = new Uint8Array(0);
function toHex(d) {
return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
function fromHex(hex) {
const hexes = hex.match(/../g);
return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
function equals(aa, bb) {
if (aa === bb)
return true;
if (aa.byteLength !== bb.byteLength) {
return false;
}
for (let ii = 0; ii < aa.byteLength; ii++) {
if (aa[ii] !== bb[ii]) {
return false;
}
}
return true;
}
function coerce(o) {
if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')
return o;
if (o instanceof ArrayBuffer)
return new Uint8Array(o);
if (ArrayBuffer.isView(o)) {
return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
}
throw new Error('Unknown type, must be binary type');
}
function isBinary(o) {
return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
function fromString(str) {
return new TextEncoder().encode(str);
}
function toString(b) {
return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.map
/***/ }),
/***/ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/cid.js":
/*!*******************************************************************************!*\
!*** ./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/cid.js ***!
\*******************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CID: () => (/* binding */ CID),
/* harmony export */ format: () => (/* binding */ format),
/* harmony export */ fromJSON: () => (/* binding */ fromJSON),
/* harmony export */ toJSON: () => (/* binding */ toJSON)
/* harmony export */ });
/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bases/base32.js");
/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bases/base58.js");
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/hashes/digest.js");
/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/varint.js");
/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/link/interface.js");
// This way TS will also expose all the types from module
function format(link, base) {
const { bytes, version } = link;
switch (version) {
case 0:
return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);
default:
return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));
}
}
function toJSON(link) {
return {
'/': format(link)
};
}
function fromJSON(json) {
return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
const baseCache = cache.get(cid);
if (baseCache == null) {
const baseCache = new Map();
cache.set(cid, baseCache);
return baseCache;
}
return baseCache;
}
class CID {
code;
version;
multihash;
bytes;
'/';
/**
* @param version - Version of the CID
* @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
* @param multihash - (Multi)hash of the of the content.
*/
constructor(version, code, multihash, bytes) {
this.code = code;
this.version = version;
this.multihash = multihash;
this.bytes = bytes;
// flag to serializers that this is a CID and
// should be treated specially
this['/'] = bytes;
}
/**
* Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
* please either use `CID.asCID(cid)` or switch to new signalling mechanism
*
* @deprecated
*/
get asCID() {
return this;
}
// ArrayBufferView
get byteOffset() {
return this.bytes.byteOffset;
}
// ArrayBufferView
get byteLength() {
return this.bytes.byteLength;
}
toV0() {
switch (this.version) {
case 0: {
return this;
}
case 1: {
const { code, multihash } = this;
if (code !== DAG_PB_CODE) {
throw new Error('Cannot convert a non dag-pb CID to CIDv0');
}
// sha2-256
if (multihash.code !== SHA_256_CODE) {
throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
}
return (CID.createV0(multihash));
}
default: {
throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
}
}
}
toV1() {
switch (this.version) {
case 0: {
const { code, digest } = this.multihash;
const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);
return (CID.createV1(this.code, multihash));
}
case 1: {
return this;
}
default: {
throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
}
}
}
equals(other) {
return CID.equals(this, other);
}
static equals(self, other) {
const unknown = other;
return (unknown != null &&
self.code === unknown.code &&
self.version === unknown.version &&
_hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));
}
toString(base) {
return format(this, base);
}
toJSON() {
return { '/': format(this) };
}
link() {
return this;
}
[Symbol.toStringTag] = 'CID';
// Legacy
[Symbol.for('nodejs.util.inspect.custom')]() {
return `CID(${this.toString()})`;
}
/**
* Takes any input `value` and returns a `CID` instance if it was
* a `CID` otherwise returns `null`. If `value` is instanceof `CID`
* it will return value back. If `value` is not instance of this CID
* class, but is compatible CID it will return new instance of this
* `CID` class. Otherwise returns null.
*
* This allows two different incompatible versions of CID library to
* co-exist and interop as long as binary interface is compatible.
*/
static asCID(input) {
if (input == null) {
return null;
}
const value = input;
if (value instanceof CID) {
// If value is instance of CID then we're all set.
return value;
}
else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
// If value isn't instance of this CID class but `this.asCID === this` or
// `value['/'] === value.bytes` is true it is CID instance coming from a
// different implementation (diff version or duplicate). In that case we
// rebase it to this `CID` implementation so caller is guaranteed to get
// instance with expected API.
const { version, code, multihash, bytes } = value;
return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
}
else if (value[cidSymbol] === true) {
// If value is a CID from older implementation that used to be tagged via
// symbol we still rebase it to the this `CID` implementation by
// delegating that to a constructor.
const { version, multihash, code } = value;
const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);
return CID.create(version, code, digest);
}
else {
// Otherwise value is not a CID (or an incompatible version of it) in
// which case we return `null`.
return null;
}
}
/**
* @param version - Version of the CID
* @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
* @param digest - (Multi)hash of the of the content.
*/
static create(version, code, digest) {
if (typeof code !== 'number') {
throw new Error('String codecs are no longer supported');
}
if (!(digest.bytes instanceof Uint8Array)) {
throw new Error('Invalid digest');
}
switch (version) {
case 0: {
if (code !== DAG_PB_CODE) {
throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
}
else {
return new CID(version, code, digest, digest.bytes);
}
}
case 1: {
const bytes = encodeCID(version, code, digest.bytes);
return new CID(version, code, digest, bytes);
}
default: {
throw new Error('Invalid version');
}
}
}
/**
* Simplified version of `create` for CIDv0.
*/
static createV0(digest) {
return CID.create(0, DAG_PB_CODE, digest);
}
/**
* Simplified version of `create` for CIDv1.
*
* @param code - Content encoding format code.
* @param digest - Multihash of the content.
*/
static createV1(code, digest) {
return CID.create(1, code, digest);
}
/**
* Decoded a CID from its binary representation. The byte array must contain
* only the CID with no additional bytes.
*
* An error will be thrown if the bytes provided do not contain a valid
* binary representation of a CID.
*/
static decode(bytes) {
const [cid, remainder] = CID.decodeFirst(bytes);
if (remainder.length !== 0) {
throw new Error('Incorrect length');
}
return cid;
}
/**
* Decoded a CID from its binary representation at the beginning of a byte
* array.
*
* Returns an array with the first element containing the CID and the second
* element containing the remainder of the original byte array. The remainder
* will be a zero-length byte array if the provided bytes only contained a
* binary CID representation.
*/
static decodeFirst(bytes) {
const specs = CID.inspectBytes(bytes);
const prefixSize = specs.size - specs.multihashSize;
const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
if (multihashBytes.byteLength !== specs.multihashSize) {
throw new Error('Incorrect length');
}
const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
const cid = specs.version === 0
? CID.createV0(digest)
: CID.createV1(specs.codec, digest);
return [cid, bytes.subarray(specs.size)];
}
/**
* Inspect the initial bytes of a CID to determine its properties.
*
* Involves decoding up to 4 varints. Typically this will require only 4 to 6
* bytes but for larger multicodec code values and larger multihash digest
* lengths these varints can be quite large. It is recommended that at least
* 10 bytes be made available in the `initialBytes` argument for a complete
* inspection.
*/
static inspectBytes(initialBytes) {
let offset = 0;
const next = () => {
const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));
offset += length;
return i;
};
let version = next();
let codec = DAG_PB_CODE;
if (version === 18) {
// CIDv0
version = 0;
offset = 0;
}
else {
codec = next();
}
if (version !== 0 && version !== 1) {
throw new RangeError(`Invalid CID version ${version}`);
}
const prefixSize = offset;
const multihashCode = next(); // multihash code
const digestSize = next(); // multihash length
const size = offset + digestSize;
const multihashSize = size - prefixSize;
return { version, codec, multihashCode, digestSize, multihashSize, size };
}
/**
* Takes cid in a string representation and creates an instance. If `base`
* decoder is not provided will use a default from the configuration. It will
* throw an error if encoding of the CID is not compatible with supplied (or
* a default decoder).
*/
static parse(source, base) {
const [prefix, bytes] = parseCIDtoBytes(source, base);
const cid = CID.decode(bytes);
if (cid.version === 0 && source[0] !== 'Q') {
throw Error('Version 0 CID string must not include multibase prefix');
}
// Cache string representation to avoid computing it on `this.toString()`
baseCache(cid).set(prefix, source);
return cid;
}
}
function parseCIDtoBytes(source, base) {
switch (source[0]) {
// CIDv0 is parsed differently
case 'Q': {
const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;
return [
_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,
decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)
];
}
case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {
const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;
return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];
}
case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {
const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;
return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];
}
default: {
if (base == null) {
throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');
}
return [source[0], base.decode(source)];
}
}
}
function toStringV0(bytes, cache, base) {
const { prefix } = base;
if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {
throw Error(`Cannot string encode V0 in ${base.name} encoding`);
}
const cid = cache.get(prefix);
if (cid == null) {
const cid = base.encode(bytes).slice(1);
cache.set(prefix, cid);
return cid;
}
else {
return cid;
}
}
function toStringV1(bytes, cache, base) {
const { prefix } = base;
const cid = cache.get(prefix);
if (cid == null) {
const cid = base.encode(bytes);
cache.set(prefix, cid);
return cid;
}
else {
return cid;
}
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);
const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);
const bytes = new Uint8Array(hashOffset + multihash.byteLength);
_varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);
_varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);
bytes.set(multihash, hashOffset);
return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.map
/***/ }),
/***/ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/hashes/digest.js":
/*!*****************************************************************************************!*\
!*** ./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/hashes/digest.js ***!
\*****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Digest: () => (/* binding */ Digest),
/* harmony export */ create: () => (/* binding */ create),
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ equals: () => (/* binding */ equals)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/varint.js");
/**
* Creates a multihash digest.
*/
function create(code, digest) {
const size = digest.byteLength;
const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);
const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);
const bytes = new Uint8Array(digestOffset + size);
_varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);
_varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);
bytes.set(digest, digestOffset);
return new Digest(code, size, digest, bytes);
}
/**
* Turns bytes representation of multihash digest into an instance.
*/
function decode(multihash) {
const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);
const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);
const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));
const digest = bytes.subarray(sizeOffset + digestOffset);
if (digest.byteLength !== size) {
throw new Error('Incorrect length');
}
return new Digest(code, size, digest, bytes);
}
function equals(a, b) {
if (a === b) {
return true;
}
else {
const data = b;
return (a.code === data.code &&
a.size === data.size &&
data.bytes instanceof Uint8Array &&
(0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));
}
}
/**
* Represents a multihash digest which carries information about the
* hashing algorithm and an actual hash digest.
*/
class Digest {
code;
size;
digest;
bytes;
/**
* Creates a multihash digest.
*/
constructor(code, size, digest, bytes) {
this.code = code;
this.size = size;
this.digest = digest;
this.bytes = bytes;
}
}
//# sourceMappingURL=digest.js.map
/***/ }),
/***/ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/link/interface.js":
/*!******************************************************************************************!*\
!*** ./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/link/interface.js ***!
\******************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* eslint-disable @typescript-eslint/no-unnecessary-type-constraint */
/* eslint-disable no-use-before-define */
//# sourceMappingURL=interface.js.map
/***/ }),
/***/ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/varint.js":
/*!**********************************************************************************!*\
!*** ./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/varint.js ***!
\**********************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ encodeTo: () => (/* binding */ encodeTo),
/* harmony export */ encodingLength: () => (/* binding */ encodingLength)
/* harmony export */ });
/* harmony import */ var _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vendor/varint.js */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/vendor/varint.js");
function decode(data, offset = 0) {
const code = _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].decode(data, offset);
return [code, _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].decode.bytes];
}
function encodeTo(int, target, offset = 0) {
_vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].encode(int, target, offset);
return target;
}
function encodingLength(int) {
return _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].encodingLength(int);
}
//# sourceMappingURL=varint.js.map
/***/ }),
/***/ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/vendor/base-x.js":
/*!*****************************************************************************************!*\
!*** ./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/vendor/base-x.js ***!
\*****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
* @param {string} ALPHABET
* @param {any} name
*/
function base(ALPHABET, name) {
if (ALPHABET.length >= 255) {
throw new TypeError('Alphabet too long');
}
var BASE_MAP = new Uint8Array(256);
for (var j = 0; j < BASE_MAP.length; j++) {
BASE_MAP[j] = 255;
}
for (var i = 0; i < ALPHABET.length; i++) {
var x = ALPHABET.charAt(i);
var xc = x.charCodeAt(0);
if (BASE_MAP[xc] !== 255) {
throw new TypeError(x + ' is ambiguous');
}
BASE_MAP[xc] = i;
}
var BASE = ALPHABET.length;
var LEADER = ALPHABET.charAt(0);
var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
/**
* @param {any[] | Iterable<number>} source
*/
function encode(source) {
// @ts-ignore
if (source instanceof Uint8Array)
;
else if (ArrayBuffer.isView(source)) {
source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
}
else if (Array.isArray(source)) {
source = Uint8Array.from(source);
}
if (!(source instanceof Uint8Array)) {
throw new TypeError('Expected Uint8Array');
}
if (source.length === 0) {
return '';
}
// Skip & count leading zeroes.
var zeroes = 0;
var length = 0;
var pbegin = 0;
var pend = source.length;
while (pbegin !== pend && source[pbegin] === 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
var b58 = new Uint8Array(size);
// Process the bytes.
while (pbegin !== pend) {
var carry = source[pbegin];
// Apply "b58 = b58 * 256 + ch".
var i = 0;
for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
carry += (256 * b58[it1]) >>> 0;
b58[it1] = (carry % BASE) >>> 0;
carry = (carry / BASE) >>> 0;
}
if (carry !== 0) {
throw new Error('Non-zero carry');
}
length = i;
pbegin++;
}
// Skip leading zeroes in base58 result.
var it2 = size - length;
while (it2 !== size && b58[it2] === 0) {
it2++;
}
// Translate the result into a string.
var str = LEADER.repeat(zeroes);
for (; it2 < size; ++it2) {
str += ALPHABET.charAt(b58[it2]);
}
return str;
}
/**
* @param {string | string[]} source
*/
function decodeUnsafe(source) {
if (typeof source !== 'string') {
throw new TypeError('Expected String');
}
if (source.length === 0) {
return new Uint8Array();
}
var psz = 0;
// Skip leading spaces.
if (source[psz] === ' ') {
return;
}
// Skip and count leading '1's.
var zeroes = 0;
var length = 0;
while (source[psz] === LEADER) {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
var b256 = new Uint8Array(size);
// Process the characters.
while (source[psz]) {
// Decode character
var carry = BASE_MAP[source.charCodeAt(psz)];
// Invalid character
if (carry === 255) {
return;
}
var i = 0;
for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
carry += (BASE * b256[it3]) >>> 0;
b256[it3] = (carry % 256) >>> 0;
carry = (carry / 256) >>> 0;
}
if (carry !== 0) {
throw new Error('Non-zero carry');
}
length = i;
psz++;
}
// Skip trailing spaces.
if (source[psz] === ' ') {
return;
}
// Skip leading zeroes in b256.
var it4 = size - length;
while (it4 !== size && b256[it4] === 0) {
it4++;
}
var vch = new Uint8Array(zeroes + (size - it4));
var j = zeroes;
while (it4 !== size) {
vch[j++] = b256[it4++];
}
return vch;
}
/**
* @param {string | string[]} string
*/
function decode(string) {
var buffer = decodeUnsafe(string);
if (buffer) {
return buffer;
}
throw new Error(`Non-${name} character`);
}
return {
encode: encode,
decodeUnsafe: decodeUnsafe,
decode: decode
};
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp__multiformats_scope_baseX);
//# sourceMappingURL=base-x.js.map
/***/ }),
/***/ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/vendor/varint.js":
/*!*****************************************************************************************!*\
!*** ./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/vendor/varint.js ***!
\*****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
* @param {number} num
* @param {number[]} out
* @param {number} offset
*/
function encode(num, out, offset) {
out = out || [];
offset = offset || 0;
var oldOffset = offset;
while (num >= INT) {
out[offset++] = (num & 0xFF) | MSB;
num /= 128;
}
while (num & MSBALL) {
out[offset++] = (num & 0xFF) | MSB;
num >>>= 7;
}
out[offset] = num | 0;
// @ts-ignore
encode.bytes = offset - oldOffset + 1;
return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
* @param {string | any[]} buf
* @param {number} offset
*/
function read(buf, offset) {
var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
do {
if (counter >= l) {
// @ts-ignore
read.bytes = 0;
throw new RangeError('Could not decode varint');
}
b = buf[counter++];
res += shift < 28
? (b & REST$1) << shift
: (b & REST$1) * Math.pow(2, shift);
shift += 7;
} while (b >= MSB$1);
// @ts-ignore
read.bytes = counter - offset;
return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
return (value < N1 ? 1
: value < N2 ? 2
: value < N3 ? 3
: value < N4 ? 4
: value < N5 ? 5
: value < N6 ? 6
: value < N7 ? 7
: value < N8 ? 8
: value < N9 ? 9
: 10);
};
var varint = {
encode: encode_1,
decode: decode,
encodingLength: length
};
var _brrp_varint = varint;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp_varint);
//# sourceMappingURL=varint.js.map
/***/ }),
/***/ "./node_modules/@ipld/dag-cbor/src/index.js":
/*!**************************************************!*\
!*** ./node_modules/@ipld/dag-cbor/src/index.js ***!
\**************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ code: () => (/* binding */ code),
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ decodeOptions: () => (/* binding */ decodeOptions),
/* harmony export */ encode: () => (/* binding */ encode),
/* harmony export */ encodeOptions: () => (/* binding */ encodeOptions),
/* harmony export */ name: () => (/* binding */ name),
/* harmony export */ toByteView: () => (/* binding */ toByteView)
/* harmony export */ });
/* harmony import */ var cborg__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cborg */ "./node_modules/cborg/cborg.js");
/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/cid */ "./node_modules/@ipld/dag-cbor/node_modules/multiformats/dist/src/cid.js");
// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42
/**
* @template T
* @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
*/
/**
* @template T
* @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
*/
/**
* @template T
* @param {ByteView<T> | ArrayBufferView<T>} buf
* @returns {ByteView<T>}
*/
function toByteView (buf) {
if (buf instanceof ArrayBuffer) {
return new Uint8Array(buf, 0, buf.byteLength)
}
return buf
}
/**
* cidEncoder will receive all Objects during encode, it needs to filter out
* anything that's not a CID and return `null` for that so it's encoded as
* normal.
*
* @param {any} obj
* @returns {cborg.Token[]|null}
*/
function cidEncoder (obj) {
if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
return null // any other kind of object
}
const cid = multiformats_cid__WEBPACK_IMPORTED_MODULE_1__.CID.asCID(obj)
/* c8 ignore next 4 */
// very unlikely case, and it'll probably throw a recursion error in cborg
if (!cid) {
return null
}
const bytes = new Uint8Array(cid.bytes.byteLength + 1)
bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
return [
new cborg__WEBPACK_IMPORTED_MODULE_0__.Token(cborg__WEBPACK_IMPORTED_MODULE_0__.Type.tag, CID_CBOR_TAG),
new cborg__WEBPACK_IMPORTED_MODULE_0__.Token(cborg__WEBPACK_IMPORTED_MODULE_0__.Type.bytes, bytes)
]
}
// eslint-disable-next-line jsdoc/require-returns-check
/**
* Intercept all `undefined` values from an object walk and reject the entire
* object if we find one.
*
* @returns {null}
*/
function undefinedEncoder () {
throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}
/**
* Intercept all `number` values from an object walk and reject the entire
* object if we find something that doesn't fit the IPLD data model (NaN &
* Infinity).
*
* @param {number} num
* @returns {null}
*/
function numberEncoder (num) {
if (Number.isNaN(num)) {
throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
}
if (num === Infinity || num === -Infinity) {
throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
}
return null
}
const _encodeOptions = {
float64: true,
typeEncoders: {
Object: cidEncoder,
undefined: undefinedEncoder,
number: numberEncoder
}
}
const encodeOptions = {
..._encodeOptions,
typeEncoders: {
..._encodeOptions.typeEncoders
}
}
/**
* @param {Uint8Array} bytes
* @returns {CID}
*/
function cidDecoder (bytes) {
if (bytes[0] !== 0) {
throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
}
return multiformats_cid__WEBPACK_IMPORTED_MODULE_1__.CID.decode(bytes.subarray(1)) // ignore leading 0x00
}
const _decodeOptions = {
allowIndefinite: false,
coerceUndefinedToNull: true,
allowNaN: false,
allowInfinity: false,
allowBigInt: true, // this will lead to BigInt for ints outside of
// safe-integer range, which may surprise users
strict: true,
useMaps: false,
rejectDuplicateMapKeys: true,
/** @type {import('cborg').TagDecoder[]} */
tags: []
}
_decodeOptions.tags[CID_CBOR_TAG] = cidDecoder
const decodeOptions = {
..._decodeOptions,
tags: _decodeOptions.tags.slice()
}
const name = 'dag-cbor'
const code = 0x71
/**
* @template T
* @param {T} node
* @returns {ByteView<T>}
*/
const encode = (node) => cborg__WEBPACK_IMPORTED_MODULE_0__.encode(node, _encodeOptions)
/**
* @template T
* @param {ByteView<T> | ArrayBufferView<T>} data
* @returns {T}
*/
const decode = (data) => cborg__WEBPACK_IMPORTED_MODULE_0__.decode(toByteView(data), _decodeOptions)
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/errors.js":
/*!********************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/errors.js ***!
\********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ SigningError: () => (/* binding */ SigningError),
/* harmony export */ VerificationError: () => (/* binding */ VerificationError),
/* harmony export */ WebCryptoMissingError: () => (/* binding */ WebCryptoMissingError)
/* harmony export */ });
/**
* Signing a message failed
*/
class SigningError extends Error {
constructor(message = 'An error occurred while signing a message') {
super(message);
this.name = 'SigningError';
}
}
/**
* Verifying a message signature failed
*/
class VerificationError extends Error {
constructor(message = 'An error occurred while verifying a message') {
super(message);
this.name = 'VerificationError';
}
}
/**
* WebCrypto was not available in the current context
*/
class WebCryptoMissingError extends Error {
constructor(message = 'Missing Web Crypto API') {
super(message);
this.name = 'WebCryptoMissingError';
}
}
//# sourceMappingURL=errors.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/hmac/index.browser.js":
/*!********************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/hmac/index.browser.js ***!
\********************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ create: () => (/* binding */ create)
/* harmony export */ });
/* harmony import */ var _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../webcrypto/index.js */ "./node_modules/@libp2p/crypto/dist/src/webcrypto/index.js");
/* harmony import */ var _lengths_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./lengths.js */ "./node_modules/@libp2p/crypto/dist/src/hmac/lengths.js");
const hashTypes = {
SHA1: 'SHA-1',
SHA256: 'SHA-256',
SHA512: 'SHA-512'
};
const sign = async (key, data) => {
const buf = await _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].get().subtle.sign({ name: 'HMAC' }, key, data);
return new Uint8Array(buf, 0, buf.byteLength);
};
async function create(hashType, secret) {
const hash = hashTypes[hashType];
const key = await _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].get().subtle.importKey('raw', secret, {
name: 'HMAC',
hash: { name: hash }
}, false, ['sign']);
return {
async digest(data) {
return sign(key, data);
},
length: _lengths_js__WEBPACK_IMPORTED_MODULE_1__["default"][hashType]
};
}
//# sourceMappingURL=index.browser.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/hmac/lengths.js":
/*!**************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/hmac/lengths.js ***!
\**************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
SHA1: 20,
SHA256: 32,
SHA512: 64
});
//# sourceMappingURL=lengths.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/ecdh/index.browser.js":
/*!*************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/ecdh/index.browser.js ***!
\*************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ generateEphemeralKeyPair: () => (/* binding */ generateEphemeralKeyPair)
/* harmony export */ });
/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ "./node_modules/@libp2p/interface/dist/src/errors.js");
/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/concat */ "./node_modules/uint8arrays/dist/src/concat.js");
/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/equals */ "./node_modules/uint8arrays/dist/src/equals.js");
/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/to-string */ "./node_modules/uint8arrays/dist/src/to-string.js");
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../util.js */ "./node_modules/@libp2p/crypto/dist/src/util.js");
/* harmony import */ var _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../webcrypto/index.js */ "./node_modules/@libp2p/crypto/dist/src/webcrypto/index.js");
const curveLengths = {
'P-256': 32,
'P-384': 48,
'P-521': 66
};
const curveTypes = Object.keys(curveLengths);
const names = curveTypes.join(' / ');
async function generateEphemeralKeyPair(curve) {
if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.InvalidParametersError(`Unknown curve: ${curve}. Must be ${names}`);
}
const pair = await _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_4__["default"].get().subtle.generateKey({
name: 'ECDH',
namedCurve: curve
}, true, ['deriveBits']);
// forcePrivate is used for testing only
const genSharedKey = async (theirPub, forcePrivate) => {
let privateKey;
if (forcePrivate != null) {
privateKey = await _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_4__["default"].get().subtle.importKey('jwk', unmarshalPrivateKey(curve, forcePrivate), {
name: 'ECDH',
namedCurve: curve
}, false, ['deriveBits']);
}
else {
privateKey = pair.privateKey;
}
const key = await _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_4__["default"].get().subtle.importKey('jwk', unmarshalPublicKey(curve, theirPub), {
name: 'ECDH',
namedCurve: curve
}, false, []);
const buffer = await _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_4__["default"].get().subtle.deriveBits({
name: 'ECDH',
public: key
}, privateKey, curveLengths[curve] * 8);
return new Uint8Array(buffer, 0, buffer.byteLength);
};
const publicKey = await _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_4__["default"].get().subtle.exportKey('jwk', pair.publicKey);
const ecdhKey = {
key: marshalPublicKey(publicKey),
genSharedKey
};
return ecdhKey;
}
// Marshal converts a jwk encoded ECDH public key into the
// form specified in section 4.3.6 of ANSI X9.62. (This is the format
// go-ipfs uses)
function marshalPublicKey(jwk) {
if (jwk.crv == null || jwk.x == null || jwk.y == null) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.InvalidParametersError('JWK was missing components');
}
if (jwk.crv !== 'P-256' && jwk.crv !== 'P-384' && jwk.crv !== 'P-521') {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.InvalidParametersError(`Unknown curve: ${jwk.crv}. Must be ${names}`);
}
const byteLen = curveLengths[jwk.crv];
return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)([
Uint8Array.from([4]), // uncompressed point
(0,_util_js__WEBPACK_IMPORTED_MODULE_5__.base64urlToBuffer)(jwk.x, byteLen),
(0,_util_js__WEBPACK_IMPORTED_MODULE_5__.base64urlToBuffer)(jwk.y, byteLen)
], 1 + byteLen * 2);
}
/**
* Unmarshal converts a point, serialized by Marshal, into an jwk encoded key
*/
function unmarshalPublicKey(curve, key) {
if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.InvalidParametersError(`Unknown curve: ${curve}. Must be ${names}`);
}
const byteLen = curveLengths[curve];
if (!(0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__.equals)(key.subarray(0, 1), Uint8Array.from([4]))) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.InvalidParametersError('Cannot unmarshal public key - invalid key format');
}
return {
kty: 'EC',
crv: curve,
x: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(key.subarray(1, byteLen + 1), 'base64url'),
y: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(key.subarray(1 + byteLen), 'base64url'),
ext: true
};
}
const unmarshalPrivateKey = (curve, key) => ({
...unmarshalPublicKey(curve, key.public),
d: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(key.private, 'base64url')
});
//# sourceMappingURL=index.browser.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/ed25519/ed25519.js":
/*!**********************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/ed25519/ed25519.js ***!
\**********************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Ed25519PrivateKey: () => (/* binding */ Ed25519PrivateKey),
/* harmony export */ Ed25519PublicKey: () => (/* binding */ Ed25519PublicKey)
/* harmony export */ });
/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base58.js");
/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/cid */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/cid.js");
/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/hashes/digest */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/digest.js");
/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/identity */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/identity.js");
/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! uint8arrays/equals */ "./node_modules/uint8arrays/dist/src/equals.js");
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../index.js */ "./node_modules/@libp2p/crypto/dist/src/keys/index.js");
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@libp2p/crypto/dist/src/keys/ed25519/utils.js");
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./index.js */ "./node_modules/@libp2p/crypto/dist/src/keys/ed25519/index.browser.js");
class Ed25519PublicKey {
type = 'Ed25519';
raw;
constructor(key) {
this.raw = (0,_utils_js__WEBPACK_IMPORTED_MODULE_5__.ensureEd25519Key)(key, _index_js__WEBPACK_IMPORTED_MODULE_6__.publicKeyLength);
}
toMultihash() {
return multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_3__.identity.digest((0,_index_js__WEBPACK_IMPORTED_MODULE_7__.publicKeyToProtobuf)(this));
}
toCID() {
return multiformats_cid__WEBPACK_IMPORTED_MODULE_1__.CID.createV1(114, this.toMultihash());
}
toString() {
return multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.toMultihash().bytes).substring(1);
}
equals(key) {
if (key == null || !(key.raw instanceof Uint8Array)) {
return false;
}
return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_4__.equals)(this.raw, key.raw);
}
verify(data, sig) {
return _index_js__WEBPACK_IMPORTED_MODULE_6__.hashAndVerify(this.raw, sig, data);
}
}
class Ed25519PrivateKey {
type = 'Ed25519';
raw;
publicKey;
// key - 64 byte Uint8Array containing private key
// publicKey - 32 byte Uint8Array containing public key
constructor(key, publicKey) {
this.raw = (0,_utils_js__WEBPACK_IMPORTED_MODULE_5__.ensureEd25519Key)(key, _index_js__WEBPACK_IMPORTED_MODULE_6__.privateKeyLength);
this.publicKey = new Ed25519PublicKey(publicKey);
}
equals(key) {
if (key == null || !(key.raw instanceof Uint8Array)) {
return false;
}
return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_4__.equals)(this.raw, key.raw);
}
sign(message) {
return _index_js__WEBPACK_IMPORTED_MODULE_6__.hashAndSign(this.raw, message);
}
}
//# sourceMappingURL=ed25519.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/ed25519/index.browser.js":
/*!****************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/ed25519/index.browser.js ***!
\****************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ generateKey: () => (/* binding */ generateKey),
/* harmony export */ generateKeyFromSeed: () => (/* binding */ generateKeyFromSeed),
/* harmony export */ hashAndSign: () => (/* binding */ hashAndSign),
/* harmony export */ hashAndVerify: () => (/* binding */ hashAndVerify),
/* harmony export */ privateKeyLength: () => (/* binding */ PRIVATE_KEY_BYTE_LENGTH),
/* harmony export */ publicKeyLength: () => (/* binding */ PUBLIC_KEY_BYTE_LENGTH)
/* harmony export */ });
/* harmony import */ var _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @noble/curves/ed25519 */ "./node_modules/@noble/curves/esm/ed25519.js");
const PUBLIC_KEY_BYTE_LENGTH = 32;
const PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys
const KEYS_BYTE_LENGTH = 32;
function generateKey() {
// the actual private key (32 bytes)
const privateKeyRaw = _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.utils.randomPrivateKey();
const publicKey = _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.getPublicKey(privateKeyRaw);
// concatenated the public key to the private key
const privateKey = concatKeys(privateKeyRaw, publicKey);
return {
privateKey,
publicKey
};
}
/**
* Generate keypair from a 32 byte uint8array
*/
function generateKeyFromSeed(seed) {
if (seed.length !== KEYS_BYTE_LENGTH) {
throw new TypeError('"seed" must be 32 bytes in length.');
}
else if (!(seed instanceof Uint8Array)) {
throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');
}
// based on node forges algorithm, the seed is used directly as private key
const privateKeyRaw = seed;
const publicKey = _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.getPublicKey(privateKeyRaw);
const privateKey = concatKeys(privateKeyRaw, publicKey);
return {
privateKey,
publicKey
};
}
function hashAndSign(privateKey, msg) {
const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);
return _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);
}
function hashAndVerify(publicKey, sig, msg) {
return _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);
}
function concatKeys(privateKeyRaw, publicKey) {
const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);
for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {
privateKey[i] = privateKeyRaw[i];
privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];
}
return privateKey;
}
//# sourceMappingURL=index.browser.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/ed25519/utils.js":
/*!********************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/ed25519/utils.js ***!
\********************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ensureEd25519Key: () => (/* binding */ ensureEd25519Key),
/* harmony export */ generateEd25519KeyPair: () => (/* binding */ generateEd25519KeyPair),
/* harmony export */ generateEd25519KeyPairFromSeed: () => (/* binding */ generateEd25519KeyPairFromSeed),
/* harmony export */ unmarshalEd25519PrivateKey: () => (/* binding */ unmarshalEd25519PrivateKey),
/* harmony export */ unmarshalEd25519PublicKey: () => (/* binding */ unmarshalEd25519PublicKey)
/* harmony export */ });
/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ "./node_modules/@libp2p/interface/dist/src/errors.js");
/* harmony import */ var _ed25519_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ed25519.js */ "./node_modules/@libp2p/crypto/dist/src/keys/ed25519/ed25519.js");
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./index.js */ "./node_modules/@libp2p/crypto/dist/src/keys/ed25519/index.browser.js");
function unmarshalEd25519PrivateKey(bytes) {
// Try the old, redundant public key version
if (bytes.length > _index_js__WEBPACK_IMPORTED_MODULE_0__.privateKeyLength) {
bytes = ensureEd25519Key(bytes, _index_js__WEBPACK_IMPORTED_MODULE_0__.privateKeyLength + _index_js__WEBPACK_IMPORTED_MODULE_0__.publicKeyLength);
const privateKeyBytes = bytes.subarray(0, _index_js__WEBPACK_IMPORTED_MODULE_0__.privateKeyLength);
const publicKeyBytes = bytes.subarray(_index_js__WEBPACK_IMPORTED_MODULE_0__.privateKeyLength, bytes.length);
return new _ed25519_js__WEBPACK_IMPORTED_MODULE_1__.Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);
}
bytes = ensureEd25519Key(bytes, _index_js__WEBPACK_IMPORTED_MODULE_0__.privateKeyLength);
const privateKeyBytes = bytes.subarray(0, _index_js__WEBPACK_IMPORTED_MODULE_0__.privateKeyLength);
const publicKeyBytes = bytes.subarray(_index_js__WEBPACK_IMPORTED_MODULE_0__.publicKeyLength);
return new _ed25519_js__WEBPACK_IMPORTED_MODULE_1__.Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);
}
function unmarshalEd25519PublicKey(bytes) {
bytes = ensureEd25519Key(bytes, _index_js__WEBPACK_IMPORTED_MODULE_0__.publicKeyLength);
return new _ed25519_js__WEBPACK_IMPORTED_MODULE_1__.Ed25519PublicKey(bytes);
}
async function generateEd25519KeyPair() {
const { privateKey, publicKey } = _index_js__WEBPACK_IMPORTED_MODULE_0__.generateKey();
return new _ed25519_js__WEBPACK_IMPORTED_MODULE_1__.Ed25519PrivateKey(privateKey, publicKey);
}
async function generateEd25519KeyPairFromSeed(seed) {
const { privateKey, publicKey } = _index_js__WEBPACK_IMPORTED_MODULE_0__.generateKeyFromSeed(seed);
return new _ed25519_js__WEBPACK_IMPORTED_MODULE_1__.Ed25519PrivateKey(privateKey, publicKey);
}
function ensureEd25519Key(key, length) {
key = Uint8Array.from(key ?? []);
if (key.length !== length) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`);
}
return key;
}
//# sourceMappingURL=utils.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/index.js":
/*!************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/index.js ***!
\************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ generateEphemeralKeyPair: () => (/* reexport safe */ _ecdh_index_js__WEBPACK_IMPORTED_MODULE_0__.generateEphemeralKeyPair),
/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),
/* harmony export */ generateKeyPairFromSeed: () => (/* binding */ generateKeyPairFromSeed),
/* harmony export */ keyStretcher: () => (/* reexport safe */ _key_stretcher_js__WEBPACK_IMPORTED_MODULE_1__.keyStretcher),
/* harmony export */ privateKeyFromProtobuf: () => (/* binding */ privateKeyFromProtobuf),
/* harmony export */ privateKeyFromRaw: () => (/* binding */ privateKeyFromRaw),
/* harmony export */ privateKeyToProtobuf: () => (/* binding */ privateKeyToProtobuf),
/* harmony export */ publicKeyFromMultihash: () => (/* binding */ publicKeyFromMultihash),
/* harmony export */ publicKeyFromProtobuf: () => (/* binding */ publicKeyFromProtobuf),
/* harmony export */ publicKeyFromRaw: () => (/* binding */ publicKeyFromRaw),
/* harmony export */ publicKeyToProtobuf: () => (/* binding */ publicKeyToProtobuf)
/* harmony export */ });
/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/interface */ "./node_modules/@libp2p/interface/dist/src/errors.js");
/* harmony import */ var _ed25519_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ed25519/utils.js */ "./node_modules/@libp2p/crypto/dist/src/keys/ed25519/utils.js");
/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./keys.js */ "./node_modules/@libp2p/crypto/dist/src/keys/keys.js");
/* harmony import */ var _rsa_utils_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./rsa/utils.js */ "./node_modules/@libp2p/crypto/dist/src/keys/rsa/utils.js");
/* harmony import */ var _secp256k1_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./secp256k1/utils.js */ "./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/utils.js");
/* harmony import */ var _ecdh_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ecdh/index.js */ "./node_modules/@libp2p/crypto/dist/src/keys/ecdh/index.browser.js");
/* harmony import */ var _key_stretcher_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./key-stretcher.js */ "./node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js");
/**
* @packageDocumentation
*
* ## Supported Key Types
*
* Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.
*
* For encryption / decryption support, RSA keys should be used.
*/
async function generateKeyPair(type, bits) {
if (type === 'Ed25519') {
return (0,_ed25519_utils_js__WEBPACK_IMPORTED_MODULE_2__.generateEd25519KeyPair)();
}
if (type === 'secp256k1') {
return (0,_secp256k1_utils_js__WEBPACK_IMPORTED_MODULE_3__.generateSecp256k1KeyPair)();
}
if (type === 'RSA') {
return (0,_rsa_utils_js__WEBPACK_IMPORTED_MODULE_4__.generateRSAKeyPair)(bits ?? 2048);
}
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.UnsupportedKeyTypeError();
}
async function generateKeyPairFromSeed(type, seed) {
if (type !== 'Ed25519') {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.UnsupportedKeyTypeError('Seed key derivation only supported for Ed25519 keys');
}
return (0,_ed25519_utils_js__WEBPACK_IMPORTED_MODULE_2__.generateEd25519KeyPairFromSeed)(seed);
}
/**
* Converts a protobuf serialized public key into its representative object
*/
function publicKeyFromProtobuf(buf) {
const { Type, Data } = _keys_js__WEBPACK_IMPORTED_MODULE_6__.PublicKey.decode(buf);
const data = Data ?? new Uint8Array();
switch (Type) {
case _keys_js__WEBPACK_IMPORTED_MODULE_6__.KeyType.RSA:
return (0,_rsa_utils_js__WEBPACK_IMPORTED_MODULE_4__.pkixToRSAPublicKey)(data);
case _keys_js__WEBPACK_IMPORTED_MODULE_6__.KeyType.Ed25519:
return (0,_ed25519_utils_js__WEBPACK_IMPORTED_MODULE_2__.unmarshalEd25519PublicKey)(data);
case _keys_js__WEBPACK_IMPORTED_MODULE_6__.KeyType.secp256k1:
return (0,_secp256k1_utils_js__WEBPACK_IMPORTED_MODULE_3__.unmarshalSecp256k1PublicKey)(data);
default:
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.UnsupportedKeyTypeError();
}
}
/**
* Creates a public key from the raw key bytes
*/
function publicKeyFromRaw(buf) {
if (buf.byteLength === 32) {
return (0,_ed25519_utils_js__WEBPACK_IMPORTED_MODULE_2__.unmarshalEd25519PublicKey)(buf);
}
else if (buf.byteLength === 33) {
return (0,_secp256k1_utils_js__WEBPACK_IMPORTED_MODULE_3__.unmarshalSecp256k1PublicKey)(buf);
}
else {
return (0,_rsa_utils_js__WEBPACK_IMPORTED_MODULE_4__.pkixToRSAPublicKey)(buf);
}
}
/**
* Creates a public key from an identity multihash which contains a protobuf
* encoded Ed25519 or secp256k1 public key.
*
* RSA keys are not supported as in practice we they are not stored in identity
* multihashes since the hash would be very large.
*/
function publicKeyFromMultihash(digest) {
const { Type, Data } = _keys_js__WEBPACK_IMPORTED_MODULE_6__.PublicKey.decode(digest.digest);
const data = Data ?? new Uint8Array();
switch (Type) {
case _keys_js__WEBPACK_IMPORTED_MODULE_6__.KeyType.Ed25519:
return (0,_ed25519_utils_js__WEBPACK_IMPORTED_MODULE_2__.unmarshalEd25519PublicKey)(data);
case _keys_js__WEBPACK_IMPORTED_MODULE_6__.KeyType.secp256k1:
return (0,_secp256k1_utils_js__WEBPACK_IMPORTED_MODULE_3__.unmarshalSecp256k1PublicKey)(data);
default:
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.UnsupportedKeyTypeError();
}
}
/**
* Converts a public key object into a protobuf serialized public key
*/
function publicKeyToProtobuf(key) {
return _keys_js__WEBPACK_IMPORTED_MODULE_6__.PublicKey.encode({
Type: _keys_js__WEBPACK_IMPORTED_MODULE_6__.KeyType[key.type],
Data: key.raw
});
}
/**
* Converts a protobuf serialized private key into its representative object
*/
function privateKeyFromProtobuf(buf) {
const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_6__.PrivateKey.decode(buf);
const data = decoded.Data ?? new Uint8Array();
switch (decoded.Type) {
case _keys_js__WEBPACK_IMPORTED_MODULE_6__.KeyType.RSA:
return (0,_rsa_utils_js__WEBPACK_IMPORTED_MODULE_4__.pkcs1ToRSAPrivateKey)(data);
case _keys_js__WEBPACK_IMPORTED_MODULE_6__.KeyType.Ed25519:
return (0,_ed25519_utils_js__WEBPACK_IMPORTED_MODULE_2__.unmarshalEd25519PrivateKey)(data);
case _keys_js__WEBPACK_IMPORTED_MODULE_6__.KeyType.secp256k1:
return (0,_secp256k1_utils_js__WEBPACK_IMPORTED_MODULE_3__.unmarshalSecp256k1PrivateKey)(data);
default:
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.UnsupportedKeyTypeError();
}
}
/**
* Creates a private key from the raw key bytes. For Ed25519 keys this requires
* the public key to be appended to the private key otherwise we can't
* differentiate between Ed25519 and secp256k1 keys as they are the same length.
*/
function privateKeyFromRaw(buf) {
if (buf.byteLength === 64) {
return (0,_ed25519_utils_js__WEBPACK_IMPORTED_MODULE_2__.unmarshalEd25519PrivateKey)(buf);
}
else if (buf.byteLength === 32) {
return (0,_secp256k1_utils_js__WEBPACK_IMPORTED_MODULE_3__.unmarshalSecp256k1PrivateKey)(buf);
}
else {
return (0,_rsa_utils_js__WEBPACK_IMPORTED_MODULE_4__.pkcs1ToRSAPrivateKey)(buf);
}
}
/**
* Converts a private key object into a protobuf serialized private key
*/
function privateKeyToProtobuf(key) {
return _keys_js__WEBPACK_IMPORTED_MODULE_6__.PrivateKey.encode({
Type: _keys_js__WEBPACK_IMPORTED_MODULE_6__.KeyType[key.type],
Data: key.raw
});
}
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js":
/*!********************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js ***!
\********************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ keyStretcher: () => (/* binding */ keyStretcher)
/* harmony export */ });
/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ "./node_modules/@libp2p/interface/dist/src/errors.js");
/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/concat */ "./node_modules/uint8arrays/dist/src/concat.js");
/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ "./node_modules/uint8arrays/dist/src/from-string.js");
/* harmony import */ var _hmac_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../hmac/index.js */ "./node_modules/@libp2p/crypto/dist/src/hmac/index.browser.js");
const cipherMap = {
'AES-128': {
ivSize: 16,
keySize: 16
},
'AES-256': {
ivSize: 16,
keySize: 32
},
Blowfish: {
ivSize: 8,
keySize: 32
}
};
/**
* Generates a set of keys for each party by stretching the shared key.
* (myIV, theirIV, myCipherKey, theirCipherKey, myMACKey, theirMACKey)
*/
async function keyStretcher(cipherType, hash, secret) {
if (cipherType !== 'AES-128' && cipherType !== 'AES-256' && cipherType !== 'Blowfish') {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.InvalidParametersError('Cipher type was missing or unsupported');
}
if (hash !== 'SHA1' && hash !== 'SHA256' && hash !== 'SHA512') {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.InvalidParametersError('Hash type was missing or unsupported');
}
if (secret == null || !(secret instanceof Uint8Array)) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.InvalidParametersError('Secret was missing or an incorrect type');
}
const cipher = cipherMap[cipherType];
const cipherKeySize = cipher.keySize;
const ivSize = cipher.ivSize;
const hmacKeySize = 20;
const seed = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)('key expansion');
const resultLength = 2 * (ivSize + cipherKeySize + hmacKeySize);
const m = await _hmac_index_js__WEBPACK_IMPORTED_MODULE_3__.create(hash, secret);
let a = await m.digest(seed);
const result = [];
let j = 0;
while (j < resultLength) {
const b = await m.digest((0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)([a, seed]));
let todo = b.length;
if (j + todo > resultLength) {
todo = resultLength - j;
}
result.push(b);
j += todo;
a = await m.digest(a);
}
const half = resultLength / 2;
const resultBuffer = (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)(result);
const r1 = resultBuffer.subarray(0, half);
const r2 = resultBuffer.subarray(half, resultLength);
const createKey = (res) => ({
iv: res.subarray(0, ivSize),
cipherKey: res.subarray(ivSize, ivSize + cipherKeySize),
macKey: res.subarray(ivSize + cipherKeySize)
});
return {
k1: createKey(r1),
k2: createKey(r2)
};
}
//# sourceMappingURL=key-stretcher.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/keys.js":
/*!***********************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/keys.js ***!
\***********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ KeyType: () => (/* binding */ KeyType),
/* harmony export */ PrivateKey: () => (/* binding */ PrivateKey),
/* harmony export */ PublicKey: () => (/* binding */ PublicKey)
/* harmony export */ });
/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ "./node_modules/protons-runtime/dist/src/index.js");
/* eslint-disable import/export */
/* eslint-disable complexity */
/* eslint-disable @typescript-eslint/no-namespace */
/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */
/* eslint-disable @typescript-eslint/no-empty-interface */
var KeyType;
(function (KeyType) {
KeyType["RSA"] = "RSA";
KeyType["Ed25519"] = "Ed25519";
KeyType["secp256k1"] = "secp256k1";
})(KeyType || (KeyType = {}));
var __KeyTypeValues;
(function (__KeyTypeValues) {
__KeyTypeValues[__KeyTypeValues["RSA"] = 0] = "RSA";
__KeyTypeValues[__KeyTypeValues["Ed25519"] = 1] = "Ed25519";
__KeyTypeValues[__KeyTypeValues["secp256k1"] = 2] = "secp256k1";
})(__KeyTypeValues || (__KeyTypeValues = {}));
(function (KeyType) {
KeyType.codec = () => {
return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.enumeration)(__KeyTypeValues);
};
})(KeyType || (KeyType = {}));
var PublicKey;
(function (PublicKey) {
let _codec;
PublicKey.codec = () => {
if (_codec == null) {
_codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {
if (opts.lengthDelimited !== false) {
w.fork();
}
if (obj.Type != null) {
w.uint32(8);
KeyType.codec().encode(obj.Type, w);
}
if (obj.Data != null) {
w.uint32(18);
w.bytes(obj.Data);
}
if (opts.lengthDelimited !== false) {
w.ldelim();
}
}, (reader, length, opts = {}) => {
const obj = {};
const end = length == null ? reader.len : reader.pos + length;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
obj.Type = KeyType.codec().decode(reader);
break;
}
case 2: {
obj.Data = reader.bytes();
break;
}
default: {
reader.skipType(tag & 7);
break;
}
}
}
return obj;
});
}
return _codec;
};
PublicKey.encode = (obj) => {
return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PublicKey.codec());
};
PublicKey.decode = (buf, opts) => {
return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PublicKey.codec(), opts);
};
})(PublicKey || (PublicKey = {}));
var PrivateKey;
(function (PrivateKey) {
let _codec;
PrivateKey.codec = () => {
if (_codec == null) {
_codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {
if (opts.lengthDelimited !== false) {
w.fork();
}
if (obj.Type != null) {
w.uint32(8);
KeyType.codec().encode(obj.Type, w);
}
if (obj.Data != null) {
w.uint32(18);
w.bytes(obj.Data);
}
if (opts.lengthDelimited !== false) {
w.ldelim();
}
}, (reader, length, opts = {}) => {
const obj = {};
const end = length == null ? reader.len : reader.pos + length;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1: {
obj.Type = KeyType.codec().decode(reader);
break;
}
case 2: {
obj.Data = reader.bytes();
break;
}
default: {
reader.skipType(tag & 7);
break;
}
}
}
return obj;
});
}
return _codec;
};
PrivateKey.encode = (obj) => {
return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PrivateKey.codec());
};
PrivateKey.decode = (buf, opts) => {
return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PrivateKey.codec(), opts);
};
})(PrivateKey || (PrivateKey = {}));
//# sourceMappingURL=keys.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/rsa/index.browser.js":
/*!************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/rsa/index.browser.js ***!
\************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ generateRSAKey: () => (/* binding */ generateRSAKey),
/* harmony export */ getRandomValues: () => (/* reexport safe */ _random_bytes_js__WEBPACK_IMPORTED_MODULE_3__["default"]),
/* harmony export */ hashAndSign: () => (/* binding */ hashAndSign),
/* harmony export */ hashAndVerify: () => (/* binding */ hashAndVerify),
/* harmony export */ rsaKeySize: () => (/* binding */ rsaKeySize),
/* harmony export */ utils: () => (/* reexport module object */ _utils_js__WEBPACK_IMPORTED_MODULE_1__)
/* harmony export */ });
/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ "./node_modules/@libp2p/interface/dist/src/errors.js");
/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/from-string */ "./node_modules/uint8arrays/dist/src/from-string.js");
/* harmony import */ var _random_bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../random-bytes.js */ "./node_modules/@libp2p/crypto/dist/src/random-bytes.js");
/* harmony import */ var _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../webcrypto/index.js */ "./node_modules/@libp2p/crypto/dist/src/webcrypto/index.js");
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@libp2p/crypto/dist/src/keys/rsa/utils.js");
async function generateRSAKey(bits) {
const pair = await _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_2__["default"].get().subtle.generateKey({
name: 'RSASSA-PKCS1-v1_5',
modulusLength: bits,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: 'SHA-256' }
}, true, ['sign', 'verify']);
const keys = await exportKey(pair);
return {
privateKey: keys[0],
publicKey: keys[1]
};
}
async function hashAndSign(key, msg) {
const privateKey = await _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_2__["default"].get().subtle.importKey('jwk', key, {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' }
}, false, ['sign']);
const sig = await _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_2__["default"].get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());
return new Uint8Array(sig, 0, sig.byteLength);
}
async function hashAndVerify(key, sig, msg) {
const publicKey = await _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_2__["default"].get().subtle.importKey('jwk', key, {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' }
}, false, ['verify']);
return _webcrypto_index_js__WEBPACK_IMPORTED_MODULE_2__["default"].get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());
}
async function exportKey(pair) {
if (pair.privateKey == null || pair.publicKey == null) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.InvalidParametersError('Private and public key are required');
}
return Promise.all([
_webcrypto_index_js__WEBPACK_IMPORTED_MODULE_2__["default"].get().subtle.exportKey('jwk', pair.privateKey),
_webcrypto_index_js__WEBPACK_IMPORTED_MODULE_2__["default"].get().subtle.exportKey('jwk', pair.publicKey)
]);
}
function rsaKeySize(jwk) {
if (jwk.kty !== 'RSA') {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.InvalidParametersError('invalid key type');
}
else if (jwk.n == null) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.InvalidParametersError('invalid key modulus');
}
const bytes = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(jwk.n, 'base64url');
return bytes.length * 8;
}
//# sourceMappingURL=index.browser.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/rsa/rsa.js":
/*!**************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/rsa/rsa.js ***!
\**************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ RSAPrivateKey: () => (/* binding */ RSAPrivateKey),
/* harmony export */ RSAPublicKey: () => (/* binding */ RSAPublicKey)
/* harmony export */ });
/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base58.js");
/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/cid */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/cid.js");
/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/hashes/digest */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/digest.js");
/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/equals */ "./node_modules/uint8arrays/dist/src/equals.js");
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./index.js */ "./node_modules/@libp2p/crypto/dist/src/keys/rsa/utils.js");
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./index.js */ "./node_modules/@libp2p/crypto/dist/src/keys/rsa/index.browser.js");
class RSAPublicKey {
type = 'RSA';
_key;
_raw;
_multihash;
constructor(key, digest) {
this._key = key;
this._multihash = digest;
}
get raw() {
if (this._raw == null) {
this._raw = _index_js__WEBPACK_IMPORTED_MODULE_4__.jwkToPkix(this._key);
}
return this._raw;
}
toMultihash() {
return this._multihash;
}
toCID() {
return multiformats_cid__WEBPACK_IMPORTED_MODULE_1__.CID.createV1(114, this._multihash);
}
toString() {
return multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.toMultihash().bytes).substring(1);
}
equals(key) {
if (key == null || !(key.raw instanceof Uint8Array)) {
return false;
}
return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_3__.equals)(this.raw, key.raw);
}
verify(data, sig) {
return (0,_index_js__WEBPACK_IMPORTED_MODULE_5__.hashAndVerify)(this._key, sig, data);
}
}
class RSAPrivateKey {
type = 'RSA';
_key;
_raw;
publicKey;
constructor(key, publicKey) {
this._key = key;
this.publicKey = publicKey;
}
get raw() {
if (this._raw == null) {
this._raw = _index_js__WEBPACK_IMPORTED_MODULE_4__.jwkToPkcs1(this._key);
}
return this._raw;
}
equals(key) {
if (key == null || !(key.raw instanceof Uint8Array)) {
return false;
}
return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_3__.equals)(this.raw, key.raw);
}
sign(message) {
return (0,_index_js__WEBPACK_IMPORTED_MODULE_5__.hashAndSign)(this._key, message);
}
}
//# sourceMappingURL=rsa.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/rsa/utils.js":
/*!****************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/rsa/utils.js ***!
\****************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ MAX_RSA_KEY_SIZE: () => (/* binding */ MAX_RSA_KEY_SIZE),
/* harmony export */ generateRSAKeyPair: () => (/* binding */ generateRSAKeyPair),
/* harmony export */ jwkToJWKKeyPair: () => (/* binding */ jwkToJWKKeyPair),
/* harmony export */ jwkToPkcs1: () => (/* binding */ jwkToPkcs1),
/* harmony export */ jwkToPkix: () => (/* binding */ jwkToPkix),
/* harmony export */ jwkToRSAPrivateKey: () => (/* binding */ jwkToRSAPrivateKey),
/* harmony export */ pkcs1ToJwk: () => (/* binding */ pkcs1ToJwk),
/* harmony export */ pkcs1ToRSAPrivateKey: () => (/* binding */ pkcs1ToRSAPrivateKey),
/* harmony export */ pkixToJwk: () => (/* binding */ pkixToJwk),
/* harmony export */ pkixToRSAPublicKey: () => (/* binding */ pkixToRSAPublicKey)
/* harmony export */ });
/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ "./node_modules/@libp2p/interface/dist/src/errors.js");
/* harmony import */ var _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/esm/sha256.js");
/* harmony import */ var asn1js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! asn1js */ "./node_modules/asn1js/build/index.es.js");
/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/hashes/digest */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/digest.js");
/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/from-string */ "./node_modules/uint8arrays/dist/src/from-string.js");
/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/to-string */ "./node_modules/uint8arrays/dist/src/to-string.js");
/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../keys.js */ "./node_modules/@libp2p/crypto/dist/src/keys/keys.js");
/* harmony import */ var _rsa_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./rsa.js */ "./node_modules/@libp2p/crypto/dist/src/keys/rsa/rsa.js");
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./index.js */ "./node_modules/@libp2p/crypto/dist/src/keys/rsa/index.browser.js");
const MAX_RSA_KEY_SIZE = 8192;
const SHA2_256_CODE = 0x12;
/**
* Convert a PKCS#1 in ASN1 DER format to a JWK key
*/
function pkcs1ToJwk(bytes) {
const { result } = asn1js__WEBPACK_IMPORTED_MODULE_0__.fromBER(bytes);
// @ts-expect-error this looks fragile but DER is a canonical format so we are
// safe to have deeply property chains like this
const values = result.valueBlock.value;
const key = {
n: asn1jsIntegerToBase64(values[1]),
e: asn1jsIntegerToBase64(values[2]),
d: asn1jsIntegerToBase64(values[3]),
p: asn1jsIntegerToBase64(values[4]),
q: asn1jsIntegerToBase64(values[5]),
dp: asn1jsIntegerToBase64(values[6]),
dq: asn1jsIntegerToBase64(values[7]),
qi: asn1jsIntegerToBase64(values[8]),
kty: 'RSA',
alg: 'RS256'
};
return key;
}
/**
* Convert a JWK key into PKCS#1 in ASN1 DER format
*/
function jwkToPkcs1(jwk) {
if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.InvalidParametersError('JWK was missing components');
}
const root = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({
value: [
new asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer({ value: 0 }),
asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__.fromString)(jwk.n, 'base64url'))),
asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__.fromString)(jwk.e, 'base64url'))),
asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__.fromString)(jwk.d, 'base64url'))),
asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__.fromString)(jwk.p, 'base64url'))),
asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__.fromString)(jwk.q, 'base64url'))),
asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__.fromString)(jwk.dp, 'base64url'))),
asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__.fromString)(jwk.dq, 'base64url'))),
asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__.fromString)(jwk.qi, 'base64url')))
]
});
const der = root.toBER();
return new Uint8Array(der, 0, der.byteLength);
}
/**
* Convert a PKIX in ASN1 DER format to a JWK key
*/
function pkixToJwk(bytes) {
const { result } = asn1js__WEBPACK_IMPORTED_MODULE_0__.fromBER(bytes);
// @ts-expect-error this looks fragile but DER is a canonical format so we are
// safe to have deeply property chains like this
const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;
return {
kty: 'RSA',
n: asn1jsIntegerToBase64(values[0]),
e: asn1jsIntegerToBase64(values[1])
};
}
/**
* Convert a JWK key to PKIX in ASN1 DER format
*/
function jwkToPkix(jwk) {
if (jwk.n == null || jwk.e == null) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.InvalidParametersError('JWK was missing components');
}
const root = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({
value: [
new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({
value: [
// rsaEncryption
new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({
value: '1.2.840.113549.1.1.1'
}),
new asn1js__WEBPACK_IMPORTED_MODULE_0__.Null()
]
}),
// this appears to be a bug in asn1js.js - this should really be a Sequence
// and not a BitString but it generates the same bytes as node-forge so 🤷♂️
new asn1js__WEBPACK_IMPORTED_MODULE_0__.BitString({
valueHex: new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({
value: [
asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__.fromString)(jwk.n, 'base64url'))),
asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__.fromString)(jwk.e, 'base64url')))
]
}).toBER()
})
]
});
const der = root.toBER();
return new Uint8Array(der, 0, der.byteLength);
}
function asn1jsIntegerToBase64(int) {
let buf = int.valueBlock.valueHexView;
// chrome rejects values with leading 0s
while (buf[0] === 0) {
buf = buf.subarray(1);
}
return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_3__.toString)(buf, 'base64url');
}
function bufToBn(u8) {
const hex = [];
u8.forEach(function (i) {
let h = i.toString(16);
if (h.length % 2 > 0) {
h = `0${h}`;
}
hex.push(h);
});
return BigInt('0x' + hex.join(''));
}
/**
* Turn PCKS#1 DER bytes to a PrivateKey
*/
function pkcs1ToRSAPrivateKey(bytes) {
const jwk = pkcs1ToJwk(bytes);
return jwkToRSAPrivateKey(jwk);
}
/**
* Turn PKIX bytes to a PublicKey
*/
function pkixToRSAPublicKey(bytes) {
const jwk = pkixToJwk(bytes);
if ((0,_index_js__WEBPACK_IMPORTED_MODULE_5__.rsaKeySize)(jwk) > MAX_RSA_KEY_SIZE) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.InvalidPublicKeyError('Key size is too large');
}
const hash = (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_6__.sha256)(_keys_js__WEBPACK_IMPORTED_MODULE_7__.PublicKey.encode({
Type: _keys_js__WEBPACK_IMPORTED_MODULE_7__.KeyType.RSA,
Data: bytes
}));
const digest = (0,multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_1__.create)(SHA2_256_CODE, hash);
return new _rsa_js__WEBPACK_IMPORTED_MODULE_8__.RSAPublicKey(jwk, digest);
}
function jwkToRSAPrivateKey(jwk) {
if ((0,_index_js__WEBPACK_IMPORTED_MODULE_5__.rsaKeySize)(jwk) > MAX_RSA_KEY_SIZE) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.InvalidParametersError('Key size is too large');
}
const keys = jwkToJWKKeyPair(jwk);
const hash = (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_6__.sha256)(_keys_js__WEBPACK_IMPORTED_MODULE_7__.PublicKey.encode({
Type: _keys_js__WEBPACK_IMPORTED_MODULE_7__.KeyType.RSA,
Data: jwkToPkix(keys.publicKey)
}));
const digest = (0,multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_1__.create)(SHA2_256_CODE, hash);
return new _rsa_js__WEBPACK_IMPORTED_MODULE_8__.RSAPrivateKey(keys.privateKey, new _rsa_js__WEBPACK_IMPORTED_MODULE_8__.RSAPublicKey(keys.publicKey, digest));
}
async function generateRSAKeyPair(bits) {
if (bits > MAX_RSA_KEY_SIZE) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.InvalidParametersError('Key size is too large');
}
const keys = await (0,_index_js__WEBPACK_IMPORTED_MODULE_5__.generateRSAKey)(bits);
const hash = (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_6__.sha256)(_keys_js__WEBPACK_IMPORTED_MODULE_7__.PublicKey.encode({
Type: _keys_js__WEBPACK_IMPORTED_MODULE_7__.KeyType.RSA,
Data: jwkToPkix(keys.publicKey)
}));
const digest = (0,multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_1__.create)(SHA2_256_CODE, hash);
return new _rsa_js__WEBPACK_IMPORTED_MODULE_8__.RSAPrivateKey(keys.privateKey, new _rsa_js__WEBPACK_IMPORTED_MODULE_8__.RSAPublicKey(keys.publicKey, digest));
}
/**
* Takes a jwk key and returns a JWK KeyPair
*/
function jwkToJWKKeyPair(key) {
if (key == null) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.InvalidParametersError('Missing key parameter');
}
return {
privateKey: key,
publicKey: {
kty: key.kty,
n: key.n,
e: key.e
}
};
}
//# sourceMappingURL=utils.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/index.browser.js":
/*!******************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/index.browser.js ***!
\******************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ hashAndSign: () => (/* binding */ hashAndSign),
/* harmony export */ hashAndVerify: () => (/* binding */ hashAndVerify)
/* harmony export */ });
/* harmony import */ var _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/@noble/curves/esm/secp256k1.js");
/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/hashes/sha2 */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/sha2-browser.js");
/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../errors.js */ "./node_modules/@libp2p/crypto/dist/src/errors.js");
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../util.js */ "./node_modules/@libp2p/crypto/dist/src/util.js");
/**
* Hash and sign message with private key
*/
function hashAndSign(key, msg) {
const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());
if ((0,_util_js__WEBPACK_IMPORTED_MODULE_1__.isPromise)(p)) {
return p.then(({ digest }) => _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_2__.secp256k1.sign(digest, key).toDERRawBytes())
.catch(err => {
throw new _errors_js__WEBPACK_IMPORTED_MODULE_3__.SigningError(String(err));
});
}
try {
return _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_2__.secp256k1.sign(p.digest, key).toDERRawBytes();
}
catch (err) {
throw new _errors_js__WEBPACK_IMPORTED_MODULE_3__.SigningError(String(err));
}
}
/**
* Hash message and verify signature with public key
*/
function hashAndVerify(key, sig, msg) {
const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());
if ((0,_util_js__WEBPACK_IMPORTED_MODULE_1__.isPromise)(p)) {
return p.then(({ digest }) => _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_2__.secp256k1.verify(sig, digest, key))
.catch(err => {
throw new _errors_js__WEBPACK_IMPORTED_MODULE_3__.VerificationError(String(err));
});
}
try {
return _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_2__.secp256k1.verify(sig, p.digest, key);
}
catch (err) {
throw new _errors_js__WEBPACK_IMPORTED_MODULE_3__.VerificationError(String(err));
}
}
//# sourceMappingURL=index.browser.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/secp256k1.js":
/*!**************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/secp256k1.js ***!
\**************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Secp256k1PrivateKey: () => (/* binding */ Secp256k1PrivateKey),
/* harmony export */ Secp256k1PublicKey: () => (/* binding */ Secp256k1PublicKey)
/* harmony export */ });
/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base58.js");
/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/cid */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/cid.js");
/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/hashes/identity */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/identity.js");
/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/equals */ "./node_modules/uint8arrays/dist/src/equals.js");
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../index.js */ "./node_modules/@libp2p/crypto/dist/src/keys/index.js");
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/utils.js");
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./index.js */ "./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/index.browser.js");
class Secp256k1PublicKey {
type = 'secp256k1';
raw;
_key;
constructor(key) {
this._key = (0,_utils_js__WEBPACK_IMPORTED_MODULE_4__.validateSecp256k1PublicKey)(key);
this.raw = (0,_utils_js__WEBPACK_IMPORTED_MODULE_4__.compressSecp256k1PublicKey)(this._key);
}
toMultihash() {
return multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_2__.identity.digest((0,_index_js__WEBPACK_IMPORTED_MODULE_5__.publicKeyToProtobuf)(this));
}
toCID() {
return multiformats_cid__WEBPACK_IMPORTED_MODULE_1__.CID.createV1(114, this.toMultihash());
}
toString() {
return multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.toMultihash().bytes).substring(1);
}
equals(key) {
if (key == null || !(key.raw instanceof Uint8Array)) {
return false;
}
return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_3__.equals)(this.raw, key.raw);
}
verify(data, sig) {
return (0,_index_js__WEBPACK_IMPORTED_MODULE_6__.hashAndVerify)(this._key, sig, data);
}
}
class Secp256k1PrivateKey {
type = 'secp256k1';
raw;
publicKey;
constructor(key, publicKey) {
this.raw = (0,_utils_js__WEBPACK_IMPORTED_MODULE_4__.validateSecp256k1PrivateKey)(key);
this.publicKey = new Secp256k1PublicKey(publicKey ?? (0,_utils_js__WEBPACK_IMPORTED_MODULE_4__.computeSecp256k1PublicKey)(key));
}
equals(key) {
if (key == null || !(key.raw instanceof Uint8Array)) {
return false;
}
return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_3__.equals)(this.raw, key.raw);
}
sign(message) {
return (0,_index_js__WEBPACK_IMPORTED_MODULE_6__.hashAndSign)(this.raw, message);
}
}
//# sourceMappingURL=secp256k1.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/utils.js":
/*!**********************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/utils.js ***!
\**********************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ compressSecp256k1PublicKey: () => (/* binding */ compressSecp256k1PublicKey),
/* harmony export */ computeSecp256k1PublicKey: () => (/* binding */ computeSecp256k1PublicKey),
/* harmony export */ decompressSecp256k1PublicKey: () => (/* binding */ decompressSecp256k1PublicKey),
/* harmony export */ generateSecp256k1KeyPair: () => (/* binding */ generateSecp256k1KeyPair),
/* harmony export */ generateSecp256k1PrivateKey: () => (/* binding */ generateSecp256k1PrivateKey),
/* harmony export */ privateKeyLength: () => (/* binding */ PRIVATE_KEY_BYTE_LENGTH),
/* harmony export */ unmarshalSecp256k1PrivateKey: () => (/* binding */ unmarshalSecp256k1PrivateKey),
/* harmony export */ unmarshalSecp256k1PublicKey: () => (/* binding */ unmarshalSecp256k1PublicKey),
/* harmony export */ validateSecp256k1PrivateKey: () => (/* binding */ validateSecp256k1PrivateKey),
/* harmony export */ validateSecp256k1PublicKey: () => (/* binding */ validateSecp256k1PublicKey)
/* harmony export */ });
/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ "./node_modules/@libp2p/interface/dist/src/errors.js");
/* harmony import */ var _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/curves/secp256k1 */ "./node_modules/@noble/curves/esm/secp256k1.js");
/* harmony import */ var _secp256k1_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./secp256k1.js */ "./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/secp256k1.js");
const PRIVATE_KEY_BYTE_LENGTH = 32;
function unmarshalSecp256k1PrivateKey(bytes) {
return new _secp256k1_js__WEBPACK_IMPORTED_MODULE_0__.Secp256k1PrivateKey(bytes);
}
function unmarshalSecp256k1PublicKey(bytes) {
return new _secp256k1_js__WEBPACK_IMPORTED_MODULE_0__.Secp256k1PublicKey(bytes);
}
async function generateSecp256k1KeyPair() {
const privateKeyBytes = generateSecp256k1PrivateKey();
return new _secp256k1_js__WEBPACK_IMPORTED_MODULE_0__.Secp256k1PrivateKey(privateKeyBytes);
}
function compressSecp256k1PublicKey(key) {
const point = _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);
return point;
}
function decompressSecp256k1PublicKey(key) {
const point = _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.ProjectivePoint.fromHex(key).toRawBytes(false);
return point;
}
function validateSecp256k1PrivateKey(key) {
try {
_noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.getPublicKey(key, true);
return key;
}
catch (err) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.InvalidPrivateKeyError(String(err));
}
}
function validateSecp256k1PublicKey(key) {
try {
_noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.ProjectivePoint.fromHex(key);
return key;
}
catch (err) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.InvalidPublicKeyError(String(err));
}
}
function computeSecp256k1PublicKey(privateKey) {
try {
return _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.getPublicKey(privateKey, true);
}
catch (err) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.InvalidPrivateKeyError(String(err));
}
}
function generateSecp256k1PrivateKey() {
return _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.utils.randomPrivateKey();
}
//# sourceMappingURL=utils.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/random-bytes.js":
/*!**************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/random-bytes.js ***!
\**************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ randomBytes)
/* harmony export */ });
/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @libp2p/interface */ "./node_modules/@libp2p/interface/dist/src/errors.js");
/* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/esm/utils.js");
/**
* Generates a Uint8Array with length `number` populated by random bytes
*/
function randomBytes(length) {
if (isNaN(length) || length <= 0) {
throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_0__.InvalidParametersError('random bytes length must be a Number bigger than 0');
}
return (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__.randomBytes)(length);
}
//# sourceMappingURL=random-bytes.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/util.js":
/*!******************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/util.js ***!
\******************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base64urlToBuffer: () => (/* binding */ base64urlToBuffer),
/* harmony export */ isPromise: () => (/* binding */ isPromise)
/* harmony export */ });
/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/concat */ "./node_modules/uint8arrays/dist/src/concat.js");
/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ "./node_modules/uint8arrays/dist/src/from-string.js");
function base64urlToBuffer(str, len) {
let buf = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(str, 'base64urlpad');
if (len != null) {
if (buf.length > len)
throw new Error('byte array longer than desired length');
buf = (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)([new Uint8Array(len - buf.length), buf]);
}
return buf;
}
function isPromise(thing) {
if (thing == null) {
return false;
}
return typeof thing.then === 'function' &&
typeof thing.catch === 'function' &&
typeof thing.finally === 'function';
}
//# sourceMappingURL=util.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/webcrypto/index.js":
/*!*****************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/webcrypto/index.js ***!
\*****************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webcrypto.js */ "./node_modules/@libp2p/crypto/dist/src/webcrypto/webcrypto.browser.js");
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_webcrypto_js__WEBPACK_IMPORTED_MODULE_0__["default"]);
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/dist/src/webcrypto/webcrypto.browser.js":
/*!*****************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/dist/src/webcrypto/webcrypto.browser.js ***!
\*****************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors.js */ "./node_modules/@libp2p/crypto/dist/src/errors.js");
/* eslint-env browser */
// Check native crypto exists and is enabled (In insecure context `self.crypto`
// exists but `self.crypto.subtle` does not).
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
get(win = globalThis) {
const nativeCrypto = win.crypto;
if (nativeCrypto?.subtle == null) {
throw new _errors_js__WEBPACK_IMPORTED_MODULE_0__.WebCryptoMissingError('Missing Web Crypto API. ' +
'The most likely cause of this error is that this page is being accessed ' +
'from an insecure context (i.e. not HTTPS). For more information and ' +
'possible resolutions see ' +
'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api');
}
return nativeCrypto;
}
});
//# sourceMappingURL=webcrypto.browser.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base.js":
/*!**************************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base.js ***!
\**************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Codec: () => (/* binding */ Codec),
/* harmony export */ baseX: () => (/* binding */ baseX),
/* harmony export */ from: () => (/* binding */ from),
/* harmony export */ or: () => (/* binding */ or),
/* harmony export */ rfc4648: () => (/* binding */ rfc4648)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/vendor/base-x.js");
/**
* Class represents both BaseEncoder and MultibaseEncoder meaning it
* can be used to encode to multibase or base encode without multibase
* prefix.
*/
class Encoder {
name;
prefix;
baseEncode;
constructor(name, prefix, baseEncode) {
this.name = name;
this.prefix = prefix;
this.baseEncode = baseEncode;
}
encode(bytes) {
if (bytes instanceof Uint8Array) {
return `${this.prefix}${this.baseEncode(bytes)}`;
}
else {
throw Error('Unknown type, must be binary type');
}
}
}
/**
* Class represents both BaseDecoder and MultibaseDecoder so it could be used
* to decode multibases (with matching prefix) or just base decode strings
* with corresponding base encoding.
*/
class Decoder {
name;
prefix;
baseDecode;
prefixCodePoint;
constructor(name, prefix, baseDecode) {
this.name = name;
this.prefix = prefix;
const prefixCodePoint = prefix.codePointAt(0);
/* c8 ignore next 3 */
if (prefixCodePoint === undefined) {
throw new Error('Invalid prefix character');
}
this.prefixCodePoint = prefixCodePoint;
this.baseDecode = baseDecode;
}
decode(text) {
if (typeof text === 'string') {
if (text.codePointAt(0) !== this.prefixCodePoint) {
throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
}
return this.baseDecode(text.slice(this.prefix.length));
}
else {
throw Error('Can only multibase decode strings');
}
}
or(decoder) {
return or(this, decoder);
}
}
class ComposedDecoder {
decoders;
constructor(decoders) {
this.decoders = decoders;
}
or(decoder) {
return or(this, decoder);
}
decode(input) {
const prefix = input[0];
const decoder = this.decoders[prefix];
if (decoder != null) {
return decoder.decode(input);
}
else {
throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
}
}
}
function or(left, right) {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return new ComposedDecoder({
...(left.decoders ?? { [left.prefix]: left }),
...(right.decoders ?? { [right.prefix]: right })
});
}
class Codec {
name;
prefix;
baseEncode;
baseDecode;
encoder;
decoder;
constructor(name, prefix, baseEncode, baseDecode) {
this.name = name;
this.prefix = prefix;
this.baseEncode = baseEncode;
this.baseDecode = baseDecode;
this.encoder = new Encoder(name, prefix, baseEncode);
this.decoder = new Decoder(name, prefix, baseDecode);
}
encode(input) {
return this.encoder.encode(input);
}
decode(input) {
return this.decoder.decode(input);
}
}
function from({ name, prefix, encode, decode }) {
return new Codec(name, prefix, encode, decode);
}
function baseX({ name, prefix, alphabet }) {
const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__["default"])(alphabet, name);
return from({
prefix,
name,
encode,
decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))
});
}
function decode(string, alphabet, bitsPerChar, name) {
// Build the character lookup table:
const codes = {};
for (let i = 0; i < alphabet.length; ++i) {
codes[alphabet[i]] = i;
}
// Count the padding bytes:
let end = string.length;
while (string[end - 1] === '=') {
--end;
}
// Allocate the output:
const out = new Uint8Array((end * bitsPerChar / 8) | 0);
// Parse the data:
let bits = 0; // Number of bits currently in the buffer
let buffer = 0; // Bits waiting to be written out, MSB first
let written = 0; // Next byte to write
for (let i = 0; i < end; ++i) {
// Read one character from the string:
const value = codes[string[i]];
if (value === undefined) {
throw new SyntaxError(`Non-${name} character`);
}
// Append the bits to the buffer:
buffer = (buffer << bitsPerChar) | value;
bits += bitsPerChar;
// Write out some bits if the buffer has a byte's worth:
if (bits >= 8) {
bits -= 8;
out[written++] = 0xff & (buffer >> bits);
}
}
// Verify that we have received just enough bits:
if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
throw new SyntaxError('Unexpected end of data');
}
return out;
}
function encode(data, alphabet, bitsPerChar) {
const pad = alphabet[alphabet.length - 1] === '=';
const mask = (1 << bitsPerChar) - 1;
let out = '';
let bits = 0; // Number of bits currently in the buffer
let buffer = 0; // Bits waiting to be written out, MSB first
for (let i = 0; i < data.length; ++i) {
// Slurp data into the buffer:
buffer = (buffer << 8) | data[i];
bits += 8;
// Write out as much as we can:
while (bits > bitsPerChar) {
bits -= bitsPerChar;
out += alphabet[mask & (buffer >> bits)];
}
}
// Partial character:
if (bits !== 0) {
out += alphabet[mask & (buffer << (bitsPerChar - bits))];
}
// Add padding characters until we hit a byte boundary:
if (pad) {
while (((out.length * bitsPerChar) & 7) !== 0) {
out += '=';
}
}
return out;
}
/**
* RFC4648 Factory
*/
function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
return from({
prefix,
name,
encode(input) {
return encode(input, alphabet, bitsPerChar);
},
decode(input) {
return decode(input, alphabet, bitsPerChar, name);
}
});
}
//# sourceMappingURL=base.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base32.js":
/*!****************************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base32.js ***!
\****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base32: () => (/* binding */ base32),
/* harmony export */ base32hex: () => (/* binding */ base32hex),
/* harmony export */ base32hexpad: () => (/* binding */ base32hexpad),
/* harmony export */ base32hexpadupper: () => (/* binding */ base32hexpadupper),
/* harmony export */ base32hexupper: () => (/* binding */ base32hexupper),
/* harmony export */ base32pad: () => (/* binding */ base32pad),
/* harmony export */ base32padupper: () => (/* binding */ base32padupper),
/* harmony export */ base32upper: () => (/* binding */ base32upper),
/* harmony export */ base32z: () => (/* binding */ base32z)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base.js");
const base32 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'b',
name: 'base32',
alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
bitsPerChar: 5
});
const base32upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'B',
name: 'base32upper',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
bitsPerChar: 5
});
const base32pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'c',
name: 'base32pad',
alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
bitsPerChar: 5
});
const base32padupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'C',
name: 'base32padupper',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
bitsPerChar: 5
});
const base32hex = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'v',
name: 'base32hex',
alphabet: '0123456789abcdefghijklmnopqrstuv',
bitsPerChar: 5
});
const base32hexupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'V',
name: 'base32hexupper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
bitsPerChar: 5
});
const base32hexpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 't',
name: 'base32hexpad',
alphabet: '0123456789abcdefghijklmnopqrstuv=',
bitsPerChar: 5
});
const base32hexpadupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'T',
name: 'base32hexpadupper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
bitsPerChar: 5
});
const base32z = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'h',
name: 'base32z',
alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
bitsPerChar: 5
});
//# sourceMappingURL=base32.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base36.js":
/*!****************************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base36.js ***!
\****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base36: () => (/* binding */ base36),
/* harmony export */ base36upper: () => (/* binding */ base36upper)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base.js");
const base36 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
prefix: 'k',
name: 'base36',
alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
const base36upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
prefix: 'K',
name: 'base36upper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base58.js":
/*!****************************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base58.js ***!
\****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base58btc: () => (/* binding */ base58btc),
/* harmony export */ base58flickr: () => (/* binding */ base58flickr)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base.js");
const base58btc = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
name: 'base58btc',
prefix: 'z',
alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
const base58flickr = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
name: 'base58flickr',
prefix: 'Z',
alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bytes.js":
/*!*********************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bytes.js ***!
\*********************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ coerce: () => (/* binding */ coerce),
/* harmony export */ empty: () => (/* binding */ empty),
/* harmony export */ equals: () => (/* binding */ equals),
/* harmony export */ fromHex: () => (/* binding */ fromHex),
/* harmony export */ fromString: () => (/* binding */ fromString),
/* harmony export */ isBinary: () => (/* binding */ isBinary),
/* harmony export */ toHex: () => (/* binding */ toHex),
/* harmony export */ toString: () => (/* binding */ toString)
/* harmony export */ });
const empty = new Uint8Array(0);
function toHex(d) {
return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
function fromHex(hex) {
const hexes = hex.match(/../g);
return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
function equals(aa, bb) {
if (aa === bb)
return true;
if (aa.byteLength !== bb.byteLength) {
return false;
}
for (let ii = 0; ii < aa.byteLength; ii++) {
if (aa[ii] !== bb[ii]) {
return false;
}
}
return true;
}
function coerce(o) {
if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')
return o;
if (o instanceof ArrayBuffer)
return new Uint8Array(o);
if (ArrayBuffer.isView(o)) {
return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
}
throw new Error('Unknown type, must be binary type');
}
function isBinary(o) {
return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
function fromString(str) {
return new TextEncoder().encode(str);
}
function toString(b) {
return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/cid.js":
/*!*******************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/cid.js ***!
\*******************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CID: () => (/* binding */ CID),
/* harmony export */ format: () => (/* binding */ format),
/* harmony export */ fromJSON: () => (/* binding */ fromJSON),
/* harmony export */ toJSON: () => (/* binding */ toJSON)
/* harmony export */ });
/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base32.js");
/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base36.js");
/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bases/base58.js");
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/digest.js");
/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/varint.js");
/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/link/interface.js");
// This way TS will also expose all the types from module
function format(link, base) {
const { bytes, version } = link;
switch (version) {
case 0:
return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);
default:
return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));
}
}
function toJSON(link) {
return {
'/': format(link)
};
}
function fromJSON(json) {
return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
const baseCache = cache.get(cid);
if (baseCache == null) {
const baseCache = new Map();
cache.set(cid, baseCache);
return baseCache;
}
return baseCache;
}
class CID {
code;
version;
multihash;
bytes;
'/';
/**
* @param version - Version of the CID
* @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
* @param multihash - (Multi)hash of the of the content.
*/
constructor(version, code, multihash, bytes) {
this.code = code;
this.version = version;
this.multihash = multihash;
this.bytes = bytes;
// flag to serializers that this is a CID and
// should be treated specially
this['/'] = bytes;
}
/**
* Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
* please either use `CID.asCID(cid)` or switch to new signalling mechanism
*
* @deprecated
*/
get asCID() {
return this;
}
// ArrayBufferView
get byteOffset() {
return this.bytes.byteOffset;
}
// ArrayBufferView
get byteLength() {
return this.bytes.byteLength;
}
toV0() {
switch (this.version) {
case 0: {
return this;
}
case 1: {
const { code, multihash } = this;
if (code !== DAG_PB_CODE) {
throw new Error('Cannot convert a non dag-pb CID to CIDv0');
}
// sha2-256
if (multihash.code !== SHA_256_CODE) {
throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
}
return (CID.createV0(multihash));
}
default: {
throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
}
}
}
toV1() {
switch (this.version) {
case 0: {
const { code, digest } = this.multihash;
const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);
return (CID.createV1(this.code, multihash));
}
case 1: {
return this;
}
default: {
throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
}
}
}
equals(other) {
return CID.equals(this, other);
}
static equals(self, other) {
const unknown = other;
return (unknown != null &&
self.code === unknown.code &&
self.version === unknown.version &&
_hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));
}
toString(base) {
return format(this, base);
}
toJSON() {
return { '/': format(this) };
}
link() {
return this;
}
[Symbol.toStringTag] = 'CID';
// Legacy
[Symbol.for('nodejs.util.inspect.custom')]() {
return `CID(${this.toString()})`;
}
/**
* Takes any input `value` and returns a `CID` instance if it was
* a `CID` otherwise returns `null`. If `value` is instanceof `CID`
* it will return value back. If `value` is not instance of this CID
* class, but is compatible CID it will return new instance of this
* `CID` class. Otherwise returns null.
*
* This allows two different incompatible versions of CID library to
* co-exist and interop as long as binary interface is compatible.
*/
static asCID(input) {
if (input == null) {
return null;
}
const value = input;
if (value instanceof CID) {
// If value is instance of CID then we're all set.
return value;
}
else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
// If value isn't instance of this CID class but `this.asCID === this` or
// `value['/'] === value.bytes` is true it is CID instance coming from a
// different implementation (diff version or duplicate). In that case we
// rebase it to this `CID` implementation so caller is guaranteed to get
// instance with expected API.
const { version, code, multihash, bytes } = value;
return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
}
else if (value[cidSymbol] === true) {
// If value is a CID from older implementation that used to be tagged via
// symbol we still rebase it to the this `CID` implementation by
// delegating that to a constructor.
const { version, multihash, code } = value;
const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);
return CID.create(version, code, digest);
}
else {
// Otherwise value is not a CID (or an incompatible version of it) in
// which case we return `null`.
return null;
}
}
/**
* @param version - Version of the CID
* @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
* @param digest - (Multi)hash of the of the content.
*/
static create(version, code, digest) {
if (typeof code !== 'number') {
throw new Error('String codecs are no longer supported');
}
if (!(digest.bytes instanceof Uint8Array)) {
throw new Error('Invalid digest');
}
switch (version) {
case 0: {
if (code !== DAG_PB_CODE) {
throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
}
else {
return new CID(version, code, digest, digest.bytes);
}
}
case 1: {
const bytes = encodeCID(version, code, digest.bytes);
return new CID(version, code, digest, bytes);
}
default: {
throw new Error('Invalid version');
}
}
}
/**
* Simplified version of `create` for CIDv0.
*/
static createV0(digest) {
return CID.create(0, DAG_PB_CODE, digest);
}
/**
* Simplified version of `create` for CIDv1.
*
* @param code - Content encoding format code.
* @param digest - Multihash of the content.
*/
static createV1(code, digest) {
return CID.create(1, code, digest);
}
/**
* Decoded a CID from its binary representation. The byte array must contain
* only the CID with no additional bytes.
*
* An error will be thrown if the bytes provided do not contain a valid
* binary representation of a CID.
*/
static decode(bytes) {
const [cid, remainder] = CID.decodeFirst(bytes);
if (remainder.length !== 0) {
throw new Error('Incorrect length');
}
return cid;
}
/**
* Decoded a CID from its binary representation at the beginning of a byte
* array.
*
* Returns an array with the first element containing the CID and the second
* element containing the remainder of the original byte array. The remainder
* will be a zero-length byte array if the provided bytes only contained a
* binary CID representation.
*/
static decodeFirst(bytes) {
const specs = CID.inspectBytes(bytes);
const prefixSize = specs.size - specs.multihashSize;
const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
if (multihashBytes.byteLength !== specs.multihashSize) {
throw new Error('Incorrect length');
}
const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
const cid = specs.version === 0
? CID.createV0(digest)
: CID.createV1(specs.codec, digest);
return [cid, bytes.subarray(specs.size)];
}
/**
* Inspect the initial bytes of a CID to determine its properties.
*
* Involves decoding up to 4 varints. Typically this will require only 4 to 6
* bytes but for larger multicodec code values and larger multihash digest
* lengths these varints can be quite large. It is recommended that at least
* 10 bytes be made available in the `initialBytes` argument for a complete
* inspection.
*/
static inspectBytes(initialBytes) {
let offset = 0;
const next = () => {
const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));
offset += length;
return i;
};
let version = next();
let codec = DAG_PB_CODE;
if (version === 18) {
// CIDv0
version = 0;
offset = 0;
}
else {
codec = next();
}
if (version !== 0 && version !== 1) {
throw new RangeError(`Invalid CID version ${version}`);
}
const prefixSize = offset;
const multihashCode = next(); // multihash code
const digestSize = next(); // multihash length
const size = offset + digestSize;
const multihashSize = size - prefixSize;
return { version, codec, multihashCode, digestSize, multihashSize, size };
}
/**
* Takes cid in a string representation and creates an instance. If `base`
* decoder is not provided will use a default from the configuration. It will
* throw an error if encoding of the CID is not compatible with supplied (or
* a default decoder).
*/
static parse(source, base) {
const [prefix, bytes] = parseCIDtoBytes(source, base);
const cid = CID.decode(bytes);
if (cid.version === 0 && source[0] !== 'Q') {
throw Error('Version 0 CID string must not include multibase prefix');
}
// Cache string representation to avoid computing it on `this.toString()`
baseCache(cid).set(prefix, source);
return cid;
}
}
function parseCIDtoBytes(source, base) {
switch (source[0]) {
// CIDv0 is parsed differently
case 'Q': {
const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;
return [
_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,
decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)
];
}
case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {
const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;
return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];
}
case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {
const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;
return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];
}
case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {
const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;
return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];
}
default: {
if (base == null) {
throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
}
return [source[0], base.decode(source)];
}
}
}
function toStringV0(bytes, cache, base) {
const { prefix } = base;
if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {
throw Error(`Cannot string encode V0 in ${base.name} encoding`);
}
const cid = cache.get(prefix);
if (cid == null) {
const cid = base.encode(bytes).slice(1);
cache.set(prefix, cid);
return cid;
}
else {
return cid;
}
}
function toStringV1(bytes, cache, base) {
const { prefix } = base;
const cid = cache.get(prefix);
if (cid == null) {
const cid = base.encode(bytes);
cache.set(prefix, cid);
return cid;
}
else {
return cid;
}
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);
const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);
const bytes = new Uint8Array(hashOffset + multihash.byteLength);
_varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);
_varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);
bytes.set(multihash, hashOffset);
return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/digest.js":
/*!*****************************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/digest.js ***!
\*****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Digest: () => (/* binding */ Digest),
/* harmony export */ create: () => (/* binding */ create),
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ equals: () => (/* binding */ equals),
/* harmony export */ hasCode: () => (/* binding */ hasCode)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/varint.js");
/**
* Creates a multihash digest.
*/
function create(code, digest) {
const size = digest.byteLength;
const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);
const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);
const bytes = new Uint8Array(digestOffset + size);
_varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);
_varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);
bytes.set(digest, digestOffset);
return new Digest(code, size, digest, bytes);
}
/**
* Turns bytes representation of multihash digest into an instance.
*/
function decode(multihash) {
const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);
const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);
const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));
const digest = bytes.subarray(sizeOffset + digestOffset);
if (digest.byteLength !== size) {
throw new Error('Incorrect length');
}
return new Digest(code, size, digest, bytes);
}
function equals(a, b) {
if (a === b) {
return true;
}
else {
const data = b;
return (a.code === data.code &&
a.size === data.size &&
data.bytes instanceof Uint8Array &&
(0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));
}
}
/**
* Represents a multihash digest which carries information about the
* hashing algorithm and an actual hash digest.
*/
class Digest {
code;
size;
digest;
bytes;
/**
* Creates a multihash digest.
*/
constructor(code, size, digest, bytes) {
this.code = code;
this.size = size;
this.digest = digest;
this.bytes = bytes;
}
}
/**
* Used to check that the passed multihash has the passed code
*/
function hasCode(digest, code) {
return digest.code === code;
}
//# sourceMappingURL=digest.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/hasher.js":
/*!*****************************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/hasher.js ***!
\*****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Hasher: () => (/* binding */ Hasher),
/* harmony export */ from: () => (/* binding */ from)
/* harmony export */ });
/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./digest.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/digest.js");
function from({ name, code, encode }) {
return new Hasher(name, code, encode);
}
/**
* Hasher represents a hashing algorithm implementation that produces as
* `MultihashDigest`.
*/
class Hasher {
name;
code;
encode;
constructor(name, code, encode) {
this.name = name;
this.code = code;
this.encode = encode;
}
digest(input) {
if (input instanceof Uint8Array) {
const result = this.encode(input);
return result instanceof Uint8Array
? _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, result)
/* c8 ignore next 1 */
: result.then(digest => _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, digest));
}
else {
throw Error('Unknown type, must be binary type');
/* c8 ignore next 1 */
}
}
}
//# sourceMappingURL=hasher.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/identity.js":
/*!*******************************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/identity.js ***!
\*******************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ identity: () => (/* binding */ identity)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./digest.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/digest.js");
const code = 0x0;
const name = 'identity';
const encode = _bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce;
function digest(input) {
return _digest_js__WEBPACK_IMPORTED_MODULE_1__.create(code, encode(input));
}
const identity = { code, name, encode, digest };
//# sourceMappingURL=identity.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/sha2-browser.js":
/*!***********************************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/sha2-browser.js ***!
\***********************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ sha256: () => (/* binding */ sha256),
/* harmony export */ sha512: () => (/* binding */ sha512)
/* harmony export */ });
/* harmony import */ var _hasher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hasher.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/hashes/hasher.js");
/* global crypto */
function sha(name) {
return async (data) => new Uint8Array(await crypto.subtle.digest(name, data));
}
const sha256 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({
name: 'sha2-256',
code: 0x12,
encode: sha('SHA-256')
});
const sha512 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({
name: 'sha2-512',
code: 0x13,
encode: sha('SHA-512')
});
//# sourceMappingURL=sha2-browser.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/link/interface.js":
/*!******************************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/link/interface.js ***!
\******************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* eslint-disable @typescript-eslint/no-unnecessary-type-constraint */
/* eslint-disable no-use-before-define */
//# sourceMappingURL=interface.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/varint.js":
/*!**********************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/varint.js ***!
\**********************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ encodeTo: () => (/* binding */ encodeTo),
/* harmony export */ encodingLength: () => (/* binding */ encodingLength)
/* harmony export */ });
/* harmony import */ var _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vendor/varint.js */ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/vendor/varint.js");
function decode(data, offset = 0) {
const code = _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].decode(data, offset);
return [code, _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].decode.bytes];
}
function encodeTo(int, target, offset = 0) {
_vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].encode(int, target, offset);
return target;
}
function encodingLength(int) {
return _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].encodingLength(int);
}
//# sourceMappingURL=varint.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/vendor/base-x.js":
/*!*****************************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/vendor/base-x.js ***!
\*****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
* @param {string} ALPHABET
* @param {any} name
*/
function base(ALPHABET, name) {
if (ALPHABET.length >= 255) {
throw new TypeError('Alphabet too long');
}
var BASE_MAP = new Uint8Array(256);
for (var j = 0; j < BASE_MAP.length; j++) {
BASE_MAP[j] = 255;
}
for (var i = 0; i < ALPHABET.length; i++) {
var x = ALPHABET.charAt(i);
var xc = x.charCodeAt(0);
if (BASE_MAP[xc] !== 255) {
throw new TypeError(x + ' is ambiguous');
}
BASE_MAP[xc] = i;
}
var BASE = ALPHABET.length;
var LEADER = ALPHABET.charAt(0);
var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
/**
* @param {any[] | Iterable<number>} source
*/
function encode(source) {
// @ts-ignore
if (source instanceof Uint8Array)
;
else if (ArrayBuffer.isView(source)) {
source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
}
else if (Array.isArray(source)) {
source = Uint8Array.from(source);
}
if (!(source instanceof Uint8Array)) {
throw new TypeError('Expected Uint8Array');
}
if (source.length === 0) {
return '';
}
// Skip & count leading zeroes.
var zeroes = 0;
var length = 0;
var pbegin = 0;
var pend = source.length;
while (pbegin !== pend && source[pbegin] === 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
var b58 = new Uint8Array(size);
// Process the bytes.
while (pbegin !== pend) {
var carry = source[pbegin];
// Apply "b58 = b58 * 256 + ch".
var i = 0;
for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
carry += (256 * b58[it1]) >>> 0;
b58[it1] = (carry % BASE) >>> 0;
carry = (carry / BASE) >>> 0;
}
if (carry !== 0) {
throw new Error('Non-zero carry');
}
length = i;
pbegin++;
}
// Skip leading zeroes in base58 result.
var it2 = size - length;
while (it2 !== size && b58[it2] === 0) {
it2++;
}
// Translate the result into a string.
var str = LEADER.repeat(zeroes);
for (; it2 < size; ++it2) {
str += ALPHABET.charAt(b58[it2]);
}
return str;
}
/**
* @param {string | string[]} source
*/
function decodeUnsafe(source) {
if (typeof source !== 'string') {
throw new TypeError('Expected String');
}
if (source.length === 0) {
return new Uint8Array();
}
var psz = 0;
// Skip leading spaces.
if (source[psz] === ' ') {
return;
}
// Skip and count leading '1's.
var zeroes = 0;
var length = 0;
while (source[psz] === LEADER) {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
var b256 = new Uint8Array(size);
// Process the characters.
while (source[psz]) {
// Decode character
var carry = BASE_MAP[source.charCodeAt(psz)];
// Invalid character
if (carry === 255) {
return;
}
var i = 0;
for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
carry += (BASE * b256[it3]) >>> 0;
b256[it3] = (carry % 256) >>> 0;
carry = (carry / 256) >>> 0;
}
if (carry !== 0) {
throw new Error('Non-zero carry');
}
length = i;
psz++;
}
// Skip trailing spaces.
if (source[psz] === ' ') {
return;
}
// Skip leading zeroes in b256.
var it4 = size - length;
while (it4 !== size && b256[it4] === 0) {
it4++;
}
var vch = new Uint8Array(zeroes + (size - it4));
var j = zeroes;
while (it4 !== size) {
vch[j++] = b256[it4++];
}
return vch;
}
/**
* @param {string | string[]} string
*/
function decode(string) {
var buffer = decodeUnsafe(string);
if (buffer) {
return buffer;
}
throw new Error(`Non-${name} character`);
}
return {
encode: encode,
decodeUnsafe: decodeUnsafe,
decode: decode
};
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp__multiformats_scope_baseX);
//# sourceMappingURL=base-x.js.map
/***/ }),
/***/ "./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/vendor/varint.js":
/*!*****************************************************************************************!*\
!*** ./node_modules/@libp2p/crypto/node_modules/multiformats/dist/src/vendor/varint.js ***!
\*****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
* @param {number} num
* @param {number[]} out
* @param {number} offset
*/
function encode(num, out, offset) {
out = out || [];
offset = offset || 0;
var oldOffset = offset;
while (num >= INT) {
out[offset++] = (num & 0xFF) | MSB;
num /= 128;
}
while (num & MSBALL) {
out[offset++] = (num & 0xFF) | MSB;
num >>>= 7;
}
out[offset] = num | 0;
// @ts-ignore
encode.bytes = offset - oldOffset + 1;
return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
* @param {string | any[]} buf
* @param {number} offset
*/
function read(buf, offset) {
var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
do {
if (counter >= l) {
// @ts-ignore
read.bytes = 0;
throw new RangeError('Could not decode varint');
}
b = buf[counter++];
res += shift < 28
? (b & REST$1) << shift
: (b & REST$1) * Math.pow(2, shift);
shift += 7;
} while (b >= MSB$1);
// @ts-ignore
read.bytes = counter - offset;
return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
return (value < N1 ? 1
: value < N2 ? 2
: value < N3 ? 3
: value < N4 ? 4
: value < N5 ? 5
: value < N6 ? 6
: value < N7 ? 7
: value < N8 ? 8
: value < N9 ? 9
: 10);
};
var varint = {
encode: encode_1,
decode: decode,
encodingLength: length
};
var _brrp_varint = varint;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp_varint);
//# sourceMappingURL=varint.js.map
/***/ }),
/***/ "./node_modules/@libp2p/interface/dist/src/errors.js":
/*!***********************************************************!*\
!*** ./node_modules/@libp2p/interface/dist/src/errors.js ***!
\***********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AbortError: () => (/* binding */ AbortError),
/* harmony export */ AlreadyStartedError: () => (/* binding */ AlreadyStartedError),
/* harmony export */ ConnectionClosedError: () => (/* binding */ ConnectionClosedError),
/* harmony export */ ConnectionClosingError: () => (/* binding */ ConnectionClosingError),
/* harmony export */ ConnectionFailedError: () => (/* binding */ ConnectionFailedError),
/* harmony export */ DialError: () => (/* binding */ DialError),
/* harmony export */ InvalidCIDError: () => (/* binding */ InvalidCIDError),
/* harmony export */ InvalidCryptoExchangeError: () => (/* binding */ InvalidCryptoExchangeError),
/* harmony export */ InvalidMessageError: () => (/* binding */ InvalidMessageError),
/* harmony export */ InvalidMultiaddrError: () => (/* binding */ InvalidMultiaddrError),
/* harmony export */ InvalidMultihashError: () => (/* binding */ InvalidMultihashError),
/* harmony export */ InvalidParametersError: () => (/* binding */ InvalidParametersError),
/* harmony export */ InvalidPeerIdError: () => (/* binding */ InvalidPeerIdError),
/* harmony export */ InvalidPrivateKeyError: () => (/* binding */ InvalidPrivateKeyError),
/* harmony export */ InvalidPublicKeyError: () => (/* binding */ InvalidPublicKeyError),
/* harmony export */ LimitedConnectionError: () => (/* binding */ LimitedConnectionError),
/* harmony export */ ListenError: () => (/* binding */ ListenError),
/* harmony export */ MuxerClosedError: () => (/* binding */ MuxerClosedError),
/* harmony export */ NotFoundError: () => (/* binding */ NotFoundError),
/* harmony export */ NotStartedError: () => (/* binding */ NotStartedError),
/* harmony export */ ProtocolError: () => (/* binding */ ProtocolError),
/* harmony export */ StreamResetError: () => (/* binding */ StreamResetError),
/* harmony export */ StreamStateError: () => (/* binding */ StreamStateError),
/* harmony export */ TimeoutError: () => (/* binding */ TimeoutError),
/* harmony export */ TooManyInboundProtocolStreamsError: () => (/* binding */ TooManyInboundProtocolStreamsError),
/* harmony export */ TooManyOutboundProtocolStreamsError: () => (/* binding */ TooManyOutboundProtocolStreamsError),
/* harmony export */ UnexpectedPeerError: () => (/* binding */ UnexpectedPeerError),
/* harmony export */ UnsupportedKeyTypeError: () => (/* binding */ UnsupportedKeyTypeError),
/* harmony export */ UnsupportedOperationError: () => (/* binding */ UnsupportedOperationError),
/* harmony export */ UnsupportedProtocolError: () => (/* binding */ UnsupportedProtocolError)
/* harmony export */ });
/**
* When this error is thrown it means an operation was aborted,
* usually in response to the `abort` event being emitted by an
* AbortSignal.
*/
class AbortError extends Error {
static name = 'AbortError';
constructor(message = 'The operation was aborted') {
super(message);
this.name = 'AbortError';
}
}
/**
* Thrown when a remote Peer ID does not match the expected one
*/
class UnexpectedPeerError extends Error {
static name = 'UnexpectedPeerError';
constructor(message = 'Unexpected Peer') {
super(message);
this.name = 'UnexpectedPeerError';
}
}
/**
* Thrown when a crypto exchange fails
*/
class InvalidCryptoExchangeError extends Error {
static name = 'InvalidCryptoExchangeError';
constructor(message = 'Invalid crypto exchange') {
super(message);
this.name = 'InvalidCryptoExchangeError';
}
}
/**
* Thrown when invalid parameters are passed to a function or method call
*/
class InvalidParametersError extends Error {
static name = 'InvalidParametersError';
constructor(message = 'Invalid parameters') {
super(message);
this.name = 'InvalidParametersError';
}
}
/**
* Thrown when a public key is invalid
*/
class InvalidPublicKeyError extends Error {
static name = 'InvalidPublicKeyError';
constructor(message = 'Invalid public key') {
super(message);
this.name = 'InvalidPublicKeyError';
}
}
/**
* Thrown when a private key is invalid
*/
class InvalidPrivateKeyError extends Error {
static name = 'InvalidPrivateKeyError';
constructor(message = 'Invalid private key') {
super(message);
this.name = 'InvalidPrivateKeyError';
}
}
/**
* Thrown when a operation is unsupported
*/
class UnsupportedOperationError extends Error {
static name = 'UnsupportedOperationError';
constructor(message = 'Unsupported operation') {
super(message);
this.name = 'UnsupportedOperationError';
}
}
/**
* Thrown when a connection is closing
*/
class ConnectionClosingError extends Error {
static name = 'ConnectionClosingError';
constructor(message = 'The connection is closing') {
super(message);
this.name = 'ConnectionClosingError';
}
}
/**
* Thrown when a connection is closed
*/
class ConnectionClosedError extends Error {
static name = 'ConnectionClosedError';
constructor(message = 'The connection is closed') {
super(message);
this.name = 'ConnectionClosedError';
}
}
/**
* Thrown when a connection fails
*/
class ConnectionFailedError extends Error {
static name = 'ConnectionFailedError';
constructor(message = 'Connection failed') {
super(message);
this.name = 'ConnectionFailedError';
}
}
/**
* Thrown when the muxer is closed and an attempt to open a stream occurs
*/
class MuxerClosedError extends Error {
static name = 'MuxerClosedError';
constructor(message = 'The muxer is closed') {
super(message);
this.name = 'MuxerClosedError';
}
}
/**
* Thrown when a protocol stream is reset by the remote muxer
*/
class StreamResetError extends Error {
static name = 'StreamResetError';
constructor(message = 'The stream has been reset') {
super(message);
this.name = 'StreamResetError';
}
}
/**
* Thrown when a stream is in an invalid state
*/
class StreamStateError extends Error {
static name = 'StreamStateError';
constructor(message = 'The stream is in an invalid state') {
super(message);
this.name = 'StreamStateError';
}
}
/**
* Thrown when a value could not be found
*/
class NotFoundError extends Error {
static name = 'NotFoundError';
constructor(message = 'Not found') {
super(message);
this.name = 'NotFoundError';
}
}
/**
* Thrown when an invalid peer ID is encountered
*/
class InvalidPeerIdError extends Error {
static name = 'InvalidPeerIdError';
constructor(message = 'Invalid PeerID') {
super(message);
this.name = 'InvalidPeerIdError';
}
}
/**
* Thrown when an invalid multiaddr is encountered
*/
class InvalidMultiaddrError extends Error {
static name = 'InvalidMultiaddrError';
constructor(message = 'Invalid multiaddr') {
super(message);
this.name = 'InvalidMultiaddrError';
}
}
/**
* Thrown when an invalid CID is encountered
*/
class InvalidCIDError extends Error {
static name = 'InvalidCIDError';
constructor(message = 'Invalid CID') {
super(message);
this.name = 'InvalidCIDError';
}
}
/**
* Thrown when an invalid multihash is encountered
*/
class InvalidMultihashError extends Error {
static name = 'InvalidMultihashError';
constructor(message = 'Invalid Multihash') {
super(message);
this.name = 'InvalidMultihashError';
}
}
/**
* Thrown when a protocol is not supported
*/
class UnsupportedProtocolError extends Error {
static name = 'UnsupportedProtocolError';
constructor(message = 'Unsupported protocol error') {
super(message);
this.name = 'UnsupportedProtocolError';
}
}
/**
* An invalid or malformed message was encountered during a protocol exchange
*/
class InvalidMessageError extends Error {
static name = 'InvalidMessageError';
constructor(message = 'Invalid message') {
super(message);
this.name = 'InvalidMessageError';
}
}
/**
* Thrown when a remote peer sends a structurally valid message that does not
* comply with the protocol
*/
class ProtocolError extends Error {
static name = 'ProtocolError';
constructor(message = 'Protocol error') {
super(message);
this.name = 'ProtocolError';
}
}
/**
* Throw when an operation times out
*/
class TimeoutError extends Error {
static name = 'TimeoutError';
constructor(message = 'Timed out') {
super(message);
this.name = 'TimeoutError';
}
}
/**
* Thrown when a startable component is interacted with but it has not been
* started yet
*/
class NotStartedError extends Error {
static name = 'NotStartedError';
constructor(message = 'Not started') {
super(message);
this.name = 'NotStartedError';
}
}
/**
* Thrown when a component is started that has already been started
*/
class AlreadyStartedError extends Error {
static name = 'AlreadyStartedError';
constructor(message = 'Already started') {
super(message);
this.name = 'AlreadyStartedError';
}
}
/**
* Thrown when dialing an address failed
*/
class DialError extends Error {
static name = 'DialError';
constructor(message = 'Dial error') {
super(message);
this.name = 'DialError';
}
}
/**
* Thrown when listening on an address failed
*/
class ListenError extends Error {
static name = 'ListenError';
constructor(message = 'Listen error') {
super(message);
this.name = 'ListenError';
}
}
/**
* This error is thrown when a limited connection is encountered, i.e. if the
* user tried to open a stream on a connection for a protocol that is not
* configured to run over limited connections.
*/
class LimitedConnectionError extends Error {
static name = 'LimitedConnectionError';
constructor(message = 'Limited connection') {
super(message);
this.name = 'LimitedConnectionError';
}
}
/**
* This error is thrown where there are too many inbound protocols streams open
*/
class TooManyInboundProtocolStreamsError extends Error {
static name = 'TooManyInboundProtocolStreamsError';
constructor(message = 'Too many inbound protocol streams') {
super(message);
this.name = 'TooManyInboundProtocolStreamsError';
}
}
/**
* This error is thrown where there are too many outbound protocols streams open
*/
class TooManyOutboundProtocolStreamsError extends Error {
static name = 'TooManyOutboundProtocolStreamsError';
constructor(message = 'Too many outbound protocol streams') {
super(message);
this.name = 'TooManyOutboundProtocolStreamsError';
}
}
/**
* Thrown when and attempt to operate on an unsupported key was made
*/
class UnsupportedKeyTypeError extends Error {
static name = 'UnsupportedKeyTypeError';
constructor(message = 'Unsupported key type') {
super(message);
this.name = 'UnsupportedKeyTypeError';
}
}
//# sourceMappingURL=errors.js.map
/***/ }),
/***/ "./node_modules/@noble/curves/esm/_shortw_utils.js":
/*!*********************************************************!*\
!*** ./node_modules/@noble/curves/esm/_shortw_utils.js ***!
\*********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ createCurve: () => (/* binding */ createCurve),
/* harmony export */ getHash: () => (/* binding */ getHash)
/* harmony export */ });
/* harmony import */ var _noble_hashes_hmac__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @noble/hashes/hmac */ "./node_modules/@noble/hashes/esm/hmac.js");
/* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/esm/utils.js");
/* harmony import */ var _abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./abstract/weierstrass.js */ "./node_modules/@noble/curves/esm/abstract/weierstrass.js");
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// connects noble-curves to noble-hashes
function getHash(hash) {
return {
hash,
hmac: (key, ...msgs) => (0,_noble_hashes_hmac__WEBPACK_IMPORTED_MODULE_0__.hmac)(hash, key, (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__.concatBytes)(...msgs)),
randomBytes: _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__.randomBytes,
};
}
function createCurve(curveDef, defHash) {
const create = (hash) => (0,_abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_2__.weierstrass)({ ...curveDef, ...getHash(hash) });
return Object.freeze({ ...create(defHash), create });
}
//# sourceMappingURL=_shortw_utils.js.map
/***/ }),
/***/ "./node_modules/@noble/curves/esm/abstract/curve.js":
/*!**********************************************************!*\
!*** ./node_modules/@noble/curves/esm/abstract/curve.js ***!
\**********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ validateBasic: () => (/* binding */ validateBasic),
/* harmony export */ wNAF: () => (/* binding */ wNAF)
/* harmony export */ });
/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./modular.js */ "./node_modules/@noble/curves/esm/abstract/modular.js");
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// Abelian group utilities
const _0n = BigInt(0);
const _1n = BigInt(1);
// Elliptic curve multiplication of Point by scalar. Fragile.
// Scalars should always be less than curve order: this should be checked inside of a curve itself.
// Creates precomputation tables for fast multiplication:
// - private scalar is split by fixed size windows of W bits
// - every window point is collected from window's table & added to accumulator
// - since windows are different, same point inside tables won't be accessed more than once per calc
// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
// - +1 window is neccessary for wNAF
// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
// windows to be in different memory locations
function wNAF(c, bits) {
const constTimeNegate = (condition, item) => {
const neg = item.negate();
return condition ? neg : item;
};
const opts = (W) => {
const windows = Math.ceil(bits / W) + 1; // +1, because
const windowSize = 2 ** (W - 1); // -1 because we skip zero
return { windows, windowSize };
};
return {
constTimeNegate,
// non-const time multiplication ladder
unsafeLadder(elm, n) {
let p = c.ZERO;
let d = elm;
while (n > _0n) {
if (n & _1n)
p = p.add(d);
d = d.double();
n >>= _1n;
}
return p;
},
/**
* Creates a wNAF precomputation window. Used for caching.
* Default window size is set by `utils.precompute()` and is equal to 8.
* Number of precomputed points depends on the curve size:
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
* - 𝑊 is the window size
* - 𝑛 is the bitlength of the curve order.
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
* @returns precomputed point tables flattened to a single array
*/
precomputeWindow(elm, W) {
const { windows, windowSize } = opts(W);
const points = [];
let p = elm;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
// =1, because we skip zero
for (let i = 1; i < windowSize; i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
},
/**
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
* @param W window size
* @param precomputes precomputed tables
* @param n scalar (we don't check here, but should be less than curve order)
* @returns real and fake (for const-time) points
*/
wNAF(W, precomputes, n) {
// TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
// But need to carefully remove other checks before wNAF. ORDER == bits here
const { windows, windowSize } = opts(W);
let p = c.ZERO;
let f = c.BASE;
const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
const maxNumber = 2 ** W;
const shiftBy = BigInt(W);
for (let window = 0; window < windows; window++) {
const offset = window * windowSize;
// Extract W bits.
let wbits = Number(n & mask);
// Shift number by W bits.
n >>= shiftBy;
// If the bits are bigger than max size, we'll split those.
// +224 => 256 - 32
if (wbits > windowSize) {
wbits -= maxNumber;
n += _1n;
}
// This code was first written with assumption that 'f' and 'p' will never be infinity point:
// since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
// there is negate now: it is possible that negated element from low value
// would be the same as high element, which will create carry into next window.
// It's not obvious how this can fail, but still worth investigating later.
// Check if we're onto Zero point.
// Add random point inside current window to f.
const offset1 = offset;
const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
const cond1 = window % 2 !== 0;
const cond2 = wbits < 0;
if (wbits === 0) {
// The most important part for const-time getPublicKey
f = f.add(constTimeNegate(cond1, precomputes[offset1]));
}
else {
p = p.add(constTimeNegate(cond2, precomputes[offset2]));
}
}
// JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
// Even if the variable is still unused, there are some checks which will
// throw an exception, so compiler needs to prove they won't happen, which is hard.
// At this point there is a way to F be infinity-point even if p is not,
// which makes it less const-time: around 1 bigint multiply.
return { p, f };
},
wNAFCached(P, precomputesMap, n, transform) {
// @ts-ignore
const W = P._WINDOW_SIZE || 1;
// Calculate precomputes on a first run, reuse them after
let comp = precomputesMap.get(P);
if (!comp) {
comp = this.precomputeWindow(P, W);
if (W !== 1) {
precomputesMap.set(P, transform(comp));
}
}
return this.wNAF(W, comp, n);
},
};
}
function validateBasic(curve) {
(0,_modular_js__WEBPACK_IMPORTED_MODULE_0__.validateField)(curve.Fp);
(0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject)(curve, {
n: 'bigint',
h: 'bigint',
Gx: 'field',
Gy: 'field',
}, {
nBitLength: 'isSafeInteger',
nByteLength: 'isSafeInteger',
});
// Set defaults
return Object.freeze({
...(0,_modular_js__WEBPACK_IMPORTED_MODULE_0__.nLength)(curve.n, curve.nBitLength),
...curve,
...{ p: curve.Fp.ORDER },
});
}
//# sourceMappingURL=curve.js.map
/***/ }),
/***/ "./node_modules/@noble/curves/esm/abstract/edwards.js":
/*!************************************************************!*\
!*** ./node_modules/@noble/curves/esm/abstract/edwards.js ***!
\************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ twistedEdwards: () => (/* binding */ twistedEdwards)
/* harmony export */ });
/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./modular.js */ "./node_modules/@noble/curves/esm/abstract/modular.js");
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
/* harmony import */ var _curve_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./curve.js */ "./node_modules/@noble/curves/esm/abstract/curve.js");
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);
// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:
const VERIFY_DEFAULT = { zip215: true };
function validateOpts(curve) {
const opts = (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.validateBasic)(curve);
_utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject(curve, {
hash: 'function',
a: 'bigint',
d: 'bigint',
randomBytes: 'function',
}, {
adjustScalarBytes: 'function',
domain: 'function',
uvRatio: 'function',
mapToCurve: 'function',
});
// Set defaults
return Object.freeze({ ...opts });
}
// It is not generic twisted curve for now, but ed25519/ed448 generic implementation
function twistedEdwards(curveDef) {
const CURVE = validateOpts(curveDef);
const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
const MASK = _2n << (BigInt(nByteLength * 8) - _1n);
const modP = Fp.create; // Function overrides
// sqrt(u/v)
const uvRatio = CURVE.uvRatio ||
((u, v) => {
try {
return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };
}
catch (e) {
return { isValid: false, value: _0n };
}
});
const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP
const domain = CURVE.domain ||
((data, ctx, phflag) => {
if (ctx.length || phflag)
throw new Error('Contexts/pre-hash are not supported');
return data;
}); // NOOP
const inBig = (n) => typeof n === 'bigint' && _0n < n; // n in [1..]
const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]
const in0MaskRange = (n) => n === _0n || inRange(n, MASK); // n in [0..MASK-1]
function assertInRange(n, max) {
// n in [1..max-1]
if (inRange(n, max))
return n;
throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);
}
function assertGE0(n) {
// n in [0..CURVE_ORDER-1]
return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group
}
const pointPrecomputes = new Map();
function isPoint(other) {
if (!(other instanceof Point))
throw new Error('ExtendedPoint expected');
}
// Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).
// https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
class Point {
constructor(ex, ey, ez, et) {
this.ex = ex;
this.ey = ey;
this.ez = ez;
this.et = et;
if (!in0MaskRange(ex))
throw new Error('x required');
if (!in0MaskRange(ey))
throw new Error('y required');
if (!in0MaskRange(ez))
throw new Error('z required');
if (!in0MaskRange(et))
throw new Error('t required');
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
static fromAffine(p) {
if (p instanceof Point)
throw new Error('extended point not allowed');
const { x, y } = p || {};
if (!in0MaskRange(x) || !in0MaskRange(y))
throw new Error('invalid affine point');
return new Point(x, y, _1n, modP(x * y));
}
static normalizeZ(points) {
const toInv = Fp.invertBatch(points.map((p) => p.ez));
return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
}
// "Private method", don't use it directly
_setWindowSize(windowSize) {
this._WINDOW_SIZE = windowSize;
pointPrecomputes.delete(this);
}
// Not required for fromHex(), which always creates valid points.
// Could be useful for fromAffine().
assertValidity() {
const { a, d } = CURVE;
if (this.is0())
throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
// Equation in affine coordinates: ax² + y² = 1 + dx²y²
// Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
const { ex: X, ey: Y, ez: Z, et: T } = this;
const X2 = modP(X * X); // X²
const Y2 = modP(Y * Y); // Y²
const Z2 = modP(Z * Z); // Z²
const Z4 = modP(Z2 * Z2); // Z⁴
const aX2 = modP(X2 * a); // aX²
const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
if (left !== right)
throw new Error('bad point: equation left != right (1)');
// In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
const XY = modP(X * Y);
const ZT = modP(Z * T);
if (XY !== ZT)
throw new Error('bad point: equation left != right (2)');
}
// Compare one point to another.
equals(other) {
isPoint(other);
const { ex: X1, ey: Y1, ez: Z1 } = this;
const { ex: X2, ey: Y2, ez: Z2 } = other;
const X1Z2 = modP(X1 * Z2);
const X2Z1 = modP(X2 * Z1);
const Y1Z2 = modP(Y1 * Z2);
const Y2Z1 = modP(Y2 * Z1);
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
}
is0() {
return this.equals(Point.ZERO);
}
negate() {
// Flips point sign to a negative one (-x, y in affine coords)
return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));
}
// Fast algo for doubling Extended Point.
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
// Cost: 4M + 4S + 1*a + 6add + 1*2.
double() {
const { a } = CURVE;
const { ex: X1, ey: Y1, ez: Z1 } = this;
const A = modP(X1 * X1); // A = X12
const B = modP(Y1 * Y1); // B = Y12
const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12
const D = modP(a * A); // D = a*A
const x1y1 = X1 + Y1;
const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B
const G = D + B; // G = D+B
const F = G - C; // F = G-C
const H = D - B; // H = D-B
const X3 = modP(E * F); // X3 = E*F
const Y3 = modP(G * H); // Y3 = G*H
const T3 = modP(E * H); // T3 = E*H
const Z3 = modP(F * G); // Z3 = F*G
return new Point(X3, Y3, Z3, T3);
}
// Fast algo for adding 2 Extended Points.
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
// Cost: 9M + 1*a + 1*d + 7add.
add(other) {
isPoint(other);
const { a, d } = CURVE;
const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;
// Faster algo for adding 2 Extended Points when curve's a=-1.
// http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4
// Cost: 8M + 8add + 2*2.
// Note: It does not check whether the `other` point is valid.
if (a === BigInt(-1)) {
const A = modP((Y1 - X1) * (Y2 + X2));
const B = modP((Y1 + X1) * (Y2 - X2));
const F = modP(B - A);
if (F === _0n)
return this.double(); // Same point. Tests say it doesn't affect timing
const C = modP(Z1 * _2n * T2);
const D = modP(T1 * _2n * Z2);
const E = D + C;
const G = B + A;
const H = D - C;
const X3 = modP(E * F);
const Y3 = modP(G * H);
const T3 = modP(E * H);
const Z3 = modP(F * G);
return new Point(X3, Y3, Z3, T3);
}
const A = modP(X1 * X2); // A = X1*X2
const B = modP(Y1 * Y2); // B = Y1*Y2
const C = modP(T1 * d * T2); // C = T1*d*T2
const D = modP(Z1 * Z2); // D = Z1*Z2
const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B
const F = D - C; // F = D-C
const G = D + C; // G = D+C
const H = modP(B - a * A); // H = B-a*A
const X3 = modP(E * F); // X3 = E*F
const Y3 = modP(G * H); // Y3 = G*H
const T3 = modP(E * H); // T3 = E*H
const Z3 = modP(F * G); // Z3 = F*G
return new Point(X3, Y3, Z3, T3);
}
subtract(other) {
return this.add(other.negate());
}
wNAF(n) {
return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);
}
// Constant-time multiplication.
multiply(scalar) {
const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));
return Point.normalizeZ([p, f])[0];
}
// Non-constant-time multiplication. Uses double-and-add algorithm.
// It's faster, but should only be used when you don't care about
// an exposed private key e.g. sig verification.
// Does NOT allow scalars higher than CURVE.n.
multiplyUnsafe(scalar) {
let n = assertGE0(scalar); // 0 <= scalar < CURVE.n
if (n === _0n)
return I;
if (this.equals(I) || n === _1n)
return this;
if (this.equals(G))
return this.wNAF(n).p;
return wnaf.unsafeLadder(this, n);
}
// Checks if point is of small order.
// If you add something to small order point, you will have "dirty"
// point with torsion component.
// Multiplies point by cofactor and checks if the result is 0.
isSmallOrder() {
return this.multiplyUnsafe(cofactor).is0();
}
// Multiplies point by curve order and checks if the result is 0.
// Returns `false` is the point is dirty.
isTorsionFree() {
return wnaf.unsafeLadder(this, CURVE_ORDER).is0();
}
// Converts Extended point to default (x, y) coordinates.
// Can accept precomputed Z^-1 - for example, from invertBatch.
toAffine(iz) {
const { ex: x, ey: y, ez: z } = this;
const is0 = this.is0();
if (iz == null)
iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily
const ax = modP(x * iz);
const ay = modP(y * iz);
const zz = modP(z * iz);
if (is0)
return { x: _0n, y: _1n };
if (zz !== _1n)
throw new Error('invZ was invalid');
return { x: ax, y: ay };
}
clearCofactor() {
const { h: cofactor } = CURVE;
if (cofactor === _1n)
return this;
return this.multiplyUnsafe(cofactor);
}
// Converts hash string or Uint8Array to Point.
// Uses algo from RFC8032 5.1.3.
static fromHex(hex, zip215 = false) {
const { d, a } = CURVE;
const len = Fp.BYTES;
hex = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('pointHex', hex, len); // copy hex to a new array
const normed = hex.slice(); // copy again, we'll manipulate it
const lastByte = hex[len - 1]; // select last byte
normed[len - 1] = lastByte & ~0x80; // clear last bit
const y = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberLE(normed);
if (y === _0n) {
// y=0 is allowed
}
else {
// RFC8032 prohibits >= p, but ZIP215 doesn't
if (zip215)
assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)
else
assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)
}
// Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:
// ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)
const y2 = modP(y * y); // denominator is always non-0 mod p.
const u = modP(y2 - _1n); // u = y² - 1
const v = modP(d * y2 - a); // v = d y² + 1.
let { isValid, value: x } = uvRatio(u, v); // √(u/v)
if (!isValid)
throw new Error('Point.fromHex: invalid y coordinate');
const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper
const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
if (!zip215 && x === _0n && isLastByteOdd)
// if x=0 and x_0 = 1, fail
throw new Error('Point.fromHex: x=0 and x_0=1');
if (isLastByteOdd !== isXOdd)
x = modP(-x); // if x_0 != x mod 2, set x = p-x
return Point.fromAffine({ x, y });
}
static fromPrivateKey(privKey) {
return getExtendedPublicKey(privKey).point;
}
toRawBytes() {
const { x, y } = this.toAffine();
const bytes = _utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)
bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y
return bytes; // and use the last byte to encode sign of x
}
toHex() {
return _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.
}
}
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));
Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0
const { BASE: G, ZERO: I } = Point;
const wnaf = (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.wNAF)(Point, nByteLength * 8);
function modN(a) {
return (0,_modular_js__WEBPACK_IMPORTED_MODULE_2__.mod)(a, CURVE_ORDER);
}
// Little-endian SHA512 with modulo n
function modN_LE(hash) {
return modN(_utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberLE(hash));
}
/** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */
function getExtendedPublicKey(key) {
const len = nByteLength;
key = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('private key', key, len);
// Hash private key with curve's hash function to produce uniformingly random input
// Check byte lengths: ensure(64, h(ensure(32, key)))
const hashed = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('hashed private key', cHash(key), 2 * len);
const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE
const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)
const scalar = modN_LE(head); // The actual private scalar
const point = G.multiply(scalar); // Point on Edwards curve aka public key
const pointBytes = point.toRawBytes(); // Uint8Array representation
return { head, prefix, scalar, point, pointBytes };
}
// Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared
function getPublicKey(privKey) {
return getExtendedPublicKey(privKey).pointBytes;
}
// int('LE', SHA512(dom2(F, C) || msgs)) mod N
function hashDomainToScalar(context = new Uint8Array(), ...msgs) {
const msg = _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes(...msgs);
return modN_LE(cHash(domain(msg, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('context', context), !!prehash)));
}
/** Signs message with privateKey. RFC8032 5.1.6 */
function sign(msg, privKey, options = {}) {
msg = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('message', msg);
if (prehash)
msg = prehash(msg); // for ed25519ph etc.
const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);
const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)
const R = G.multiply(r).toRawBytes(); // R = rG
const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)
const s = modN(r + k * scalar); // S = (r + k * s) mod L
assertGE0(s); // 0 <= s < l
const res = _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes(R, _utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesLE(s, Fp.BYTES));
return (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('result', res, nByteLength * 2); // 64-byte signature
}
const verifyOpts = VERIFY_DEFAULT;
function verify(sig, msg, publicKey, options = verifyOpts) {
const { context, zip215 } = options;
const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
sig = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('signature', sig, 2 * len); // An extended group equation is checked.
msg = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('message', msg);
if (prehash)
msg = prehash(msg); // for ed25519ph, etc
const s = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberLE(sig.slice(len, 2 * len));
// zip215: true is good for consensus-critical apps and allows points < 2^256
// zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p
let A, R, SB;
try {
A = Point.fromHex(publicKey, zip215);
R = Point.fromHex(sig.slice(0, len), zip215);
SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside
}
catch (error) {
return false;
}
if (!zip215 && A.isSmallOrder())
return false;
const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
const RkA = R.add(A.multiplyUnsafe(k));
// [8][S]B = [8]R + [8][k]A'
return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
}
G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
const utils = {
getExtendedPublicKey,
// ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.
randomPrivateKey: () => randomBytes(Fp.BYTES),
/**
* We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT
* values. This slows down first getPublicKey() by milliseconds (see Speed section),
* but allows to speed-up subsequent getPublicKey() calls up to 20x.
* @param windowSize 2, 4, 8, 16
*/
precompute(windowSize = 8, point = Point.BASE) {
point._setWindowSize(windowSize);
point.multiply(BigInt(3));
return point;
},
};
return {
CURVE,
getPublicKey,
sign,
verify,
ExtendedPoint: Point,
utils,
};
}
//# sourceMappingURL=edwards.js.map
/***/ }),
/***/ "./node_modules/@noble/curves/esm/abstract/hash-to-curve.js":
/*!******************************************************************!*\
!*** ./node_modules/@noble/curves/esm/abstract/hash-to-curve.js ***!
\******************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ createHasher: () => (/* binding */ createHasher),
/* harmony export */ expand_message_xmd: () => (/* binding */ expand_message_xmd),
/* harmony export */ expand_message_xof: () => (/* binding */ expand_message_xof),
/* harmony export */ hash_to_field: () => (/* binding */ hash_to_field),
/* harmony export */ isogenyMap: () => (/* binding */ isogenyMap)
/* harmony export */ });
/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./modular.js */ "./node_modules/@noble/curves/esm/abstract/modular.js");
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = _utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
if (value < 0 || value >= 1 << (8 * length)) {
throw new Error(`bad I2OSP call: value=${value} length=${length}`);
}
const res = Array.from({ length }).fill(0);
for (let i = length - 1; i >= 0; i--) {
res[i] = value & 0xff;
value >>>= 8;
}
return new Uint8Array(res);
}
function strxor(a, b) {
const arr = new Uint8Array(a.length);
for (let i = 0; i < a.length; i++) {
arr[i] = a[i] ^ b[i];
}
return arr;
}
function anum(item) {
if (!Number.isSafeInteger(item))
throw new Error('number expected');
}
// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits
// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1
function expand_message_xmd(msg, DST, lenInBytes, H) {
(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(msg);
(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(DST);
anum(lenInBytes);
// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
if (DST.length > 255)
DST = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)('H2C-OVERSIZE-DST-'), DST));
const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
const ell = Math.ceil(lenInBytes / b_in_bytes);
if (ell > 255)
throw new Error('Invalid xmd length');
const DST_prime = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(DST, i2osp(DST.length, 1));
const Z_pad = i2osp(0, r_in_bytes);
const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
const b = new Array(ell);
const b_0 = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
b[0] = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(b_0, i2osp(1, 1), DST_prime));
for (let i = 1; i <= ell; i++) {
const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
b[i] = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(...args));
}
const pseudo_random_bytes = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(...b);
return pseudo_random_bytes.slice(0, lenInBytes);
}
// Produces a uniformly random byte string using an extendable-output function (XOF) H.
// 1. The collision resistance of H MUST be at least k bits.
// 2. H MUST be an XOF that has been proved indifferentiable from
// a random oracle under a reasonable cryptographic assumption.
// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2
function expand_message_xof(msg, DST, lenInBytes, k, H) {
(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(msg);
(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(DST);
anum(lenInBytes);
// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
// DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
if (DST.length > 255) {
const dkLen = Math.ceil((2 * k) / 8);
DST = H.create({ dkLen }).update((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)('H2C-OVERSIZE-DST-')).update(DST).digest();
}
if (lenInBytes > 65535 || DST.length > 255)
throw new Error('expand_message_xof: invalid lenInBytes');
return (H.create({ dkLen: lenInBytes })
.update(msg)
.update(i2osp(lenInBytes, 2))
// 2. DST_prime = DST || I2OSP(len(DST), 1)
.update(DST)
.update(i2osp(DST.length, 1))
.digest());
}
/**
* Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F
* https://www.rfc-editor.org/rfc/rfc9380#section-5.2
* @param msg a byte string containing the message to hash
* @param count the number of elements of F to output
* @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
* @returns [u_0, ..., u_(count - 1)], a list of field elements.
*/
function hash_to_field(msg, count, options) {
(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject)(options, {
DST: 'stringOrUint8Array',
p: 'bigint',
m: 'isSafeInteger',
k: 'isSafeInteger',
hash: 'hash',
});
const { p, k, m, hash, expand, DST: _DST } = options;
(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(msg);
anum(count);
const DST = typeof _DST === 'string' ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)(_DST) : _DST;
const log2p = p.toString(2).length;
const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
const len_in_bytes = count * m * L;
let prb; // pseudo_random_bytes
if (expand === 'xmd') {
prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
}
else if (expand === 'xof') {
prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
}
else if (expand === '_internal_pass') {
// for internal tests only
prb = msg;
}
else {
throw new Error('expand must be "xmd" or "xof"');
}
const u = new Array(count);
for (let i = 0; i < count; i++) {
const e = new Array(m);
for (let j = 0; j < m; j++) {
const elm_offset = L * (j + i * m);
const tv = prb.subarray(elm_offset, elm_offset + L);
e[j] = (0,_modular_js__WEBPACK_IMPORTED_MODULE_1__.mod)(os2ip(tv), p);
}
u[i] = e;
}
return u;
}
function isogenyMap(field, map) {
// Make same order as in spec
const COEFF = map.map((i) => Array.from(i).reverse());
return (x, y) => {
const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
x = field.div(xNum, xDen); // xNum / xDen
y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev)
return { x, y };
};
}
function createHasher(Point, mapToCurve, def) {
if (typeof mapToCurve !== 'function')
throw new Error('mapToCurve() must be defined');
return {
// Encodes byte string to elliptic curve.
// hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
hashToCurve(msg, options) {
const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options });
const u0 = Point.fromAffine(mapToCurve(u[0]));
const u1 = Point.fromAffine(mapToCurve(u[1]));
const P = u0.add(u1).clearCofactor();
P.assertValidity();
return P;
},
// Encodes byte string to elliptic curve.
// encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
encodeToCurve(msg, options) {
const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options });
const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();
P.assertValidity();
return P;
},
};
}
//# sourceMappingURL=hash-to-curve.js.map
/***/ }),
/***/ "./node_modules/@noble/curves/esm/abstract/modular.js":
/*!************************************************************!*\
!*** ./node_modules/@noble/curves/esm/abstract/modular.js ***!
\************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Field: () => (/* binding */ Field),
/* harmony export */ FpDiv: () => (/* binding */ FpDiv),
/* harmony export */ FpInvertBatch: () => (/* binding */ FpInvertBatch),
/* harmony export */ FpIsSquare: () => (/* binding */ FpIsSquare),
/* harmony export */ FpPow: () => (/* binding */ FpPow),
/* harmony export */ FpSqrt: () => (/* binding */ FpSqrt),
/* harmony export */ FpSqrtEven: () => (/* binding */ FpSqrtEven),
/* harmony export */ FpSqrtOdd: () => (/* binding */ FpSqrtOdd),
/* harmony export */ getFieldBytesLength: () => (/* binding */ getFieldBytesLength),
/* harmony export */ getMinHashLength: () => (/* binding */ getMinHashLength),
/* harmony export */ hashToPrivateScalar: () => (/* binding */ hashToPrivateScalar),
/* harmony export */ invert: () => (/* binding */ invert),
/* harmony export */ isNegativeLE: () => (/* binding */ isNegativeLE),
/* harmony export */ mapHashToField: () => (/* binding */ mapHashToField),
/* harmony export */ mod: () => (/* binding */ mod),
/* harmony export */ nLength: () => (/* binding */ nLength),
/* harmony export */ pow: () => (/* binding */ pow),
/* harmony export */ pow2: () => (/* binding */ pow2),
/* harmony export */ tonelliShanks: () => (/* binding */ tonelliShanks),
/* harmony export */ validateField: () => (/* binding */ validateField)
/* harmony export */ });
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// Utilities for modular arithmetics and finite fields
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
// prettier-ignore
const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);
// prettier-ignore
const _9n = BigInt(9), _16n = BigInt(16);
// Calculates a modulo b
function mod(a, b) {
const result = a % b;
return result >= _0n ? result : b + result;
}
/**
* Efficiently raise num to power and do modular division.
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
* @example
* pow(2n, 6n, 11n) // 64n % 11n == 9n
*/
// TODO: use field version && remove
function pow(num, power, modulo) {
if (modulo <= _0n || power < _0n)
throw new Error('Expected power/modulo > 0');
if (modulo === _1n)
return _0n;
let res = _1n;
while (power > _0n) {
if (power & _1n)
res = (res * num) % modulo;
num = (num * num) % modulo;
power >>= _1n;
}
return res;
}
// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
function pow2(x, power, modulo) {
let res = x;
while (power-- > _0n) {
res *= res;
res %= modulo;
}
return res;
}
// Inverses number over modulo
function invert(number, modulo) {
if (number === _0n || modulo <= _0n) {
throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
}
// Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
// Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
let a = mod(number, modulo);
let b = modulo;
// prettier-ignore
let x = _0n, y = _1n, u = _1n, v = _0n;
while (a !== _0n) {
// JIT applies optimization if those two lines follow each other
const q = b / a;
const r = b % a;
const m = x - u * q;
const n = y - v * q;
// prettier-ignore
b = a, a = r, x = u, y = v, u = m, v = n;
}
const gcd = b;
if (gcd !== _1n)
throw new Error('invert: does not exist');
return mod(x, modulo);
}
/**
* Tonelli-Shanks square root search algorithm.
* 1. https://eprint.iacr.org/2012/685.pdf (page 12)
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
* Will start an infinite loop if field order P is not prime.
* @param P field order
* @returns function that takes field Fp (created from P) and number n
*/
function tonelliShanks(P) {
// Legendre constant: used to calculate Legendre symbol (a | p),
// which denotes the value of a^((p-1)/2) (mod p).
// (a | p) ≡ 1 if a is a square (mod p)
// (a | p) ≡ -1 if a is not a square (mod p)
// (a | p) ≡ 0 if a ≡ 0 (mod p)
const legendreC = (P - _1n) / _2n;
let Q, S, Z;
// Step 1: By factoring out powers of 2 from p - 1,
// find q and s such that p - 1 = q*(2^s) with q odd
for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)
;
// Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)
;
// Fast-path
if (S === 1) {
const p1div4 = (P + _1n) / _4n;
return function tonelliFast(Fp, n) {
const root = Fp.pow(n, p1div4);
if (!Fp.eql(Fp.sqr(root), n))
throw new Error('Cannot find square root');
return root;
};
}
// Slow-path
const Q1div2 = (Q + _1n) / _2n;
return function tonelliSlow(Fp, n) {
// Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
throw new Error('Cannot find square root');
let r = S;
// TODO: will fail at Fp2/etc
let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
let x = Fp.pow(n, Q1div2); // first guess at the square root
let b = Fp.pow(n, Q); // first guess at the fudge factor
while (!Fp.eql(b, Fp.ONE)) {
if (Fp.eql(b, Fp.ZERO))
return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
// Find m such b^(2^m)==1
let m = 1;
for (let t2 = Fp.sqr(b); m < r; m++) {
if (Fp.eql(t2, Fp.ONE))
break;
t2 = Fp.sqr(t2); // t2 *= t2
}
// NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)
g = Fp.sqr(ge); // g = ge * ge
x = Fp.mul(x, ge); // x *= ge
b = Fp.mul(b, g); // b *= g
r = m;
}
return x;
};
}
function FpSqrt(P) {
// NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
// For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
// P ≡ 3 (mod 4)
// √n = n^((P+1)/4)
if (P % _4n === _3n) {
// Not all roots possible!
// const ORDER =
// 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
// const NUM = 72057594037927816n;
const p1div4 = (P + _1n) / _4n;
return function sqrt3mod4(Fp, n) {
const root = Fp.pow(n, p1div4);
// Throw if root**2 != n
if (!Fp.eql(Fp.sqr(root), n))
throw new Error('Cannot find square root');
return root;
};
}
// Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
if (P % _8n === _5n) {
const c1 = (P - _5n) / _8n;
return function sqrt5mod8(Fp, n) {
const n2 = Fp.mul(n, _2n);
const v = Fp.pow(n2, c1);
const nv = Fp.mul(n, v);
const i = Fp.mul(Fp.mul(nv, _2n), v);
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
if (!Fp.eql(Fp.sqr(root), n))
throw new Error('Cannot find square root');
return root;
};
}
// P ≡ 9 (mod 16)
if (P % _16n === _9n) {
// NOTE: tonelli is too slow for bls-Fp2 calculations even on start
// Means we cannot use sqrt for constants at all!
//
// const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
// const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
// const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
// const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
// sqrt = (x) => {
// let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4
// let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1
// const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1
// let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1
// const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x
// const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x
// tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
// tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
// const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x
// return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2
// }
}
// Other cases: Tonelli-Shanks algorithm
return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
'eql', 'add', 'sub', 'mul', 'pow', 'div',
'addN', 'subN', 'mulN', 'sqrN'
];
function validateField(field) {
const initial = {
ORDER: 'bigint',
MASK: 'bigint',
BYTES: 'isSafeInteger',
BITS: 'isSafeInteger',
};
const opts = FIELD_FIELDS.reduce((map, val) => {
map[val] = 'function';
return map;
}, initial);
return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject)(field, opts);
}
// Generic field functions
/**
* Same as `pow` but for Fp: non-constant-time.
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
*/
function FpPow(f, num, power) {
// Should have same speed as pow for bigints
// TODO: benchmark!
if (power < _0n)
throw new Error('Expected power > 0');
if (power === _0n)
return f.ONE;
if (power === _1n)
return num;
let p = f.ONE;
let d = num;
while (power > _0n) {
if (power & _1n)
p = f.mul(p, d);
d = f.sqr(d);
power >>= _1n;
}
return p;
}
/**
* Efficiently invert an array of Field elements.
* `inv(0)` will return `undefined` here: make sure to throw an error.
*/
function FpInvertBatch(f, nums) {
const tmp = new Array(nums.length);
// Walk from first to last, multiply them by each other MOD p
const lastMultiplied = nums.reduce((acc, num, i) => {
if (f.is0(num))
return acc;
tmp[i] = acc;
return f.mul(acc, num);
}, f.ONE);
// Invert last element
const inverted = f.inv(lastMultiplied);
// Walk from last to first, multiply them by inverted each other MOD p
nums.reduceRight((acc, num, i) => {
if (f.is0(num))
return acc;
tmp[i] = f.mul(acc, tmp[i]);
return f.mul(acc, num);
}, inverted);
return tmp;
}
function FpDiv(f, lhs, rhs) {
return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));
}
// This function returns True whenever the value x is a square in the field F.
function FpIsSquare(f) {
const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic
return (x) => {
const p = f.pow(x, legendreConst);
return f.eql(p, f.ZERO) || f.eql(p, f.ONE);
};
}
// CURVE.n lengths
function nLength(n, nBitLength) {
// Bit size, byte size of CURVE.n
const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
const nByteLength = Math.ceil(_nBitLength / 8);
return { nBitLength: _nBitLength, nByteLength };
}
/**
* Initializes a finite field over prime. **Non-primes are not supported.**
* Do not init in loop: slow. Very fragile: always run a benchmark on a change.
* Major performance optimizations:
* * a) denormalized operations like mulN instead of mul
* * b) same object shape: never add or remove keys
* * c) Object.freeze
* @param ORDER prime positive bigint
* @param bitLen how many bits the field consumes
* @param isLE (def: false) if encoding / decoding should be in little-endian
* @param redef optional faster redefinitions of sqrt and other methods
*/
function Field(ORDER, bitLen, isLE = false, redef = {}) {
if (ORDER <= _0n)
throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
if (BYTES > 2048)
throw new Error('Field lengths over 2048 bytes are not supported');
const sqrtP = FpSqrt(ORDER);
const f = Object.freeze({
ORDER,
BITS,
BYTES,
MASK: (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bitMask)(BITS),
ZERO: _0n,
ONE: _1n,
create: (num) => mod(num, ORDER),
isValid: (num) => {
if (typeof num !== 'bigint')
throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
},
is0: (num) => num === _0n,
isOdd: (num) => (num & _1n) === _1n,
neg: (num) => mod(-num, ORDER),
eql: (lhs, rhs) => lhs === rhs,
sqr: (num) => mod(num * num, ORDER),
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
pow: (num, power) => FpPow(f, num, power),
div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
// Same as above, but doesn't normalize
sqrN: (num) => num * num,
addN: (lhs, rhs) => lhs + rhs,
subN: (lhs, rhs) => lhs - rhs,
mulN: (lhs, rhs) => lhs * rhs,
inv: (num) => invert(num, ORDER),
sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
invertBatch: (lst) => FpInvertBatch(f, lst),
// TODO: do we really need constant cmov?
// We don't have const-time bigints anyway, so probably will be not very useful
cmov: (a, b, c) => (c ? b : a),
toBytes: (num) => (isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesLE)(num, BYTES) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesBE)(num, BYTES)),
fromBytes: (bytes) => {
if (bytes.length !== BYTES)
throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
return isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(bytes) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE)(bytes);
},
});
return Object.freeze(f);
}
function FpSqrtOdd(Fp, elm) {
if (!Fp.isOdd)
throw new Error(`Field doesn't have isOdd`);
const root = Fp.sqrt(elm);
return Fp.isOdd(root) ? root : Fp.neg(root);
}
function FpSqrtEven(Fp, elm) {
if (!Fp.isOdd)
throw new Error(`Field doesn't have isOdd`);
const root = Fp.sqrt(elm);
return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
* "Constant-time" private key generation utility.
* Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
* Which makes it slightly more biased, less secure.
* @deprecated use mapKeyToField instead
*/
function hashToPrivateScalar(hash, groupOrder, isLE = false) {
hash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('privateHash', hash);
const hashLen = hash.length;
const minLen = nLength(groupOrder).nByteLength + 8;
if (minLen < 24 || hashLen < minLen || hashLen > 1024)
throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
const num = isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(hash) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE)(hash);
return mod(num, groupOrder - _1n) + _1n;
}
/**
* Returns total number of bytes consumed by the field element.
* For example, 32 bytes for usual 256-bit weierstrass curve.
* @param fieldOrder number of field elements, usually CURVE.n
* @returns byte length of field
*/
function getFieldBytesLength(fieldOrder) {
if (typeof fieldOrder !== 'bigint')
throw new Error('field order must be bigint');
const bitLength = fieldOrder.toString(2).length;
return Math.ceil(bitLength / 8);
}
/**
* Returns minimal amount of bytes that can be safely reduced
* by field order.
* Should be 2^-128 for 128-bit curve such as P256.
* @param fieldOrder number of field elements, usually CURVE.n
* @returns byte length of target hash
*/
function getMinHashLength(fieldOrder) {
const length = getFieldBytesLength(fieldOrder);
return length + Math.ceil(length / 2);
}
/**
* "Constant-time" private key generation utility.
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
* and convert them into private scalar, with the modulo bias being negligible.
* Needs at least 48 bytes of input for 32-byte private key.
* https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
* FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
* RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
* @param hash hash output from SHA3 or a similar function
* @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
* @param isLE interpret hash bytes as LE num
* @returns valid private scalar
*/
function mapHashToField(key, fieldOrder, isLE = false) {
const len = key.length;
const fieldLen = getFieldBytesLength(fieldOrder);
const minLen = getMinHashLength(fieldOrder);
// No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
if (len < 16 || len < minLen || len > 1024)
throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
const num = isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE)(key) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(key);
// `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
const reduced = mod(num, fieldOrder - _1n) + _1n;
return isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesLE)(reduced, fieldLen) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesBE)(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map
/***/ }),
/***/ "./node_modules/@noble/curves/esm/abstract/montgomery.js":
/*!***************************************************************!*\
!*** ./node_modules/@noble/curves/esm/abstract/montgomery.js ***!
\***************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ montgomery: () => (/* binding */ montgomery)
/* harmony export */ });
/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./modular.js */ "./node_modules/@noble/curves/esm/abstract/modular.js");
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n = BigInt(0);
const _1n = BigInt(1);
function validateOpts(curve) {
(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject)(curve, {
a: 'bigint',
}, {
montgomeryBits: 'isSafeInteger',
nByteLength: 'isSafeInteger',
adjustScalarBytes: 'function',
domain: 'function',
powPminus2: 'function',
Gu: 'bigint',
});
// Set defaults
return Object.freeze({ ...curve });
}
// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)
// Uses only one coordinate instead of two
function montgomery(curveDef) {
const CURVE = validateOpts(curveDef);
const { P } = CURVE;
const modP = (n) => (0,_modular_js__WEBPACK_IMPORTED_MODULE_1__.mod)(n, P);
const montgomeryBits = CURVE.montgomeryBits;
const montgomeryBytes = Math.ceil(montgomeryBits / 8);
const fieldLen = CURVE.nByteLength;
const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes);
const powPminus2 = CURVE.powPminus2 || ((x) => (0,_modular_js__WEBPACK_IMPORTED_MODULE_1__.pow)(x, P - BigInt(2), P));
// cswap from RFC7748. But it is not from RFC7748!
/*
cswap(swap, x_2, x_3):
dummy = mask(swap) AND (x_2 XOR x_3)
x_2 = x_2 XOR dummy
x_3 = x_3 XOR dummy
Return (x_2, x_3)
Where mask(swap) is the all-1 or all-0 word of the same length as x_2
and x_3, computed, e.g., as mask(swap) = 0 - swap.
*/
function cswap(swap, x_2, x_3) {
const dummy = modP(swap * (x_2 - x_3));
x_2 = modP(x_2 - dummy);
x_3 = modP(x_3 + dummy);
return [x_2, x_3];
}
// Accepts 0 as well
function assertFieldElement(n) {
if (typeof n === 'bigint' && _0n <= n && n < P)
return n;
throw new Error('Expected valid scalar 0 < scalar < CURVE.P');
}
// x25519 from 4
// The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519
const a24 = (CURVE.a - BigInt(2)) / BigInt(4);
/**
*
* @param pointU u coordinate (x) on Montgomery Curve 25519
* @param scalar by which the point would be multiplied
* @returns new Point on Montgomery curve
*/
function montgomeryLadder(pointU, scalar) {
const u = assertFieldElement(pointU);
// Section 5: Implementations MUST accept non-canonical values and process them as
// if they had been reduced modulo the field prime.
const k = assertFieldElement(scalar);
const x_1 = u;
let x_2 = _1n;
let z_2 = _0n;
let x_3 = u;
let z_3 = _1n;
let swap = _0n;
let sw;
for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {
const k_t = (k >> t) & _1n;
swap ^= k_t;
sw = cswap(swap, x_2, x_3);
x_2 = sw[0];
x_3 = sw[1];
sw = cswap(swap, z_2, z_3);
z_2 = sw[0];
z_3 = sw[1];
swap = k_t;
const A = x_2 + z_2;
const AA = modP(A * A);
const B = x_2 - z_2;
const BB = modP(B * B);
const E = AA - BB;
const C = x_3 + z_3;
const D = x_3 - z_3;
const DA = modP(D * A);
const CB = modP(C * B);
const dacb = DA + CB;
const da_cb = DA - CB;
x_3 = modP(dacb * dacb);
z_3 = modP(x_1 * modP(da_cb * da_cb));
x_2 = modP(AA * BB);
z_2 = modP(E * (AA + modP(a24 * E)));
}
// (x_2, x_3) = cswap(swap, x_2, x_3)
sw = cswap(swap, x_2, x_3);
x_2 = sw[0];
x_3 = sw[1];
// (z_2, z_3) = cswap(swap, z_2, z_3)
sw = cswap(swap, z_2, z_3);
z_2 = sw[0];
z_3 = sw[1];
// z_2^(p - 2)
const z2 = powPminus2(z_2);
// Return x_2 * (z_2^(p - 2))
return modP(x_2 * z2);
}
function encodeUCoordinate(u) {
return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesLE)(modP(u), montgomeryBytes);
}
function decodeUCoordinate(uEnc) {
// Section 5: When receiving such an array, implementations of X25519
// MUST mask the most significant bit in the final byte.
const u = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('u coordinate', uEnc, montgomeryBytes);
if (fieldLen === 32)
u[31] &= 127; // 0b0111_1111
return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(u);
}
function decodeScalar(n) {
const bytes = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('scalar', n);
const len = bytes.length;
if (len !== montgomeryBytes && len !== fieldLen)
throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`);
return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(adjustScalarBytes(bytes));
}
function scalarMult(scalar, u) {
const pointU = decodeUCoordinate(u);
const _scalar = decodeScalar(scalar);
const pu = montgomeryLadder(pointU, _scalar);
// The result was not contributory
// https://cr.yp.to/ecdh.html#validate
if (pu === _0n)
throw new Error('Invalid private or public key received');
return encodeUCoordinate(pu);
}
// Computes public key from private. By doing scalar multiplication of base point.
const GuBytes = encodeUCoordinate(CURVE.Gu);
function scalarMultBase(scalar) {
return scalarMult(scalar, GuBytes);
}
return {
scalarMult,
scalarMultBase,
getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),
getPublicKey: (privateKey) => scalarMultBase(privateKey),
utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) },
GuBytes: GuBytes,
};
}
//# sourceMappingURL=montgomery.js.map
/***/ }),
/***/ "./node_modules/@noble/curves/esm/abstract/utils.js":
/*!**********************************************************!*\
!*** ./node_modules/@noble/curves/esm/abstract/utils.js ***!
\**********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ abytes: () => (/* binding */ abytes),
/* harmony export */ bitGet: () => (/* binding */ bitGet),
/* harmony export */ bitLen: () => (/* binding */ bitLen),
/* harmony export */ bitMask: () => (/* binding */ bitMask),
/* harmony export */ bitSet: () => (/* binding */ bitSet),
/* harmony export */ bytesToHex: () => (/* binding */ bytesToHex),
/* harmony export */ bytesToNumberBE: () => (/* binding */ bytesToNumberBE),
/* harmony export */ bytesToNumberLE: () => (/* binding */ bytesToNumberLE),
/* harmony export */ concatBytes: () => (/* binding */ concatBytes),
/* harmony export */ createHmacDrbg: () => (/* binding */ createHmacDrbg),
/* harmony export */ ensureBytes: () => (/* binding */ ensureBytes),
/* harmony export */ equalBytes: () => (/* binding */ equalBytes),
/* harmony export */ hexToBytes: () => (/* binding */ hexToBytes),
/* harmony export */ hexToNumber: () => (/* binding */ hexToNumber),
/* harmony export */ isBytes: () => (/* binding */ isBytes),
/* harmony export */ numberToBytesBE: () => (/* binding */ numberToBytesBE),
/* harmony export */ numberToBytesLE: () => (/* binding */ numberToBytesLE),
/* harmony export */ numberToHexUnpadded: () => (/* binding */ numberToHexUnpadded),
/* harmony export */ numberToVarBytesBE: () => (/* binding */ numberToVarBytesBE),
/* harmony export */ utf8ToBytes: () => (/* binding */ utf8ToBytes),
/* harmony export */ validateObject: () => (/* binding */ validateObject)
/* harmony export */ });
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// 100 lines of code in the file are duplicated from noble-hashes (utils).
// This is OK: `abstract` directory does not use noble-hashes.
// User may opt-in into using different hashing library. This way, noble-hashes
// won't be included into their bundle.
const _0n = BigInt(0);
const _1n = BigInt(1);
const _2n = BigInt(2);
function isBytes(a) {
return (a instanceof Uint8Array ||
(a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
}
function abytes(item) {
if (!isBytes(item))
throw new Error('Uint8Array expected');
}
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
*/
function bytesToHex(bytes) {
abytes(bytes);
// pre-caching improves the speed 6x
let hex = '';
for (let i = 0; i < bytes.length; i++) {
hex += hexes[bytes[i]];
}
return hex;
}
function numberToHexUnpadded(num) {
const hex = num.toString(16);
return hex.length & 1 ? `0${hex}` : hex;
}
function hexToNumber(hex) {
if (typeof hex !== 'string')
throw new Error('hex string expected, got ' + typeof hex);
// Big Endian
return BigInt(hex === '' ? '0' : `0x${hex}`);
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
function asciiToBase16(char) {
if (char >= asciis._0 && char <= asciis._9)
return char - asciis._0;
if (char >= asciis._A && char <= asciis._F)
return char - (asciis._A - 10);
if (char >= asciis._a && char <= asciis._f)
return char - (asciis._a - 10);
return;
}
/**
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
*/
function hexToBytes(hex) {
if (typeof hex !== 'string')
throw new Error('hex string expected, got ' + typeof hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
const array = new Uint8Array(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
const n1 = asciiToBase16(hex.charCodeAt(hi));
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
if (n1 === undefined || n2 === undefined) {
const char = hex[hi] + hex[hi + 1];
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
}
array[ai] = n1 * 16 + n2;
}
return array;
}
// BE: Big Endian, LE: Little Endian
function bytesToNumberBE(bytes) {
return hexToNumber(bytesToHex(bytes));
}
function bytesToNumberLE(bytes) {
abytes(bytes);
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
}
function numberToBytesBE(n, len) {
return hexToBytes(n.toString(16).padStart(len * 2, '0'));
}
function numberToBytesLE(n, len) {
return numberToBytesBE(n, len).reverse();
}
// Unpadded, rarely used
function numberToVarBytesBE(n) {
return hexToBytes(numberToHexUnpadded(n));
}
/**
* Takes hex string or Uint8Array, converts to Uint8Array.
* Validates output length.
* Will throw error for other types.
* @param title descriptive title for an error e.g. 'private key'
* @param hex hex string or Uint8Array
* @param expectedLength optional, will compare to result array's length
* @returns
*/
function ensureBytes(title, hex, expectedLength) {
let res;
if (typeof hex === 'string') {
try {
res = hexToBytes(hex);
}
catch (e) {
throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
}
}
else if (isBytes(hex)) {
// Uint8Array.from() instead of hash.slice() because node.js Buffer
// is instance of Uint8Array, and its slice() creates **mutable** copy
res = Uint8Array.from(hex);
}
else {
throw new Error(`${title} must be hex string or Uint8Array`);
}
const len = res.length;
if (typeof expectedLength === 'number' && len !== expectedLength)
throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
return res;
}
/**
* Copies several Uint8Arrays into one.
*/
function concatBytes(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
abytes(a);
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
// Compares 2 u8a-s in kinda constant time
function equalBytes(a, b) {
if (a.length !== b.length)
return false;
let diff = 0;
for (let i = 0; i < a.length; i++)
diff |= a[i] ^ b[i];
return diff === 0;
}
/**
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
*/
function utf8ToBytes(str) {
if (typeof str !== 'string')
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
// Bit operations
/**
* Calculates amount of bits in a bigint.
* Same as `n.toString(2).length`
*/
function bitLen(n) {
let len;
for (len = 0; n > _0n; n >>= _1n, len += 1)
;
return len;
}
/**
* Gets single bit at position.
* NOTE: first bit position is 0 (same as arrays)
* Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
*/
function bitGet(n, pos) {
return (n >> BigInt(pos)) & _1n;
}
/**
* Sets single bit at position.
*/
function bitSet(n, pos, value) {
return n | ((value ? _1n : _0n) << BigInt(pos));
}
/**
* Calculate mask for N bits. Not using ** operator with bigints because of old engines.
* Same as BigInt(`0b${Array(i).fill('1').join('')}`)
*/
const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;
// DRBG
const u8n = (data) => new Uint8Array(data); // creates Uint8Array
const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
/**
* Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
* @returns function that will call DRBG until 2nd arg returns something meaningful
* @example
* const drbg = createHmacDRBG<Key>(32, 32, hmac);
* drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
*/
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
if (typeof hashLen !== 'number' || hashLen < 2)
throw new Error('hashLen must be a number');
if (typeof qByteLen !== 'number' || qByteLen < 2)
throw new Error('qByteLen must be a number');
if (typeof hmacFn !== 'function')
throw new Error('hmacFn must be a function');
// Step B, Step C: set hashLen to 8*ceil(hlen/8)
let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
let i = 0; // Iterations counter, will throw when over 1000
const reset = () => {
v.fill(1);
k.fill(0);
i = 0;
};
const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
const reseed = (seed = u8n()) => {
// HMAC-DRBG reseed() function. Steps D-G
k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
v = h(); // v = hmac(k || v)
if (seed.length === 0)
return;
k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
v = h(); // v = hmac(k || v)
};
const gen = () => {
// HMAC-DRBG generate() function
if (i++ >= 1000)
throw new Error('drbg: tried 1000 values');
let len = 0;
const out = [];
while (len < qByteLen) {
v = h();
const sl = v.slice();
out.push(sl);
len += v.length;
}
return concatBytes(...out);
};
const genUntil = (seed, pred) => {
reset();
reseed(seed); // Steps D-G
let res = undefined; // Step H: grind until k is in [1..n-1]
while (!(res = pred(gen())))
reseed();
reset();
return res;
};
return genUntil;
}
// Validating curves and fields
const validatorFns = {
bigint: (val) => typeof val === 'bigint',
function: (val) => typeof val === 'function',
boolean: (val) => typeof val === 'boolean',
string: (val) => typeof val === 'string',
stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),
isSafeInteger: (val) => Number.isSafeInteger(val),
array: (val) => Array.isArray(val),
field: (val, object) => object.Fp.isValid(val),
hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
};
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
function validateObject(object, validators, optValidators = {}) {
const checkField = (fieldName, type, isOptional) => {
const checkVal = validatorFns[type];
if (typeof checkVal !== 'function')
throw new Error(`Invalid validator "${type}", expected function`);
const val = object[fieldName];
if (isOptional && val === undefined)
return;
if (!checkVal(val, object)) {
throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
}
};
for (const [fieldName, type] of Object.entries(validators))
checkField(fieldName, type, false);
for (const [fieldName, type] of Object.entries(optValidators))
checkField(fieldName, type, true);
return object;
}
// validate type tests
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
// // Should fail type-check
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
//# sourceMappingURL=utils.js.map
/***/ }),
/***/ "./node_modules/@noble/curves/esm/abstract/weierstrass.js":
/*!****************************************************************!*\
!*** ./node_modules/@noble/curves/esm/abstract/weierstrass.js ***!
\****************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ DER: () => (/* binding */ DER),
/* harmony export */ SWUFpSqrtRatio: () => (/* binding */ SWUFpSqrtRatio),
/* harmony export */ mapToCurveSimpleSWU: () => (/* binding */ mapToCurveSimpleSWU),
/* harmony export */ weierstrass: () => (/* binding */ weierstrass),
/* harmony export */ weierstrassPoints: () => (/* binding */ weierstrassPoints)
/* harmony export */ });
/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./modular.js */ "./node_modules/@noble/curves/esm/abstract/modular.js");
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
/* harmony import */ var _curve_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./curve.js */ "./node_modules/@noble/curves/esm/abstract/curve.js");
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// Short Weierstrass curve. The formula is: y² = x³ + ax + b
function validatePointOpts(curve) {
const opts = (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.validateBasic)(curve);
_utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject(opts, {
a: 'field',
b: 'field',
}, {
allowedPrivateKeyLengths: 'array',
wrapPrivateKey: 'boolean',
isTorsionFree: 'function',
clearCofactor: 'function',
allowInfinityPoint: 'boolean',
fromBytes: 'function',
toBytes: 'function',
});
const { endo, Fp, a } = opts;
if (endo) {
if (!Fp.eql(a, Fp.ZERO)) {
throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
}
if (typeof endo !== 'object' ||
typeof endo.beta !== 'bigint' ||
typeof endo.splitScalar !== 'function') {
throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
}
}
return Object.freeze({ ...opts });
}
// ASN.1 DER encoding utilities
const { bytesToNumberBE: b2n, hexToBytes: h2b } = _utils_js__WEBPACK_IMPORTED_MODULE_1__;
const DER = {
// asn.1 DER encoding utils
Err: class DERErr extends Error {
constructor(m = '') {
super(m);
}
},
_parseInt(data) {
const { Err: E } = DER;
if (data.length < 2 || data[0] !== 0x02)
throw new E('Invalid signature integer tag');
const len = data[1];
const res = data.subarray(2, len + 2);
if (!len || res.length !== len)
throw new E('Invalid signature integer: wrong length');
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
// since we always use positive integers here. It must always be empty:
// - add zero byte if exists
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
if (res[0] & 0b10000000)
throw new E('Invalid signature integer: negative');
if (res[0] === 0x00 && !(res[1] & 0b10000000))
throw new E('Invalid signature integer: unnecessary leading zero');
return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left
},
toSig(hex) {
// parse DER signature
const { Err: E } = DER;
const data = typeof hex === 'string' ? h2b(hex) : hex;
_utils_js__WEBPACK_IMPORTED_MODULE_1__.abytes(data);
let l = data.length;
if (l < 2 || data[0] != 0x30)
throw new E('Invalid signature tag');
if (data[1] !== l - 2)
throw new E('Invalid signature: incorrect length');
const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));
const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);
if (rBytesLeft.length)
throw new E('Invalid signature: left bytes after parsing');
return { r, s };
},
hexFromSig(sig) {
// Add leading zero if first byte has negative bit enabled. More details in '_parseInt'
const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);
const h = (num) => {
const hex = num.toString(16);
return hex.length & 1 ? `0${hex}` : hex;
};
const s = slice(h(sig.s));
const r = slice(h(sig.r));
const shl = s.length / 2;
const rhl = r.length / 2;
const sl = h(shl);
const rl = h(rhl);
return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
},
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
function weierstrassPoints(opts) {
const CURVE = validatePointOpts(opts);
const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
const toBytes = CURVE.toBytes ||
((_c, point, _isCompressed) => {
const a = point.toAffine();
return _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));
});
const fromBytes = CURVE.fromBytes ||
((bytes) => {
// const head = bytes[0];
const tail = bytes.subarray(1);
// if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
return { x, y };
});
/**
* y² = x³ + ax + b: Short weierstrass curve formula
* @returns y²
*/
function weierstrassEquation(x) {
const { a, b } = CURVE;
const x2 = Fp.sqr(x); // x * x
const x3 = Fp.mul(x2, x); // x2 * x
return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b
}
// Validate whether the passed curve params are valid.
// We check if curve equation works for generator point.
// `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.
// ProjectivePoint class has not been initialized yet.
if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
throw new Error('bad generator point: equation left != right');
// Valid group elements reside in range 1..n-1
function isWithinCurveOrder(num) {
return typeof num === 'bigint' && _0n < num && num < CURVE.n;
}
function assertGE(num) {
if (!isWithinCurveOrder(num))
throw new Error('Expected valid bigint: 0 < bigint < curve.n');
}
// Validates if priv key is valid and converts it to bigint.
// Supports options allowedPrivateKeyLengths and wrapPrivateKey.
function normPrivateKeyToScalar(key) {
const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;
if (lengths && typeof key !== 'bigint') {
if (_utils_js__WEBPACK_IMPORTED_MODULE_1__.isBytes(key))
key = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToHex(key);
// Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
if (typeof key !== 'string' || !lengths.includes(key.length))
throw new Error('Invalid key');
key = key.padStart(nByteLength * 2, '0');
}
let num;
try {
num =
typeof key === 'bigint'
? key
: _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('private key', key, nByteLength));
}
catch (error) {
throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
}
if (wrapPrivateKey)
num = _modular_js__WEBPACK_IMPORTED_MODULE_2__.mod(num, n); // disabled by default, enabled for BLS
assertGE(num); // num in range [1..N-1]
return num;
}
const pointPrecomputes = new Map();
function assertPrjPoint(other) {
if (!(other instanceof Point))
throw new Error('ProjectivePoint expected');
}
/**
* Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)
* Default Point works in 2d / affine coordinates: (x, y)
* We're doing calculations in projective, because its operations don't require costly inversion.
*/
class Point {
constructor(px, py, pz) {
this.px = px;
this.py = py;
this.pz = pz;
if (px == null || !Fp.isValid(px))
throw new Error('x required');
if (py == null || !Fp.isValid(py))
throw new Error('y required');
if (pz == null || !Fp.isValid(pz))
throw new Error('z required');
}
// Does not validate if the point is on-curve.
// Use fromHex instead, or call assertValidity() later.
static fromAffine(p) {
const { x, y } = p || {};
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
throw new Error('invalid affine point');
if (p instanceof Point)
throw new Error('projective point not allowed');
const is0 = (i) => Fp.eql(i, Fp.ZERO);
// fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)
if (is0(x) && is0(y))
return Point.ZERO;
return new Point(x, y, Fp.ONE);
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
/**
* Takes a bunch of Projective Points but executes only one
* inversion on all of them. Inversion is very slow operation,
* so this improves performance massively.
* Optimization: converts a list of projective points to a list of identical points with Z=1.
*/
static normalizeZ(points) {
const toInv = Fp.invertBatch(points.map((p) => p.pz));
return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
}
/**
* Converts hash string or Uint8Array to Point.
* @param hex short/long ECDSA hex
*/
static fromHex(hex) {
const P = Point.fromAffine(fromBytes((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('pointHex', hex)));
P.assertValidity();
return P;
}
// Multiplies generator point by privateKey.
static fromPrivateKey(privateKey) {
return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
}
// "Private method", don't use it directly
_setWindowSize(windowSize) {
this._WINDOW_SIZE = windowSize;
pointPrecomputes.delete(this);
}
// A point on curve is valid if it conforms to equation.
assertValidity() {
if (this.is0()) {
// (0, 1, 0) aka ZERO is invalid in most contexts.
// In BLS, ZERO can be serialized, so we allow it.
// (0, 0, 0) is wrong representation of ZERO and is always invalid.
if (CURVE.allowInfinityPoint && !Fp.is0(this.py))
return;
throw new Error('bad point: ZERO');
}
// Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
const { x, y } = this.toAffine();
// Check if x, y are valid field elements
if (!Fp.isValid(x) || !Fp.isValid(y))
throw new Error('bad point: x or y not FE');
const left = Fp.sqr(y); // y²
const right = weierstrassEquation(x); // x³ + ax + b
if (!Fp.eql(left, right))
throw new Error('bad point: equation left != right');
if (!this.isTorsionFree())
throw new Error('bad point: not in prime-order subgroup');
}
hasEvenY() {
const { y } = this.toAffine();
if (Fp.isOdd)
return !Fp.isOdd(y);
throw new Error("Field doesn't support isOdd");
}
/**
* Compare one point to another.
*/
equals(other) {
assertPrjPoint(other);
const { px: X1, py: Y1, pz: Z1 } = this;
const { px: X2, py: Y2, pz: Z2 } = other;
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
return U1 && U2;
}
/**
* Flips point to one corresponding to (x, -y) in Affine coordinates.
*/
negate() {
return new Point(this.px, Fp.neg(this.py), this.pz);
}
// Renes-Costello-Batina exception-free doubling formula.
// There is 30% faster Jacobian formula, but it is not complete.
// https://eprint.iacr.org/2015/1060, algorithm 3
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
double() {
const { a, b } = CURVE;
const b3 = Fp.mul(b, _3n);
const { px: X1, py: Y1, pz: Z1 } = this;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
let t0 = Fp.mul(X1, X1); // step 1
let t1 = Fp.mul(Y1, Y1);
let t2 = Fp.mul(Z1, Z1);
let t3 = Fp.mul(X1, Y1);
t3 = Fp.add(t3, t3); // step 5
Z3 = Fp.mul(X1, Z1);
Z3 = Fp.add(Z3, Z3);
X3 = Fp.mul(a, Z3);
Y3 = Fp.mul(b3, t2);
Y3 = Fp.add(X3, Y3); // step 10
X3 = Fp.sub(t1, Y3);
Y3 = Fp.add(t1, Y3);
Y3 = Fp.mul(X3, Y3);
X3 = Fp.mul(t3, X3);
Z3 = Fp.mul(b3, Z3); // step 15
t2 = Fp.mul(a, t2);
t3 = Fp.sub(t0, t2);
t3 = Fp.mul(a, t3);
t3 = Fp.add(t3, Z3);
Z3 = Fp.add(t0, t0); // step 20
t0 = Fp.add(Z3, t0);
t0 = Fp.add(t0, t2);
t0 = Fp.mul(t0, t3);
Y3 = Fp.add(Y3, t0);
t2 = Fp.mul(Y1, Z1); // step 25
t2 = Fp.add(t2, t2);
t0 = Fp.mul(t2, t3);
X3 = Fp.sub(X3, t0);
Z3 = Fp.mul(t2, t1);
Z3 = Fp.add(Z3, Z3); // step 30
Z3 = Fp.add(Z3, Z3);
return new Point(X3, Y3, Z3);
}
// Renes-Costello-Batina exception-free addition formula.
// There is 30% faster Jacobian formula, but it is not complete.
// https://eprint.iacr.org/2015/1060, algorithm 1
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
add(other) {
assertPrjPoint(other);
const { px: X1, py: Y1, pz: Z1 } = this;
const { px: X2, py: Y2, pz: Z2 } = other;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
const a = CURVE.a;
const b3 = Fp.mul(CURVE.b, _3n);
let t0 = Fp.mul(X1, X2); // step 1
let t1 = Fp.mul(Y1, Y2);
let t2 = Fp.mul(Z1, Z2);
let t3 = Fp.add(X1, Y1);
let t4 = Fp.add(X2, Y2); // step 5
t3 = Fp.mul(t3, t4);
t4 = Fp.add(t0, t1);
t3 = Fp.sub(t3, t4);
t4 = Fp.add(X1, Z1);
let t5 = Fp.add(X2, Z2); // step 10
t4 = Fp.mul(t4, t5);
t5 = Fp.add(t0, t2);
t4 = Fp.sub(t4, t5);
t5 = Fp.add(Y1, Z1);
X3 = Fp.add(Y2, Z2); // step 15
t5 = Fp.mul(t5, X3);
X3 = Fp.add(t1, t2);
t5 = Fp.sub(t5, X3);
Z3 = Fp.mul(a, t4);
X3 = Fp.mul(b3, t2); // step 20
Z3 = Fp.add(X3, Z3);
X3 = Fp.sub(t1, Z3);
Z3 = Fp.add(t1, Z3);
Y3 = Fp.mul(X3, Z3);
t1 = Fp.add(t0, t0); // step 25
t1 = Fp.add(t1, t0);
t2 = Fp.mul(a, t2);
t4 = Fp.mul(b3, t4);
t1 = Fp.add(t1, t2);
t2 = Fp.sub(t0, t2); // step 30
t2 = Fp.mul(a, t2);
t4 = Fp.add(t4, t2);
t0 = Fp.mul(t1, t4);
Y3 = Fp.add(Y3, t0);
t0 = Fp.mul(t5, t4); // step 35
X3 = Fp.mul(t3, X3);
X3 = Fp.sub(X3, t0);
t0 = Fp.mul(t3, t1);
Z3 = Fp.mul(t5, Z3);
Z3 = Fp.add(Z3, t0); // step 40
return new Point(X3, Y3, Z3);
}
subtract(other) {
return this.add(other.negate());
}
is0() {
return this.equals(Point.ZERO);
}
wNAF(n) {
return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {
const toInv = Fp.invertBatch(comp.map((p) => p.pz));
return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
});
}
/**
* Non-constant-time multiplication. Uses double-and-add algorithm.
* It's faster, but should only be used when you don't care about
* an exposed private key e.g. sig verification, which works over *public* keys.
*/
multiplyUnsafe(n) {
const I = Point.ZERO;
if (n === _0n)
return I;
assertGE(n); // Will throw on 0
if (n === _1n)
return this;
const { endo } = CURVE;
if (!endo)
return wnaf.unsafeLadder(this, n);
// Apply endomorphism
let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
let k1p = I;
let k2p = I;
let d = this;
while (k1 > _0n || k2 > _0n) {
if (k1 & _1n)
k1p = k1p.add(d);
if (k2 & _1n)
k2p = k2p.add(d);
d = d.double();
k1 >>= _1n;
k2 >>= _1n;
}
if (k1neg)
k1p = k1p.negate();
if (k2neg)
k2p = k2p.negate();
k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
return k1p.add(k2p);
}
/**
* Constant time multiplication.
* Uses wNAF method. Windowed method may be 10% faster,
* but takes 2x longer to generate and consumes 2x memory.
* Uses precomputes when available.
* Uses endomorphism for Koblitz curves.
* @param scalar by which the point would be multiplied
* @returns New point
*/
multiply(scalar) {
assertGE(scalar);
let n = scalar;
let point, fake; // Fake point is used to const-time mult
const { endo } = CURVE;
if (endo) {
const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
let { p: k1p, f: f1p } = this.wNAF(k1);
let { p: k2p, f: f2p } = this.wNAF(k2);
k1p = wnaf.constTimeNegate(k1neg, k1p);
k2p = wnaf.constTimeNegate(k2neg, k2p);
k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
point = k1p.add(k2p);
fake = f1p.add(f2p);
}
else {
const { p, f } = this.wNAF(n);
point = p;
fake = f;
}
// Normalize `z` for both points, but return only real one
return Point.normalizeZ([point, fake])[0];
}
/**
* Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
* Not using Strauss-Shamir trick: precomputation tables are faster.
* The trick could be useful if both P and Q are not G (not in our case).
* @returns non-zero affine point
*/
multiplyAndAddUnsafe(Q, a, b) {
const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes
const mul = (P, a // Select faster multiply() method
) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));
const sum = mul(this, a).add(mul(Q, b));
return sum.is0() ? undefined : sum;
}
// Converts Projective point to affine (x, y) coordinates.
// Can accept precomputed Z^-1 - for example, from invertBatch.
// (x, y, z) ∋ (x=x/z, y=y/z)
toAffine(iz) {
const { px: x, py: y, pz: z } = this;
const is0 = this.is0();
// If invZ was 0, we return zero point. However we still want to execute
// all operations, so we replace invZ with a random number, 1.
if (iz == null)
iz = is0 ? Fp.ONE : Fp.inv(z);
const ax = Fp.mul(x, iz);
const ay = Fp.mul(y, iz);
const zz = Fp.mul(z, iz);
if (is0)
return { x: Fp.ZERO, y: Fp.ZERO };
if (!Fp.eql(zz, Fp.ONE))
throw new Error('invZ was invalid');
return { x: ax, y: ay };
}
isTorsionFree() {
const { h: cofactor, isTorsionFree } = CURVE;
if (cofactor === _1n)
return true; // No subgroups, always torsion-free
if (isTorsionFree)
return isTorsionFree(Point, this);
throw new Error('isTorsionFree() has not been declared for the elliptic curve');
}
clearCofactor() {
const { h: cofactor, clearCofactor } = CURVE;
if (cofactor === _1n)
return this; // Fast-path
if (clearCofactor)
return clearCofactor(Point, this);
return this.multiplyUnsafe(CURVE.h);
}
toRawBytes(isCompressed = true) {
this.assertValidity();
return toBytes(Point, this, isCompressed);
}
toHex(isCompressed = true) {
return _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToHex(this.toRawBytes(isCompressed));
}
}
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
const _bits = CURVE.nBitLength;
const wnaf = (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
// Validate if generator point is on curve
return {
CURVE,
ProjectivePoint: Point,
normPrivateKeyToScalar,
weierstrassEquation,
isWithinCurveOrder,
};
}
function validateOpts(curve) {
const opts = (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.validateBasic)(curve);
_utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject(opts, {
hash: 'hash',
hmac: 'function',
randomBytes: 'function',
}, {
bits2int: 'function',
bits2int_modN: 'function',
lowS: 'boolean',
});
return Object.freeze({ lowS: true, ...opts });
}
function weierstrass(curveDef) {
const CURVE = validateOpts(curveDef);
const { Fp, n: CURVE_ORDER } = CURVE;
const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32
const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32
function isValidFieldElement(num) {
return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE
}
function modN(a) {
return _modular_js__WEBPACK_IMPORTED_MODULE_2__.mod(a, CURVE_ORDER);
}
function invN(a) {
return _modular_js__WEBPACK_IMPORTED_MODULE_2__.invert(a, CURVE_ORDER);
}
const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
...CURVE,
toBytes(_c, point, isCompressed) {
const a = point.toAffine();
const x = Fp.toBytes(a.x);
const cat = _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes;
if (isCompressed) {
return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);
}
else {
return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));
}
},
fromBytes(bytes) {
const len = bytes.length;
const head = bytes[0];
const tail = bytes.subarray(1);
// this.assertValidity() is done inside of fromHex
if (len === compressedLen && (head === 0x02 || head === 0x03)) {
const x = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE(tail);
if (!isValidFieldElement(x))
throw new Error('Point is not on curve');
const y2 = weierstrassEquation(x); // y² = x³ + ax + b
let y;
try {
y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
}
catch (sqrtError) {
const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
throw new Error('Point is not on curve' + suffix);
}
const isYOdd = (y & _1n) === _1n;
// ECDSA
const isHeadOdd = (head & 1) === 1;
if (isHeadOdd !== isYOdd)
y = Fp.neg(y);
return { x, y };
}
else if (len === uncompressedLen && head === 0x04) {
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
return { x, y };
}
else {
throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
}
},
});
const numToNByteStr = (num) => _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToHex(_utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesBE(num, CURVE.nByteLength));
function isBiggerThanHalfOrder(number) {
const HALF = CURVE_ORDER >> _1n;
return number > HALF;
}
function normalizeS(s) {
return isBiggerThanHalfOrder(s) ? modN(-s) : s;
}
// slice bytes num
const slcNum = (b, from, to) => _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE(b.slice(from, to));
/**
* ECDSA signature with its (r, s) properties. Supports DER & compact representations.
*/
class Signature {
constructor(r, s, recovery) {
this.r = r;
this.s = s;
this.recovery = recovery;
this.assertValidity();
}
// pair (bytes of r, bytes of s)
static fromCompact(hex) {
const l = CURVE.nByteLength;
hex = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('compactSignature', hex, l * 2);
return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
}
// DER encoded ECDSA signature
// https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
static fromDER(hex) {
const { r, s } = DER.toSig((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('DER', hex));
return new Signature(r, s);
}
assertValidity() {
// can use assertGE here
if (!isWithinCurveOrder(this.r))
throw new Error('r must be 0 < r < CURVE.n');
if (!isWithinCurveOrder(this.s))
throw new Error('s must be 0 < s < CURVE.n');
}
addRecoveryBit(recovery) {
return new Signature(this.r, this.s, recovery);
}
recoverPublicKey(msgHash) {
const { r, s, recovery: rec } = this;
const h = bits2int_modN((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('msgHash', msgHash)); // Truncate hash
if (rec == null || ![0, 1, 2, 3].includes(rec))
throw new Error('recovery id invalid');
const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
if (radj >= Fp.ORDER)
throw new Error('recovery id 2 or 3 invalid');
const prefix = (rec & 1) === 0 ? '02' : '03';
const R = Point.fromHex(prefix + numToNByteStr(radj));
const ir = invN(radj); // r^-1
const u1 = modN(-h * ir); // -hr^-1
const u2 = modN(s * ir); // sr^-1
const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
if (!Q)
throw new Error('point at infinify'); // unsafe is fine: no priv data leaked
Q.assertValidity();
return Q;
}
// Signatures should be low-s, to prevent malleability.
hasHighS() {
return isBiggerThanHalfOrder(this.s);
}
normalizeS() {
return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
}
// DER-encoded
toDERRawBytes() {
return _utils_js__WEBPACK_IMPORTED_MODULE_1__.hexToBytes(this.toDERHex());
}
toDERHex() {
return DER.hexFromSig({ r: this.r, s: this.s });
}
// padded bytes of r, then padded bytes of s
toCompactRawBytes() {
return _utils_js__WEBPACK_IMPORTED_MODULE_1__.hexToBytes(this.toCompactHex());
}
toCompactHex() {
return numToNByteStr(this.r) + numToNByteStr(this.s);
}
}
const utils = {
isValidPrivateKey(privateKey) {
try {
normPrivateKeyToScalar(privateKey);
return true;
}
catch (error) {
return false;
}
},
normPrivateKeyToScalar: normPrivateKeyToScalar,
/**
* Produces cryptographically secure private key from random of size
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
*/
randomPrivateKey: () => {
const length = _modular_js__WEBPACK_IMPORTED_MODULE_2__.getMinHashLength(CURVE.n);
return _modular_js__WEBPACK_IMPORTED_MODULE_2__.mapHashToField(CURVE.randomBytes(length), CURVE.n);
},
/**
* Creates precompute table for an arbitrary EC point. Makes point "cached".
* Allows to massively speed-up `point.multiply(scalar)`.
* @returns cached point
* @example
* const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
* fast.multiply(privKey); // much faster ECDH now
*/
precompute(windowSize = 8, point = Point.BASE) {
point._setWindowSize(windowSize);
point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
return point;
},
};
/**
* Computes public key for a private key. Checks for validity of the private key.
* @param privateKey private key
* @param isCompressed whether to return compact (default), or full key
* @returns Public key, full when isCompressed=false; short when isCompressed=true
*/
function getPublicKey(privateKey, isCompressed = true) {
return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
}
/**
* Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
*/
function isProbPub(item) {
const arr = _utils_js__WEBPACK_IMPORTED_MODULE_1__.isBytes(item);
const str = typeof item === 'string';
const len = (arr || str) && item.length;
if (arr)
return len === compressedLen || len === uncompressedLen;
if (str)
return len === 2 * compressedLen || len === 2 * uncompressedLen;
if (item instanceof Point)
return true;
return false;
}
/**
* ECDH (Elliptic Curve Diffie Hellman).
* Computes shared public key from private key and public key.
* Checks: 1) private key validity 2) shared key is on-curve.
* Does NOT hash the result.
* @param privateA private key
* @param publicB different public key
* @param isCompressed whether to return compact (default), or full key
* @returns shared public key
*/
function getSharedSecret(privateA, publicB, isCompressed = true) {
if (isProbPub(privateA))
throw new Error('first arg must be private key');
if (!isProbPub(publicB))
throw new Error('second arg must be public key');
const b = Point.fromHex(publicB); // check for being on-curve
return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
}
// RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
// FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
// bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
// int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
const bits2int = CURVE.bits2int ||
function (bytes) {
// For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
// for some cases, since bytes.length * 8 is not actual bitLength.
const num = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE(bytes); // check for == u8 done here
const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits
return delta > 0 ? num >> BigInt(delta) : num;
};
const bits2int_modN = CURVE.bits2int_modN ||
function (bytes) {
return modN(bits2int(bytes)); // can't use bytesToNumberBE here
};
// NOTE: pads output with zero as per spec
const ORDER_MASK = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bitMask(CURVE.nBitLength);
/**
* Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
*/
function int2octets(num) {
if (typeof num !== 'bigint')
throw new Error('bigint expected');
if (!(_0n <= num && num < ORDER_MASK))
throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);
// works with order, can have different size than numToField!
return _utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesBE(num, CURVE.nByteLength);
}
// Steps A, D of RFC6979 3.2
// Creates RFC6979 seed; converts msg/privKey to numbers.
// Used only in sign, not in verify.
// NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
// Also it can be bigger for P224 + SHA256
function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
if (['recovered', 'canonical'].some((k) => k in opts))
throw new Error('sign() legacy options not supported');
const { hash, randomBytes } = CURVE;
let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default
if (lowS == null)
lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
msgHash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('msgHash', msgHash);
if (prehash)
msgHash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('prehashed msgHash', hash(msgHash));
// We can't later call bits2octets, since nested bits2int is broken for curves
// with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.
// const bits2octets = (bits) => int2octets(bits2int_modN(bits))
const h1int = bits2int_modN(msgHash);
const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
const seedArgs = [int2octets(d), int2octets(h1int)];
// extraEntropy. RFC6979 3.6: additional k' (optional).
if (ent != null && ent !== false) {
// K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is
seedArgs.push((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('extraEntropy', e)); // check for being bytes
}
const seed = _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes(...seedArgs); // Step D of RFC6979 3.2
const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
// Converts signature params into point w r/s, checks result for validity.
function k2sig(kBytes) {
// RFC 6979 Section 3.2, step 3: k = bits2int(T)
const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
if (!isWithinCurveOrder(k))
return; // Important: all mod() calls here must be done over N
const ik = invN(k); // k^-1 mod n
const q = Point.BASE.multiply(k).toAffine(); // q = Gk
const r = modN(q.x); // r = q.x mod n
if (r === _0n)
return;
// Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
// https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
// a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
const s = modN(ik * modN(m + r * d)); // Not using blinding here
if (s === _0n)
return;
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
let normS = s;
if (lowS && isBiggerThanHalfOrder(s)) {
normS = normalizeS(s); // if lowS was passed, ensure s is always
recovery ^= 1; // // in the bottom half of N
}
return new Signature(r, normS, recovery); // use normS, not s
}
return { seed, k2sig };
}
const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
/**
* Signs message hash with a private key.
* ```
* sign(m, d, k) where
* (x, y) = G × k
* r = x mod n
* s = (m + dr)/k mod n
* ```
* @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.
* @param privKey private key
* @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.
* @returns signature with recovery param
*/
function sign(msgHash, privKey, opts = defaultSigOpts) {
const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.
const C = CURVE;
const drbg = _utils_js__WEBPACK_IMPORTED_MODULE_1__.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
return drbg(seed, k2sig); // Steps B, C, D, E, F, G
}
// Enable precomputes. Slows down first publicKey computation by 20ms.
Point.BASE._setWindowSize(8);
// utils.precompute(8, ProjectivePoint.BASE)
/**
* Verifies a signature against message hash and public key.
* Rejects lowS signatures by default: to override,
* specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
*
* ```
* verify(r, s, h, P) where
* U1 = hs^-1 mod n
* U2 = rs^-1 mod n
* R = U1⋅G - U2⋅P
* mod(R.x, n) == r
* ```
*/
function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
const sg = signature;
msgHash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('msgHash', msgHash);
publicKey = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('publicKey', publicKey);
if ('strict' in opts)
throw new Error('options.strict was renamed to lowS');
const { lowS, prehash } = opts;
let _sig = undefined;
let P;
try {
if (typeof sg === 'string' || _utils_js__WEBPACK_IMPORTED_MODULE_1__.isBytes(sg)) {
// Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
// Since DER can also be 2*nByteLength bytes, we check for it first.
try {
_sig = Signature.fromDER(sg);
}
catch (derError) {
if (!(derError instanceof DER.Err))
throw derError;
_sig = Signature.fromCompact(sg);
}
}
else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
const { r, s } = sg;
_sig = new Signature(r, s);
}
else {
throw new Error('PARSE');
}
P = Point.fromHex(publicKey);
}
catch (error) {
if (error.message === 'PARSE')
throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
return false;
}
if (lowS && _sig.hasHighS())
return false;
if (prehash)
msgHash = CURVE.hash(msgHash);
const { r, s } = _sig;
const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element
const is = invN(s); // s^-1
const u1 = modN(h * is); // u1 = hs^-1 mod n
const u2 = modN(r * is); // u2 = rs^-1 mod n
const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P
if (!R)
return false;
const v = modN(R.x);
return v === r;
}
return {
CURVE,
getPublicKey,
getSharedSecret,
sign,
verify,
ProjectivePoint: Point,
Signature,
utils,
};
}
/**
* Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
* TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
* b = True and y = sqrt(u / v) if (u / v) is square in F, and
* b = False and y = sqrt(Z * (u / v)) otherwise.
* @param Fp
* @param Z
* @returns
*/
function SWUFpSqrtRatio(Fp, Z) {
// Generic implementation
const q = Fp.ORDER;
let l = _0n;
for (let o = q - _1n; o % _2n === _0n; o /= _2n)
l += _1n;
const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
// We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
// 2n ** c1 == 2n << (c1-1)
const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic
const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic
const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic
const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic
const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
let sqrtRatio = (u, v) => {
let tv1 = c6; // 1. tv1 = c6
let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
// 17. for i in (c1, c1 - 1, ..., 2):
for (let i = c1; i > _1n; i--) {
let tv5 = i - _2n; // 18. tv5 = i - 2
tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5
let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5
const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1
tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1
tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1
tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1
tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)
tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)
}
return { isValid: isQR, value: tv3 };
};
if (Fp.ORDER % _4n === _3n) {
// sqrt_ratio_3mod4(u, v)
const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic
const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
sqrtRatio = (u, v) => {
let tv1 = Fp.sqr(v); // 1. tv1 = v^2
const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
};
}
// No curves uses that
// if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
return sqrtRatio;
}
/**
* Simplified Shallue-van de Woestijne-Ulas Method
* https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
*/
function mapToCurveSimpleSWU(Fp, opts) {
_modular_js__WEBPACK_IMPORTED_MODULE_2__.validateField(Fp);
if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))
throw new Error('mapToCurveSimpleSWU: invalid opts');
const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);
if (!Fp.isOdd)
throw new Error('Fp.isOdd is not implemented!');
// Input: u, an element of F.
// Output: (x, y), a point on E.
return (u) => {
// prettier-ignore
let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
tv1 = Fp.sqr(u); // 1. tv1 = u^2
tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1
tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2
tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1
tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1
tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3
tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)
tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4
tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2
tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6
tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6
tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3
const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1
y = Fp.mul(y, value); // 20. y = y * y1
x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)
y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)
const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)
y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)
x = Fp.div(x, tv4); // 25. x = x / tv4
return { x, y };
};
}
//# sourceMappingURL=weierstrass.js.map
/***/ }),
/***/ "./node_modules/@noble/curves/esm/ed25519.js":
/*!***************************************************!*\
!*** ./node_modules/@noble/curves/esm/ed25519.js ***!
\***************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ED25519_TORSION_SUBGROUP: () => (/* binding */ ED25519_TORSION_SUBGROUP),
/* harmony export */ RistrettoPoint: () => (/* binding */ RistrettoPoint),
/* harmony export */ ed25519: () => (/* binding */ ed25519),
/* harmony export */ ed25519ctx: () => (/* binding */ ed25519ctx),
/* harmony export */ ed25519ph: () => (/* binding */ ed25519ph),
/* harmony export */ edwardsToMontgomery: () => (/* binding */ edwardsToMontgomery),
/* harmony export */ edwardsToMontgomeryPriv: () => (/* binding */ edwardsToMontgomeryPriv),
/* harmony export */ edwardsToMontgomeryPub: () => (/* binding */ edwardsToMontgomeryPub),
/* harmony export */ encodeToCurve: () => (/* binding */ encodeToCurve),
/* harmony export */ hashToCurve: () => (/* binding */ hashToCurve),
/* harmony export */ hashToRistretto255: () => (/* binding */ hashToRistretto255),
/* harmony export */ hash_to_ristretto255: () => (/* binding */ hash_to_ristretto255),
/* harmony export */ x25519: () => (/* binding */ x25519)
/* harmony export */ });
/* harmony import */ var _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/sha512 */ "./node_modules/@noble/hashes/esm/sha512.js");
/* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/esm/utils.js");
/* harmony import */ var _abstract_edwards_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./abstract/edwards.js */ "./node_modules/@noble/curves/esm/abstract/edwards.js");
/* harmony import */ var _abstract_montgomery_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./abstract/montgomery.js */ "./node_modules/@noble/curves/esm/abstract/montgomery.js");
/* harmony import */ var _abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./abstract/modular.js */ "./node_modules/@noble/curves/esm/abstract/modular.js");
/* harmony import */ var _abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./abstract/utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
/* harmony import */ var _abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./abstract/hash-to-curve.js */ "./node_modules/@noble/curves/esm/abstract/hash-to-curve.js");
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
/**
* ed25519 Twisted Edwards curve with following addons:
* - X25519 ECDH
* - Ristretto cofactor elimination
* - Elligator hash-to-group / point indistinguishability
*/
const ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');
// √(-1) aka √(a) aka 2^((p-1)/4)
const ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5);
// prettier-ignore
const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
function ed25519_pow_2_252_3(x) {
const P = ED25519_P;
const x2 = (x * x) % P;
const b2 = (x2 * x) % P; // x^3, 11
const b4 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b2, _2n, P) * b2) % P; // x^15, 1111
const b5 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b4, _1n, P) * x) % P; // x^31
const b10 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b5, _5n, P) * b5) % P;
const b20 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b10, _10n, P) * b10) % P;
const b40 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b20, _20n, P) * b20) % P;
const b80 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b40, _40n, P) * b40) % P;
const b160 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b80, _80n, P) * b80) % P;
const b240 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b160, _80n, P) * b80) % P;
const b250 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b240, _10n, P) * b10) % P;
const pow_p_5_8 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b250, _2n, P) * x) % P;
// ^ To pow to (p+3)/8, multiply it by x.
return { pow_p_5_8, b2 };
}
function adjustScalarBytes(bytes) {
// Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,
// set the three least significant bits of the first byte
bytes[0] &= 248; // 0b1111_1000
// and the most significant bit of the last to zero,
bytes[31] &= 127; // 0b0111_1111
// set the second most significant bit of the last byte to 1
bytes[31] |= 64; // 0b0100_0000
return bytes;
}
// sqrt(u/v)
function uvRatio(u, v) {
const P = ED25519_P;
const v3 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(v * v * v, P); // v³
const v7 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(v3 * v3 * v, P); // v⁷
// (p+3)/8 and (p-5)/8
const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
let x = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8
const vx2 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(v * x * x, P); // vx²
const root1 = x; // First root candidate
const root2 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(x * ED25519_SQRT_M1, P); // Second root candidate
const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root
const useRoot2 = vx2 === (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)
const noRoot = vx2 === (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)
if (useRoot1)
x = root1;
if (useRoot2 || noRoot)
x = root2; // We return root2 anyway, for const-time
if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(x, P))
x = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(-x, P);
return { isValid: useRoot1 || useRoot2, value: x };
}
// Just in case
const ED25519_TORSION_SUBGROUP = [
'0100000000000000000000000000000000000000000000000000000000000000',
'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',
'0000000000000000000000000000000000000000000000000000000000000080',
'26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',
'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',
'26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',
'0000000000000000000000000000000000000000000000000000000000000000',
'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',
];
const Fp = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.Field)(ED25519_P, undefined, true);
const ed25519Defaults = {
// Param: a
a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster
// d is equal to -121665/121666 over finite field.
// Negative number is P - number, and division is invert(number, P)
d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
// Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n
Fp,
// Subgroup order: how many points curve has
// 2n**252n + 27742317777372353535851937790883648493n;
n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),
// Cofactor
h: BigInt(8),
// Base point (x, y) aka generator point
Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
hash: _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__.sha512,
randomBytes: _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.randomBytes,
adjustScalarBytes,
// dom2
// Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
// Constant-time, u/√v
uvRatio,
};
const ed25519 = /* @__PURE__ */ (0,_abstract_edwards_js__WEBPACK_IMPORTED_MODULE_3__.twistedEdwards)(ed25519Defaults);
function ed25519_domain(data, ctx, phflag) {
if (ctx.length > 255)
throw new Error('Context is too big');
return (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.concatBytes)((0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.utf8ToBytes)('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
}
const ed25519ctx = /* @__PURE__ */ (0,_abstract_edwards_js__WEBPACK_IMPORTED_MODULE_3__.twistedEdwards)({
...ed25519Defaults,
domain: ed25519_domain,
});
const ed25519ph = /* @__PURE__ */ (0,_abstract_edwards_js__WEBPACK_IMPORTED_MODULE_3__.twistedEdwards)({
...ed25519Defaults,
domain: ed25519_domain,
prehash: _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__.sha512,
});
const x25519 = /* @__PURE__ */ (() => (0,_abstract_montgomery_js__WEBPACK_IMPORTED_MODULE_4__.montgomery)({
P: ED25519_P,
a: BigInt(486662),
montgomeryBits: 255, // n is 253 bits
nByteLength: 32,
Gu: BigInt(9),
powPminus2: (x) => {
const P = ED25519_P;
// x^(p-2) aka x^(2^255-21)
const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
return (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(pow_p_5_8, BigInt(3), P) * b2, P);
},
adjustScalarBytes,
randomBytes: _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.randomBytes,
}))();
/**
* Converts ed25519 public key to x25519 public key. Uses formula:
* * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
* * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
* @example
* const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());
* const aPriv = x25519.utils.randomPrivateKey();
* x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))
*/
function edwardsToMontgomeryPub(edwardsPub) {
const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);
const _1n = BigInt(1);
return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));
}
const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated
/**
* Converts ed25519 secret key to x25519 secret key.
* @example
* const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());
* const aPriv = ed25519.utils.randomPrivateKey();
* x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)
*/
function edwardsToMontgomeryPriv(edwardsPriv) {
const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));
return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);
}
// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)
// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since
// SageMath returns different root first and everything falls apart
const ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic
const ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1
const ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1)
const ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic
const ELL2_J = BigInt(486662);
// prettier-ignore
function map_to_curve_elligator2_curve25519(u) {
let tv1 = Fp.sqr(u); // 1. tv1 = u^2
tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1
let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not
let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)
let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2
let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3
let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd
gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd
gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2
gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2
let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2
tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4
tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3
tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3
tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7
let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)
y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)
let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3
tv2 = Fp.sqr(y11); // 19. tv2 = y11^2
tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd
let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1
let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt
let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd
let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u
y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2
let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3
let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)
tv2 = Fp.sqr(y21); // 28. tv2 = y21^2
tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd
let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2
let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt
tv2 = Fp.sqr(y1); // 32. tv2 = y1^2
tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd
let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1
let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2
let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2
let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y
y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)
return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)
}
const ELL2_C1_EDWARDS = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.FpSqrtEven)(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0
function map_to_curve_elligator2_edwards25519(u) {
const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =
// map_to_curve_elligator2_curve25519(u)
let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd
xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1
let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM
let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd
let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)
let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd
let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0
xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)
xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)
yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)
yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)
const inv = Fp.invertBatch([xd, yd]); // batch division
return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)
}
const htf = /* @__PURE__ */ (() => (0,_abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.createHasher)(ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {
DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',
encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',
p: Fp.ORDER,
m: 1,
k: 128,
expand: 'xmd',
hash: _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__.sha512,
}))();
const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();
const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();
function assertRstPoint(other) {
if (!(other instanceof RistPoint))
throw new Error('RistrettoPoint expected');
}
// √(-1) aka √(a) aka 2^((p-1)/4)
const SQRT_M1 = ED25519_SQRT_M1;
// √(ad - 1)
const SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');
// 1 / √(a-d)
const INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');
// 1-d²
const ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');
// (d-1)²
const D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');
// Calculates 1/√(number)
const invertSqrt = (number) => uvRatio(_1n, number);
const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
const bytes255ToNumberLE = (bytes) => ed25519.CURVE.Fp.create((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.bytesToNumberLE)(bytes) & MAX_255B);
// Computes Elligator map for Ristretto
// https://ristretto.group/formulas/elligator.html
function calcElligatorRistrettoMap(r0) {
const { d } = ed25519.CURVE;
const P = ed25519.CURVE.Fp.ORDER;
const mod = ed25519.CURVE.Fp.create;
const r = mod(SQRT_M1 * r0 * r0); // 1
const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2
let c = BigInt(-1); // 3
const D = mod((c - d * r) * mod(r + d)); // 4
let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5
let s_ = mod(s * r0); // 6
if (!(0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(s_, P))
s_ = mod(-s_);
if (!Ns_D_is_sq)
s = s_; // 7
if (!Ns_D_is_sq)
c = r; // 8
const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9
const s2 = s * s;
const W0 = mod((s + s) * D); // 10
const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11
const W2 = mod(_1n - s2); // 12
const W3 = mod(_1n + s2); // 13
return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
}
/**
* Each ed25519/ExtendedPoint has 8 different equivalent points. This can be
* a source of bugs for protocols like ring signatures. Ristretto was created to solve this.
* Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,
* but it should work in its own namespace: do not combine those two.
* https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448
*/
class RistPoint {
// Private property to discourage combining ExtendedPoint + RistrettoPoint
// Always use Ristretto encoding/decoding instead.
constructor(ep) {
this.ep = ep;
}
static fromAffine(ap) {
return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));
}
/**
* Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.
* The hash-to-group operation applies Elligator twice and adds the results.
* **Note:** this is one-way map, there is no conversion from point to hash.
* https://ristretto.group/formulas/elligator.html
* @param hex 64-byte output of a hash function
*/
static hashToCurve(hex) {
hex = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.ensureBytes)('ristrettoHash', hex, 64);
const r1 = bytes255ToNumberLE(hex.slice(0, 32));
const R1 = calcElligatorRistrettoMap(r1);
const r2 = bytes255ToNumberLE(hex.slice(32, 64));
const R2 = calcElligatorRistrettoMap(r2);
return new RistPoint(R1.add(R2));
}
/**
* Converts ristretto-encoded string to ristretto point.
* https://ristretto.group/formulas/decoding.html
* @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
*/
static fromHex(hex) {
hex = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.ensureBytes)('ristrettoHex', hex, 32);
const { a, d } = ed25519.CURVE;
const P = ed25519.CURVE.Fp.ORDER;
const mod = ed25519.CURVE.Fp.create;
const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';
const s = bytes255ToNumberLE(hex);
// 1. Check that s_bytes is the canonical encoding of a field element, or else abort.
// 3. Check that s is non-negative, or else abort
if (!(0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.equalBytes)((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.numberToBytesLE)(s, 32), hex) || (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(s, P))
throw new Error(emsg);
const s2 = mod(s * s);
const u1 = mod(_1n + a * s2); // 4 (a is -1)
const u2 = mod(_1n - a * s2); // 5
const u1_2 = mod(u1 * u1);
const u2_2 = mod(u2 * u2);
const v = mod(a * d * u1_2 - u2_2); // 6
const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7
const Dx = mod(I * u2); // 8
const Dy = mod(I * Dx * v); // 9
let x = mod((s + s) * Dx); // 10
if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(x, P))
x = mod(-x); // 10
const y = mod(u1 * Dy); // 11
const t = mod(x * y); // 12
if (!isValid || (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(t, P) || y === _0n)
throw new Error(emsg);
return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));
}
/**
* Encodes ristretto point to Uint8Array.
* https://ristretto.group/formulas/encoding.html
*/
toRawBytes() {
let { ex: x, ey: y, ez: z, et: t } = this.ep;
const P = ed25519.CURVE.Fp.ORDER;
const mod = ed25519.CURVE.Fp.create;
const u1 = mod(mod(z + y) * mod(z - y)); // 1
const u2 = mod(x * y); // 2
// Square root always exists
const u2sq = mod(u2 * u2);
const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3
const D1 = mod(invsqrt * u1); // 4
const D2 = mod(invsqrt * u2); // 5
const zInv = mod(D1 * D2 * t); // 6
let D; // 7
if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(t * zInv, P)) {
let _x = mod(y * SQRT_M1);
let _y = mod(x * SQRT_M1);
x = _x;
y = _y;
D = mod(D1 * INVSQRT_A_MINUS_D);
}
else {
D = D2; // 8
}
if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(x * zInv, P))
y = mod(-y); // 9
let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))
if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(s, P))
s = mod(-s);
return (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.numberToBytesLE)(s, 32); // 11
}
toHex() {
return (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.bytesToHex)(this.toRawBytes());
}
toString() {
return this.toHex();
}
// Compare one point to another.
equals(other) {
assertRstPoint(other);
const { ex: X1, ey: Y1 } = this.ep;
const { ex: X2, ey: Y2 } = other.ep;
const mod = ed25519.CURVE.Fp.create;
// (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)
const one = mod(X1 * Y2) === mod(Y1 * X2);
const two = mod(Y1 * Y2) === mod(X1 * X2);
return one || two;
}
add(other) {
assertRstPoint(other);
return new RistPoint(this.ep.add(other.ep));
}
subtract(other) {
assertRstPoint(other);
return new RistPoint(this.ep.subtract(other.ep));
}
multiply(scalar) {
return new RistPoint(this.ep.multiply(scalar));
}
multiplyUnsafe(scalar) {
return new RistPoint(this.ep.multiplyUnsafe(scalar));
}
double() {
return new RistPoint(this.ep.double());
}
negate() {
return new RistPoint(this.ep.negate());
}
}
const RistrettoPoint = /* @__PURE__ */ (() => {
if (!RistPoint.BASE)
RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);
if (!RistPoint.ZERO)
RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);
return RistPoint;
})();
// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B
const hashToRistretto255 = (msg, options) => {
const d = options.DST;
const DST = typeof d === 'string' ? (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.utf8ToBytes)(d) : d;
const uniform_bytes = (0,_abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.expand_message_xmd)(msg, DST, 64, _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__.sha512);
const P = RistPoint.hashToCurve(uniform_bytes);
return P;
};
const hash_to_ristretto255 = hashToRistretto255; // legacy
//# sourceMappingURL=ed25519.js.map
/***/ }),
/***/ "./node_modules/@noble/curves/esm/secp256k1.js":
/*!*****************************************************!*\
!*** ./node_modules/@noble/curves/esm/secp256k1.js ***!
\*****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ encodeToCurve: () => (/* binding */ encodeToCurve),
/* harmony export */ hashToCurve: () => (/* binding */ hashToCurve),
/* harmony export */ schnorr: () => (/* binding */ schnorr),
/* harmony export */ secp256k1: () => (/* binding */ secp256k1)
/* harmony export */ });
/* harmony import */ var _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @noble/hashes/sha256 */ "./node_modules/@noble/hashes/esm/sha256.js");
/* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @noble/hashes/utils */ "./node_modules/@noble/hashes/esm/utils.js");
/* harmony import */ var _abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./abstract/modular.js */ "./node_modules/@noble/curves/esm/abstract/modular.js");
/* harmony import */ var _abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./abstract/weierstrass.js */ "./node_modules/@noble/curves/esm/abstract/weierstrass.js");
/* harmony import */ var _abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./abstract/utils.js */ "./node_modules/@noble/curves/esm/abstract/utils.js");
/* harmony import */ var _abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./abstract/hash-to-curve.js */ "./node_modules/@noble/curves/esm/abstract/hash-to-curve.js");
/* harmony import */ var _shortw_utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_shortw_utils.js */ "./node_modules/@noble/curves/esm/_shortw_utils.js");
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
const _1n = BigInt(1);
const _2n = BigInt(2);
const divNearest = (a, b) => (a + b / _2n) / b;
/**
* √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
* (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
*/
function sqrtMod(y) {
const P = secp256k1P;
// prettier-ignore
const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
// prettier-ignore
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
const b2 = (y * y * y) % P; // x^3, 11
const b3 = (b2 * b2 * y) % P; // x^7
const b6 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b3, _3n, P) * b3) % P;
const b9 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b6, _3n, P) * b3) % P;
const b11 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b9, _2n, P) * b2) % P;
const b22 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b11, _11n, P) * b11) % P;
const b44 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b22, _22n, P) * b22) % P;
const b88 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b44, _44n, P) * b44) % P;
const b176 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b88, _88n, P) * b88) % P;
const b220 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b176, _44n, P) * b44) % P;
const b223 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b220, _3n, P) * b3) % P;
const t1 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b223, _23n, P) * b22) % P;
const t2 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(t1, _6n, P) * b2) % P;
const root = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(t2, _2n, P);
if (!Fp.eql(Fp.sqr(root), y))
throw new Error('Cannot find square root');
return root;
}
const Fp = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.Field)(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
const secp256k1 = (0,_shortw_utils_js__WEBPACK_IMPORTED_MODULE_1__.createCurve)({
a: BigInt(0), // equation params: a, b
b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975
Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n
n: secp256k1N, // Curve order, total count of valid points in the field
// Base point (x, y) aka generator point
Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
h: BigInt(1), // Cofactor
lowS: true, // Allow only low-S signatures by default in sign() and verify()
/**
* secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
* Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
* For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
* Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
*/
endo: {
beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
splitScalar: (k) => {
const n = secp256k1N;
const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
const b2 = a1;
const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)
const c1 = divNearest(b2 * k, n);
const c2 = divNearest(-b1 * k, n);
let k1 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(k - c1 * a1 - c2 * a2, n);
let k2 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(-c1 * b1 - c2 * b2, n);
const k1neg = k1 > POW_2_128;
const k2neg = k2 > POW_2_128;
if (k1neg)
k1 = n - k1;
if (k2neg)
k2 = n - k2;
if (k1 > POW_2_128 || k2 > POW_2_128) {
throw new Error('splitScalar: Endomorphism failed, k=' + k);
}
return { k1neg, k1, k2neg, k2 };
},
},
}, _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
const _0n = BigInt(0);
const fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P;
const ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N;
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
let tagP = TAGGED_HASH_PREFIXES[tag];
if (tagP === undefined) {
const tagH = (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256)(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
tagP = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.concatBytes)(tagH, tagH);
TAGGED_HASH_PREFIXES[tag] = tagP;
}
return (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256)((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.concatBytes)(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toRawBytes(true).slice(1);
const numTo32b = (n) => (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.numberToBytesBE)(n, 32);
const modP = (x) => (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(x, secp256k1P);
const modN = (x) => (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(x, secp256k1N);
const Point = secp256k1.ProjectivePoint;
const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey
let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside
const scalar = p.hasEvenY() ? d_ : modN(-d_);
return { scalar: scalar, bytes: pointToBytes(p) };
}
/**
* lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
* @returns valid point checked for being on-curve
*/
function lift_x(x) {
if (!fe(x))
throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.
const xx = modP(x * x);
const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.
if (y % _2n !== _0n)
y = modP(-y); // Return the unique point P such that x(P) = x and
const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
p.assertValidity();
return p;
}
/**
* Create tagged hash, convert it to bigint, reduce modulo-n.
*/
function challenge(...args) {
return modN((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE)(taggedHash('BIP0340/challenge', ...args)));
}
/**
* Schnorr public key is just `x` coordinate of Point as per BIP340.
*/
function schnorrGetPublicKey(privateKey) {
return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
* Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
* auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
*/
function schnorrSign(message, privateKey, auxRand = (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_4__.randomBytes)(32)) {
const m = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('message', message);
const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder
const a = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
const t = numTo32b(d ^ (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE)(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
const k_ = modN((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE)(rand)); // Let k' = int(rand) mod n
if (k_ === _0n)
throw new Error('sign failed: k is zero'); // Fail if k' = 0.
const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.
const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
sig.set(rx, 0);
sig.set(numTo32b(modN(k + e * d)), 32);
// If Verify(bytes(P), m, sig) (see below) returns failure, abort
if (!schnorrVerify(sig, m, px))
throw new Error('sign: Invalid signature produced');
return sig;
}
/**
* Verifies Schnorr signature.
* Will swallow errors & return false except for initial type validation of arguments.
*/
function schnorrVerify(signature, message, publicKey) {
const sig = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('signature', signature, 64);
const m = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('message', message);
const pub = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('publicKey', publicKey, 32);
try {
const P = lift_x((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE)(pub)); // P = lift_x(int(pk)); fail if that fails
const r = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE)(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
if (!fe(r))
return false;
const s = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE)(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
if (!ge(s))
return false;
const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n
const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P
if (!R || !R.hasEvenY() || R.toAffine().x !== r)
return false; // -eP == (n-e)P
return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
}
catch (error) {
return false;
}
}
const schnorr = /* @__PURE__ */ (() => ({
getPublicKey: schnorrGetPublicKey,
sign: schnorrSign,
verify: schnorrVerify,
utils: {
randomPrivateKey: secp256k1.utils.randomPrivateKey,
lift_x,
pointToBytes,
numberToBytesBE: _abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.numberToBytesBE,
bytesToNumberBE: _abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE,
taggedHash,
mod: _abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod,
},
}))();
const isoMap = /* @__PURE__ */ (() => (0,_abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.isogenyMap)(Fp, [
// xNum
[
'0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
'0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
'0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
'0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
],
// xDen
[
'0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
'0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
'0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
],
// yNum
[
'0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
'0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
'0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
'0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
],
// yDen
[
'0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
'0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
'0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
'0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => (0,_abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_6__.mapToCurveSimpleSWU)(Fp, {
A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
B: BigInt('1771'),
Z: Fp.create(BigInt('-11')),
}))();
const htf = /* @__PURE__ */ (() => (0,_abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.createHasher)(secp256k1.ProjectivePoint, (scalars) => {
const { x, y } = mapSWU(Fp.create(scalars[0]));
return isoMap(x, y);
}, {
DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
p: Fp.ORDER,
m: 1,
k: 128,
expand: 'xmd',
hash: _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256,
}))();
const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();
const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map
/***/ }),
/***/ "./node_modules/@noble/hashes/esm/_assert.js":
/*!***************************************************!*\
!*** ./node_modules/@noble/hashes/esm/_assert.js ***!
\***************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ bool: () => (/* binding */ bool),
/* harmony export */ bytes: () => (/* binding */ bytes),
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */ exists: () => (/* binding */ exists),
/* harmony export */ hash: () => (/* binding */ hash),
/* harmony export */ isBytes: () => (/* binding */ isBytes),
/* harmony export */ number: () => (/* binding */ number),
/* harmony export */ output: () => (/* binding */ output)
/* harmony export */ });
function number(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`positive integer expected, not ${n}`);
}
function bool(b) {
if (typeof b !== 'boolean')
throw new Error(`boolean expected, not ${b}`);
}
// copied from utils
function isBytes(a) {
return (a instanceof Uint8Array ||
(a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
}
function bytes(b, ...lengths) {
if (!isBytes(b))
throw new Error('Uint8Array expected');
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
}
function hash(h) {
if (typeof h !== 'function' || typeof h.create !== 'function')
throw new Error('Hash should be wrapped by utils.wrapConstructor');
number(h.outputLen);
number(h.blockLen);
}
function exists(instance, checkFinished = true) {
if (instance.destroyed)
throw new Error('Hash instance has been destroyed');
if (checkFinished && instance.finished)
throw new Error('Hash#digest() has already been called');
}
function output(out, instance) {
bytes(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error(`digestInto() expects output buffer of length at least ${min}`);
}
}
const assert = { number, bool, bytes, hash, exists, output };
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (assert);
//# sourceMappingURL=_assert.js.map
/***/ }),
/***/ "./node_modules/@noble/hashes/esm/_md.js":
/*!***********************************************!*\
!*** ./node_modules/@noble/hashes/esm/_md.js ***!
\***********************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Chi: () => (/* binding */ Chi),
/* harmony export */ HashMD: () => (/* binding */ HashMD),
/* harmony export */ Maj: () => (/* binding */ Maj)
/* harmony export */ });
/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_assert.js */ "./node_modules/@noble/hashes/esm/_assert.js");
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/hashes/esm/utils.js");
// Polyfill for Safari 14
function setBigUint64(view, byteOffset, value, isLE) {
if (typeof view.setBigUint64 === 'function')
return view.setBigUint64(byteOffset, value, isLE);
const _32n = BigInt(32);
const _u32_max = BigInt(0xffffffff);
const wh = Number((value >> _32n) & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE ? 4 : 0;
const l = isLE ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE);
view.setUint32(byteOffset + l, wl, isLE);
}
// Choice: a ? b : c
const Chi = (a, b, c) => (a & b) ^ (~a & c);
// Majority function, true if any two inpust is true
const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
/**
* Merkle-Damgard hash construction base class.
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
*/
class HashMD extends _utils_js__WEBPACK_IMPORTED_MODULE_0__.Hash {
constructor(blockLen, outputLen, padOffset, isLE) {
super();
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE;
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.buffer = new Uint8Array(blockLen);
this.view = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(this.buffer);
}
update(data) {
(0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.exists)(this);
const { view, buffer, blockLen } = this;
data = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.toBytes)(data);
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
// Fast path: we have at least one block in input, cast it to view and process
if (take === blockLen) {
const dataView = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
(0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.exists)(this);
(0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.output)(out, this);
this.finished = true;
// Padding
// We can avoid allocation of buffer for padding completely if it
// was previously not allocated here. But it won't change performance.
const { buffer, view, blockLen, isLE } = this;
let { pos } = this;
// append the bit '1' to the message
buffer[pos++] = 0b10000000;
this.buffer.subarray(pos).fill(0);
// we have less than padOffset left in buffer, so we cannot put length in
// current block, need process it and pad again
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
// Pad until full block byte with zeros
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
// Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
// You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
// So we just write lowest 64 bits of that value.
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
this.process(view, 0);
const oview = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(out);
const len = this.outputLen;
// NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
if (len % 4)
throw new Error('_sha2: outputLen should be aligned to 32bit');
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error('_sha2: outputLen bigger than state');
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.length = length;
to.pos = pos;
to.finished = finished;
to.destroyed = destroyed;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
}
//# sourceMappingURL=_md.js.map
/***/ }),
/***/ "./node_modules/@noble/hashes/esm/_u64.js":
/*!************************************************!*\
!*** ./node_modules/@noble/hashes/esm/_u64.js ***!
\************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ add: () => (/* binding */ add),
/* harmony export */ add3H: () => (/* binding */ add3H),
/* harmony export */ add3L: () => (/* binding */ add3L),
/* harmony export */ add4H: () => (/* binding */ add4H),
/* harmony export */ add4L: () => (/* binding */ add4L),
/* harmony export */ add5H: () => (/* binding */ add5H),
/* harmony export */ add5L: () => (/* binding */ add5L),
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */ fromBig: () => (/* binding */ fromBig),
/* harmony export */ rotlBH: () => (/* binding */ rotlBH),
/* harmony export */ rotlBL: () => (/* binding */ rotlBL),
/* harmony export */ rotlSH: () => (/* binding */ rotlSH),
/* harmony export */ rotlSL: () => (/* binding */ rotlSL),
/* harmony export */ rotr32H: () => (/* binding */ rotr32H),
/* harmony export */ rotr32L: () => (/* binding */ rotr32L),
/* harmony export */ rotrBH: () => (/* binding */ rotrBH),
/* harmony export */ rotrBL: () => (/* binding */ rotrBL),
/* harmony export */ rotrSH: () => (/* binding */ rotrSH),
/* harmony export */ rotrSL: () => (/* binding */ rotrSL),
/* harmony export */ shrSH: () => (/* binding */ shrSH),
/* harmony export */ shrSL: () => (/* binding */ shrSL),
/* harmony export */ split: () => (/* binding */ split),
/* harmony export */ toBig: () => (/* binding */ toBig)
/* harmony export */ });
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
// We are not using BigUint64Array, because they are extremely slow as per 2022
function fromBig(n, le = false) {
if (le)
return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
let Ah = new Uint32Array(lst.length);
let Al = new Uint32Array(lst.length);
for (let i = 0; i < lst.length; i++) {
const { h, l } = fromBig(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
const rotr32L = (h, _l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
const l = (Al >>> 0) + (Bl >>> 0);
return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
// prettier-ignore
const u64 = {
fromBig, split, toBig,
shrSH, shrSL,
rotrSH, rotrSL, rotrBH, rotrBL,
rotr32H, rotr32L,
rotlSH, rotlSL, rotlBH, rotlBL,
add, add3L, add3H, add4L, add4H, add5H, add5L,
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (u64);
//# sourceMappingURL=_u64.js.map
/***/ }),
/***/ "./node_modules/@noble/hashes/esm/crypto.js":
/*!**************************************************!*\
!*** ./node_modules/@noble/hashes/esm/crypto.js ***!
\**************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ crypto: () => (/* binding */ crypto)
/* harmony export */ });
const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map
/***/ }),
/***/ "./node_modules/@noble/hashes/esm/hmac.js":
/*!************************************************!*\
!*** ./node_modules/@noble/hashes/esm/hmac.js ***!
\************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ HMAC: () => (/* binding */ HMAC),
/* harmony export */ hmac: () => (/* binding */ hmac)
/* harmony export */ });
/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_assert.js */ "./node_modules/@noble/hashes/esm/_assert.js");
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/hashes/esm/utils.js");
// HMAC (RFC 2104)
class HMAC extends _utils_js__WEBPACK_IMPORTED_MODULE_0__.Hash {
constructor(hash, _key) {
super();
this.finished = false;
this.destroyed = false;
(0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.hash)(hash);
const key = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.toBytes)(_key);
this.iHash = hash.create();
if (typeof this.iHash.update !== 'function')
throw new Error('Expected instance of class which extends utils.Hash');
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad = new Uint8Array(blockLen);
// blockLen can be bigger than outputLen
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 0x36;
this.iHash.update(pad);
// By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
this.oHash = hash.create();
// Undo internal XOR && apply outer XOR
for (let i = 0; i < pad.length; i++)
pad[i] ^= 0x36 ^ 0x5c;
this.oHash.update(pad);
pad.fill(0);
}
update(buf) {
(0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.exists)(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
(0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.exists)(this);
(0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.bytes)(out, this.outputLen);
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
// Create new instance without calling constructor since key already in state and we don't know it.
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
}
/**
* HMAC: RFC2104 message authentication code.
* @param hash - function that would be used e.g. sha256
* @param key - message key
* @param message - message data
*/
const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map
/***/ }),
/***/ "./node_modules/@noble/hashes/esm/sha256.js":
/*!**************************************************!*\
!*** ./node_modules/@noble/hashes/esm/sha256.js ***!
\**************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ sha224: () => (/* binding */ sha224),
/* harmony export */ sha256: () => (/* binding */ sha256)
/* harmony export */ });
/* harmony import */ var _md_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_md.js */ "./node_modules/@noble/hashes/esm/_md.js");
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/hashes/esm/utils.js");
// SHA2-256 need to try 2^128 hashes to execute birthday attack.
// BTC network is doing 2^67 hashes/sec as per early 2023.
// Round constants:
// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
// prettier-ignore
const SHA256_K = /* @__PURE__ */ new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
// Initial state:
// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19
// prettier-ignore
const SHA256_IV = /* @__PURE__ */ new Uint32Array([
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
]);
// Temporary buffer, not used to store anything between runs
// Named this way because it matches specification.
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
class SHA256 extends _md_js__WEBPACK_IMPORTED_MODULE_0__.HashMD {
constructor() {
super(64, 32, 8, false);
// We cannot use array here since array allows indexing by variable
// which means optimizer/compiler cannot use registers.
this.A = SHA256_IV[0] | 0;
this.B = SHA256_IV[1] | 0;
this.C = SHA256_IV[2] | 0;
this.D = SHA256_IV[3] | 0;
this.E = SHA256_IV[4] | 0;
this.F = SHA256_IV[5] | 0;
this.G = SHA256_IV[6] | 0;
this.H = SHA256_IV[7] | 0;
}
get() {
const { A, B, C, D, E, F, G, H } = this;
return [A, B, C, D, E, F, G, H];
}
// prettier-ignore
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
// Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
for (let i = 0; i < 16; i++, offset += 4)
SHA256_W[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W[i - 15];
const W2 = SHA256_W[i - 2];
const s0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W15, 7) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W15, 18) ^ (W15 >>> 3);
const s1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W2, 17) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W2, 19) ^ (W2 >>> 10);
SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
}
// Compression function main loop, 64 rounds
let { A, B, C, D, E, F, G, H } = this;
for (let i = 0; i < 64; i++) {
const sigma1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 6) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 11) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 25);
const T1 = (H + sigma1 + (0,_md_js__WEBPACK_IMPORTED_MODULE_0__.Chi)(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
const sigma0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 2) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 13) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 22);
const T2 = (sigma0 + (0,_md_js__WEBPACK_IMPORTED_MODULE_0__.Maj)(A, B, C)) | 0;
H = G;
G = F;
F = E;
E = (D + T1) | 0;
D = C;
C = B;
B = A;
A = (T1 + T2) | 0;
}
// Add the compressed chunk to the current hash value
A = (A + this.A) | 0;
B = (B + this.B) | 0;
C = (C + this.C) | 0;
D = (D + this.D) | 0;
E = (E + this.E) | 0;
F = (F + this.F) | 0;
G = (G + this.G) | 0;
H = (H + this.H) | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
SHA256_W.fill(0);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
this.buffer.fill(0);
}
}
// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
class SHA224 extends SHA256 {
constructor() {
super();
this.A = 0xc1059ed8 | 0;
this.B = 0x367cd507 | 0;
this.C = 0x3070dd17 | 0;
this.D = 0xf70e5939 | 0;
this.E = 0xffc00b31 | 0;
this.F = 0x68581511 | 0;
this.G = 0x64f98fa7 | 0;
this.H = 0xbefa4fa4 | 0;
this.outputLen = 28;
}
}
/**
* SHA2-256 hash function
* @param message - data that would be hashed
*/
const sha256 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new SHA256());
const sha224 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new SHA224());
//# sourceMappingURL=sha256.js.map
/***/ }),
/***/ "./node_modules/@noble/hashes/esm/sha512.js":
/*!**************************************************!*\
!*** ./node_modules/@noble/hashes/esm/sha512.js ***!
\**************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ SHA512: () => (/* binding */ SHA512),
/* harmony export */ sha384: () => (/* binding */ sha384),
/* harmony export */ sha512: () => (/* binding */ sha512),
/* harmony export */ sha512_224: () => (/* binding */ sha512_224),
/* harmony export */ sha512_256: () => (/* binding */ sha512_256)
/* harmony export */ });
/* harmony import */ var _md_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_md.js */ "./node_modules/@noble/hashes/esm/_md.js");
/* harmony import */ var _u64_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_u64.js */ "./node_modules/@noble/hashes/esm/_u64.js");
/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@noble/hashes/esm/utils.js");
// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
// prettier-ignore
const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].split([
'0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
'0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
'0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
'0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
'0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
'0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
'0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
'0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
'0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
'0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
'0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
'0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
'0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
'0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
'0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
'0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
'0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
'0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
'0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
'0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
// Temporary buffer, not used to store anything between runs
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
class SHA512 extends _md_js__WEBPACK_IMPORTED_MODULE_1__.HashMD {
constructor() {
super(128, 64, 16, false);
// We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.
// Also looks cleaner and easier to verify with spec.
// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
// h -- high 32 bits, l -- low 32 bits
this.Ah = 0x6a09e667 | 0;
this.Al = 0xf3bcc908 | 0;
this.Bh = 0xbb67ae85 | 0;
this.Bl = 0x84caa73b | 0;
this.Ch = 0x3c6ef372 | 0;
this.Cl = 0xfe94f82b | 0;
this.Dh = 0xa54ff53a | 0;
this.Dl = 0x5f1d36f1 | 0;
this.Eh = 0x510e527f | 0;
this.El = 0xade682d1 | 0;
this.Fh = 0x9b05688c | 0;
this.Fl = 0x2b3e6c1f | 0;
this.Gh = 0x1f83d9ab | 0;
this.Gl = 0xfb41bd6b | 0;
this.Hh = 0x5be0cd19 | 0;
this.Hl = 0x137e2179 | 0;
}
// prettier-ignore
get() {
const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
}
// prettier-ignore
set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
this.Ah = Ah | 0;
this.Al = Al | 0;
this.Bh = Bh | 0;
this.Bl = Bl | 0;
this.Ch = Ch | 0;
this.Cl = Cl | 0;
this.Dh = Dh | 0;
this.Dl = Dl | 0;
this.Eh = Eh | 0;
this.El = El | 0;
this.Fh = Fh | 0;
this.Fl = Fl | 0;
this.Gh = Gh | 0;
this.Gl = Gl | 0;
this.Hh = Hh | 0;
this.Hl = Hl | 0;
}
process(view, offset) {
// Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
for (let i = 0; i < 16; i++, offset += 4) {
SHA512_W_H[i] = view.getUint32(offset);
SHA512_W_L[i] = view.getUint32((offset += 4));
}
for (let i = 16; i < 80; i++) {
// s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
const W15h = SHA512_W_H[i - 15] | 0;
const W15l = SHA512_W_L[i - 15] | 0;
const s0h = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrSH(W15h, W15l, 1) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrSH(W15h, W15l, 8) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].shrSH(W15h, W15l, 7);
const s0l = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrSL(W15h, W15l, 1) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrSL(W15h, W15l, 8) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].shrSL(W15h, W15l, 7);
// s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
const W2h = SHA512_W_H[i - 2] | 0;
const W2l = SHA512_W_L[i - 2] | 0;
const s1h = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrSH(W2h, W2l, 19) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrBH(W2h, W2l, 61) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].shrSH(W2h, W2l, 6);
const s1l = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrSL(W2h, W2l, 19) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrBL(W2h, W2l, 61) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].shrSL(W2h, W2l, 6);
// SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
const SUMl = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
const SUMh = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
SHA512_W_H[i] = SUMh | 0;
SHA512_W_L[i] = SUMl | 0;
}
let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
// Compression function main loop, 80 rounds
for (let i = 0; i < 80; i++) {
// S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
const sigma1h = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrSH(Eh, El, 14) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrSH(Eh, El, 18) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrBH(Eh, El, 41);
const sigma1l = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrSL(Eh, El, 14) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrSL(Eh, El, 18) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrBL(Eh, El, 41);
//const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
const CHIh = (Eh & Fh) ^ (~Eh & Gh);
const CHIl = (El & Fl) ^ (~El & Gl);
// T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
// prettier-ignore
const T1ll = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
const T1h = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
const T1l = T1ll | 0;
// S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
const sigma0h = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrSH(Ah, Al, 28) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrBH(Ah, Al, 34) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrBH(Ah, Al, 39);
const sigma0l = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrSL(Ah, Al, 28) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrBL(Ah, Al, 34) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].rotrBL(Ah, Al, 39);
const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
Hh = Gh | 0;
Hl = Gl | 0;
Gh = Fh | 0;
Gl = Fl | 0;
Fh = Eh | 0;
Fl = El | 0;
({ h: Eh, l: El } = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
Dh = Ch | 0;
Dl = Cl | 0;
Ch = Bh | 0;
Cl = Bl | 0;
Bh = Ah | 0;
Bl = Al | 0;
const All = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add3L(T1l, sigma0l, MAJl);
Ah = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add3H(All, T1h, sigma0h, MAJh);
Al = All | 0;
}
// Add the compressed chunk to the current hash value
({ h: Ah, l: Al } = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
({ h: Bh, l: Bl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
({ h: Ch, l: Cl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
({ h: Dh, l: Dl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
({ h: Eh, l: El } = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
({ h: Fh, l: Fl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
({ h: Gh, l: Gl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
({ h: Hh, l: Hl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__["default"].add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
}
roundClean() {
SHA512_W_H.fill(0);
SHA512_W_L.fill(0);
}
destroy() {
this.buffer.fill(0);
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
class SHA512_224 extends SHA512 {
constructor() {
super();
// h -- high 32 bits, l -- low 32 bits
this.Ah = 0x8c3d37c8 | 0;
this.Al = 0x19544da2 | 0;
this.Bh = 0x73e19966 | 0;
this.Bl = 0x89dcd4d6 | 0;
this.Ch = 0x1dfab7ae | 0;
this.Cl = 0x32ff9c82 | 0;
this.Dh = 0x679dd514 | 0;
this.Dl = 0x582f9fcf | 0;
this.Eh = 0x0f6d2b69 | 0;
this.El = 0x7bd44da8 | 0;
this.Fh = 0x77e36f73 | 0;
this.Fl = 0x04c48942 | 0;
this.Gh = 0x3f9d85a8 | 0;
this.Gl = 0x6a1d36c8 | 0;
this.Hh = 0x1112e6ad | 0;
this.Hl = 0x91d692a1 | 0;
this.outputLen = 28;
}
}
class SHA512_256 extends SHA512 {
constructor() {
super();
// h -- high 32 bits, l -- low 32 bits
this.Ah = 0x22312194 | 0;
this.Al = 0xfc2bf72c | 0;
this.Bh = 0x9f555fa3 | 0;
this.Bl = 0xc84c64c2 | 0;
this.Ch = 0x2393b86b | 0;
this.Cl = 0x6f53b151 | 0;
this.Dh = 0x96387719 | 0;
this.Dl = 0x5940eabd | 0;
this.Eh = 0x96283ee2 | 0;
this.El = 0xa88effe3 | 0;
this.Fh = 0xbe5e1e25 | 0;
this.Fl = 0x53863992 | 0;
this.Gh = 0x2b0199fc | 0;
this.Gl = 0x2c85b8aa | 0;
this.Hh = 0x0eb72ddc | 0;
this.Hl = 0x81c52ca2 | 0;
this.outputLen = 32;
}
}
class SHA384 extends SHA512 {
constructor() {
super();
// h -- high 32 bits, l -- low 32 bits
this.Ah = 0xcbbb9d5d | 0;
this.Al = 0xc1059ed8 | 0;
this.Bh = 0x629a292a | 0;
this.Bl = 0x367cd507 | 0;
this.Ch = 0x9159015a | 0;
this.Cl = 0x3070dd17 | 0;
this.Dh = 0x152fecd8 | 0;
this.Dl = 0xf70e5939 | 0;
this.Eh = 0x67332667 | 0;
this.El = 0xffc00b31 | 0;
this.Fh = 0x8eb44a87 | 0;
this.Fl = 0x68581511 | 0;
this.Gh = 0xdb0c2e0d | 0;
this.Gl = 0x64f98fa7 | 0;
this.Hh = 0x47b5481d | 0;
this.Hl = 0xbefa4fa4 | 0;
this.outputLen = 48;
}
}
const sha512 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.wrapConstructor)(() => new SHA512());
const sha512_224 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.wrapConstructor)(() => new SHA512_224());
const sha512_256 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.wrapConstructor)(() => new SHA512_256());
const sha384 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.wrapConstructor)(() => new SHA384());
//# sourceMappingURL=sha512.js.map
/***/ }),
/***/ "./node_modules/@noble/hashes/esm/utils.js":
/*!*************************************************!*\
!*** ./node_modules/@noble/hashes/esm/utils.js ***!
\*************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Hash: () => (/* binding */ Hash),
/* harmony export */ asyncLoop: () => (/* binding */ asyncLoop),
/* harmony export */ byteSwap: () => (/* binding */ byteSwap),
/* harmony export */ byteSwap32: () => (/* binding */ byteSwap32),
/* harmony export */ byteSwapIfBE: () => (/* binding */ byteSwapIfBE),
/* harmony export */ bytesToHex: () => (/* binding */ bytesToHex),
/* harmony export */ checkOpts: () => (/* binding */ checkOpts),
/* harmony export */ concatBytes: () => (/* binding */ concatBytes),
/* harmony export */ createView: () => (/* binding */ createView),
/* harmony export */ hexToBytes: () => (/* binding */ hexToBytes),
/* harmony export */ isBytes: () => (/* binding */ isBytes),
/* harmony export */ isLE: () => (/* binding */ isLE),
/* harmony export */ nextTick: () => (/* binding */ nextTick),
/* harmony export */ randomBytes: () => (/* binding */ randomBytes),
/* harmony export */ rotl: () => (/* binding */ rotl),
/* harmony export */ rotr: () => (/* binding */ rotr),
/* harmony export */ toBytes: () => (/* binding */ toBytes),
/* harmony export */ u32: () => (/* binding */ u32),
/* harmony export */ u8: () => (/* binding */ u8),
/* harmony export */ utf8ToBytes: () => (/* binding */ utf8ToBytes),
/* harmony export */ wrapConstructor: () => (/* binding */ wrapConstructor),
/* harmony export */ wrapConstructorWithOpts: () => (/* binding */ wrapConstructorWithOpts),
/* harmony export */ wrapXOFConstructorWithOpts: () => (/* binding */ wrapXOFConstructorWithOpts)
/* harmony export */ });
/* harmony import */ var _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/crypto */ "./node_modules/@noble/hashes/esm/crypto.js");
/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_assert.js */ "./node_modules/@noble/hashes/esm/_assert.js");
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
// export { isBytes } from './_assert.js';
// We can't reuse isBytes from _assert, because somehow this causes huge perf issues
function isBytes(a) {
return (a instanceof Uint8Array ||
(a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
}
// Cast array to different type
const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
// Cast array to view
const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
// The rotate right (circular right shift) operation for uint32
const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
// The rotate left (circular left shift) operation for uint32
const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);
const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
// The byte swap operation for uint32
const byteSwap = (word) => ((word << 24) & 0xff000000) |
((word << 8) & 0xff0000) |
((word >>> 8) & 0xff00) |
((word >>> 24) & 0xff);
// Conditionally byte swap if on a big-endian platform
const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);
// In place byte swap for Uint32Array
function byteSwap32(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] = byteSwap(arr[i]);
}
}
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
*/
function bytesToHex(bytes) {
(0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.bytes)(bytes);
// pre-caching improves the speed 6x
let hex = '';
for (let i = 0; i < bytes.length; i++) {
hex += hexes[bytes[i]];
}
return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
function asciiToBase16(char) {
if (char >= asciis._0 && char <= asciis._9)
return char - asciis._0;
if (char >= asciis._A && char <= asciis._F)
return char - (asciis._A - 10);
if (char >= asciis._a && char <= asciis._f)
return char - (asciis._a - 10);
return;
}
/**
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
*/
function hexToBytes(hex) {
if (typeof hex !== 'string')
throw new Error('hex string expected, got ' + typeof hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
const array = new Uint8Array(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
const n1 = asciiToBase16(hex.charCodeAt(hi));
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
if (n1 === undefined || n2 === undefined) {
const char = hex[hi] + hex[hi + 1];
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
}
array[ai] = n1 * 16 + n2;
}
return array;
}
// There is no setImmediate in browser and setTimeout is slow.
// call of async fn will return Promise, which will be fullfiled only on
// next scheduler queue processing step and this is exactly what we need.
const nextTick = async () => { };
// Returns control to thread each 'tick' ms to avoid blocking
async function asyncLoop(iters, tick, cb) {
let ts = Date.now();
for (let i = 0; i < iters; i++) {
cb(i);
// Date.now() is not monotonic, so in case if clock goes backwards we return return control too
const diff = Date.now() - ts;
if (diff >= 0 && diff < tick)
continue;
await nextTick();
ts += diff;
}
}
/**
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
*/
function utf8ToBytes(str) {
if (typeof str !== 'string')
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
* Warning: when Uint8Array is passed, it would NOT get copied.
* Keep in mind for future mutable operations.
*/
function toBytes(data) {
if (typeof data === 'string')
data = utf8ToBytes(data);
(0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.bytes)(data);
return data;
}
/**
* Copies several Uint8Arrays into one.
*/
function concatBytes(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
(0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.bytes)(a);
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
// For runtime check if class implements interface
class Hash {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
}
const toStr = {}.toString;
function checkOpts(defaults, opts) {
if (opts !== undefined && toStr.call(opts) !== '[object Object]')
throw new Error('Options should be object or undefined');
const merged = Object.assign(defaults, opts);
return merged;
}
function wrapConstructor(hashCons) {
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
const tmp = hashCons();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashCons();
return hashC;
}
function wrapConstructorWithOpts(hashCons) {
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
const tmp = hashCons({});
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (opts) => hashCons(opts);
return hashC;
}
function wrapXOFConstructorWithOpts(hashCons) {
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
const tmp = hashCons({});
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (opts) => hashCons(opts);
return hashC;
}
/**
* Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
*/
function randomBytes(bytesLength = 32) {
if (_noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto && typeof _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto.getRandomValues === 'function') {
return _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto.getRandomValues(new Uint8Array(bytesLength));
}
throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.map
/***/ }),
/***/ "./node_modules/cborg/cborg.js":
/*!*************************************!*\
!*** ./node_modules/cborg/cborg.js ***!
\*************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Token: () => (/* reexport safe */ _lib_token_js__WEBPACK_IMPORTED_MODULE_2__.Token),
/* harmony export */ Tokenizer: () => (/* reexport safe */ _lib_decode_js__WEBPACK_IMPORTED_MODULE_1__.Tokeniser),
/* harmony export */ Type: () => (/* reexport safe */ _lib_token_js__WEBPACK_IMPORTED_MODULE_2__.Type),
/* harmony export */ decode: () => (/* reexport safe */ _lib_decode_js__WEBPACK_IMPORTED_MODULE_1__.decode),
/* harmony export */ decodeFirst: () => (/* reexport safe */ _lib_decode_js__WEBPACK_IMPORTED_MODULE_1__.decodeFirst),
/* harmony export */ encode: () => (/* reexport safe */ _lib_encode_js__WEBPACK_IMPORTED_MODULE_0__.encode),
/* harmony export */ tokensToObject: () => (/* reexport safe */ _lib_decode_js__WEBPACK_IMPORTED_MODULE_1__.tokensToObject)
/* harmony export */ });
/* harmony import */ var _lib_encode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./lib/encode.js */ "./node_modules/cborg/lib/encode.js");
/* harmony import */ var _lib_decode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./lib/decode.js */ "./node_modules/cborg/lib/decode.js");
/* harmony import */ var _lib_token_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./lib/token.js */ "./node_modules/cborg/lib/token.js");
/**
* Export the types that were present in the original manual cborg.d.ts
* @typedef {import('./interface').TagDecoder} TagDecoder
* There was originally just `TypeEncoder` so don't break types by renaming or not exporting
* @typedef {import('./interface').OptionalTypeEncoder} TypeEncoder
* @typedef {import('./interface').DecodeOptions} DecodeOptions
* @typedef {import('./interface').EncodeOptions} EncodeOptions
*/
/***/ }),
/***/ "./node_modules/cborg/lib/0uint.js":
/*!*****************************************!*\
!*** ./node_modules/cborg/lib/0uint.js ***!
\*****************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decodeUint16: () => (/* binding */ decodeUint16),
/* harmony export */ decodeUint32: () => (/* binding */ decodeUint32),
/* harmony export */ decodeUint64: () => (/* binding */ decodeUint64),
/* harmony export */ decodeUint8: () => (/* binding */ decodeUint8),
/* harmony export */ encodeUint: () => (/* binding */ encodeUint),
/* harmony export */ encodeUintValue: () => (/* binding */ encodeUintValue),
/* harmony export */ readUint16: () => (/* binding */ readUint16),
/* harmony export */ readUint32: () => (/* binding */ readUint32),
/* harmony export */ readUint64: () => (/* binding */ readUint64),
/* harmony export */ readUint8: () => (/* binding */ readUint8),
/* harmony export */ uintBoundaries: () => (/* binding */ uintBoundaries)
/* harmony export */ });
/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./token.js */ "./node_modules/cborg/lib/token.js");
/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./common.js */ "./node_modules/cborg/lib/common.js");
/* globals BigInt */
const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]
/**
* @typedef {import('./bl.js').Bl} Bl
* @typedef {import('../interface').DecodeOptions} DecodeOptions
*/
/**
* @param {Uint8Array} data
* @param {number} offset
* @param {DecodeOptions} options
* @returns {number}
*/
function readUint8 (data, offset, options) {
;(0,_common_js__WEBPACK_IMPORTED_MODULE_1__.assertEnoughData)(data, offset, 1)
const value = data[offset]
if (options.strict === true && value < uintBoundaries[0]) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
}
return value
}
/**
* @param {Uint8Array} data
* @param {number} offset
* @param {DecodeOptions} options
* @returns {number}
*/
function readUint16 (data, offset, options) {
(0,_common_js__WEBPACK_IMPORTED_MODULE_1__.assertEnoughData)(data, offset, 2)
const value = (data[offset] << 8) | data[offset + 1]
if (options.strict === true && value < uintBoundaries[1]) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
}
return value
}
/**
* @param {Uint8Array} data
* @param {number} offset
* @param {DecodeOptions} options
* @returns {number}
*/
function readUint32 (data, offset, options) {
(0,_common_js__WEBPACK_IMPORTED_MODULE_1__.assertEnoughData)(data, offset, 4)
const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
if (options.strict === true && value < uintBoundaries[2]) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
}
return value
}
/**
* @param {Uint8Array} data
* @param {number} offset
* @param {DecodeOptions} options
* @returns {number|bigint}
*/
function readUint64 (data, offset, options) {
// assume BigInt, convert back to Number if within safe range
(0,_common_js__WEBPACK_IMPORTED_MODULE_1__.assertEnoughData)(data, offset, 8)
const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
if (options.strict === true && value < uintBoundaries[3]) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
}
if (value <= Number.MAX_SAFE_INTEGER) {
return Number(value)
}
if (options.allowBigInt === true) {
return value
}
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} integers outside of the safe integer range are not supported`)
}
/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
return oneByteTokens[minor]
}
*/
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeUint8 (data, pos, _minor, options) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.uint, readUint8(data, pos + 1, options), 2)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeUint16 (data, pos, _minor, options) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.uint, readUint16(data, pos + 1, options), 3)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeUint32 (data, pos, _minor, options) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.uint, readUint32(data, pos + 1, options), 5)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeUint64 (data, pos, _minor, options) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.uint, readUint64(data, pos + 1, options), 9)
}
/**
* @param {Bl} buf
* @param {Token} token
*/
function encodeUint (buf, token) {
return encodeUintValue(buf, 0, token.value)
}
/**
* @param {Bl} buf
* @param {number} major
* @param {number|bigint} uint
*/
function encodeUintValue (buf, major, uint) {
if (uint < uintBoundaries[0]) {
const nuint = Number(uint)
// pack into one byte, minor=0, additional=value
buf.push([major | nuint])
} else if (uint < uintBoundaries[1]) {
const nuint = Number(uint)
// pack into two byte, minor=0, additional=24
buf.push([major | 24, nuint])
} else if (uint < uintBoundaries[2]) {
const nuint = Number(uint)
// pack into three byte, minor=0, additional=25
buf.push([major | 25, nuint >>> 8, nuint & 0xff])
} else if (uint < uintBoundaries[3]) {
const nuint = Number(uint)
// pack into five byte, minor=0, additional=26
buf.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
} else {
const buint = BigInt(uint)
if (buint < uintBoundaries[4]) {
// pack into nine byte, minor=0, additional=27
const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
// simulate bitwise above 32 bits
let lo = Number(buint & BigInt(0xffffffff))
let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
set[8] = lo & 0xff
lo = lo >> 8
set[7] = lo & 0xff
lo = lo >> 8
set[6] = lo & 0xff
lo = lo >> 8
set[5] = lo & 0xff
set[4] = hi & 0xff
hi = hi >> 8
set[3] = hi & 0xff
hi = hi >> 8
set[2] = hi & 0xff
hi = hi >> 8
set[1] = hi & 0xff
buf.push(set)
} else {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} encountered BigInt larger than allowable range`)
}
}
}
/**
* @param {Token} token
* @returns {number}
*/
encodeUint.encodedSize = function encodedSize (token) {
return encodeUintValue.encodedSize(token.value)
}
/**
* @param {number} uint
* @returns {number}
*/
encodeUintValue.encodedSize = function encodedSize (uint) {
if (uint < uintBoundaries[0]) {
return 1
}
if (uint < uintBoundaries[1]) {
return 2
}
if (uint < uintBoundaries[2]) {
return 3
}
if (uint < uintBoundaries[3]) {
return 5
}
return 9
}
/**
* @param {Token} tok1
* @param {Token} tok2
* @returns {number}
*/
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : /* c8 ignore next */ 0
}
/***/ }),
/***/ "./node_modules/cborg/lib/1negint.js":
/*!*******************************************!*\
!*** ./node_modules/cborg/lib/1negint.js ***!
\*******************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decodeNegint16: () => (/* binding */ decodeNegint16),
/* harmony export */ decodeNegint32: () => (/* binding */ decodeNegint32),
/* harmony export */ decodeNegint64: () => (/* binding */ decodeNegint64),
/* harmony export */ decodeNegint8: () => (/* binding */ decodeNegint8),
/* harmony export */ encodeNegint: () => (/* binding */ encodeNegint)
/* harmony export */ });
/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./token.js */ "./node_modules/cborg/lib/token.js");
/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./0uint.js */ "./node_modules/cborg/lib/0uint.js");
/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./common.js */ "./node_modules/cborg/lib/common.js");
/* eslint-env es2020 */
/**
* @typedef {import('./bl.js').Bl} Bl
* @typedef {import('../interface').DecodeOptions} DecodeOptions
*/
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeNegint8 (data, pos, _minor, options) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.negint, -1 - _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint8(data, pos + 1, options), 2)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeNegint16 (data, pos, _minor, options) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.negint, -1 - _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint16(data, pos + 1, options), 3)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeNegint32 (data, pos, _minor, options) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.negint, -1 - _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint32(data, pos + 1, options), 5)
}
const neg1b = BigInt(-1)
const pos1b = BigInt(1)
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeNegint64 (data, pos, _minor, options) {
const int = _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint64(data, pos + 1, options)
if (typeof int !== 'bigint') {
const value = -1 - int
if (value >= Number.MIN_SAFE_INTEGER) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.negint, value, 9)
}
}
if (options.allowBigInt !== true) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_2__.decodeErrPrefix} integers outside of the safe integer range are not supported`)
}
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.negint, neg1b - BigInt(int), 9)
}
/**
* @param {Bl} buf
* @param {Token} token
*/
function encodeNegint (buf, token) {
const negint = token.value
const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
_0uint_js__WEBPACK_IMPORTED_MODULE_1__.encodeUintValue(buf, token.type.majorEncoded, unsigned)
}
/**
* @param {Token} token
* @returns {number}
*/
encodeNegint.encodedSize = function encodedSize (token) {
const negint = token.value
const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
/* c8 ignore next 4 */
// handled by quickEncode, we shouldn't get here but it's included for completeness
if (unsigned < _0uint_js__WEBPACK_IMPORTED_MODULE_1__.uintBoundaries[0]) {
return 1
}
if (unsigned < _0uint_js__WEBPACK_IMPORTED_MODULE_1__.uintBoundaries[1]) {
return 2
}
if (unsigned < _0uint_js__WEBPACK_IMPORTED_MODULE_1__.uintBoundaries[2]) {
return 3
}
if (unsigned < _0uint_js__WEBPACK_IMPORTED_MODULE_1__.uintBoundaries[3]) {
return 5
}
return 9
}
/**
* @param {Token} tok1
* @param {Token} tok2
* @returns {number}
*/
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
// opposite of the uint comparison since we store the uint version in bytes
return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : /* c8 ignore next */ 0
}
/***/ }),
/***/ "./node_modules/cborg/lib/2bytes.js":
/*!******************************************!*\
!*** ./node_modules/cborg/lib/2bytes.js ***!
\******************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ compareBytes: () => (/* binding */ compareBytes),
/* harmony export */ decodeBytes16: () => (/* binding */ decodeBytes16),
/* harmony export */ decodeBytes32: () => (/* binding */ decodeBytes32),
/* harmony export */ decodeBytes64: () => (/* binding */ decodeBytes64),
/* harmony export */ decodeBytes8: () => (/* binding */ decodeBytes8),
/* harmony export */ decodeBytesCompact: () => (/* binding */ decodeBytesCompact),
/* harmony export */ encodeBytes: () => (/* binding */ encodeBytes)
/* harmony export */ });
/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./token.js */ "./node_modules/cborg/lib/token.js");
/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./common.js */ "./node_modules/cborg/lib/common.js");
/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./0uint.js */ "./node_modules/cborg/lib/0uint.js");
/* harmony import */ var _byte_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./byte-utils.js */ "./node_modules/cborg/lib/byte-utils.js");
/**
* @typedef {import('./bl.js').Bl} Bl
* @typedef {import('../interface').DecodeOptions} DecodeOptions
*/
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} prefix
* @param {number} length
* @returns {Token}
*/
function toToken (data, pos, prefix, length) {
(0,_common_js__WEBPACK_IMPORTED_MODULE_1__.assertEnoughData)(data, pos, prefix + length)
const buf = (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_3__.slice)(data, pos + prefix, pos + prefix + length)
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.bytes, buf, prefix + length)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} minor
* @param {DecodeOptions} _options
* @returns {Token}
*/
function decodeBytesCompact (data, pos, minor, _options) {
return toToken(data, pos, 1, minor)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeBytes8 (data, pos, _minor, options) {
return toToken(data, pos, 2, _0uint_js__WEBPACK_IMPORTED_MODULE_2__.readUint8(data, pos + 1, options))
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeBytes16 (data, pos, _minor, options) {
return toToken(data, pos, 3, _0uint_js__WEBPACK_IMPORTED_MODULE_2__.readUint16(data, pos + 1, options))
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeBytes32 (data, pos, _minor, options) {
return toToken(data, pos, 5, _0uint_js__WEBPACK_IMPORTED_MODULE_2__.readUint32(data, pos + 1, options))
}
// TODO: maybe we shouldn't support this ..
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeBytes64 (data, pos, _minor, options) {
const l = _0uint_js__WEBPACK_IMPORTED_MODULE_2__.readUint64(data, pos + 1, options)
if (typeof l === 'bigint') {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} 64-bit integer bytes lengths not supported`)
}
return toToken(data, pos, 9, l)
}
/**
* `encodedBytes` allows for caching when we do a byte version of a string
* for key sorting purposes
* @param {Token} token
* @returns {Uint8Array}
*/
function tokenBytes (token) {
if (token.encodedBytes === undefined) {
token.encodedBytes = token.type === _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.string ? (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_3__.fromString)(token.value) : token.value
}
// @ts-ignore c'mon
return token.encodedBytes
}
/**
* @param {Bl} buf
* @param {Token} token
*/
function encodeBytes (buf, token) {
const bytes = tokenBytes(token)
_0uint_js__WEBPACK_IMPORTED_MODULE_2__.encodeUintValue(buf, token.type.majorEncoded, bytes.length)
buf.push(bytes)
}
/**
* @param {Token} token
* @returns {number}
*/
encodeBytes.encodedSize = function encodedSize (token) {
const bytes = tokenBytes(token)
return _0uint_js__WEBPACK_IMPORTED_MODULE_2__.encodeUintValue.encodedSize(bytes.length) + bytes.length
}
/**
* @param {Token} tok1
* @param {Token} tok2
* @returns {number}
*/
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}
/**
* @param {Uint8Array} b1
* @param {Uint8Array} b2
* @returns {number}
*/
function compareBytes (b1, b2) {
return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_3__.compare)(b1, b2)
}
/***/ }),
/***/ "./node_modules/cborg/lib/3string.js":
/*!*******************************************!*\
!*** ./node_modules/cborg/lib/3string.js ***!
\*******************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decodeString16: () => (/* binding */ decodeString16),
/* harmony export */ decodeString32: () => (/* binding */ decodeString32),
/* harmony export */ decodeString64: () => (/* binding */ decodeString64),
/* harmony export */ decodeString8: () => (/* binding */ decodeString8),
/* harmony export */ decodeStringCompact: () => (/* binding */ decodeStringCompact),
/* harmony export */ encodeString: () => (/* binding */ encodeString)
/* harmony export */ });
/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./token.js */ "./node_modules/cborg/lib/token.js");
/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./common.js */ "./node_modules/cborg/lib/common.js");
/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./0uint.js */ "./node_modules/cborg/lib/0uint.js");
/* harmony import */ var _2bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./2bytes.js */ "./node_modules/cborg/lib/2bytes.js");
/* harmony import */ var _byte_utils_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./byte-utils.js */ "./node_modules/cborg/lib/byte-utils.js");
/**
* @typedef {import('./bl.js').Bl} Bl
* @typedef {import('../interface').DecodeOptions} DecodeOptions
*/
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} prefix
* @param {number} length
* @param {DecodeOptions} options
* @returns {Token}
*/
function toToken (data, pos, prefix, length, options) {
const totLength = prefix + length
;(0,_common_js__WEBPACK_IMPORTED_MODULE_1__.assertEnoughData)(data, pos, totLength)
const tok = new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.string, (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_4__.toString)(data, pos + prefix, pos + totLength), totLength)
if (options.retainStringBytes === true) {
tok.byteValue = (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_4__.slice)(data, pos + prefix, pos + totLength)
}
return tok
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeStringCompact (data, pos, minor, options) {
return toToken(data, pos, 1, minor, options)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeString8 (data, pos, _minor, options) {
return toToken(data, pos, 2, _0uint_js__WEBPACK_IMPORTED_MODULE_2__.readUint8(data, pos + 1, options), options)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeString16 (data, pos, _minor, options) {
return toToken(data, pos, 3, _0uint_js__WEBPACK_IMPORTED_MODULE_2__.readUint16(data, pos + 1, options), options)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeString32 (data, pos, _minor, options) {
return toToken(data, pos, 5, _0uint_js__WEBPACK_IMPORTED_MODULE_2__.readUint32(data, pos + 1, options), options)
}
// TODO: maybe we shouldn't support this ..
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeString64 (data, pos, _minor, options) {
const l = _0uint_js__WEBPACK_IMPORTED_MODULE_2__.readUint64(data, pos + 1, options)
if (typeof l === 'bigint') {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} 64-bit integer string lengths not supported`)
}
return toToken(data, pos, 9, l, options)
}
const encodeString = _2bytes_js__WEBPACK_IMPORTED_MODULE_3__.encodeBytes
/***/ }),
/***/ "./node_modules/cborg/lib/4array.js":
/*!******************************************!*\
!*** ./node_modules/cborg/lib/4array.js ***!
\******************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decodeArray16: () => (/* binding */ decodeArray16),
/* harmony export */ decodeArray32: () => (/* binding */ decodeArray32),
/* harmony export */ decodeArray64: () => (/* binding */ decodeArray64),
/* harmony export */ decodeArray8: () => (/* binding */ decodeArray8),
/* harmony export */ decodeArrayCompact: () => (/* binding */ decodeArrayCompact),
/* harmony export */ decodeArrayIndefinite: () => (/* binding */ decodeArrayIndefinite),
/* harmony export */ encodeArray: () => (/* binding */ encodeArray)
/* harmony export */ });
/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./token.js */ "./node_modules/cborg/lib/token.js");
/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./0uint.js */ "./node_modules/cborg/lib/0uint.js");
/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./common.js */ "./node_modules/cborg/lib/common.js");
/**
* @typedef {import('./bl.js').Bl} Bl
* @typedef {import('../interface').DecodeOptions} DecodeOptions
*/
/**
* @param {Uint8Array} _data
* @param {number} _pos
* @param {number} prefix
* @param {number} length
* @returns {Token}
*/
function toToken (_data, _pos, prefix, length) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.array, length, prefix)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} minor
* @param {DecodeOptions} _options
* @returns {Token}
*/
function decodeArrayCompact (data, pos, minor, _options) {
return toToken(data, pos, 1, minor)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeArray8 (data, pos, _minor, options) {
return toToken(data, pos, 2, _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint8(data, pos + 1, options))
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeArray16 (data, pos, _minor, options) {
return toToken(data, pos, 3, _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint16(data, pos + 1, options))
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeArray32 (data, pos, _minor, options) {
return toToken(data, pos, 5, _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint32(data, pos + 1, options))
}
// TODO: maybe we shouldn't support this ..
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeArray64 (data, pos, _minor, options) {
const l = _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint64(data, pos + 1, options)
if (typeof l === 'bigint') {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_2__.decodeErrPrefix} 64-bit integer array lengths not supported`)
}
return toToken(data, pos, 9, l)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeArrayIndefinite (data, pos, _minor, options) {
if (options.allowIndefinite === false) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_2__.decodeErrPrefix} indefinite length items not allowed`)
}
return toToken(data, pos, 1, Infinity)
}
/**
* @param {Bl} buf
* @param {Token} token
*/
function encodeArray (buf, token) {
_0uint_js__WEBPACK_IMPORTED_MODULE_1__.encodeUintValue(buf, _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.array.majorEncoded, token.value)
}
// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = _0uint_js__WEBPACK_IMPORTED_MODULE_1__.encodeUint.compareTokens
/**
* @param {Token} token
* @returns {number}
*/
encodeArray.encodedSize = function encodedSize (token) {
return _0uint_js__WEBPACK_IMPORTED_MODULE_1__.encodeUintValue.encodedSize(token.value)
}
/***/ }),
/***/ "./node_modules/cborg/lib/5map.js":
/*!****************************************!*\
!*** ./node_modules/cborg/lib/5map.js ***!
\****************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decodeMap16: () => (/* binding */ decodeMap16),
/* harmony export */ decodeMap32: () => (/* binding */ decodeMap32),
/* harmony export */ decodeMap64: () => (/* binding */ decodeMap64),
/* harmony export */ decodeMap8: () => (/* binding */ decodeMap8),
/* harmony export */ decodeMapCompact: () => (/* binding */ decodeMapCompact),
/* harmony export */ decodeMapIndefinite: () => (/* binding */ decodeMapIndefinite),
/* harmony export */ encodeMap: () => (/* binding */ encodeMap)
/* harmony export */ });
/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./token.js */ "./node_modules/cborg/lib/token.js");
/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./0uint.js */ "./node_modules/cborg/lib/0uint.js");
/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./common.js */ "./node_modules/cborg/lib/common.js");
/**
* @typedef {import('./bl.js').Bl} Bl
* @typedef {import('../interface').DecodeOptions} DecodeOptions
*/
/**
* @param {Uint8Array} _data
* @param {number} _pos
* @param {number} prefix
* @param {number} length
* @returns {Token}
*/
function toToken (_data, _pos, prefix, length) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.map, length, prefix)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} minor
* @param {DecodeOptions} _options
* @returns {Token}
*/
function decodeMapCompact (data, pos, minor, _options) {
return toToken(data, pos, 1, minor)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeMap8 (data, pos, _minor, options) {
return toToken(data, pos, 2, _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint8(data, pos + 1, options))
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeMap16 (data, pos, _minor, options) {
return toToken(data, pos, 3, _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint16(data, pos + 1, options))
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeMap32 (data, pos, _minor, options) {
return toToken(data, pos, 5, _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint32(data, pos + 1, options))
}
// TODO: maybe we shouldn't support this ..
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeMap64 (data, pos, _minor, options) {
const l = _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint64(data, pos + 1, options)
if (typeof l === 'bigint') {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_2__.decodeErrPrefix} 64-bit integer map lengths not supported`)
}
return toToken(data, pos, 9, l)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeMapIndefinite (data, pos, _minor, options) {
if (options.allowIndefinite === false) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_2__.decodeErrPrefix} indefinite length items not allowed`)
}
return toToken(data, pos, 1, Infinity)
}
/**
* @param {Bl} buf
* @param {Token} token
*/
function encodeMap (buf, token) {
_0uint_js__WEBPACK_IMPORTED_MODULE_1__.encodeUintValue(buf, _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.map.majorEncoded, token.value)
}
// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = _0uint_js__WEBPACK_IMPORTED_MODULE_1__.encodeUint.compareTokens
/**
* @param {Token} token
* @returns {number}
*/
encodeMap.encodedSize = function encodedSize (token) {
return _0uint_js__WEBPACK_IMPORTED_MODULE_1__.encodeUintValue.encodedSize(token.value)
}
/***/ }),
/***/ "./node_modules/cborg/lib/6tag.js":
/*!****************************************!*\
!*** ./node_modules/cborg/lib/6tag.js ***!
\****************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decodeTag16: () => (/* binding */ decodeTag16),
/* harmony export */ decodeTag32: () => (/* binding */ decodeTag32),
/* harmony export */ decodeTag64: () => (/* binding */ decodeTag64),
/* harmony export */ decodeTag8: () => (/* binding */ decodeTag8),
/* harmony export */ decodeTagCompact: () => (/* binding */ decodeTagCompact),
/* harmony export */ encodeTag: () => (/* binding */ encodeTag)
/* harmony export */ });
/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./token.js */ "./node_modules/cborg/lib/token.js");
/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./0uint.js */ "./node_modules/cborg/lib/0uint.js");
/**
* @typedef {import('./bl.js').Bl} Bl
* @typedef {import('../interface').DecodeOptions} DecodeOptions
*/
/**
* @param {Uint8Array} _data
* @param {number} _pos
* @param {number} minor
* @param {DecodeOptions} _options
* @returns {Token}
*/
function decodeTagCompact (_data, _pos, minor, _options) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.tag, minor, 1)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeTag8 (data, pos, _minor, options) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.tag, _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint8(data, pos + 1, options), 2)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeTag16 (data, pos, _minor, options) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.tag, _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint16(data, pos + 1, options), 3)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeTag32 (data, pos, _minor, options) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.tag, _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint32(data, pos + 1, options), 5)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeTag64 (data, pos, _minor, options) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.tag, _0uint_js__WEBPACK_IMPORTED_MODULE_1__.readUint64(data, pos + 1, options), 9)
}
/**
* @param {Bl} buf
* @param {Token} token
*/
function encodeTag (buf, token) {
_0uint_js__WEBPACK_IMPORTED_MODULE_1__.encodeUintValue(buf, _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.tag.majorEncoded, token.value)
}
encodeTag.compareTokens = _0uint_js__WEBPACK_IMPORTED_MODULE_1__.encodeUint.compareTokens
/**
* @param {Token} token
* @returns {number}
*/
encodeTag.encodedSize = function encodedSize (token) {
return _0uint_js__WEBPACK_IMPORTED_MODULE_1__.encodeUintValue.encodedSize(token.value)
}
/***/ }),
/***/ "./node_modules/cborg/lib/7float.js":
/*!******************************************!*\
!*** ./node_modules/cborg/lib/7float.js ***!
\******************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decodeBreak: () => (/* binding */ decodeBreak),
/* harmony export */ decodeFloat16: () => (/* binding */ decodeFloat16),
/* harmony export */ decodeFloat32: () => (/* binding */ decodeFloat32),
/* harmony export */ decodeFloat64: () => (/* binding */ decodeFloat64),
/* harmony export */ decodeUndefined: () => (/* binding */ decodeUndefined),
/* harmony export */ encodeFloat: () => (/* binding */ encodeFloat)
/* harmony export */ });
/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./token.js */ "./node_modules/cborg/lib/token.js");
/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./common.js */ "./node_modules/cborg/lib/common.js");
/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./0uint.js */ "./node_modules/cborg/lib/0uint.js");
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible
/**
* @typedef {import('./bl.js').Bl} Bl
* @typedef {import('../interface').DecodeOptions} DecodeOptions
* @typedef {import('../interface').EncodeOptions} EncodeOptions
*/
const MINOR_FALSE = 20
const MINOR_TRUE = 21
const MINOR_NULL = 22
const MINOR_UNDEFINED = 23
/**
* @param {Uint8Array} _data
* @param {number} _pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeUndefined (_data, _pos, _minor, options) {
if (options.allowUndefined === false) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} undefined values are not supported`)
} else if (options.coerceUndefinedToNull === true) {
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.null, null, 1)
}
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.undefined, undefined, 1)
}
/**
* @param {Uint8Array} _data
* @param {number} _pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeBreak (_data, _pos, _minor, options) {
if (options.allowIndefinite === false) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} indefinite length items not allowed`)
}
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.break, undefined, 1)
}
/**
* @param {number} value
* @param {number} bytes
* @param {DecodeOptions} options
* @returns {Token}
*/
function createToken (value, bytes, options) {
if (options) {
if (options.allowNaN === false && Number.isNaN(value)) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} NaN values are not supported`)
}
if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} Infinity values are not supported`)
}
}
return new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.float, value, bytes)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeFloat16 (data, pos, _minor, options) {
return createToken(readFloat16(data, pos + 1), 3, options)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeFloat32 (data, pos, _minor, options) {
return createToken(readFloat32(data, pos + 1), 5, options)
}
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} _minor
* @param {DecodeOptions} options
* @returns {Token}
*/
function decodeFloat64 (data, pos, _minor, options) {
return createToken(readFloat64(data, pos + 1), 9, options)
}
/**
* @param {Bl} buf
* @param {Token} token
* @param {EncodeOptions} options
*/
function encodeFloat (buf, token, options) {
const float = token.value
if (float === false) {
buf.push([_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.float.majorEncoded | MINOR_FALSE])
} else if (float === true) {
buf.push([_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.float.majorEncoded | MINOR_TRUE])
} else if (float === null) {
buf.push([_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.float.majorEncoded | MINOR_NULL])
} else if (float === undefined) {
buf.push([_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.float.majorEncoded | MINOR_UNDEFINED])
} else {
let decoded
let success = false
if (!options || options.float64 !== true) {
encodeFloat16(float)
decoded = readFloat16(ui8a, 1)
if (float === decoded || Number.isNaN(float)) {
ui8a[0] = 0xf9
buf.push(ui8a.slice(0, 3))
success = true
} else {
encodeFloat32(float)
decoded = readFloat32(ui8a, 1)
if (float === decoded) {
ui8a[0] = 0xfa
buf.push(ui8a.slice(0, 5))
success = true
}
}
}
if (!success) {
encodeFloat64(float)
decoded = readFloat64(ui8a, 1)
ui8a[0] = 0xfb
buf.push(ui8a.slice(0, 9))
}
}
}
/**
* @param {Token} token
* @param {EncodeOptions} options
* @returns {number}
*/
encodeFloat.encodedSize = function encodedSize (token, options) {
const float = token.value
if (float === false || float === true || float === null || float === undefined) {
return 1
}
if (!options || options.float64 !== true) {
encodeFloat16(float)
let decoded = readFloat16(ui8a, 1)
if (float === decoded || Number.isNaN(float)) {
return 3
}
encodeFloat32(float)
decoded = readFloat32(ui8a, 1)
if (float === decoded) {
return 5
}
}
return 9
}
const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)
/**
* @param {number} inp
*/
function encodeFloat16 (inp) {
if (inp === Infinity) {
dataView.setUint16(0, 0x7c00, false)
} else if (inp === -Infinity) {
dataView.setUint16(0, 0xfc00, false)
} else if (Number.isNaN(inp)) {
dataView.setUint16(0, 0x7e00, false)
} else {
dataView.setFloat32(0, inp)
const valu32 = dataView.getUint32(0)
const exponent = (valu32 & 0x7f800000) >> 23
const mantissa = valu32 & 0x7fffff
/* c8 ignore next 6 */
if (exponent === 0xff) {
// too big, Infinity, but this should be hard (impossible?) to trigger
dataView.setUint16(0, 0x7c00, false)
} else if (exponent === 0x00) {
// 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
dataView.setUint16(0, ((inp & 0x80000000) >> 16) | (mantissa >> 13), false)
} else { // standard numbers
// chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
const logicalExponent = exponent - 127
// Now we know that 2^exponent <= 0 logically
/* c8 ignore next 6 */
if (logicalExponent < -24) {
/* No unambiguous representation exists, this float is not a half float
and is too small to be represented using a half, round off to zero.
Consistent with the reference implementation. */
// should be difficult (impossible?) to get here in JS
dataView.setUint16(0, 0)
} else if (logicalExponent < -14) {
/* Offset the remaining decimal places by shifting the significand, the
value is lost. This is an implementation decision that works around the
absence of standard half-float in the language. */
dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
} else {
dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
}
}
}
}
/**
* @param {Uint8Array} ui8a
* @param {number} pos
* @returns {number}
*/
function readFloat16 (ui8a, pos) {
if (ui8a.length - pos < 2) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} not enough data for float16`)
}
const half = (ui8a[pos] << 8) + ui8a[pos + 1]
if (half === 0x7c00) {
return Infinity
}
if (half === 0xfc00) {
return -Infinity
}
if (half === 0x7e00) {
return NaN
}
const exp = (half >> 10) & 0x1f
const mant = half & 0x3ff
let val
if (exp === 0) {
val = mant * (2 ** -24)
} else if (exp !== 31) {
val = (mant + 1024) * (2 ** (exp - 25))
/* c8 ignore next 4 */
} else {
// may not be possible to get here
val = mant === 0 ? Infinity : NaN
}
return (half & 0x8000) ? -val : val
}
/**
* @param {number} inp
*/
function encodeFloat32 (inp) {
dataView.setFloat32(0, inp, false)
}
/**
* @param {Uint8Array} ui8a
* @param {number} pos
* @returns {number}
*/
function readFloat32 (ui8a, pos) {
if (ui8a.length - pos < 4) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} not enough data for float32`)
}
const offset = (ui8a.byteOffset || 0) + pos
return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}
/**
* @param {number} inp
*/
function encodeFloat64 (inp) {
dataView.setFloat64(0, inp, false)
}
/**
* @param {Uint8Array} ui8a
* @param {number} pos
* @returns {number}
*/
function readFloat64 (ui8a, pos) {
if (ui8a.length - pos < 8) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_1__.decodeErrPrefix} not enough data for float64`)
}
const offset = (ui8a.byteOffset || 0) + pos
return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}
/**
* @param {Token} _tok1
* @param {Token} _tok2
* @returns {number}
*/
encodeFloat.compareTokens = _0uint_js__WEBPACK_IMPORTED_MODULE_2__.encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
return _tok1
throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/***/ }),
/***/ "./node_modules/cborg/lib/bl.js":
/*!**************************************!*\
!*** ./node_modules/cborg/lib/bl.js ***!
\**************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Bl: () => (/* binding */ Bl)
/* harmony export */ });
/* harmony import */ var _byte_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./byte-utils.js */ "./node_modules/cborg/lib/byte-utils.js");
/**
* Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
* writing rather than reading.
* A Bl object accepts set() operations for individual bytes and copyTo() for
* inserting byte arrays. These write operations don't automatically increment
* the internal cursor so its "length" won't be changed. Instead, increment()
* must be called to extend its length to cover the inserted data.
* The toBytes() call will convert all internal memory to a single Uint8Array of
* the correct length, truncating any data that is stored but hasn't been
* included by an increment().
* get() can retrieve a single byte.
* All operations (except toBytes()) take an "offset" argument that will perform
* the write at the offset _from the current cursor_. For most operations this
* will be `0` to write at the current cursor position but it can be ahead of
* the current cursor. Negative offsets probably work but are untested.
*/
// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.
const defaultChunkSize = 256
class Bl {
/**
* @param {number} [chunkSize]
*/
constructor (chunkSize = defaultChunkSize) {
this.chunkSize = chunkSize
/** @type {number} */
this.cursor = 0
/** @type {number} */
this.maxCursor = -1
/** @type {(Uint8Array|number[])[]} */
this.chunks = []
// keep the first chunk around if we can to save allocations for future encodes
/** @type {Uint8Array|number[]|null} */
this._initReuseChunk = null
}
reset () {
this.cursor = 0
this.maxCursor = -1
if (this.chunks.length) {
this.chunks = []
}
if (this._initReuseChunk !== null) {
this.chunks.push(this._initReuseChunk)
this.maxCursor = this._initReuseChunk.length - 1
}
}
/**
* @param {Uint8Array|number[]} bytes
*/
push (bytes) {
let topChunk = this.chunks[this.chunks.length - 1]
const newMax = this.cursor + bytes.length
if (newMax <= this.maxCursor + 1) {
// we have at least one chunk and we can fit these bytes into that chunk
const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
// @ts-ignore
topChunk.set(bytes, chunkPos)
} else {
// can't fit it in
if (topChunk) {
// trip the last chunk to `cursor` if we need to
const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
if (chunkPos < topChunk.length) {
// @ts-ignore
this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
this.maxCursor = this.cursor - 1
}
}
if (bytes.length < 64 && bytes.length < this.chunkSize) {
// make a new chunk and copy the new one into it
topChunk = (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_0__.alloc)(this.chunkSize)
this.chunks.push(topChunk)
this.maxCursor += topChunk.length
if (this._initReuseChunk === null) {
this._initReuseChunk = topChunk
}
// @ts-ignore
topChunk.set(bytes, 0)
} else {
// push the new bytes in as its own chunk
this.chunks.push(bytes)
this.maxCursor += bytes.length
}
}
this.cursor += bytes.length
}
/**
* @param {boolean} [reset]
* @returns {Uint8Array}
*/
toBytes (reset = false) {
let byts
if (this.chunks.length === 1) {
const chunk = this.chunks[0]
if (reset && this.cursor > chunk.length / 2) {
/* c8 ignore next 2 */
// @ts-ignore
byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
this._initReuseChunk = null
this.chunks = []
} else {
// @ts-ignore
byts = (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_0__.slice)(chunk, 0, this.cursor)
}
} else {
// @ts-ignore
byts = (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_0__.concat)(this.chunks, this.cursor)
}
if (reset) {
this.reset()
}
return byts
}
}
/***/ }),
/***/ "./node_modules/cborg/lib/byte-utils.js":
/*!**********************************************!*\
!*** ./node_modules/cborg/lib/byte-utils.js ***!
\**********************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ alloc: () => (/* binding */ alloc),
/* harmony export */ asU8A: () => (/* binding */ asU8A),
/* harmony export */ compare: () => (/* binding */ compare),
/* harmony export */ concat: () => (/* binding */ concat),
/* harmony export */ decodeCodePointsArray: () => (/* binding */ decodeCodePointsArray),
/* harmony export */ fromArray: () => (/* binding */ fromArray),
/* harmony export */ fromHex: () => (/* binding */ fromHex),
/* harmony export */ fromString: () => (/* binding */ fromString),
/* harmony export */ slice: () => (/* binding */ slice),
/* harmony export */ toHex: () => (/* binding */ toHex),
/* harmony export */ toString: () => (/* binding */ toString),
/* harmony export */ useBuffer: () => (/* binding */ useBuffer)
/* harmony export */ });
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill
// @ts-ignore
const useBuffer = globalThis.process &&
// @ts-ignore
!globalThis.process.browser &&
// @ts-ignore
globalThis.Buffer &&
// @ts-ignore
typeof globalThis.Buffer.isBuffer === 'function'
const textDecoder = new TextDecoder()
const textEncoder = new TextEncoder()
/**
* @param {Uint8Array} buf
* @returns {boolean}
*/
function isBuffer (buf) {
// @ts-ignore
return useBuffer && globalThis.Buffer.isBuffer(buf)
}
/**
* @param {Uint8Array|number[]} buf
* @returns {Uint8Array}
*/
function asU8A (buf) {
/* c8 ignore next */
if (!(buf instanceof Uint8Array)) {
return Uint8Array.from(buf)
}
return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}
const toString = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array} bytes
* @param {number} start
* @param {number} end
*/
(bytes, start, end) => {
return end - start > 64
? // eslint-disable-line operator-linebreak
// @ts-ignore
globalThis.Buffer.from(bytes.subarray(start, end)).toString('utf8')
: utf8Slice(bytes, start, end)
}
/* c8 ignore next 11 */
: // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array} bytes
* @param {number} start
* @param {number} end
*/
(bytes, start, end) => {
return end - start > 64
? textDecoder.decode(bytes.subarray(start, end))
: utf8Slice(bytes, start, end)
}
const fromString = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {string} string
*/
(string) => {
return string.length > 64
? // eslint-disable-line operator-linebreak
// @ts-ignore
globalThis.Buffer.from(string)
: utf8ToBytes(string)
}
/* c8 ignore next 7 */
: // eslint-disable-line operator-linebreak
/**
* @param {string} string
*/
(string) => {
return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string)
}
/**
* Buffer variant not fast enough for what we need
* @param {number[]} arr
* @returns {Uint8Array}
*/
const fromArray = (arr) => {
return Uint8Array.from(arr)
}
const slice = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array} bytes
* @param {number} start
* @param {number} end
*/
(bytes, start, end) => {
if (isBuffer(bytes)) {
return new Uint8Array(bytes.subarray(start, end))
}
return bytes.slice(start, end)
}
/* c8 ignore next 9 */
: // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array} bytes
* @param {number} start
* @param {number} end
*/
(bytes, start, end) => {
return bytes.slice(start, end)
}
const concat = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array[]} chunks
* @param {number} length
* @returns {Uint8Array}
*/
(chunks, length) => {
// might get a stray plain Array here
/* c8 ignore next 1 */
chunks = chunks.map((c) => c instanceof Uint8Array
? c
// this case is occasionally missed during test runs so becomes coverage-flaky
/* c8 ignore next 4 */
: // eslint-disable-line operator-linebreak
// @ts-ignore
globalThis.Buffer.from(c))
// @ts-ignore
return asU8A(globalThis.Buffer.concat(chunks, length))
}
/* c8 ignore next 19 */
: // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array[]} chunks
* @param {number} length
* @returns {Uint8Array}
*/
(chunks, length) => {
const out = new Uint8Array(length)
let off = 0
for (let b of chunks) {
if (off + b.length > out.length) {
// final chunk that's bigger than we need
b = b.subarray(0, out.length - off)
}
out.set(b, off)
off += b.length
}
return out
}
const alloc = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {number} size
* @returns {Uint8Array}
*/
(size) => {
// we always write over the contents we expose so this should be safe
// @ts-ignore
return globalThis.Buffer.allocUnsafe(size)
}
/* c8 ignore next 8 */
: // eslint-disable-line operator-linebreak
/**
* @param {number} size
* @returns {Uint8Array}
*/
(size) => {
return new Uint8Array(size)
}
const toHex = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array} d
* @returns {string}
*/
(d) => {
if (typeof d === 'string') {
return d
}
// @ts-ignore
return globalThis.Buffer.from(toBytes(d)).toString('hex')
}
/* c8 ignore next 12 */
: // eslint-disable-line operator-linebreak
/**
* @param {Uint8Array} d
* @returns {string}
*/
(d) => {
if (typeof d === 'string') {
return d
}
// @ts-ignore not smart enough to figure this out
return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
}
const fromHex = useBuffer
? // eslint-disable-line operator-linebreak
/**
* @param {string|Uint8Array} hex
* @returns {Uint8Array}
*/
(hex) => {
if (hex instanceof Uint8Array) {
return hex
}
// @ts-ignore
return globalThis.Buffer.from(hex, 'hex')
}
/* c8 ignore next 17 */
: // eslint-disable-line operator-linebreak
/**
* @param {string|Uint8Array} hex
* @returns {Uint8Array}
*/
(hex) => {
if (hex instanceof Uint8Array) {
return hex
}
if (!hex.length) {
return new Uint8Array(0)
}
return new Uint8Array(hex.split('')
.map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
.filter(Boolean)
.map((/** @type {string} */ e) => parseInt(e, 16)))
}
/**
* @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
* @returns {Uint8Array}
*/
function toBytes (obj) {
if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
return obj
}
if (obj instanceof ArrayBuffer) {
return new Uint8Array(obj)
}
if (ArrayBuffer.isView(obj)) {
return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
}
/* c8 ignore next */
throw new Error('Unknown type, must be binary type')
}
/**
* @param {Uint8Array} b1
* @param {Uint8Array} b2
* @returns {number}
*/
function compare (b1, b2) {
/* c8 ignore next 5 */
if (isBuffer(b1) && isBuffer(b2)) {
// probably not possible to get here in the current API
// @ts-ignore Buffer
return b1.compare(b2)
}
for (let i = 0; i < b1.length; i++) {
if (b1[i] === b2[i]) {
continue
}
return b1[i] < b2[i] ? -1 : 1
} /* c8 ignore next 3 */
return 0
}
// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.
/**
* @param {string} str
* @returns {number[]}
*/
function utf8ToBytes (str) {
const out = []
let p = 0
for (let i = 0; i < str.length; i++) {
let c = str.charCodeAt(i)
if (c < 128) {
out[p++] = c
} else if (c < 2048) {
out[p++] = (c >> 6) | 192
out[p++] = (c & 63) | 128
} else if (
((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
// Surrogate Pair
c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
out[p++] = (c >> 18) | 240
out[p++] = ((c >> 12) & 63) | 128
out[p++] = ((c >> 6) & 63) | 128
out[p++] = (c & 63) | 128
} else {
out[p++] = (c >> 12) | 224
out[p++] = ((c >> 6) & 63) | 128
out[p++] = (c & 63) | 128
}
}
return out
}
// The below code is mostly taken from https://github.com/feross/buffer
// Licensed MIT. Copyright (c) Feross Aboukhadijeh
/**
* @param {Uint8Array} buf
* @param {number} offset
* @param {number} end
* @returns {string}
*/
function utf8Slice (buf, offset, end) {
const res = []
while (offset < end) {
const firstByte = buf[offset]
let codePoint = null
let bytesPerSequence = (firstByte > 0xef) ? 4 : (firstByte > 0xdf) ? 3 : (firstByte > 0xbf) ? 2 : 1
if (offset + bytesPerSequence <= end) {
let secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[offset + 1]
if ((secondByte & 0xc0) === 0x80) {
tempCodePoint = (firstByte & 0x1f) << 0x6 | (secondByte & 0x3f)
if (tempCodePoint > 0x7f) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[offset + 1]
thirdByte = buf[offset + 2]
if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) {
tempCodePoint = (firstByte & 0xf) << 0xc | (secondByte & 0x3f) << 0x6 | (thirdByte & 0x3f)
/* c8 ignore next 3 */
if (tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[offset + 1]
thirdByte = buf[offset + 2]
fourthByte = buf[offset + 3]
if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80 && (fourthByte & 0xc0) === 0x80) {
tempCodePoint = (firstByte & 0xf) << 0x12 | (secondByte & 0x3f) << 0xc | (thirdByte & 0x3f) << 0x6 | (fourthByte & 0x3f)
if (tempCodePoint > 0xffff && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
/* c8 ignore next 5 */
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xfffd
bytesPerSequence = 1
} else if (codePoint > 0xffff) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3ff | 0xd800)
codePoint = 0xdc00 | codePoint & 0x3ff
}
res.push(codePoint)
offset += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000
/**
* @param {number[]} codePoints
* @returns {string}
*/
function decodeCodePointsArray (codePoints) {
const len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
/* c8 ignore next 10 */
// Decode in chunks to avoid "call stack size exceeded".
let res = ''
let i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
/***/ }),
/***/ "./node_modules/cborg/lib/common.js":
/*!******************************************!*\
!*** ./node_modules/cborg/lib/common.js ***!
\******************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ assertEnoughData: () => (/* binding */ assertEnoughData),
/* harmony export */ decodeErrPrefix: () => (/* binding */ decodeErrPrefix),
/* harmony export */ encodeErrPrefix: () => (/* binding */ encodeErrPrefix),
/* harmony export */ uintMinorPrefixBytes: () => (/* binding */ uintMinorPrefixBytes)
/* harmony export */ });
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'
const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} need
*/
function assertEnoughData (data, pos, need) {
if (data.length - pos < need) {
throw new Error(`${decodeErrPrefix} not enough data for type`)
}
}
/***/ }),
/***/ "./node_modules/cborg/lib/decode.js":
/*!******************************************!*\
!*** ./node_modules/cborg/lib/decode.js ***!
\******************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Tokeniser: () => (/* binding */ Tokeniser),
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ decodeFirst: () => (/* binding */ decodeFirst),
/* harmony export */ tokensToObject: () => (/* binding */ tokensToObject)
/* harmony export */ });
/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./common.js */ "./node_modules/cborg/lib/common.js");
/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./token.js */ "./node_modules/cborg/lib/token.js");
/* harmony import */ var _jump_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./jump.js */ "./node_modules/cborg/lib/jump.js");
/**
* @typedef {import('./token.js').Token} Token
* @typedef {import('../interface').DecodeOptions} DecodeOptions
* @typedef {import('../interface').DecodeTokenizer} DecodeTokenizer
*/
const defaultDecodeOptions = {
strict: false,
allowIndefinite: true,
allowUndefined: true,
allowBigInt: true
}
/**
* @implements {DecodeTokenizer}
*/
class Tokeniser {
/**
* @param {Uint8Array} data
* @param {DecodeOptions} options
*/
constructor (data, options = {}) {
this._pos = 0
this.data = data
this.options = options
}
pos () {
return this._pos
}
done () {
return this._pos >= this.data.length
}
next () {
const byt = this.data[this._pos]
let token = _jump_js__WEBPACK_IMPORTED_MODULE_2__.quick[byt]
if (token === undefined) {
const decoder = _jump_js__WEBPACK_IMPORTED_MODULE_2__.jump[byt]
/* c8 ignore next 4 */
// if we're here then there's something wrong with our jump or quick lists!
if (!decoder) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
}
const minor = byt & 31
token = decoder(this.data, this._pos, minor, this.options)
}
// @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
this._pos += token.encodedLength
return token
}
}
const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')
/**
* @param {Token} token
* @param {DecodeTokenizer} tokeniser
* @param {DecodeOptions} options
* @returns {any|BREAK|DONE}
*/
function tokenToArray (token, tokeniser, options) {
const arr = []
for (let i = 0; i < token.value; i++) {
const value = tokensToObject(tokeniser, options)
if (value === BREAK) {
if (token.value === Infinity) {
// normal end to indefinite length array
break
}
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} got unexpected break to lengthed array`)
}
if (value === DONE) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
}
arr[i] = value
}
return arr
}
/**
* @param {Token} token
* @param {DecodeTokenizer} tokeniser
* @param {DecodeOptions} options
* @returns {any|BREAK|DONE}
*/
function tokenToMap (token, tokeniser, options) {
const useMaps = options.useMaps === true
const obj = useMaps ? undefined : {}
const m = useMaps ? new Map() : undefined
for (let i = 0; i < token.value; i++) {
const key = tokensToObject(tokeniser, options)
if (key === BREAK) {
if (token.value === Infinity) {
// normal end to indefinite length map
break
}
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} got unexpected break to lengthed map`)
}
if (key === DONE) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
}
if (useMaps !== true && typeof key !== 'string') {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
}
if (options.rejectDuplicateMapKeys === true) {
// @ts-ignore
if ((useMaps && m.has(key)) || (!useMaps && (key in obj))) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} found repeat map key "${key}"`)
}
}
const value = tokensToObject(tokeniser, options)
if (value === DONE) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
}
if (useMaps) {
// @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
m.set(key, value)
} else {
// @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
obj[key] = value
}
}
// @ts-ignore c'mon man
return useMaps ? m : obj
}
/**
* @param {DecodeTokenizer} tokeniser
* @param {DecodeOptions} options
* @returns {any|BREAK|DONE}
*/
function tokensToObject (tokeniser, options) {
// should we support array as an argument?
// check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
if (tokeniser.done()) {
return DONE
}
const token = tokeniser.next()
if (token.type === _token_js__WEBPACK_IMPORTED_MODULE_1__.Type.break) {
return BREAK
}
if (token.type.terminal) {
return token.value
}
if (token.type === _token_js__WEBPACK_IMPORTED_MODULE_1__.Type.array) {
return tokenToArray(token, tokeniser, options)
}
if (token.type === _token_js__WEBPACK_IMPORTED_MODULE_1__.Type.map) {
return tokenToMap(token, tokeniser, options)
}
if (token.type === _token_js__WEBPACK_IMPORTED_MODULE_1__.Type.tag) {
if (options.tags && typeof options.tags[token.value] === 'function') {
const tagged = tokensToObject(tokeniser, options)
return options.tags[token.value](tagged)
}
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} tag not supported (${token.value})`)
}
/* c8 ignore next */
throw new Error('unsupported')
}
/**
* @param {Uint8Array} data
* @param {DecodeOptions} [options]
* @returns {[any, Uint8Array]}
*/
function decodeFirst (data, options) {
if (!(data instanceof Uint8Array)) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} data to decode must be a Uint8Array`)
}
options = Object.assign({}, defaultDecodeOptions, options)
const tokeniser = options.tokenizer || new Tokeniser(data, options)
const decoded = tokensToObject(tokeniser, options)
if (decoded === DONE) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} did not find any content to decode`)
}
if (decoded === BREAK) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} got unexpected break`)
}
return [decoded, data.subarray(tokeniser.pos())]
}
/**
* @param {Uint8Array} data
* @param {DecodeOptions} [options]
* @returns {any}
*/
function decode (data, options) {
const [decoded, remainder] = decodeFirst(data, options)
if (remainder.length > 0) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_0__.decodeErrPrefix} too many terminals, data makes no sense`)
}
return decoded
}
/***/ }),
/***/ "./node_modules/cborg/lib/encode.js":
/*!******************************************!*\
!*** ./node_modules/cborg/lib/encode.js ***!
\******************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Ref: () => (/* binding */ Ref),
/* harmony export */ encode: () => (/* binding */ encode),
/* harmony export */ encodeCustom: () => (/* binding */ encodeCustom),
/* harmony export */ makeCborEncoders: () => (/* binding */ makeCborEncoders),
/* harmony export */ objectToTokens: () => (/* binding */ objectToTokens)
/* harmony export */ });
/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./is.js */ "./node_modules/cborg/lib/is.js");
/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./token.js */ "./node_modules/cborg/lib/token.js");
/* harmony import */ var _bl_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bl.js */ "./node_modules/cborg/lib/bl.js");
/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./common.js */ "./node_modules/cborg/lib/common.js");
/* harmony import */ var _jump_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./jump.js */ "./node_modules/cborg/lib/jump.js");
/* harmony import */ var _byte_utils_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./byte-utils.js */ "./node_modules/cborg/lib/byte-utils.js");
/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./0uint.js */ "./node_modules/cborg/lib/0uint.js");
/* harmony import */ var _1negint_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./1negint.js */ "./node_modules/cborg/lib/1negint.js");
/* harmony import */ var _2bytes_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./2bytes.js */ "./node_modules/cborg/lib/2bytes.js");
/* harmony import */ var _3string_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./3string.js */ "./node_modules/cborg/lib/3string.js");
/* harmony import */ var _4array_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./4array.js */ "./node_modules/cborg/lib/4array.js");
/* harmony import */ var _5map_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./5map.js */ "./node_modules/cborg/lib/5map.js");
/* harmony import */ var _6tag_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./6tag.js */ "./node_modules/cborg/lib/6tag.js");
/* harmony import */ var _7float_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./7float.js */ "./node_modules/cborg/lib/7float.js");
/**
* @typedef {import('../interface').EncodeOptions} EncodeOptions
* @typedef {import('../interface').OptionalTypeEncoder} OptionalTypeEncoder
* @typedef {import('../interface').Reference} Reference
* @typedef {import('../interface').StrictTypeEncoder} StrictTypeEncoder
* @typedef {import('../interface').TokenTypeEncoder} TokenTypeEncoder
* @typedef {import('../interface').TokenOrNestedTokens} TokenOrNestedTokens
*/
/** @type {EncodeOptions} */
const defaultEncodeOptions = {
float64: false,
mapSorter,
quickEncodeToken: _jump_js__WEBPACK_IMPORTED_MODULE_4__.quickEncodeToken
}
/** @returns {TokenTypeEncoder[]} */
function makeCborEncoders () {
const encoders = []
encoders[_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.uint.major] = _0uint_js__WEBPACK_IMPORTED_MODULE_6__.encodeUint
encoders[_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.negint.major] = _1negint_js__WEBPACK_IMPORTED_MODULE_7__.encodeNegint
encoders[_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.bytes.major] = _2bytes_js__WEBPACK_IMPORTED_MODULE_8__.encodeBytes
encoders[_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.string.major] = _3string_js__WEBPACK_IMPORTED_MODULE_9__.encodeString
encoders[_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.array.major] = _4array_js__WEBPACK_IMPORTED_MODULE_10__.encodeArray
encoders[_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.map.major] = _5map_js__WEBPACK_IMPORTED_MODULE_11__.encodeMap
encoders[_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.tag.major] = _6tag_js__WEBPACK_IMPORTED_MODULE_12__.encodeTag
encoders[_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.float.major] = _7float_js__WEBPACK_IMPORTED_MODULE_13__.encodeFloat
return encoders
}
const cborEncoders = makeCborEncoders()
const buf = new _bl_js__WEBPACK_IMPORTED_MODULE_2__.Bl()
/** @implements {Reference} */
class Ref {
/**
* @param {object|any[]} obj
* @param {Reference|undefined} parent
*/
constructor (obj, parent) {
this.obj = obj
this.parent = parent
}
/**
* @param {object|any[]} obj
* @returns {boolean}
*/
includes (obj) {
/** @type {Reference|undefined} */
let p = this
do {
if (p.obj === obj) {
return true
}
} while (p = p.parent) // eslint-disable-line
return false
}
/**
* @param {Reference|undefined} stack
* @param {object|any[]} obj
* @returns {Reference}
*/
static createCheck (stack, obj) {
if (stack && stack.includes(obj)) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_3__.encodeErrPrefix} object contains circular references`)
}
return new Ref(obj, stack)
}
}
const simpleTokens = {
null: new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.null, null),
undefined: new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.undefined, undefined),
true: new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.true, true),
false: new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.false, false),
emptyArray: new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.array, 0),
emptyMap: new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.map, 0)
}
/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
/**
* @param {any} obj
* @param {string} _typ
* @param {EncodeOptions} _options
* @param {Reference} [_refStack]
* @returns {TokenOrNestedTokens}
*/
number (obj, _typ, _options, _refStack) {
if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
return new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.float, obj)
} else if (obj >= 0) {
return new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.uint, obj)
} else {
return new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.negint, obj)
}
},
/**
* @param {any} obj
* @param {string} _typ
* @param {EncodeOptions} _options
* @param {Reference} [_refStack]
* @returns {TokenOrNestedTokens}
*/
bigint (obj, _typ, _options, _refStack) {
if (obj >= BigInt(0)) {
return new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.uint, obj)
} else {
return new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.negint, obj)
}
},
/**
* @param {any} obj
* @param {string} _typ
* @param {EncodeOptions} _options
* @param {Reference} [_refStack]
* @returns {TokenOrNestedTokens}
*/
Uint8Array (obj, _typ, _options, _refStack) {
return new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.bytes, obj)
},
/**
* @param {any} obj
* @param {string} _typ
* @param {EncodeOptions} _options
* @param {Reference} [_refStack]
* @returns {TokenOrNestedTokens}
*/
string (obj, _typ, _options, _refStack) {
return new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.string, obj)
},
/**
* @param {any} obj
* @param {string} _typ
* @param {EncodeOptions} _options
* @param {Reference} [_refStack]
* @returns {TokenOrNestedTokens}
*/
boolean (obj, _typ, _options, _refStack) {
return obj ? simpleTokens.true : simpleTokens.false
},
/**
* @param {any} _obj
* @param {string} _typ
* @param {EncodeOptions} _options
* @param {Reference} [_refStack]
* @returns {TokenOrNestedTokens}
*/
null (_obj, _typ, _options, _refStack) {
return simpleTokens.null
},
/**
* @param {any} _obj
* @param {string} _typ
* @param {EncodeOptions} _options
* @param {Reference} [_refStack]
* @returns {TokenOrNestedTokens}
*/
undefined (_obj, _typ, _options, _refStack) {
return simpleTokens.undefined
},
/**
* @param {any} obj
* @param {string} _typ
* @param {EncodeOptions} _options
* @param {Reference} [_refStack]
* @returns {TokenOrNestedTokens}
*/
ArrayBuffer (obj, _typ, _options, _refStack) {
return new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.bytes, new Uint8Array(obj))
},
/**
* @param {any} obj
* @param {string} _typ
* @param {EncodeOptions} _options
* @param {Reference} [_refStack]
* @returns {TokenOrNestedTokens}
*/
DataView (obj, _typ, _options, _refStack) {
return new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
},
/**
* @param {any} obj
* @param {string} _typ
* @param {EncodeOptions} options
* @param {Reference} [refStack]
* @returns {TokenOrNestedTokens}
*/
Array (obj, _typ, options, refStack) {
if (!obj.length) {
if (options.addBreakTokens === true) {
return [simpleTokens.emptyArray, new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.break)]
}
return simpleTokens.emptyArray
}
refStack = Ref.createCheck(refStack, obj)
const entries = []
let i = 0
for (const e of obj) {
entries[i++] = objectToTokens(e, options, refStack)
}
if (options.addBreakTokens) {
return [new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.array, obj.length), entries, new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.break)]
}
return [new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.array, obj.length), entries]
},
/**
* @param {any} obj
* @param {string} typ
* @param {EncodeOptions} options
* @param {Reference} [refStack]
* @returns {TokenOrNestedTokens}
*/
Object (obj, typ, options, refStack) {
// could be an Object or a Map
const isMap = typ !== 'Object'
// it's slightly quicker to use Object.keys() than Object.entries()
const keys = isMap ? obj.keys() : Object.keys(obj)
const length = isMap ? obj.size : keys.length
if (!length) {
if (options.addBreakTokens === true) {
return [simpleTokens.emptyMap, new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.break)]
}
return simpleTokens.emptyMap
}
refStack = Ref.createCheck(refStack, obj)
/** @type {TokenOrNestedTokens[]} */
const entries = []
let i = 0
for (const key of keys) {
entries[i++] = [
objectToTokens(key, options, refStack),
objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)
]
}
sortMapEntries(entries, options)
if (options.addBreakTokens) {
return [new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.map, length), entries, new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.break)]
}
return [new _token_js__WEBPACK_IMPORTED_MODULE_1__.Token(_token_js__WEBPACK_IMPORTED_MODULE_1__.Type.map, length), entries]
}
}
typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
typeEncoders[`${typ}Array`] = typeEncoders.DataView
}
/**
* @param {any} obj
* @param {EncodeOptions} [options]
* @param {Reference} [refStack]
* @returns {TokenOrNestedTokens}
*/
function objectToTokens (obj, options = {}, refStack) {
const typ = (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.is)(obj)
const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
if (typeof customTypeEncoder === 'function') {
const tokens = customTypeEncoder(obj, typ, options, refStack)
if (tokens != null) {
return tokens
}
}
const typeEncoder = typeEncoders[typ]
if (!typeEncoder) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_3__.encodeErrPrefix} unsupported type: ${typ}`)
}
return typeEncoder(obj, typ, options, refStack)
}
/*
CBOR key sorting is a mess.
The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:
> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
> * If two keys have different lengths, the shorter one sorts
earlier;
> * If two keys have the same length, the one with the lower value
in (byte-wise) lexical order sorts earlier.
1. It is not clear what "bytes of the representation of the key" means: is it
the CBOR representation, or the binary representation of the object itself?
Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
and compare on that? Or do we omit the special prefix byte, (mostly) treating
the key in its plain binary representation form.
The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding
> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
> * If the major types are different, the one with the lower value in numerical
> order sorts earlier.
> * If two keys have different lengths, the shorter one sorts earlier;
> * If two keys have the same length, the one with the lower value in
> (byte-wise) lexical order sorts earlier.
Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151
This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).
We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).
Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/
/*
(UPDATE, Dec 2020)
https://tools.ietf.org/html/rfc8949 is the updated CBOR spec and clarifies some
of the questions above with a new recommendation for sorting order being much
closer to what would be expected in other environments (i.e. no length-first
weirdness).
This new sorting order is not yet implemented here but could be added as an
option. "Determinism" (canonicity) is system dependent and it's difficult to
change existing systems that are built with existing expectations. So if a new
ordering is introduced here, the old needs to be kept as well with the user
having the option.
*/
/**
* @param {TokenOrNestedTokens[]} entries
* @param {EncodeOptions} options
*/
function sortMapEntries (entries, options) {
if (options.mapSorter) {
entries.sort(options.mapSorter)
}
}
/**
* @param {(Token|Token[])[]} e1
* @param {(Token|Token[])[]} e2
* @returns {number}
*/
function mapSorter (e1, e2) {
// the key position ([0]) could have a single token or an array
// almost always it'll be a single token but complex key might get involved
/* c8 ignore next 2 */
const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]
// different key types
if (keyToken1.type !== keyToken2.type) {
return keyToken1.type.compare(keyToken2.type)
}
const major = keyToken1.type.major
// TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
/* c8 ignore next 5 */
if (tcmp === 0) {
// duplicate key or complex type where the first token matched,
// i.e. a map or array and we're only comparing the opening token
console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
}
return tcmp
}
/**
* @param {Bl} buf
* @param {TokenOrNestedTokens} tokens
* @param {TokenTypeEncoder[]} encoders
* @param {EncodeOptions} options
*/
function tokensToEncoded (buf, tokens, encoders, options) {
if (Array.isArray(tokens)) {
for (const token of tokens) {
tokensToEncoded(buf, token, encoders, options)
}
} else {
encoders[tokens.type.major](buf, tokens, options)
}
}
/**
* @param {any} data
* @param {TokenTypeEncoder[]} encoders
* @param {EncodeOptions} options
* @returns {Uint8Array}
*/
function encodeCustom (data, encoders, options) {
const tokens = objectToTokens(data, options)
if (!Array.isArray(tokens) && options.quickEncodeToken) {
const quickBytes = options.quickEncodeToken(tokens)
if (quickBytes) {
return quickBytes
}
const encoder = encoders[tokens.type.major]
if (encoder.encodedSize) {
const size = encoder.encodedSize(tokens, options)
const buf = new _bl_js__WEBPACK_IMPORTED_MODULE_2__.Bl(size)
encoder(buf, tokens, options)
/* c8 ignore next 4 */
// this would be a problem with encodedSize() functions
if (buf.chunks.length !== 1) {
throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
}
return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_5__.asU8A)(buf.chunks[0])
}
}
buf.reset()
tokensToEncoded(buf, tokens, encoders, options)
return buf.toBytes(true)
}
/**
* @param {any} data
* @param {EncodeOptions} [options]
* @returns {Uint8Array}
*/
function encode (data, options) {
options = Object.assign({}, defaultEncodeOptions, options)
return encodeCustom(data, cborEncoders, options)
}
/***/ }),
/***/ "./node_modules/cborg/lib/is.js":
/*!**************************************!*\
!*** ./node_modules/cborg/lib/is.js ***!
\**************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ is: () => (/* binding */ is)
/* harmony export */ });
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.
const typeofs = [
'string',
'number',
'bigint',
'symbol'
]
const objectTypeNames = [
'Function',
'Generator',
'AsyncGenerator',
'GeneratorFunction',
'AsyncGeneratorFunction',
'AsyncFunction',
'Observable',
'Array',
'Buffer',
'Object',
'RegExp',
'Date',
'Error',
'Map',
'Set',
'WeakMap',
'WeakSet',
'ArrayBuffer',
'SharedArrayBuffer',
'DataView',
'Promise',
'URL',
'HTMLElement',
'Int8Array',
'Uint8Array',
'Uint8ClampedArray',
'Int16Array',
'Uint16Array',
'Int32Array',
'Uint32Array',
'Float32Array',
'Float64Array',
'BigInt64Array',
'BigUint64Array'
]
/**
* @param {any} value
* @returns {string}
*/
function is (value) {
if (value === null) {
return 'null'
}
if (value === undefined) {
return 'undefined'
}
if (value === true || value === false) {
return 'boolean'
}
const typeOf = typeof value
if (typeofs.includes(typeOf)) {
return typeOf
}
/* c8 ignore next 4 */
// not going to bother testing this, it's not going to be valid anyway
if (typeOf === 'function') {
return 'Function'
}
if (Array.isArray(value)) {
return 'Array'
}
if (isBuffer(value)) {
return 'Buffer'
}
const objectType = getObjectType(value)
if (objectType) {
return objectType
}
/* c8 ignore next */
return 'Object'
}
/**
* @param {any} value
* @returns {boolean}
*/
function isBuffer (value) {
return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value)
}
/**
* @param {any} value
* @returns {string|undefined}
*/
function getObjectType (value) {
const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
if (objectTypeNames.includes(objectTypeName)) {
return objectTypeName
}
/* c8 ignore next */
return undefined
}
/***/ }),
/***/ "./node_modules/cborg/lib/jump.js":
/*!****************************************!*\
!*** ./node_modules/cborg/lib/jump.js ***!
\****************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ jump: () => (/* binding */ jump),
/* harmony export */ quick: () => (/* binding */ quick),
/* harmony export */ quickEncodeToken: () => (/* binding */ quickEncodeToken)
/* harmony export */ });
/* harmony import */ var _token_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./token.js */ "./node_modules/cborg/lib/token.js");
/* harmony import */ var _0uint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./0uint.js */ "./node_modules/cborg/lib/0uint.js");
/* harmony import */ var _1negint_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./1negint.js */ "./node_modules/cborg/lib/1negint.js");
/* harmony import */ var _2bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./2bytes.js */ "./node_modules/cborg/lib/2bytes.js");
/* harmony import */ var _3string_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./3string.js */ "./node_modules/cborg/lib/3string.js");
/* harmony import */ var _4array_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./4array.js */ "./node_modules/cborg/lib/4array.js");
/* harmony import */ var _5map_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./5map.js */ "./node_modules/cborg/lib/5map.js");
/* harmony import */ var _6tag_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./6tag.js */ "./node_modules/cborg/lib/6tag.js");
/* harmony import */ var _7float_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./7float.js */ "./node_modules/cborg/lib/7float.js");
/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./common.js */ "./node_modules/cborg/lib/common.js");
/* harmony import */ var _byte_utils_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./byte-utils.js */ "./node_modules/cborg/lib/byte-utils.js");
/**
* @typedef {import('../interface').DecodeOptions} DecodeOptions
*/
/**
* @param {Uint8Array} data
* @param {number} pos
* @param {number} minor
*/
function invalidMinor (data, pos, minor) {
throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_9__.decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}
/**
* @param {string} msg
* @returns {()=>any}
*/
function errorer (msg) {
return () => { throw new Error(`${_common_js__WEBPACK_IMPORTED_MODULE_9__.decodeErrPrefix} ${msg}`) }
}
/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
const jump = []
// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = _0uint_js__WEBPACK_IMPORTED_MODULE_1__.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = _0uint_js__WEBPACK_IMPORTED_MODULE_1__.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = _0uint_js__WEBPACK_IMPORTED_MODULE_1__.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = _0uint_js__WEBPACK_IMPORTED_MODULE_1__.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = _1negint_js__WEBPACK_IMPORTED_MODULE_2__.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = _1negint_js__WEBPACK_IMPORTED_MODULE_2__.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = _1negint_js__WEBPACK_IMPORTED_MODULE_2__.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = _1negint_js__WEBPACK_IMPORTED_MODULE_2__.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
jump[i] = _2bytes_js__WEBPACK_IMPORTED_MODULE_3__.decodeBytesCompact
}
jump[0x58] = _2bytes_js__WEBPACK_IMPORTED_MODULE_3__.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = _2bytes_js__WEBPACK_IMPORTED_MODULE_3__.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = _2bytes_js__WEBPACK_IMPORTED_MODULE_3__.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = _2bytes_js__WEBPACK_IMPORTED_MODULE_3__.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
jump[i] = _3string_js__WEBPACK_IMPORTED_MODULE_4__.decodeStringCompact
}
jump[0x78] = _3string_js__WEBPACK_IMPORTED_MODULE_4__.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = _3string_js__WEBPACK_IMPORTED_MODULE_4__.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = _3string_js__WEBPACK_IMPORTED_MODULE_4__.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = _3string_js__WEBPACK_IMPORTED_MODULE_4__.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
jump[i] = _4array_js__WEBPACK_IMPORTED_MODULE_5__.decodeArrayCompact
}
jump[0x98] = _4array_js__WEBPACK_IMPORTED_MODULE_5__.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = _4array_js__WEBPACK_IMPORTED_MODULE_5__.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = _4array_js__WEBPACK_IMPORTED_MODULE_5__.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = _4array_js__WEBPACK_IMPORTED_MODULE_5__.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = _4array_js__WEBPACK_IMPORTED_MODULE_5__.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
jump[i] = _5map_js__WEBPACK_IMPORTED_MODULE_6__.decodeMapCompact
}
jump[0xb8] = _5map_js__WEBPACK_IMPORTED_MODULE_6__.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = _5map_js__WEBPACK_IMPORTED_MODULE_6__.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = _5map_js__WEBPACK_IMPORTED_MODULE_6__.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = _5map_js__WEBPACK_IMPORTED_MODULE_6__.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = _5map_js__WEBPACK_IMPORTED_MODULE_6__.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
jump[i] = _6tag_js__WEBPACK_IMPORTED_MODULE_7__.decodeTagCompact
}
jump[0xd8] = _6tag_js__WEBPACK_IMPORTED_MODULE_7__.decodeTag8
jump[0xd9] = _6tag_js__WEBPACK_IMPORTED_MODULE_7__.decodeTag16
jump[0xda] = _6tag_js__WEBPACK_IMPORTED_MODULE_7__.decodeTag32
jump[0xdb] = _6tag_js__WEBPACK_IMPORTED_MODULE_7__.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = _7float_js__WEBPACK_IMPORTED_MODULE_8__.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = _7float_js__WEBPACK_IMPORTED_MODULE_8__.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = _7float_js__WEBPACK_IMPORTED_MODULE_8__.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = _7float_js__WEBPACK_IMPORTED_MODULE_8__.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = _7float_js__WEBPACK_IMPORTED_MODULE_8__.decodeBreak // "break" stop code
/** @type {Token[]} */
const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
quick[i] = new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
quick[31 - i] = new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.string, '', 1)
// empty list
quick[0x80] = new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.array, 0, 1)
// empty map
quick[0xa0] = new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.map, 0, 1)
// false
quick[0xf4] = new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.false, false, 1)
// true
quick[0xf5] = new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.true, true, 1)
// null
quick[0xf6] = new _token_js__WEBPACK_IMPORTED_MODULE_0__.Token(_token_js__WEBPACK_IMPORTED_MODULE_0__.Type.null, null, 1)
/**
* @param {Token} token
* @returns {Uint8Array|undefined}
*/
function quickEncodeToken (token) {
switch (token.type) {
case _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.false:
return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__.fromArray)([0xf4])
case _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.true:
return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__.fromArray)([0xf5])
case _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.null:
return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__.fromArray)([0xf6])
case _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.bytes:
if (!token.value.length) {
return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__.fromArray)([0x40])
}
return
case _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.string:
if (token.value === '') {
return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__.fromArray)([0x60])
}
return
case _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.array:
if (token.value === 0) {
return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__.fromArray)([0x80])
}
/* c8 ignore next 2 */
// shouldn't be possible if this were called when there was only one token
return
case _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.map:
if (token.value === 0) {
return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__.fromArray)([0xa0])
}
/* c8 ignore next 2 */
// shouldn't be possible if this were called when there was only one token
return
case _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.uint:
if (token.value < 24) {
return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__.fromArray)([Number(token.value)])
}
return
case _token_js__WEBPACK_IMPORTED_MODULE_0__.Type.negint:
if (token.value >= -24) {
return (0,_byte_utils_js__WEBPACK_IMPORTED_MODULE_10__.fromArray)([31 - Number(token.value)])
}
}
}
/***/ }),
/***/ "./node_modules/cborg/lib/token.js":
/*!*****************************************!*\
!*** ./node_modules/cborg/lib/token.js ***!
\*****************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Token: () => (/* binding */ Token),
/* harmony export */ Type: () => (/* binding */ Type)
/* harmony export */ });
class Type {
/**
* @param {number} major
* @param {string} name
* @param {boolean} terminal
*/
constructor (major, name, terminal) {
this.major = major
this.majorEncoded = major << 5
this.name = name
this.terminal = terminal
}
/* c8 ignore next 3 */
toString () {
return `Type[${this.major}].${this.name}`
}
/**
* @param {Type} typ
* @returns {number}
*/
compare (typ) {
/* c8 ignore next 1 */
return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
}
}
// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)
class Token {
/**
* @param {Type} type
* @param {any} [value]
* @param {number} [encodedLength]
*/
constructor (type, value, encodedLength) {
this.type = type
this.value = value
this.encodedLength = encodedLength
/** @type {Uint8Array|undefined} */
this.encodedBytes = undefined
/** @type {Uint8Array|undefined} */
this.byteValue = undefined
}
/* c8 ignore next 3 */
toString () {
return `Token[${this.type}].${this.value}`
}
}
/***/ }),
/***/ "./node_modules/eventemitter3/index.mjs":
/*!**********************************************!*\
!*** ./node_modules/eventemitter3/index.mjs ***!
\**********************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ EventEmitter: () => (/* reexport default export from named module */ _index_js__WEBPACK_IMPORTED_MODULE_0__),
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./index.js */ "./node_modules/eventemitter3/index.js");
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_index_js__WEBPACK_IMPORTED_MODULE_0__);
/***/ }),
/***/ "./node_modules/it-drain/dist/src/index.js":
/*!*************************************************!*\
!*** ./node_modules/it-drain/dist/src/index.js ***!
\*************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/**
* @packageDocumentation
*
* Mostly useful for tests or when you want to be explicit about consuming an iterable without doing anything with any yielded values.
*
* @example
*
* ```javascript
* import drain from 'it-drain'
*
* // This can also be an iterator, generator, etc
* const values = [0, 1, 2, 3, 4]
*
* drain(values)
* ```
*
* Async sources must be awaited:
*
* ```javascript
* import drain from 'it-drain'
*
* const values = async function * {
* yield * [0, 1, 2, 3, 4]
* }
*
* await drain(values())
* ```
*/
function isAsyncIterable(thing) {
return thing[Symbol.asyncIterator] != null;
}
function drain(source) {
if (isAsyncIterable(source)) {
return (async () => {
for await (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars
})();
}
else {
for (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars
}
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (drain);
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "./node_modules/it-merge/dist/src/index.js":
/*!*************************************************!*\
!*** ./node_modules/it-merge/dist/src/index.js ***!
\*************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var it_pushable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-pushable */ "./node_modules/it-pushable/dist/src/index.js");
/**
* @packageDocumentation
*
* Merge several (async)iterables into one, yield values as they arrive.
*
* Nb. sources are iterated over in parallel so the order of emitted items is not guaranteed.
*
* @example
*
* ```javascript
* import merge from 'it-merge'
* import all from 'it-all'
*
* // This can also be an iterator, generator, etc
* const values1 = [0, 1, 2, 3, 4]
* const values2 = [5, 6, 7, 8, 9]
*
* const arr = all(merge(values1, values2))
*
* console.info(arr) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
* ```
*
* Async sources must be awaited:
*
* ```javascript
* import merge from 'it-merge'
* import all from 'it-all'
*
* // This can also be an iterator, async iterator, generator, etc
* const values1 = async function * () {
* yield * [0, 1, 2, 3, 4]
* }
* const values2 = async function * () {
* yield * [5, 6, 7, 8, 9]
* }
*
* const arr = await all(merge(values1(), values2()))
*
* console.info(arr) // 0, 1, 5, 6, 2, 3, 4, 7, 8, 9 <- nb. order is not guaranteed
* ```
*/
function isAsyncIterable(thing) {
return thing[Symbol.asyncIterator] != null;
}
function merge(...sources) {
const syncSources = [];
for (const source of sources) {
if (!isAsyncIterable(source)) {
syncSources.push(source);
}
}
if (syncSources.length === sources.length) {
// all sources are synchronous
return (function* () {
for (const source of syncSources) {
yield* source;
}
})();
}
return (async function* () {
const output = (0,it_pushable__WEBPACK_IMPORTED_MODULE_0__.pushable)({
objectMode: true
});
void Promise.resolve().then(async () => {
try {
await Promise.all(sources.map(async (source) => {
for await (const item of source) {
output.push(item);
}
}));
output.end();
}
catch (err) {
output.end(err);
}
});
yield* output;
})();
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (merge);
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "./node_modules/it-pipe/dist/src/index.js":
/*!************************************************!*\
!*** ./node_modules/it-pipe/dist/src/index.js ***!
\************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ pipe: () => (/* binding */ pipe),
/* harmony export */ rawPipe: () => (/* binding */ rawPipe)
/* harmony export */ });
/* harmony import */ var it_pushable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-pushable */ "./node_modules/it-pushable/dist/src/index.js");
/* harmony import */ var it_merge__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! it-merge */ "./node_modules/it-merge/dist/src/index.js");
function pipe(first, ...rest) {
if (first == null) {
throw new Error('Empty pipeline');
}
// Duplex at start: wrap in function and return duplex source
if (isDuplex(first)) {
const duplex = first;
first = () => duplex.source;
// Iterable at start: wrap in function
}
else if (isIterable(first) || isAsyncIterable(first)) {
const source = first;
first = () => source;
}
const fns = [first, ...rest];
if (fns.length > 1) {
// Duplex at end: use duplex sink
if (isDuplex(fns[fns.length - 1])) {
fns[fns.length - 1] = fns[fns.length - 1].sink;
}
}
if (fns.length > 2) {
// Duplex in the middle, consume source with duplex sink and return duplex source
for (let i = 1; i < fns.length - 1; i++) {
if (isDuplex(fns[i])) {
fns[i] = duplexPipelineFn(fns[i]);
}
}
}
return rawPipe(...fns);
}
const rawPipe = (...fns) => {
let res;
while (fns.length > 0) {
res = fns.shift()(res);
}
return res;
};
const isAsyncIterable = (obj) => {
return obj?.[Symbol.asyncIterator] != null;
};
const isIterable = (obj) => {
return obj?.[Symbol.iterator] != null;
};
const isDuplex = (obj) => {
if (obj == null) {
return false;
}
return obj.sink != null && obj.source != null;
};
const duplexPipelineFn = (duplex) => {
return (source) => {
const p = duplex.sink(source);
if (p?.then != null) {
const stream = (0,it_pushable__WEBPACK_IMPORTED_MODULE_0__.pushable)({
objectMode: true
});
p.then(() => {
stream.end();
}, (err) => {
stream.end(err);
});
let sourceWrap;
const source = duplex.source;
if (isAsyncIterable(source)) {
sourceWrap = async function* () {
yield* source;
stream.end();
};
}
else if (isIterable(source)) {
sourceWrap = function* () {
yield* source;
stream.end();
};
}
else {
throw new Error('Unknown duplex source type - must be Iterable or AsyncIterable');
}
return (0,it_merge__WEBPACK_IMPORTED_MODULE_1__["default"])(stream, sourceWrap());
}
return duplex.source;
};
};
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "./node_modules/it-pushable/dist/src/fifo.js":
/*!***************************************************!*\
!*** ./node_modules/it-pushable/dist/src/fifo.js ***!
\***************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ FIFO: () => (/* binding */ FIFO)
/* harmony export */ });
// ported from https://www.npmjs.com/package/fast-fifo
class FixedFIFO {
buffer;
mask;
top;
btm;
next;
constructor(hwm) {
if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {
throw new Error('Max size for a FixedFIFO should be a power of two');
}
this.buffer = new Array(hwm);
this.mask = hwm - 1;
this.top = 0;
this.btm = 0;
this.next = null;
}
push(data) {
if (this.buffer[this.top] !== undefined) {
return false;
}
this.buffer[this.top] = data;
this.top = (this.top + 1) & this.mask;
return true;
}
shift() {
const last = this.buffer[this.btm];
if (last === undefined) {
return undefined;
}
this.buffer[this.btm] = undefined;
this.btm = (this.btm + 1) & this.mask;
return last;
}
isEmpty() {
return this.buffer[this.btm] === undefined;
}
}
class FIFO {
size;
hwm;
head;
tail;
constructor(options = {}) {
this.hwm = options.splitLimit ?? 16;
this.head = new FixedFIFO(this.hwm);
this.tail = this.head;
this.size = 0;
}
calculateSize(obj) {
if (obj?.byteLength != null) {
return obj.byteLength;
}
return 1;
}
push(val) {
if (val?.value != null) {
this.size += this.calculateSize(val.value);
}
if (!this.head.push(val)) {
const prev = this.head;
this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
this.head.push(val);
}
}
shift() {
let val = this.tail.shift();
if (val === undefined && (this.tail.next != null)) {
const next = this.tail.next;
this.tail.next = null;
this.tail = next;
val = this.tail.shift();
}
if (val?.value != null) {
this.size -= this.calculateSize(val.value);
}
return val;
}
isEmpty() {
return this.head.isEmpty();
}
}
//# sourceMappingURL=fifo.js.map
/***/ }),
/***/ "./node_modules/it-pushable/dist/src/index.js":
/*!****************************************************!*\
!*** ./node_modules/it-pushable/dist/src/index.js ***!
\****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AbortError: () => (/* binding */ AbortError),
/* harmony export */ pushable: () => (/* binding */ pushable),
/* harmony export */ pushableV: () => (/* binding */ pushableV)
/* harmony export */ });
/* harmony import */ var p_defer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! p-defer */ "./node_modules/p-defer/index.js");
/* harmony import */ var _fifo_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./fifo.js */ "./node_modules/it-pushable/dist/src/fifo.js");
/**
* @packageDocumentation
*
* An iterable that you can push values into.
*
* @example
*
* ```js
* import { pushable } from 'it-pushable'
*
* const source = pushable()
*
* setTimeout(() => source.push('hello'), 100)
* setTimeout(() => source.push('world'), 200)
* setTimeout(() => source.end(), 300)
*
* const start = Date.now()
*
* for await (const value of source) {
* console.log(`got "${value}" after ${Date.now() - start}ms`)
* }
* console.log(`done after ${Date.now() - start}ms`)
*
* // Output:
* // got "hello" after 105ms
* // got "world" after 207ms
* // done after 309ms
* ```
*
* @example
*
* ```js
* import { pushableV } from 'it-pushable'
* import all from 'it-all'
*
* const source = pushableV()
*
* source.push(1)
* source.push(2)
* source.push(3)
* source.end()
*
* console.info(await all(source))
*
* // Output:
* // [ [1, 2, 3] ]
* ```
*/
class AbortError extends Error {
type;
code;
constructor(message, code) {
super(message ?? 'The operation was aborted');
this.type = 'aborted';
this.code = code ?? 'ABORT_ERR';
}
}
function pushable(options = {}) {
const getNext = (buffer) => {
const next = buffer.shift();
if (next == null) {
return { done: true };
}
if (next.error != null) {
throw next.error;
}
return {
done: next.done === true,
// @ts-expect-error if done is false, value will be present
value: next.value
};
};
return _pushable(getNext, options);
}
function pushableV(options = {}) {
const getNext = (buffer) => {
let next;
const values = [];
while (!buffer.isEmpty()) {
next = buffer.shift();
if (next == null) {
break;
}
if (next.error != null) {
throw next.error;
}
if (next.done === false) {
// @ts-expect-error if done is false value should be pushed
values.push(next.value);
}
}
if (next == null) {
return { done: true };
}
return {
done: next.done === true,
value: values
};
};
return _pushable(getNext, options);
}
function _pushable(getNext, options) {
options = options ?? {};
let onEnd = options.onEnd;
let buffer = new _fifo_js__WEBPACK_IMPORTED_MODULE_0__.FIFO();
let pushable;
let onNext;
let ended;
let drain = (0,p_defer__WEBPACK_IMPORTED_MODULE_1__["default"])();
const waitNext = async () => {
try {
if (!buffer.isEmpty()) {
return getNext(buffer);
}
if (ended) {
return { done: true };
}
return await new Promise((resolve, reject) => {
onNext = (next) => {
onNext = null;
buffer.push(next);
try {
resolve(getNext(buffer));
}
catch (err) {
reject(err);
}
return pushable;
};
});
}
finally {
if (buffer.isEmpty()) {
// settle promise in the microtask queue to give consumers a chance to
// await after calling .push
queueMicrotask(() => {
drain.resolve();
drain = (0,p_defer__WEBPACK_IMPORTED_MODULE_1__["default"])();
});
}
}
};
const bufferNext = (next) => {
if (onNext != null) {
return onNext(next);
}
buffer.push(next);
return pushable;
};
const bufferError = (err) => {
buffer = new _fifo_js__WEBPACK_IMPORTED_MODULE_0__.FIFO();
if (onNext != null) {
return onNext({ error: err });
}
buffer.push({ error: err });
return pushable;
};
const push = (value) => {
if (ended) {
return pushable;
}
// @ts-expect-error `byteLength` is not declared on PushType
if (options?.objectMode !== true && value?.byteLength == null) {
throw new Error('objectMode was not true but tried to push non-Uint8Array value');
}
return bufferNext({ done: false, value });
};
const end = (err) => {
if (ended)
return pushable;
ended = true;
return (err != null) ? bufferError(err) : bufferNext({ done: true });
};
const _return = () => {
buffer = new _fifo_js__WEBPACK_IMPORTED_MODULE_0__.FIFO();
end();
return { done: true };
};
const _throw = (err) => {
end(err);
return { done: true };
};
pushable = {
[Symbol.asyncIterator]() { return this; },
next: waitNext,
return: _return,
throw: _throw,
push,
end,
get readableLength() {
return buffer.size;
},
onEmpty: async (options) => {
const signal = options?.signal;
signal?.throwIfAborted();
if (buffer.isEmpty()) {
return;
}
let cancel;
let listener;
if (signal != null) {
cancel = new Promise((resolve, reject) => {
listener = () => {
reject(new AbortError());
};
signal.addEventListener('abort', listener);
});
}
try {
await Promise.race([
drain.promise,
cancel
]);
}
finally {
if (listener != null && signal != null) {
signal?.removeEventListener('abort', listener);
}
}
}
};
if (onEnd == null) {
return pushable;
}
const _pushable = pushable;
pushable = {
[Symbol.asyncIterator]() { return this; },
next() {
return _pushable.next();
},
throw(err) {
_pushable.throw(err);
if (onEnd != null) {
onEnd(err);
onEnd = undefined;
}
return { done: true };
},
return() {
_pushable.return();
if (onEnd != null) {
onEnd();
onEnd = undefined;
}
return { done: true };
},
push,
end(err) {
_pushable.end(err);
if (onEnd != null) {
onEnd(err);
onEnd = undefined;
}
return pushable;
},
get readableLength() {
return _pushable.readableLength;
},
onEmpty: (opts) => {
return _pushable.onEmpty(opts);
}
};
return pushable;
}
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "./node_modules/multiformats/src/bases/base.js":
/*!*****************************************************!*\
!*** ./node_modules/multiformats/src/bases/base.js ***!
\*****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Codec: () => (/* binding */ Codec),
/* harmony export */ baseX: () => (/* binding */ baseX),
/* harmony export */ from: () => (/* binding */ from),
/* harmony export */ or: () => (/* binding */ or),
/* harmony export */ rfc4648: () => (/* binding */ rfc4648)
/* harmony export */ });
/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../vendor/base-x.js */ "./node_modules/multiformats/vendor/base-x.js");
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../bytes.js */ "./node_modules/multiformats/src/bytes.js");
/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./interface.js */ "./node_modules/multiformats/src/bases/interface.js");
// Linter can't see that API is used in types.
// eslint-disable-next-line
/**
* Class represents both BaseEncoder and MultibaseEncoder meaning it
* can be used to encode to multibase or base encode without multibase
* prefix.
*
* @class
* @template {string} Base
* @template {string} Prefix
* @implements {API.MultibaseEncoder<Prefix>}
* @implements {API.BaseEncoder}
*/
class Encoder {
/**
* @param {Base} name
* @param {Prefix} prefix
* @param {(bytes:Uint8Array) => string} baseEncode
*/
constructor (name, prefix, baseEncode) {
this.name = name
this.prefix = prefix
this.baseEncode = baseEncode
}
/**
* @param {Uint8Array} bytes
* @returns {API.Multibase<Prefix>}
*/
encode (bytes) {
if (bytes instanceof Uint8Array) {
return `${this.prefix}${this.baseEncode(bytes)}`
} else {
throw Error('Unknown type, must be binary type')
}
}
}
/**
* @template {string} Prefix
*/
/**
* Class represents both BaseDecoder and MultibaseDecoder so it could be used
* to decode multibases (with matching prefix) or just base decode strings
* with corresponding base encoding.
*
* @class
* @template {string} Base
* @template {string} Prefix
* @implements {API.MultibaseDecoder<Prefix>}
* @implements {API.UnibaseDecoder<Prefix>}
* @implements {API.BaseDecoder}
*/
class Decoder {
/**
* @param {Base} name
* @param {Prefix} prefix
* @param {(text:string) => Uint8Array} baseDecode
*/
constructor (name, prefix, baseDecode) {
this.name = name
this.prefix = prefix
/* c8 ignore next 3 */
if (prefix.codePointAt(0) === undefined) {
throw new Error('Invalid prefix character')
}
/** @private */
this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0))
this.baseDecode = baseDecode
}
/**
* @param {string} text
*/
decode (text) {
if (typeof text === 'string') {
if (text.codePointAt(0) !== this.prefixCodePoint) {
throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)
}
return this.baseDecode(text.slice(this.prefix.length))
} else {
throw Error('Can only multibase decode strings')
}
}
/**
* @template {string} OtherPrefix
* @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
* @returns {ComposedDecoder<Prefix|OtherPrefix>}
*/
or (decoder) {
return or(this, decoder)
}
}
/**
* @template {string} Prefix
* @typedef {Record<Prefix, API.UnibaseDecoder<Prefix>>} Decoders
*/
/**
* @template {string} Prefix
* @implements {API.MultibaseDecoder<Prefix>}
* @implements {API.CombobaseDecoder<Prefix>}
*/
class ComposedDecoder {
/**
* @param {Decoders<Prefix>} decoders
*/
constructor (decoders) {
this.decoders = decoders
}
/**
* @template {string} OtherPrefix
* @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
* @returns {ComposedDecoder<Prefix|OtherPrefix>}
*/
or (decoder) {
return or(this, decoder)
}
/**
* @param {string} input
* @returns {Uint8Array}
*/
decode (input) {
const prefix = /** @type {Prefix} */ (input[0])
const decoder = this.decoders[prefix]
if (decoder) {
return decoder.decode(input)
} else {
throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)
}
}
}
/**
* @template {string} L
* @template {string} R
* @param {API.UnibaseDecoder<L>|API.CombobaseDecoder<L>} left
* @param {API.UnibaseDecoder<R>|API.CombobaseDecoder<R>} right
* @returns {ComposedDecoder<L|R>}
*/
const or = (left, right) => new ComposedDecoder(/** @type {Decoders<L|R>} */({
...(left.decoders || { [/** @type API.UnibaseDecoder<L> */(left).prefix]: left }),
...(right.decoders || { [/** @type API.UnibaseDecoder<R> */(right).prefix]: right })
}))
/**
* @class
* @template {string} Base
* @template {string} Prefix
* @implements {API.MultibaseCodec<Prefix>}
* @implements {API.MultibaseEncoder<Prefix>}
* @implements {API.MultibaseDecoder<Prefix>}
* @implements {API.BaseCodec}
* @implements {API.BaseEncoder}
* @implements {API.BaseDecoder}
*/
class Codec {
/**
* @param {Base} name
* @param {Prefix} prefix
* @param {(bytes:Uint8Array) => string} baseEncode
* @param {(text:string) => Uint8Array} baseDecode
*/
constructor (name, prefix, baseEncode, baseDecode) {
this.name = name
this.prefix = prefix
this.baseEncode = baseEncode
this.baseDecode = baseDecode
this.encoder = new Encoder(name, prefix, baseEncode)
this.decoder = new Decoder(name, prefix, baseDecode)
}
/**
* @param {Uint8Array} input
*/
encode (input) {
return this.encoder.encode(input)
}
/**
* @param {string} input
*/
decode (input) {
return this.decoder.decode(input)
}
}
/**
* @template {string} Base
* @template {string} Prefix
* @param {object} options
* @param {Base} options.name
* @param {Prefix} options.prefix
* @param {(bytes:Uint8Array) => string} options.encode
* @param {(input:string) => Uint8Array} options.decode
* @returns {Codec<Base, Prefix>}
*/
const from = ({ name, prefix, encode, decode }) =>
new Codec(name, prefix, encode, decode)
/**
* @template {string} Base
* @template {string} Prefix
* @param {object} options
* @param {Base} options.name
* @param {Prefix} options.prefix
* @param {string} options.alphabet
* @returns {Codec<Base, Prefix>}
*/
const baseX = ({ prefix, name, alphabet }) => {
const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_0__["default"])(alphabet, name)
return from({
prefix,
name,
encode,
/**
* @param {string} text
*/
decode: text => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_1__.coerce)(decode(text))
})
}
/**
* @param {string} string
* @param {string} alphabet
* @param {number} bitsPerChar
* @param {string} name
* @returns {Uint8Array}
*/
const decode = (string, alphabet, bitsPerChar, name) => {
// Build the character lookup table:
/** @type {Record<string, number>} */
const codes = {}
for (let i = 0; i < alphabet.length; ++i) {
codes[alphabet[i]] = i
}
// Count the padding bytes:
let end = string.length
while (string[end - 1] === '=') {
--end
}
// Allocate the output:
const out = new Uint8Array((end * bitsPerChar / 8) | 0)
// Parse the data:
let bits = 0 // Number of bits currently in the buffer
let buffer = 0 // Bits waiting to be written out, MSB first
let written = 0 // Next byte to write
for (let i = 0; i < end; ++i) {
// Read one character from the string:
const value = codes[string[i]]
if (value === undefined) {
throw new SyntaxError(`Non-${name} character`)
}
// Append the bits to the buffer:
buffer = (buffer << bitsPerChar) | value
bits += bitsPerChar
// Write out some bits if the buffer has a byte's worth:
if (bits >= 8) {
bits -= 8
out[written++] = 0xff & (buffer >> bits)
}
}
// Verify that we have received just enough bits:
if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {
throw new SyntaxError('Unexpected end of data')
}
return out
}
/**
* @param {Uint8Array} data
* @param {string} alphabet
* @param {number} bitsPerChar
* @returns {string}
*/
const encode = (data, alphabet, bitsPerChar) => {
const pad = alphabet[alphabet.length - 1] === '='
const mask = (1 << bitsPerChar) - 1
let out = ''
let bits = 0 // Number of bits currently in the buffer
let buffer = 0 // Bits waiting to be written out, MSB first
for (let i = 0; i < data.length; ++i) {
// Slurp data into the buffer:
buffer = (buffer << 8) | data[i]
bits += 8
// Write out as much as we can:
while (bits > bitsPerChar) {
bits -= bitsPerChar
out += alphabet[mask & (buffer >> bits)]
}
}
// Partial character:
if (bits) {
out += alphabet[mask & (buffer << (bitsPerChar - bits))]
}
// Add padding characters until we hit a byte boundary:
if (pad) {
while ((out.length * bitsPerChar) & 7) {
out += '='
}
}
return out
}
/**
* RFC4648 Factory
*
* @template {string} Base
* @template {string} Prefix
* @param {object} options
* @param {Base} options.name
* @param {Prefix} options.prefix
* @param {string} options.alphabet
* @param {number} options.bitsPerChar
*/
const rfc4648 = ({ name, prefix, bitsPerChar, alphabet }) => {
return from({
prefix,
name,
encode (input) {
return encode(input, alphabet, bitsPerChar)
},
decode (input) {
return decode(input, alphabet, bitsPerChar, name)
}
})
}
/***/ }),
/***/ "./node_modules/multiformats/src/bases/base32.js":
/*!*******************************************************!*\
!*** ./node_modules/multiformats/src/bases/base32.js ***!
\*******************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base32: () => (/* binding */ base32),
/* harmony export */ base32hex: () => (/* binding */ base32hex),
/* harmony export */ base32hexpad: () => (/* binding */ base32hexpad),
/* harmony export */ base32hexpadupper: () => (/* binding */ base32hexpadupper),
/* harmony export */ base32hexupper: () => (/* binding */ base32hexupper),
/* harmony export */ base32pad: () => (/* binding */ base32pad),
/* harmony export */ base32padupper: () => (/* binding */ base32padupper),
/* harmony export */ base32upper: () => (/* binding */ base32upper),
/* harmony export */ base32z: () => (/* binding */ base32z)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/multiformats/src/bases/base.js");
const base32 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'b',
name: 'base32',
alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
bitsPerChar: 5
})
const base32upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'B',
name: 'base32upper',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
bitsPerChar: 5
})
const base32pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'c',
name: 'base32pad',
alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
bitsPerChar: 5
})
const base32padupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'C',
name: 'base32padupper',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
bitsPerChar: 5
})
const base32hex = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'v',
name: 'base32hex',
alphabet: '0123456789abcdefghijklmnopqrstuv',
bitsPerChar: 5
})
const base32hexupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'V',
name: 'base32hexupper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
bitsPerChar: 5
})
const base32hexpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 't',
name: 'base32hexpad',
alphabet: '0123456789abcdefghijklmnopqrstuv=',
bitsPerChar: 5
})
const base32hexpadupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'T',
name: 'base32hexpadupper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
bitsPerChar: 5
})
const base32z = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'h',
name: 'base32z',
alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
bitsPerChar: 5
})
/***/ }),
/***/ "./node_modules/multiformats/src/bases/base58.js":
/*!*******************************************************!*\
!*** ./node_modules/multiformats/src/bases/base58.js ***!
\*******************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base58btc: () => (/* binding */ base58btc),
/* harmony export */ base58flickr: () => (/* binding */ base58flickr)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/multiformats/src/bases/base.js");
const base58btc = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
name: 'base58btc',
prefix: 'z',
alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
})
const base58flickr = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
name: 'base58flickr',
prefix: 'Z',
alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
})
/***/ }),
/***/ "./node_modules/multiformats/src/bases/interface.js":
/*!**********************************************************!*\
!*** ./node_modules/multiformats/src/bases/interface.js ***!
\**********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
// this is dummy module overlayed by interface.ts
/***/ }),
/***/ "./node_modules/multiformats/src/block.js":
/*!************************************************!*\
!*** ./node_modules/multiformats/src/block.js ***!
\************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Block: () => (/* binding */ Block),
/* harmony export */ create: () => (/* binding */ create),
/* harmony export */ createUnsafe: () => (/* binding */ createUnsafe),
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ encode: () => (/* binding */ encode)
/* harmony export */ });
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./index.js */ "./node_modules/multiformats/src/index.js");
/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./interface.js */ "./node_modules/multiformats/src/interface.js");
// Linter can see that API is used in types.
// eslint-disable-next-line
function readonly ({ enumerable = true, configurable = false } = {}) {
return { enumerable, configurable, writable: false }
}
/**
* @param {[string|number, string]} path
* @param {any} value
* @returns {Iterable<[string, CID]>}
*/
function * linksWithin (path, value) {
if (value != null && typeof value === 'object') {
if (Array.isArray(value)) {
for (const [index, element] of value.entries()) {
const elementPath = [...path, index]
const cid = _index_js__WEBPACK_IMPORTED_MODULE_0__.CID.asCID(element)
if (cid) {
yield [elementPath.join('/'), cid]
} else if (typeof element === 'object') {
yield * links(element, elementPath)
}
}
} else {
const cid = _index_js__WEBPACK_IMPORTED_MODULE_0__.CID.asCID(value)
if (cid) {
yield [path.join('/'), cid]
} else {
yield * links(value, path)
}
}
}
}
/**
* @template T
* @param {T} source
* @param {Array<string|number>} base
* @returns {Iterable<[string, CID]>}
*/
function * links (source, base) {
if (source == null || source instanceof Uint8Array) {
return
}
const cid = _index_js__WEBPACK_IMPORTED_MODULE_0__.CID.asCID(source)
if (cid) {
yield [base.join('/'), cid]
}
for (const [key, value] of Object.entries(source)) {
const path = /** @type {[string|number, string]} */ ([...base, key])
yield * linksWithin(path, value)
}
}
/**
* @param {[string|number, string]} path
* @param {any} value
* @returns {Iterable<string>}
*/
function * treeWithin (path, value) {
if (Array.isArray(value)) {
for (const [index, element] of value.entries()) {
const elementPath = [...path, index]
yield elementPath.join('/')
if (typeof element === 'object' && !_index_js__WEBPACK_IMPORTED_MODULE_0__.CID.asCID(element)) {
yield * tree(element, elementPath)
}
}
} else {
yield * tree(value, path)
}
}
/**
* @template T
* @param {T} source
* @param {Array<string|number>} base
* @returns {Iterable<string>}
*/
function * tree (source, base) {
if (source == null || typeof source !== 'object') {
return
}
for (const [key, value] of Object.entries(source)) {
const path = /** @type {[string|number, string]} */ ([...base, key])
yield path.join('/')
if (value != null && !(value instanceof Uint8Array) && typeof value === 'object' && !_index_js__WEBPACK_IMPORTED_MODULE_0__.CID.asCID(value)) {
yield * treeWithin(path, value)
}
}
}
/**
*
* @template T
* @param {T} source
* @param {string[]} path
* @returns {API.BlockCursorView<unknown>}
*/
function get (source, path) {
let node = /** @type {Record<string, any>} */(source)
for (const [index, key] of path.entries()) {
node = node[key]
if (node == null) {
throw new Error(`Object has no property at ${path.slice(0, index + 1).map(part => `[${JSON.stringify(part)}]`).join('')}`)
}
const cid = _index_js__WEBPACK_IMPORTED_MODULE_0__.CID.asCID(node)
if (cid) {
return { value: cid, remaining: path.slice(index + 1).join('/') }
}
}
return { value: node }
}
/**
* @template {unknown} T - Logical type of the data encoded in the block
* @template {number} C - multicodec code corresponding to codec used to encode the block
* @template {number} A - multicodec code corresponding to the hashing algorithm used in CID creation.
* @template {API.Version} V - CID version
* @implements {API.BlockView<T, C, A, V>}
*/
class Block {
/**
* @param {object} options
* @param {CID<T, C, A, V>} options.cid
* @param {API.ByteView<T>} options.bytes
* @param {T} options.value
*/
constructor ({ cid, bytes, value }) {
if (!cid || !bytes || typeof value === 'undefined') { throw new Error('Missing required argument') }
this.cid = cid
this.bytes = bytes
this.value = value
this.asBlock = this
// Mark all the properties immutable
Object.defineProperties(this, {
cid: readonly(),
bytes: readonly(),
value: readonly(),
asBlock: readonly()
})
}
links () {
return links(this.value, [])
}
tree () {
return tree(this.value, [])
}
/**
*
* @param {string} [path]
* @returns {API.BlockCursorView<unknown>}
*/
get (path = '/') {
return get(this.value, path.split('/').filter(Boolean))
}
}
/**
* @template {unknown} T - Logical type of the data encoded in the block
* @template {number} Code - multicodec code corresponding to codec used to encode the block
* @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.
* @param {object} options
* @param {T} options.value
* @param {API.BlockEncoder<Code, T>} options.codec
* @param {API.MultihashHasher<Alg>} options.hasher
* @returns {Promise<API.BlockView<T, Code, Alg>>}
*/
async function encode ({ value, codec, hasher }) {
if (typeof value === 'undefined') throw new Error('Missing required argument "value"')
if (!codec || !hasher) throw new Error('Missing required argument: codec or hasher')
const bytes = codec.encode(value)
const hash = await hasher.digest(bytes)
/** @type {CID<T, Code, Alg, 1>} */
const cid = _index_js__WEBPACK_IMPORTED_MODULE_0__.CID.create(
1,
codec.code,
hash
)
return new Block({ value, bytes, cid })
}
/**
* @template {unknown} T - Logical type of the data encoded in the block
* @template {number} Code - multicodec code corresponding to codec used to encode the block
* @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.
* @param {object} options
* @param {API.ByteView<T>} options.bytes
* @param {API.BlockDecoder<Code, T>} options.codec
* @param {API.MultihashHasher<Alg>} options.hasher
* @returns {Promise<API.BlockView<T, Code, Alg>>}
*/
async function decode ({ bytes, codec, hasher }) {
if (!bytes) throw new Error('Missing required argument "bytes"')
if (!codec || !hasher) throw new Error('Missing required argument: codec or hasher')
const value = codec.decode(bytes)
const hash = await hasher.digest(bytes)
/** @type {CID<T, Code, Alg, 1>} */
const cid = _index_js__WEBPACK_IMPORTED_MODULE_0__.CID.create(1, codec.code, hash)
return new Block({ value, bytes, cid })
}
/**
* @typedef {object} RequiredCreateOptions
* @property {CID} options.cid
*/
/**
* @template {unknown} T - Logical type of the data encoded in the block
* @template {number} Code - multicodec code corresponding to codec used to encode the block
* @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.
* @template {API.Version} V - CID version
* @param {{ cid: API.Link<T, Code, Alg, V>, value:T, codec?: API.BlockDecoder<Code, T>, bytes: API.ByteView<T> }|{cid:API.Link<T, Code, Alg, V>, bytes:API.ByteView<T>, value?:void, codec:API.BlockDecoder<Code, T>}} options
* @returns {API.BlockView<T, Code, Alg, V>}
*/
function createUnsafe ({ bytes, cid, value: maybeValue, codec }) {
const value = maybeValue !== undefined
? maybeValue
: (codec && codec.decode(bytes))
if (value === undefined) throw new Error('Missing required argument, must either provide "value" or "codec"')
return new Block({
// eslint-disable-next-line object-shorthand
cid: /** @type {CID<T, Code, Alg, V>} */ (cid),
bytes,
value
})
}
/**
* @template {unknown} T - Logical type of the data encoded in the block
* @template {number} Code - multicodec code corresponding to codec used to encode the block
* @template {number} Alg - multicodec code corresponding to the hashing algorithm used in CID creation.
* @template {API.Version} V - CID version
* @param {object} options
* @param {API.Link<T, Code, Alg, V>} options.cid
* @param {API.ByteView<T>} options.bytes
* @param {API.BlockDecoder<Code, T>} options.codec
* @param {API.MultihashHasher<Alg>} options.hasher
* @returns {Promise<API.BlockView<T, Code, Alg, V>>}
*/
async function create ({ bytes, cid, hasher, codec }) {
if (!bytes) throw new Error('Missing required argument "bytes"')
if (!hasher) throw new Error('Missing required argument "hasher"')
const value = codec.decode(bytes)
const hash = await hasher.digest(bytes)
if (!_index_js__WEBPACK_IMPORTED_MODULE_0__.bytes.equals(cid.multihash.bytes, hash.bytes)) {
throw new Error('CID hash does not match bytes')
}
return createUnsafe({
bytes,
cid,
value,
codec
})
}
/***/ }),
/***/ "./node_modules/multiformats/src/bytes.js":
/*!************************************************!*\
!*** ./node_modules/multiformats/src/bytes.js ***!
\************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ coerce: () => (/* binding */ coerce),
/* harmony export */ empty: () => (/* binding */ empty),
/* harmony export */ equals: () => (/* binding */ equals),
/* harmony export */ fromHex: () => (/* binding */ fromHex),
/* harmony export */ fromString: () => (/* binding */ fromString),
/* harmony export */ isBinary: () => (/* binding */ isBinary),
/* harmony export */ toHex: () => (/* binding */ toHex),
/* harmony export */ toString: () => (/* binding */ toString)
/* harmony export */ });
const empty = new Uint8Array(0)
/**
* @param {Uint8Array} d
*/
const toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')
/**
* @param {string} hex
*/
const fromHex = hex => {
const hexes = hex.match(/../g)
return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty
}
/**
* @param {Uint8Array} aa
* @param {Uint8Array} bb
*/
const equals = (aa, bb) => {
if (aa === bb) return true
if (aa.byteLength !== bb.byteLength) {
return false
}
for (let ii = 0; ii < aa.byteLength; ii++) {
if (aa[ii] !== bb[ii]) {
return false
}
}
return true
}
/**
* @param {ArrayBufferView|ArrayBuffer|Uint8Array} o
* @returns {Uint8Array}
*/
const coerce = o => {
if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o
if (o instanceof ArrayBuffer) return new Uint8Array(o)
if (ArrayBuffer.isView(o)) {
return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)
}
throw new Error('Unknown type, must be binary type')
}
/**
* @param {any} o
* @returns {o is ArrayBuffer|ArrayBufferView}
*/
const isBinary = o =>
o instanceof ArrayBuffer || ArrayBuffer.isView(o)
/**
* @param {string} str
* @returns {Uint8Array}
*/
const fromString = str => (new TextEncoder()).encode(str)
/**
* @param {Uint8Array} b
* @returns {string}
*/
const toString = b => (new TextDecoder()).decode(b)
/***/ }),
/***/ "./node_modules/multiformats/src/cid.js":
/*!**********************************************!*\
!*** ./node_modules/multiformats/src/cid.js ***!
\**********************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CID: () => (/* binding */ CID),
/* harmony export */ format: () => (/* binding */ format),
/* harmony export */ fromJSON: () => (/* binding */ fromJSON),
/* harmony export */ toJSON: () => (/* binding */ toJSON)
/* harmony export */ });
/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ "./node_modules/multiformats/src/bases/base32.js");
/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ "./node_modules/multiformats/src/bases/base58.js");
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ "./node_modules/multiformats/src/bytes.js");
/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ "./node_modules/multiformats/src/hashes/digest.js");
/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./link/interface.js */ "./node_modules/multiformats/src/link/interface.js");
/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ "./node_modules/multiformats/src/varint.js");
// Linter can see that API is used in types.
// eslint-disable-next-line
// This way TS will also expose all the types from module
/**
* @template {API.Link<unknown, number, number, API.Version>} T
* @template {string} Prefix
* @param {T} link
* @param {API.MultibaseEncoder<Prefix>} [base]
* @returns {API.ToString<T, Prefix>}
*/
const format = (link, base) => {
const { bytes, version } = link
switch (version) {
case 0:
return toStringV0(
bytes,
baseCache(link),
/** @type {API.MultibaseEncoder<"z">} */ (base) || _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder
)
default:
return toStringV1(
bytes,
baseCache(link),
/** @type {API.MultibaseEncoder<Prefix>} */ (base || _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder)
)
}
}
/**
* @template {API.UnknownLink} Link
* @param {Link} link
* @returns {API.LinkJSON<Link>}
*/
const toJSON = (link) => ({
'/': format(link)
})
/**
* @template {API.UnknownLink} Link
* @param {API.LinkJSON<Link>} json
*/
const fromJSON = (json) =>
CID.parse(json['/'])
/** @type {WeakMap<API.UnknownLink, Map<string, string>>} */
const cache = new WeakMap()
/**
* @param {API.UnknownLink} cid
* @returns {Map<string, string>}
*/
const baseCache = cid => {
const baseCache = cache.get(cid)
if (baseCache == null) {
const baseCache = new Map()
cache.set(cid, baseCache)
return baseCache
}
return baseCache
}
/**
* @template {unknown} [Data=unknown]
* @template {number} [Format=number]
* @template {number} [Alg=number]
* @template {API.Version} [Version=API.Version]
* @implements {API.Link<Data, Format, Alg, Version>}
*/
class CID {
/**
* @param {Version} version - Version of the CID
* @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
* @param {API.MultihashDigest<Alg>} multihash - (Multi)hash of the of the content.
* @param {Uint8Array} bytes
*/
constructor (version, code, multihash, bytes) {
/** @readonly */
this.code = code
/** @readonly */
this.version = version
/** @readonly */
this.multihash = multihash
/** @readonly */
this.bytes = bytes
// flag to serializers that this is a CID and
// should be treated specially
/** @readonly */
this['/'] = bytes
}
/**
* Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
* please either use `CID.asCID(cid)` or switch to new signalling mechanism
*
* @deprecated
*/
get asCID () {
return this
}
// ArrayBufferView
get byteOffset () {
return this.bytes.byteOffset
}
// ArrayBufferView
get byteLength () {
return this.bytes.byteLength
}
/**
* @returns {CID<Data, API.DAG_PB, API.SHA_256, 0>}
*/
toV0 () {
switch (this.version) {
case 0: {
return /** @type {CID<Data, API.DAG_PB, API.SHA_256, 0>} */ (this)
}
case 1: {
const { code, multihash } = this
if (code !== DAG_PB_CODE) {
throw new Error('Cannot convert a non dag-pb CID to CIDv0')
}
// sha2-256
if (multihash.code !== SHA_256_CODE) {
throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')
}
return /** @type {CID<Data, API.DAG_PB, API.SHA_256, 0>} */ (
CID.createV0(
/** @type {API.MultihashDigest<API.SHA_256>} */ (multihash)
)
)
}
default: {
throw Error(
`Can not convert CID version ${this.version} to version 0. This is a bug please report`
)
}
}
}
/**
* @returns {CID<Data, Format, Alg, 1>}
*/
toV1 () {
switch (this.version) {
case 0: {
const { code, digest } = this.multihash
const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest)
return /** @type {CID<Data, Format, Alg, 1>} */ (
CID.createV1(this.code, multihash)
)
}
case 1: {
return /** @type {CID<Data, Format, Alg, 1>} */ (this)
}
default: {
throw Error(
`Can not convert CID version ${this.version} to version 1. This is a bug please report`
)
}
}
}
/**
* @param {unknown} other
* @returns {other is CID<Data, Format, Alg, Version>}
*/
equals (other) {
return CID.equals(this, other)
}
/**
* @template {unknown} Data
* @template {number} Format
* @template {number} Alg
* @template {API.Version} Version
* @param {API.Link<Data, Format, Alg, Version>} self
* @param {unknown} other
* @returns {other is CID}
*/
static equals (self, other) {
const unknown =
/** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ (
other
)
return (
unknown &&
self.code === unknown.code &&
self.version === unknown.version &&
_hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash)
)
}
/**
* @param {API.MultibaseEncoder<string>} [base]
* @returns {string}
*/
toString (base) {
return format(this, base)
}
/**
* @returns {API.LinkJSON<this>}
*/
toJSON () {
return { '/': format(this) }
}
link () {
return this
}
get [Symbol.toStringTag] () {
return 'CID'
}
// Legacy
[Symbol.for('nodejs.util.inspect.custom')] () {
return `CID(${this.toString()})`
}
/**
* Takes any input `value` and returns a `CID` instance if it was
* a `CID` otherwise returns `null`. If `value` is instanceof `CID`
* it will return value back. If `value` is not instance of this CID
* class, but is compatible CID it will return new instance of this
* `CID` class. Otherwise returns null.
*
* This allows two different incompatible versions of CID library to
* co-exist and interop as long as binary interface is compatible.
*
* @template {unknown} Data
* @template {number} Format
* @template {number} Alg
* @template {API.Version} Version
* @template {unknown} U
* @param {API.Link<Data, Format, Alg, Version>|U} input
* @returns {CID<Data, Format, Alg, Version>|null}
*/
static asCID (input) {
if (input == null) {
return null
}
const value = /** @type {any} */ (input)
if (value instanceof CID) {
// If value is instance of CID then we're all set.
return value
} else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
// If value isn't instance of this CID class but `this.asCID === this` or
// `value['/'] === value.bytes` is true it is CID instance coming from a
// different implementation (diff version or duplicate). In that case we
// rebase it to this `CID` implementation so caller is guaranteed to get
// instance with expected API.
const { version, code, multihash, bytes } = value
return new CID(
version,
code,
/** @type {API.MultihashDigest<Alg>} */ (multihash),
bytes || encodeCID(version, code, multihash.bytes)
)
} else if (value[cidSymbol] === true) {
// If value is a CID from older implementation that used to be tagged via
// symbol we still rebase it to the this `CID` implementation by
// delegating that to a constructor.
const { version, multihash, code } = value
const digest =
/** @type {API.MultihashDigest<Alg>} */
(_hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash))
return CID.create(version, code, digest)
} else {
// Otherwise value is not a CID (or an incompatible version of it) in
// which case we return `null`.
return null
}
}
/**
*
* @template {unknown} Data
* @template {number} Format
* @template {number} Alg
* @template {API.Version} Version
* @param {Version} version - Version of the CID
* @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
* @param {API.MultihashDigest<Alg>} digest - (Multi)hash of the of the content.
* @returns {CID<Data, Format, Alg, Version>}
*/
static create (version, code, digest) {
if (typeof code !== 'number') {
throw new Error('String codecs are no longer supported')
}
if (!(digest.bytes instanceof Uint8Array)) {
throw new Error('Invalid digest')
}
switch (version) {
case 0: {
if (code !== DAG_PB_CODE) {
throw new Error(
`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`
)
} else {
return new CID(version, code, digest, digest.bytes)
}
}
case 1: {
const bytes = encodeCID(version, code, digest.bytes)
return new CID(version, code, digest, bytes)
}
default: {
throw new Error('Invalid version')
}
}
}
/**
* Simplified version of `create` for CIDv0.
*
* @template {unknown} [T=unknown]
* @param {API.MultihashDigest<typeof SHA_256_CODE>} digest - Multihash.
* @returns {CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0>}
*/
static createV0 (digest) {
return CID.create(0, DAG_PB_CODE, digest)
}
/**
* Simplified version of `create` for CIDv1.
*
* @template {unknown} Data
* @template {number} Code
* @template {number} Alg
* @param {Code} code - Content encoding format code.
* @param {API.MultihashDigest<Alg>} digest - Miltihash of the content.
* @returns {CID<Data, Code, Alg, 1>}
*/
static createV1 (code, digest) {
return CID.create(1, code, digest)
}
/**
* Decoded a CID from its binary representation. The byte array must contain
* only the CID with no additional bytes.
*
* An error will be thrown if the bytes provided do not contain a valid
* binary representation of a CID.
*
* @template {unknown} Data
* @template {number} Code
* @template {number} Alg
* @template {API.Version} Ver
* @param {API.ByteView<API.Link<Data, Code, Alg, Ver>>} bytes
* @returns {CID<Data, Code, Alg, Ver>}
*/
static decode (bytes) {
const [cid, remainder] = CID.decodeFirst(bytes)
if (remainder.length) {
throw new Error('Incorrect length')
}
return cid
}
/**
* Decoded a CID from its binary representation at the beginning of a byte
* array.
*
* Returns an array with the first element containing the CID and the second
* element containing the remainder of the original byte array. The remainder
* will be a zero-length byte array if the provided bytes only contained a
* binary CID representation.
*
* @template {unknown} T
* @template {number} C
* @template {number} A
* @template {API.Version} V
* @param {API.ByteView<API.Link<T, C, A, V>>} bytes
* @returns {[CID<T, C, A, V>, Uint8Array]}
*/
static decodeFirst (bytes) {
const specs = CID.inspectBytes(bytes)
const prefixSize = specs.size - specs.multihashSize
const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(
bytes.subarray(prefixSize, prefixSize + specs.multihashSize)
)
if (multihashBytes.byteLength !== specs.multihashSize) {
throw new Error('Incorrect length')
}
const digestBytes = multihashBytes.subarray(
specs.multihashSize - specs.digestSize
)
const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(
specs.multihashCode,
specs.digestSize,
digestBytes,
multihashBytes
)
const cid =
specs.version === 0
? CID.createV0(/** @type {API.MultihashDigest<API.SHA_256>} */ (digest))
: CID.createV1(specs.codec, digest)
return [/** @type {CID<T, C, A, V>} */(cid), bytes.subarray(specs.size)]
}
/**
* Inspect the initial bytes of a CID to determine its properties.
*
* Involves decoding up to 4 varints. Typically this will require only 4 to 6
* bytes but for larger multicodec code values and larger multihash digest
* lengths these varints can be quite large. It is recommended that at least
* 10 bytes be made available in the `initialBytes` argument for a complete
* inspection.
*
* @template {unknown} T
* @template {number} C
* @template {number} A
* @template {API.Version} V
* @param {API.ByteView<API.Link<T, C, A, V>>} initialBytes
* @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}
*/
static inspectBytes (initialBytes) {
let offset = 0
const next = () => {
const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset))
offset += length
return i
}
let version = /** @type {V} */ (next())
let codec = /** @type {C} */ (DAG_PB_CODE)
if (/** @type {number} */(version) === 18) {
// CIDv0
version = /** @type {V} */ (0)
offset = 0
} else {
codec = /** @type {C} */ (next())
}
if (version !== 0 && version !== 1) {
throw new RangeError(`Invalid CID version ${version}`)
}
const prefixSize = offset
const multihashCode = /** @type {A} */ (next()) // multihash code
const digestSize = next() // multihash length
const size = offset + digestSize
const multihashSize = size - prefixSize
return { version, codec, multihashCode, digestSize, multihashSize, size }
}
/**
* Takes cid in a string representation and creates an instance. If `base`
* decoder is not provided will use a default from the configuration. It will
* throw an error if encoding of the CID is not compatible with supplied (or
* a default decoder).
*
* @template {string} Prefix
* @template {unknown} Data
* @template {number} Code
* @template {number} Alg
* @template {API.Version} Ver
* @param {API.ToString<API.Link<Data, Code, Alg, Ver>, Prefix>} source
* @param {API.MultibaseDecoder<Prefix>} [base]
* @returns {CID<Data, Code, Alg, Ver>}
*/
static parse (source, base) {
const [prefix, bytes] = parseCIDtoBytes(source, base)
const cid = CID.decode(bytes)
if (cid.version === 0 && source[0] !== 'Q') {
throw Error('Version 0 CID string must not include multibase prefix')
}
// Cache string representation to avoid computing it on `this.toString()`
baseCache(cid).set(prefix, source)
return cid
}
}
/**
* @template {string} Prefix
* @template {unknown} Data
* @template {number} Code
* @template {number} Alg
* @template {API.Version} Ver
* @param {API.ToString<API.Link<Data, Code, Alg, Ver>, Prefix>} source
* @param {API.MultibaseDecoder<Prefix>} [base]
* @returns {[Prefix, API.ByteView<API.Link<Data, Code, Alg, Ver>>]}
*/
const parseCIDtoBytes = (source, base) => {
switch (source[0]) {
// CIDv0 is parsed differently
case 'Q': {
const decoder = base || _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc
return [
/** @type {Prefix} */ (_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix),
decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)
]
}
case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {
const decoder = base || _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc
return [/** @type {Prefix} */(_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix), decoder.decode(source)]
}
case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {
const decoder = base || _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32
return [/** @type {Prefix} */(_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix), decoder.decode(source)]
}
default: {
if (base == null) {
throw Error(
'To parse non base32 or base58btc encoded CID multibase decoder must be provided'
)
}
return [/** @type {Prefix} */(source[0]), base.decode(source)]
}
}
}
/**
*
* @param {Uint8Array} bytes
* @param {Map<string, string>} cache
* @param {API.MultibaseEncoder<'z'>} base
*/
const toStringV0 = (bytes, cache, base) => {
const { prefix } = base
if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {
throw Error(`Cannot string encode V0 in ${base.name} encoding`)
}
const cid = cache.get(prefix)
if (cid == null) {
const cid = base.encode(bytes).slice(1)
cache.set(prefix, cid)
return cid
} else {
return cid
}
}
/**
* @template {string} Prefix
* @param {Uint8Array} bytes
* @param {Map<string, string>} cache
* @param {API.MultibaseEncoder<Prefix>} base
*/
const toStringV1 = (bytes, cache, base) => {
const { prefix } = base
const cid = cache.get(prefix)
if (cid == null) {
const cid = base.encode(bytes)
cache.set(prefix, cid)
return cid
} else {
return cid
}
}
const DAG_PB_CODE = 0x70
const SHA_256_CODE = 0x12
/**
* @param {API.Version} version
* @param {number} code
* @param {Uint8Array} multihash
* @returns {Uint8Array}
*/
const encodeCID = (version, code, multihash) => {
const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version)
const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code)
const bytes = new Uint8Array(hashOffset + multihash.byteLength)
_varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0)
_varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset)
bytes.set(multihash, hashOffset)
return bytes
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID')
/***/ }),
/***/ "./node_modules/multiformats/src/hashes/digest.js":
/*!********************************************************!*\
!*** ./node_modules/multiformats/src/hashes/digest.js ***!
\********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Digest: () => (/* binding */ Digest),
/* harmony export */ create: () => (/* binding */ create),
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ equals: () => (/* binding */ equals)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ "./node_modules/multiformats/src/bytes.js");
/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ "./node_modules/multiformats/src/varint.js");
/**
* Creates a multihash digest.
*
* @template {number} Code
* @param {Code} code
* @param {Uint8Array} digest
*/
const create = (code, digest) => {
const size = digest.byteLength
const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code)
const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size)
const bytes = new Uint8Array(digestOffset + size)
_varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0)
_varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset)
bytes.set(digest, digestOffset)
return new Digest(code, size, digest, bytes)
}
/**
* Turns bytes representation of multihash digest into an instance.
*
* @param {Uint8Array} multihash
* @returns {MultihashDigest}
*/
const decode = (multihash) => {
const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash)
const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes)
const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset))
const digest = bytes.subarray(sizeOffset + digestOffset)
if (digest.byteLength !== size) {
throw new Error('Incorrect length')
}
return new Digest(code, size, digest, bytes)
}
/**
* @param {MultihashDigest} a
* @param {unknown} b
* @returns {b is MultihashDigest}
*/
const equals = (a, b) => {
if (a === b) {
return true
} else {
const data = /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */(b)
return (
a.code === data.code &&
a.size === data.size &&
data.bytes instanceof Uint8Array &&
(0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes)
)
}
}
/**
* @typedef {import('./interface.js').MultihashDigest} MultihashDigest
*/
/**
* Represents a multihash digest which carries information about the
* hashing algorithm and an actual hash digest.
*
* @template {number} Code
* @template {number} Size
* @class
* @implements {MultihashDigest}
*/
class Digest {
/**
* Creates a multihash digest.
*
* @param {Code} code
* @param {Size} size
* @param {Uint8Array} digest
* @param {Uint8Array} bytes
*/
constructor (code, size, digest, bytes) {
this.code = code
this.size = size
this.digest = digest
this.bytes = bytes
}
}
/***/ }),
/***/ "./node_modules/multiformats/src/hashes/hasher.js":
/*!********************************************************!*\
!*** ./node_modules/multiformats/src/hashes/hasher.js ***!
\********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Hasher: () => (/* binding */ Hasher),
/* harmony export */ from: () => (/* binding */ from)
/* harmony export */ });
/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./digest.js */ "./node_modules/multiformats/src/hashes/digest.js");
/**
* @template {string} Name
* @template {number} Code
* @param {object} options
* @param {Name} options.name
* @param {Code} options.code
* @param {(input: Uint8Array) => Await<Uint8Array>} options.encode
*/
const from = ({ name, code, encode }) => new Hasher(name, code, encode)
/**
* Hasher represents a hashing algorithm implementation that produces as
* `MultihashDigest`.
*
* @template {string} Name
* @template {number} Code
* @class
* @implements {MultihashHasher<Code>}
*/
class Hasher {
/**
*
* @param {Name} name
* @param {Code} code
* @param {(input: Uint8Array) => Await<Uint8Array>} encode
*/
constructor (name, code, encode) {
this.name = name
this.code = code
this.encode = encode
}
/**
* @param {Uint8Array} input
* @returns {Await<Digest.Digest<Code, number>>}
*/
digest (input) {
if (input instanceof Uint8Array) {
const result = this.encode(input)
return result instanceof Uint8Array
? _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, result)
/* c8 ignore next 1 */
: result.then(digest => _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, digest))
} else {
throw Error('Unknown type, must be binary type')
/* c8 ignore next 1 */
}
}
}
/**
* @template {number} Alg
* @typedef {import('./interface.js').MultihashHasher} MultihashHasher
*/
/**
* @template T
* @typedef {Promise<T>|T} Await
*/
/***/ }),
/***/ "./node_modules/multiformats/src/hashes/sha2-browser.js":
/*!**************************************************************!*\
!*** ./node_modules/multiformats/src/hashes/sha2-browser.js ***!
\**************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ sha256: () => (/* binding */ sha256),
/* harmony export */ sha512: () => (/* binding */ sha512)
/* harmony export */ });
/* harmony import */ var _hasher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hasher.js */ "./node_modules/multiformats/src/hashes/hasher.js");
/* global crypto */
/**
* @param {AlgorithmIdentifier} name
*/
const sha = name =>
/**
* @param {Uint8Array} data
*/
async data => new Uint8Array(await crypto.subtle.digest(name, data))
const sha256 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({
name: 'sha2-256',
code: 0x12,
encode: sha('SHA-256')
})
const sha512 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({
name: 'sha2-512',
code: 0x13,
encode: sha('SHA-512')
})
/***/ }),
/***/ "./node_modules/multiformats/src/index.js":
/*!************************************************!*\
!*** ./node_modules/multiformats/src/index.js ***!
\************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CID: () => (/* reexport safe */ _cid_js__WEBPACK_IMPORTED_MODULE_1__.CID),
/* harmony export */ bytes: () => (/* reexport module object */ _bytes_js__WEBPACK_IMPORTED_MODULE_0__),
/* harmony export */ digest: () => (/* reexport module object */ _hashes_digest_js__WEBPACK_IMPORTED_MODULE_2__),
/* harmony export */ hasher: () => (/* reexport module object */ _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__),
/* harmony export */ varint: () => (/* reexport module object */ _varint_js__WEBPACK_IMPORTED_MODULE_4__)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bytes.js */ "./node_modules/multiformats/src/bytes.js");
/* harmony import */ var _cid_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cid.js */ "./node_modules/multiformats/src/cid.js");
/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./hashes/digest.js */ "./node_modules/multiformats/src/hashes/digest.js");
/* harmony import */ var _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/hasher.js */ "./node_modules/multiformats/src/hashes/hasher.js");
/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ "./node_modules/multiformats/src/varint.js");
/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./interface.js */ "./node_modules/multiformats/src/interface.js");
// This way TS will also expose all the types from module
/***/ }),
/***/ "./node_modules/multiformats/src/interface.js":
/*!****************************************************!*\
!*** ./node_modules/multiformats/src/interface.js ***!
\****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
// this is dummy module overlayed by interface.ts
/***/ }),
/***/ "./node_modules/multiformats/src/link/interface.js":
/*!*********************************************************!*\
!*** ./node_modules/multiformats/src/link/interface.js ***!
\*********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
// this is dummy module overlayed by interface.ts
/***/ }),
/***/ "./node_modules/multiformats/src/varint.js":
/*!*************************************************!*\
!*** ./node_modules/multiformats/src/varint.js ***!
\*************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ encodeTo: () => (/* binding */ encodeTo),
/* harmony export */ encodingLength: () => (/* binding */ encodingLength)
/* harmony export */ });
/* harmony import */ var _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../vendor/varint.js */ "./node_modules/multiformats/vendor/varint.js");
/**
* @param {Uint8Array} data
* @param {number} [offset=0]
* @returns {[number, number]}
*/
const decode = (data, offset = 0) => {
const code = _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].decode(data, offset)
return [code, _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].decode.bytes]
}
/**
* @param {number} int
* @param {Uint8Array} target
* @param {number} [offset=0]
*/
const encodeTo = (int, target, offset = 0) => {
_vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].encode(int, target, offset)
return target
}
/**
* @param {number} int
* @returns {number}
*/
const encodingLength = (int) => {
return _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].encodingLength(int)
}
/***/ }),
/***/ "./node_modules/multiformats/vendor/base-x.js":
/*!****************************************************!*\
!*** ./node_modules/multiformats/vendor/base-x.js ***!
\****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
function base (ALPHABET, name) {
if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
var BASE_MAP = new Uint8Array(256);
for (var j = 0; j < BASE_MAP.length; j++) {
BASE_MAP[j] = 255;
}
for (var i = 0; i < ALPHABET.length; i++) {
var x = ALPHABET.charAt(i);
var xc = x.charCodeAt(0);
if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
BASE_MAP[xc] = i;
}
var BASE = ALPHABET.length;
var LEADER = ALPHABET.charAt(0);
var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
function encode (source) {
if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {
source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
} else if (Array.isArray(source)) {
source = Uint8Array.from(source);
}
if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }
if (source.length === 0) { return '' }
// Skip & count leading zeroes.
var zeroes = 0;
var length = 0;
var pbegin = 0;
var pend = source.length;
while (pbegin !== pend && source[pbegin] === 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
var b58 = new Uint8Array(size);
// Process the bytes.
while (pbegin !== pend) {
var carry = source[pbegin];
// Apply "b58 = b58 * 256 + ch".
var i = 0;
for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
carry += (256 * b58[it1]) >>> 0;
b58[it1] = (carry % BASE) >>> 0;
carry = (carry / BASE) >>> 0;
}
if (carry !== 0) { throw new Error('Non-zero carry') }
length = i;
pbegin++;
}
// Skip leading zeroes in base58 result.
var it2 = size - length;
while (it2 !== size && b58[it2] === 0) {
it2++;
}
// Translate the result into a string.
var str = LEADER.repeat(zeroes);
for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }
return str
}
function decodeUnsafe (source) {
if (typeof source !== 'string') { throw new TypeError('Expected String') }
if (source.length === 0) { return new Uint8Array() }
var psz = 0;
// Skip leading spaces.
if (source[psz] === ' ') { return }
// Skip and count leading '1's.
var zeroes = 0;
var length = 0;
while (source[psz] === LEADER) {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
var b256 = new Uint8Array(size);
// Process the characters.
while (source[psz]) {
// Decode character
var carry = BASE_MAP[source.charCodeAt(psz)];
// Invalid character
if (carry === 255) { return }
var i = 0;
for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
carry += (BASE * b256[it3]) >>> 0;
b256[it3] = (carry % 256) >>> 0;
carry = (carry / 256) >>> 0;
}
if (carry !== 0) { throw new Error('Non-zero carry') }
length = i;
psz++;
}
// Skip trailing spaces.
if (source[psz] === ' ') { return }
// Skip leading zeroes in b256.
var it4 = size - length;
while (it4 !== size && b256[it4] === 0) {
it4++;
}
var vch = new Uint8Array(zeroes + (size - it4));
var j = zeroes;
while (it4 !== size) {
vch[j++] = b256[it4++];
}
return vch
}
function decode (string) {
var buffer = decodeUnsafe(string);
if (buffer) { return buffer }
throw new Error(`Non-${name} character`)
}
return {
encode: encode,
decodeUnsafe: decodeUnsafe,
decode: decode
}
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp__multiformats_scope_baseX);
/***/ }),
/***/ "./node_modules/multiformats/vendor/varint.js":
/*!****************************************************!*\
!*** ./node_modules/multiformats/vendor/varint.js ***!
\****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
var encode_1 = encode;
var MSB = 0x80
, REST = 0x7F
, MSBALL = ~REST
, INT = Math.pow(2, 31);
function encode(num, out, offset) {
out = out || [];
offset = offset || 0;
var oldOffset = offset;
while(num >= INT) {
out[offset++] = (num & 0xFF) | MSB;
num /= 128;
}
while(num & MSBALL) {
out[offset++] = (num & 0xFF) | MSB;
num >>>= 7;
}
out[offset] = num | 0;
encode.bytes = offset - oldOffset + 1;
return out
}
var decode = read;
var MSB$1 = 0x80
, REST$1 = 0x7F;
function read(buf, offset) {
var res = 0
, offset = offset || 0
, shift = 0
, counter = offset
, b
, l = buf.length;
do {
if (counter >= l) {
read.bytes = 0;
throw new RangeError('Could not decode varint')
}
b = buf[counter++];
res += shift < 28
? (b & REST$1) << shift
: (b & REST$1) * Math.pow(2, shift);
shift += 7;
} while (b >= MSB$1)
read.bytes = counter - offset;
return res
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (value) {
return (
value < N1 ? 1
: value < N2 ? 2
: value < N3 ? 3
: value < N4 ? 4
: value < N5 ? 5
: value < N6 ? 6
: value < N7 ? 7
: value < N8 ? 8
: value < N9 ? 9
: 10
)
};
var varint = {
encode: encode_1
, decode: decode
, encodingLength: length
};
var _brrp_varint = varint;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp_varint);
/***/ }),
/***/ "./node_modules/p-defer/index.js":
/*!***************************************!*\
!*** ./node_modules/p-defer/index.js ***!
\***************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ pDefer)
/* harmony export */ });
function pDefer() {
const deferred = {};
deferred.promise = new Promise((resolve, reject) => {
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred;
}
/***/ }),
/***/ "./node_modules/p-queue/dist/index.js":
/*!********************************************!*\
!*** ./node_modules/p-queue/dist/index.js ***!
\********************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ PQueue)
/* harmony export */ });
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.mjs");
/* harmony import */ var p_timeout__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! p-timeout */ "./node_modules/p-timeout/index.js");
/* harmony import */ var _priority_queue_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./priority-queue.js */ "./node_modules/p-queue/dist/priority-queue.js");
/**
Promise queue with concurrency control.
*/
class PQueue extends eventemitter3__WEBPACK_IMPORTED_MODULE_0__.EventEmitter {
#carryoverConcurrencyCount;
#isIntervalIgnored;
#intervalCount = 0;
#intervalCap;
#interval;
#intervalEnd = 0;
#intervalId;
#timeoutId;
#queue;
#queueClass;
#pending = 0;
// The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194
#concurrency;
#isPaused;
#throwOnTimeout;
/**
Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.
Applies to each future operation.
*/
timeout;
// TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`
constructor(options) {
super();
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
options = {
carryoverConcurrencyCount: false,
intervalCap: Number.POSITIVE_INFINITY,
interval: 0,
concurrency: Number.POSITIVE_INFINITY,
autoStart: true,
queueClass: _priority_queue_js__WEBPACK_IMPORTED_MODULE_2__["default"],
...options,
};
if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {
throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${options.intervalCap?.toString() ?? ''}\` (${typeof options.intervalCap})`);
}
if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {
throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${options.interval?.toString() ?? ''}\` (${typeof options.interval})`);
}
this.#carryoverConcurrencyCount = options.carryoverConcurrencyCount;
this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;
this.#intervalCap = options.intervalCap;
this.#interval = options.interval;
this.#queue = new options.queueClass();
this.#queueClass = options.queueClass;
this.concurrency = options.concurrency;
this.timeout = options.timeout;
this.#throwOnTimeout = options.throwOnTimeout === true;
this.#isPaused = options.autoStart === false;
}
get #doesIntervalAllowAnother() {
return this.#isIntervalIgnored || this.#intervalCount < this.#intervalCap;
}
get #doesConcurrentAllowAnother() {
return this.#pending < this.#concurrency;
}
#next() {
this.#pending--;
this.#tryToStartAnother();
this.emit('next');
}
#onResumeInterval() {
this.#onInterval();
this.#initializeIntervalIfNeeded();
this.#timeoutId = undefined;
}
get #isIntervalPaused() {
const now = Date.now();
if (this.#intervalId === undefined) {
const delay = this.#intervalEnd - now;
if (delay < 0) {
// Act as the interval was done
// We don't need to resume it here because it will be resumed on line 160
this.#intervalCount = (this.#carryoverConcurrencyCount) ? this.#pending : 0;
}
else {
// Act as the interval is pending
if (this.#timeoutId === undefined) {
this.#timeoutId = setTimeout(() => {
this.#onResumeInterval();
}, delay);
}
return true;
}
}
return false;
}
#tryToStartAnother() {
if (this.#queue.size === 0) {
// We can clear the interval ("pause")
// Because we can redo it later ("resume")
if (this.#intervalId) {
clearInterval(this.#intervalId);
}
this.#intervalId = undefined;
this.emit('empty');
if (this.#pending === 0) {
this.emit('idle');
}
return false;
}
if (!this.#isPaused) {
const canInitializeInterval = !this.#isIntervalPaused;
if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {
const job = this.#queue.dequeue();
if (!job) {
return false;
}
this.emit('active');
job();
if (canInitializeInterval) {
this.#initializeIntervalIfNeeded();
}
return true;
}
}
return false;
}
#initializeIntervalIfNeeded() {
if (this.#isIntervalIgnored || this.#intervalId !== undefined) {
return;
}
this.#intervalId = setInterval(() => {
this.#onInterval();
}, this.#interval);
this.#intervalEnd = Date.now() + this.#interval;
}
#onInterval() {
if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {
clearInterval(this.#intervalId);
this.#intervalId = undefined;
}
this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;
this.#processQueue();
}
/**
Executes all queued functions until it reaches the limit.
*/
#processQueue() {
// eslint-disable-next-line no-empty
while (this.#tryToStartAnother()) { }
}
get concurrency() {
return this.#concurrency;
}
set concurrency(newConcurrency) {
if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {
throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`);
}
this.#concurrency = newConcurrency;
this.#processQueue();
}
async #throwOnAbort(signal) {
return new Promise((_resolve, reject) => {
signal.addEventListener('abort', () => {
reject(signal.reason);
}, { once: true });
});
}
async add(function_, options = {}) {
options = {
timeout: this.timeout,
throwOnTimeout: this.#throwOnTimeout,
...options,
};
return new Promise((resolve, reject) => {
this.#queue.enqueue(async () => {
this.#pending++;
this.#intervalCount++;
try {
options.signal?.throwIfAborted();
let operation = function_({ signal: options.signal });
if (options.timeout) {
operation = (0,p_timeout__WEBPACK_IMPORTED_MODULE_1__["default"])(Promise.resolve(operation), { milliseconds: options.timeout });
}
if (options.signal) {
operation = Promise.race([operation, this.#throwOnAbort(options.signal)]);
}
const result = await operation;
resolve(result);
this.emit('completed', result);
}
catch (error) {
if (error instanceof p_timeout__WEBPACK_IMPORTED_MODULE_1__.TimeoutError && !options.throwOnTimeout) {
resolve();
return;
}
reject(error);
this.emit('error', error);
}
finally {
this.#next();
}
}, options);
this.emit('add');
this.#tryToStartAnother();
});
}
async addAll(functions, options) {
return Promise.all(functions.map(async (function_) => this.add(function_, options)));
}
/**
Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)
*/
start() {
if (!this.#isPaused) {
return this;
}
this.#isPaused = false;
this.#processQueue();
return this;
}
/**
Put queue execution on hold.
*/
pause() {
this.#isPaused = true;
}
/**
Clear the queue.
*/
clear() {
this.#queue = new this.#queueClass();
}
/**
Can be called multiple times. Useful if you for example add additional items at a later time.
@returns A promise that settles when the queue becomes empty.
*/
async onEmpty() {
// Instantly resolve if the queue is empty
if (this.#queue.size === 0) {
return;
}
await this.#onEvent('empty');
}
/**
@returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.
If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.
Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.
*/
async onSizeLessThan(limit) {
// Instantly resolve if the queue is empty.
if (this.#queue.size < limit) {
return;
}
await this.#onEvent('next', () => this.#queue.size < limit);
}
/**
The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
@returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.
*/
async onIdle() {
// Instantly resolve if none pending and if nothing else is queued
if (this.#pending === 0 && this.#queue.size === 0) {
return;
}
await this.#onEvent('idle');
}
async #onEvent(event, filter) {
return new Promise(resolve => {
const listener = () => {
if (filter && !filter()) {
return;
}
this.off(event, listener);
resolve();
};
this.on(event, listener);
});
}
/**
Size of the queue, the number of queued items waiting to run.
*/
get size() {
return this.#queue.size;
}
/**
Size of the queue, filtered by the given options.
For example, this can be used to find the number of items remaining in the queue with a specific priority level.
*/
sizeBy(options) {
// eslint-disable-next-line unicorn/no-array-callback-reference
return this.#queue.filter(options).length;
}
/**
Number of running items (no longer in the queue).
*/
get pending() {
return this.#pending;
}
/**
Whether the queue is currently paused.
*/
get isPaused() {
return this.#isPaused;
}
}
/***/ }),
/***/ "./node_modules/p-queue/dist/lower-bound.js":
/*!**************************************************!*\
!*** ./node_modules/p-queue/dist/lower-bound.js ***!
\**************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ lowerBound)
/* harmony export */ });
// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound
// Used to compute insertion index to keep queue sorted after insertion
function lowerBound(array, value, comparator) {
let first = 0;
let count = array.length;
while (count > 0) {
const step = Math.trunc(count / 2);
let it = first + step;
if (comparator(array[it], value) <= 0) {
first = ++it;
count -= step + 1;
}
else {
count = step;
}
}
return first;
}
/***/ }),
/***/ "./node_modules/p-queue/dist/priority-queue.js":
/*!*****************************************************!*\
!*** ./node_modules/p-queue/dist/priority-queue.js ***!
\*****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ PriorityQueue)
/* harmony export */ });
/* harmony import */ var _lower_bound_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./lower-bound.js */ "./node_modules/p-queue/dist/lower-bound.js");
class PriorityQueue {
#queue = [];
enqueue(run, options) {
options = {
priority: 0,
...options,
};
const element = {
priority: options.priority,
run,
};
if (this.size && this.#queue[this.size - 1].priority >= options.priority) {
this.#queue.push(element);
return;
}
const index = (0,_lower_bound_js__WEBPACK_IMPORTED_MODULE_0__["default"])(this.#queue, element, (a, b) => b.priority - a.priority);
this.#queue.splice(index, 0, element);
}
dequeue() {
const item = this.#queue.shift();
return item?.run;
}
filter(options) {
return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run);
}
get size() {
return this.#queue.length;
}
}
/***/ }),
/***/ "./node_modules/p-timeout/index.js":
/*!*****************************************!*\
!*** ./node_modules/p-timeout/index.js ***!
\*****************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AbortError: () => (/* binding */ AbortError),
/* harmony export */ TimeoutError: () => (/* binding */ TimeoutError),
/* harmony export */ "default": () => (/* binding */ pTimeout)
/* harmony export */ });
class TimeoutError extends Error {
constructor(message) {
super(message);
this.name = 'TimeoutError';
}
}
/**
An error to be thrown when the request is aborted by AbortController.
DOMException is thrown instead of this Error when DOMException is available.
*/
class AbortError extends Error {
constructor(message) {
super();
this.name = 'AbortError';
this.message = message;
}
}
/**
TODO: Remove AbortError and just throw DOMException when targeting Node 18.
*/
const getDOMException = errorMessage => globalThis.DOMException === undefined
? new AbortError(errorMessage)
: new DOMException(errorMessage);
/**
TODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.
*/
const getAbortedReason = signal => {
const reason = signal.reason === undefined
? getDOMException('This operation was aborted.')
: signal.reason;
return reason instanceof Error ? reason : getDOMException(reason);
};
function pTimeout(promise, options) {
const {
milliseconds,
fallback,
message,
customTimers = {setTimeout, clearTimeout},
} = options;
let timer;
const wrappedPromise = new Promise((resolve, reject) => {
if (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {
throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
}
if (options.signal) {
const {signal} = options;
if (signal.aborted) {
reject(getAbortedReason(signal));
}
signal.addEventListener('abort', () => {
reject(getAbortedReason(signal));
});
}
if (milliseconds === Number.POSITIVE_INFINITY) {
promise.then(resolve, reject);
return;
}
// We create the error outside of `setTimeout` to preserve the stack trace.
const timeoutError = new TimeoutError();
timer = customTimers.setTimeout.call(undefined, () => {
if (fallback) {
try {
resolve(fallback());
} catch (error) {
reject(error);
}
return;
}
if (typeof promise.cancel === 'function') {
promise.cancel();
}
if (message === false) {
resolve();
} else if (message instanceof Error) {
reject(message);
} else {
timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;
reject(timeoutError);
}
}, milliseconds);
(async () => {
try {
resolve(await promise);
} catch (error) {
reject(error);
}
})();
});
const cancelablePromise = wrappedPromise.finally(() => {
cancelablePromise.clear();
});
cancelablePromise.clear = () => {
customTimers.clearTimeout.call(undefined, timer);
timer = undefined;
};
return cancelablePromise;
}
/***/ }),
/***/ "./node_modules/protons-runtime/dist/src/codec.js":
/*!********************************************************!*\
!*** ./node_modules/protons-runtime/dist/src/codec.js ***!
\********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CODEC_TYPES: () => (/* binding */ CODEC_TYPES),
/* harmony export */ createCodec: () => (/* binding */ createCodec)
/* harmony export */ });
// https://developers.google.com/protocol-buffers/docs/encoding#structure
var CODEC_TYPES;
(function (CODEC_TYPES) {
CODEC_TYPES[CODEC_TYPES["VARINT"] = 0] = "VARINT";
CODEC_TYPES[CODEC_TYPES["BIT64"] = 1] = "BIT64";
CODEC_TYPES[CODEC_TYPES["LENGTH_DELIMITED"] = 2] = "LENGTH_DELIMITED";
CODEC_TYPES[CODEC_TYPES["START_GROUP"] = 3] = "START_GROUP";
CODEC_TYPES[CODEC_TYPES["END_GROUP"] = 4] = "END_GROUP";
CODEC_TYPES[CODEC_TYPES["BIT32"] = 5] = "BIT32";
})(CODEC_TYPES || (CODEC_TYPES = {}));
function createCodec(name, type, encode, decode) {
return {
name,
type,
encode,
decode
};
}
//# sourceMappingURL=codec.js.map
/***/ }),
/***/ "./node_modules/protons-runtime/dist/src/codecs/enum.js":
/*!**************************************************************!*\
!*** ./node_modules/protons-runtime/dist/src/codecs/enum.js ***!
\**************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ enumeration: () => (/* binding */ enumeration)
/* harmony export */ });
/* harmony import */ var _codec_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../codec.js */ "./node_modules/protons-runtime/dist/src/codec.js");
function enumeration(v) {
function findValue(val) {
// Use the reverse mapping to look up the enum key for the stored value
// https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings
if (v[val.toString()] == null) {
throw new Error('Invalid enum value');
}
return v[val];
}
const encode = function enumEncode(val, writer) {
const enumValue = findValue(val);
writer.int32(enumValue);
};
const decode = function enumDecode(reader) {
const val = reader.int32();
return findValue(val);
};
// @ts-expect-error yeah yeah
return (0,_codec_js__WEBPACK_IMPORTED_MODULE_0__.createCodec)('enum', _codec_js__WEBPACK_IMPORTED_MODULE_0__.CODEC_TYPES.VARINT, encode, decode);
}
//# sourceMappingURL=enum.js.map
/***/ }),
/***/ "./node_modules/protons-runtime/dist/src/codecs/message.js":
/*!*****************************************************************!*\
!*** ./node_modules/protons-runtime/dist/src/codecs/message.js ***!
\*****************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ message: () => (/* binding */ message)
/* harmony export */ });
/* harmony import */ var _codec_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../codec.js */ "./node_modules/protons-runtime/dist/src/codec.js");
function message(encode, decode) {
return (0,_codec_js__WEBPACK_IMPORTED_MODULE_0__.createCodec)('message', _codec_js__WEBPACK_IMPORTED_MODULE_0__.CODEC_TYPES.LENGTH_DELIMITED, encode, decode);
}
//# sourceMappingURL=message.js.map
/***/ }),
/***/ "./node_modules/protons-runtime/dist/src/decode.js":
/*!*********************************************************!*\
!*** ./node_modules/protons-runtime/dist/src/decode.js ***!
\*********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decodeMessage: () => (/* binding */ decodeMessage)
/* harmony export */ });
/* harmony import */ var _utils_reader_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/reader.js */ "./node_modules/protons-runtime/dist/src/utils/reader.js");
function decodeMessage(buf, codec, opts) {
const reader = (0,_utils_reader_js__WEBPACK_IMPORTED_MODULE_0__.createReader)(buf);
return codec.decode(reader, undefined, opts);
}
//# sourceMappingURL=decode.js.map
/***/ }),
/***/ "./node_modules/protons-runtime/dist/src/encode.js":
/*!*********************************************************!*\
!*** ./node_modules/protons-runtime/dist/src/encode.js ***!
\*********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ encodeMessage: () => (/* binding */ encodeMessage)
/* harmony export */ });
/* harmony import */ var _utils_writer_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/writer.js */ "./node_modules/protons-runtime/dist/src/utils/writer.js");
function encodeMessage(message, codec) {
const w = (0,_utils_writer_js__WEBPACK_IMPORTED_MODULE_0__.createWriter)();
codec.encode(message, w, {
lengthDelimited: false
});
return w.finish();
}
//# sourceMappingURL=encode.js.map
/***/ }),
/***/ "./node_modules/protons-runtime/dist/src/index.js":
/*!********************************************************!*\
!*** ./node_modules/protons-runtime/dist/src/index.js ***!
\********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CodeError: () => (/* binding */ CodeError),
/* harmony export */ MaxLengthError: () => (/* binding */ MaxLengthError),
/* harmony export */ MaxSizeError: () => (/* binding */ MaxSizeError),
/* harmony export */ NoMessagesFoundError: () => (/* binding */ NoMessagesFoundError),
/* harmony export */ ParseError: () => (/* binding */ ParseError),
/* harmony export */ decodeMessage: () => (/* reexport safe */ _decode_js__WEBPACK_IMPORTED_MODULE_0__.decodeMessage),
/* harmony export */ encodeMessage: () => (/* reexport safe */ _encode_js__WEBPACK_IMPORTED_MODULE_1__.encodeMessage),
/* harmony export */ enumeration: () => (/* reexport safe */ _codecs_enum_js__WEBPACK_IMPORTED_MODULE_2__.enumeration),
/* harmony export */ message: () => (/* reexport safe */ _codecs_message_js__WEBPACK_IMPORTED_MODULE_3__.message),
/* harmony export */ reader: () => (/* reexport safe */ _utils_reader_js__WEBPACK_IMPORTED_MODULE_4__.createReader),
/* harmony export */ writer: () => (/* reexport safe */ _utils_writer_js__WEBPACK_IMPORTED_MODULE_5__.createWriter)
/* harmony export */ });
/* harmony import */ var _decode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./decode.js */ "./node_modules/protons-runtime/dist/src/decode.js");
/* harmony import */ var _encode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./encode.js */ "./node_modules/protons-runtime/dist/src/encode.js");
/* harmony import */ var _codecs_enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./codecs/enum.js */ "./node_modules/protons-runtime/dist/src/codecs/enum.js");
/* harmony import */ var _codecs_message_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./codecs/message.js */ "./node_modules/protons-runtime/dist/src/codecs/message.js");
/* harmony import */ var _utils_reader_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/reader.js */ "./node_modules/protons-runtime/dist/src/utils/reader.js");
/* harmony import */ var _utils_writer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/writer.js */ "./node_modules/protons-runtime/dist/src/utils/writer.js");
/**
* @packageDocumentation
*
* This module contains serialization/deserialization code used when encoding/decoding protobufs.
*
* It should be declared as a dependency of your project:
*
* ```console
* npm i protons-runtime
* ```
*/
/**
* This will be removed in a future release
*
* @deprecated
*/
class CodeError extends Error {
code;
constructor(message, code) {
super(message);
this.code = code;
}
}
/**
* Thrown when a repeated field has too many elements
*/
class MaxLengthError extends Error {
/**
* This will be removed in a future release
*
* @deprecated use the `.name` property instead
*/
code = 'ERR_MAX_LENGTH';
name = 'MaxLengthError';
}
/**
* Thrown when a map has too many elements
*/
class MaxSizeError extends Error {
/**
* This will be removed in a future release
*
* @deprecated use the `.name` property instead
*/
code = 'ERR_MAX_SIZE';
name = 'MaxSizeError';
}
class ParseError extends Error {
/**
* This will be removed in a future release
*
* @deprecated use the `.name` property instead
*/
code = 'ERR_PARSE_ERROR';
name = 'ParseError';
}
class NoMessagesFoundError extends Error {
/**
* This will be removed in a future release
*
* @deprecated use the `.name` property instead
*/
code = 'ERR_NO_MESSAGES_FOUND';
name = 'NoMessagesFoundError';
}
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "./node_modules/protons-runtime/dist/src/utils/float.js":
/*!**************************************************************!*\
!*** ./node_modules/protons-runtime/dist/src/utils/float.js ***!
\**************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ readDoubleBE: () => (/* binding */ readDoubleBE),
/* harmony export */ readDoubleLE: () => (/* binding */ readDoubleLE),
/* harmony export */ readFloatBE: () => (/* binding */ readFloatBE),
/* harmony export */ readFloatLE: () => (/* binding */ readFloatLE),
/* harmony export */ writeDoubleBE: () => (/* binding */ writeDoubleBE),
/* harmony export */ writeDoubleLE: () => (/* binding */ writeDoubleLE),
/* harmony export */ writeFloatBE: () => (/* binding */ writeFloatBE),
/* harmony export */ writeFloatLE: () => (/* binding */ writeFloatLE)
/* harmony export */ });
const f32 = new Float32Array([-0]);
const f8b = new Uint8Array(f32.buffer);
/**
* Writes a 32 bit float to a buffer using little endian byte order
*/
function writeFloatLE(val, buf, pos) {
f32[0] = val;
buf[pos] = f8b[0];
buf[pos + 1] = f8b[1];
buf[pos + 2] = f8b[2];
buf[pos + 3] = f8b[3];
}
/**
* Writes a 32 bit float to a buffer using big endian byte order
*/
function writeFloatBE(val, buf, pos) {
f32[0] = val;
buf[pos] = f8b[3];
buf[pos + 1] = f8b[2];
buf[pos + 2] = f8b[1];
buf[pos + 3] = f8b[0];
}
/**
* Reads a 32 bit float from a buffer using little endian byte order
*/
function readFloatLE(buf, pos) {
f8b[0] = buf[pos];
f8b[1] = buf[pos + 1];
f8b[2] = buf[pos + 2];
f8b[3] = buf[pos + 3];
return f32[0];
}
/**
* Reads a 32 bit float from a buffer using big endian byte order
*/
function readFloatBE(buf, pos) {
f8b[3] = buf[pos];
f8b[2] = buf[pos + 1];
f8b[1] = buf[pos + 2];
f8b[0] = buf[pos + 3];
return f32[0];
}
const f64 = new Float64Array([-0]);
const d8b = new Uint8Array(f64.buffer);
/**
* Writes a 64 bit double to a buffer using little endian byte order
*/
function writeDoubleLE(val, buf, pos) {
f64[0] = val;
buf[pos] = d8b[0];
buf[pos + 1] = d8b[1];
buf[pos + 2] = d8b[2];
buf[pos + 3] = d8b[3];
buf[pos + 4] = d8b[4];
buf[pos + 5] = d8b[5];
buf[pos + 6] = d8b[6];
buf[pos + 7] = d8b[7];
}
/**
* Writes a 64 bit double to a buffer using big endian byte order
*/
function writeDoubleBE(val, buf, pos) {
f64[0] = val;
buf[pos] = d8b[7];
buf[pos + 1] = d8b[6];
buf[pos + 2] = d8b[5];
buf[pos + 3] = d8b[4];
buf[pos + 4] = d8b[3];
buf[pos + 5] = d8b[2];
buf[pos + 6] = d8b[1];
buf[pos + 7] = d8b[0];
}
/**
* Reads a 64 bit double from a buffer using little endian byte order
*/
function readDoubleLE(buf, pos) {
d8b[0] = buf[pos];
d8b[1] = buf[pos + 1];
d8b[2] = buf[pos + 2];
d8b[3] = buf[pos + 3];
d8b[4] = buf[pos + 4];
d8b[5] = buf[pos + 5];
d8b[6] = buf[pos + 6];
d8b[7] = buf[pos + 7];
return f64[0];
}
/**
* Reads a 64 bit double from a buffer using big endian byte order
*/
function readDoubleBE(buf, pos) {
d8b[7] = buf[pos];
d8b[6] = buf[pos + 1];
d8b[5] = buf[pos + 2];
d8b[4] = buf[pos + 3];
d8b[3] = buf[pos + 4];
d8b[2] = buf[pos + 5];
d8b[1] = buf[pos + 6];
d8b[0] = buf[pos + 7];
return f64[0];
}
//# sourceMappingURL=float.js.map
/***/ }),
/***/ "./node_modules/protons-runtime/dist/src/utils/longbits.js":
/*!*****************************************************************!*\
!*** ./node_modules/protons-runtime/dist/src/utils/longbits.js ***!
\*****************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ LongBits: () => (/* binding */ LongBits)
/* harmony export */ });
// the largest BigInt we can safely downcast to a Number
const MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);
const MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER);
/**
* Constructs new long bits.
*
* @classdesc Helper class for working with the low and high bits of a 64 bit value.
* @memberof util
* @function Object() { [native code] }
* @param {number} lo - Low 32 bits, unsigned
* @param {number} hi - High 32 bits, unsigned
*/
class LongBits {
lo;
hi;
constructor(lo, hi) {
// note that the casts below are theoretically unnecessary as of today, but older statically
// generated converter code might still call the ctor with signed 32bits. kept for compat.
/**
* Low bits
*/
this.lo = lo | 0;
/**
* High bits
*/
this.hi = hi | 0;
}
/**
* Converts this long bits to a possibly unsafe JavaScript number
*/
toNumber(unsigned = false) {
if (!unsigned && (this.hi >>> 31) > 0) {
const lo = ~this.lo + 1 >>> 0;
let hi = ~this.hi >>> 0;
if (lo === 0) {
hi = hi + 1 >>> 0;
}
return -(lo + hi * 4294967296);
}
return this.lo + this.hi * 4294967296;
}
/**
* Converts this long bits to a bigint
*/
toBigInt(unsigned = false) {
if (unsigned) {
return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);
}
if ((this.hi >>> 31) !== 0) {
const lo = ~this.lo + 1 >>> 0;
let hi = ~this.hi >>> 0;
if (lo === 0) {
hi = hi + 1 >>> 0;
}
return -(BigInt(lo) + (BigInt(hi) << 32n));
}
return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);
}
/**
* Converts this long bits to a string
*/
toString(unsigned = false) {
return this.toBigInt(unsigned).toString();
}
/**
* Zig-zag encodes this long bits
*/
zzEncode() {
const mask = this.hi >> 31;
this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
this.lo = (this.lo << 1 ^ mask) >>> 0;
return this;
}
/**
* Zig-zag decodes this long bits
*/
zzDecode() {
const mask = -(this.lo & 1);
this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
this.hi = (this.hi >>> 1 ^ mask) >>> 0;
return this;
}
/**
* Calculates the length of this longbits when encoded as a varint.
*/
length() {
const part0 = this.lo;
const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0;
const part2 = this.hi >>> 24;
return part2 === 0
? part1 === 0
? part0 < 16384
? part0 < 128 ? 1 : 2
: part0 < 2097152 ? 3 : 4
: part1 < 16384
? part1 < 128 ? 5 : 6
: part1 < 2097152 ? 7 : 8
: part2 < 128 ? 9 : 10;
}
/**
* Constructs new long bits from the specified number
*/
static fromBigInt(value) {
if (value === 0n) {
return zero;
}
if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {
return this.fromNumber(Number(value));
}
const negative = value < 0n;
if (negative) {
value = -value;
}
let hi = value >> 32n;
let lo = value - (hi << 32n);
if (negative) {
hi = ~hi | 0n;
lo = ~lo | 0n;
if (++lo > TWO_32) {
lo = 0n;
if (++hi > TWO_32) {
hi = 0n;
}
}
}
return new LongBits(Number(lo), Number(hi));
}
/**
* Constructs new long bits from the specified number
*/
static fromNumber(value) {
if (value === 0) {
return zero;
}
const sign = value < 0;
if (sign) {
value = -value;
}
let lo = value >>> 0;
let hi = (value - lo) / 4294967296 >>> 0;
if (sign) {
hi = ~hi >>> 0;
lo = ~lo >>> 0;
if (++lo > 4294967295) {
lo = 0;
if (++hi > 4294967295) {
hi = 0;
}
}
}
return new LongBits(lo, hi);
}
/**
* Constructs new long bits from a number, long or string
*/
static from(value) {
if (typeof value === 'number') {
return LongBits.fromNumber(value);
}
if (typeof value === 'bigint') {
return LongBits.fromBigInt(value);
}
if (typeof value === 'string') {
return LongBits.fromBigInt(BigInt(value));
}
return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
}
}
const zero = new LongBits(0, 0);
zero.toBigInt = function () { return 0n; };
zero.zzEncode = zero.zzDecode = function () { return this; };
zero.length = function () { return 1; };
const TWO_32 = 4294967296n;
//# sourceMappingURL=longbits.js.map
/***/ }),
/***/ "./node_modules/protons-runtime/dist/src/utils/pool.js":
/*!*************************************************************!*\
!*** ./node_modules/protons-runtime/dist/src/utils/pool.js ***!
\*************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ pool)
/* harmony export */ });
/* harmony import */ var uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/alloc */ "./node_modules/uint8arrays/dist/src/alloc.js");
/**
* A general purpose buffer pool
*/
function pool(size) {
const SIZE = size ?? 8192;
const MAX = SIZE >>> 1;
let slab;
let offset = SIZE;
return function poolAlloc(size) {
if (size < 1 || size > MAX) {
return (0,uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_0__.allocUnsafe)(size);
}
if (offset + size > SIZE) {
slab = (0,uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_0__.allocUnsafe)(SIZE);
offset = 0;
}
const buf = slab.subarray(offset, offset += size);
if ((offset & 7) !== 0) {
// align to 32 bit
offset = (offset | 7) + 1;
}
return buf;
};
}
//# sourceMappingURL=pool.js.map
/***/ }),
/***/ "./node_modules/protons-runtime/dist/src/utils/reader.js":
/*!***************************************************************!*\
!*** ./node_modules/protons-runtime/dist/src/utils/reader.js ***!
\***************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Uint8ArrayReader: () => (/* binding */ Uint8ArrayReader),
/* harmony export */ createReader: () => (/* binding */ createReader)
/* harmony export */ });
/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8-varint */ "./node_modules/uint8-varint/dist/src/index.js");
/* harmony import */ var _float_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./float.js */ "./node_modules/protons-runtime/dist/src/utils/float.js");
/* harmony import */ var _longbits_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./longbits.js */ "./node_modules/protons-runtime/dist/src/utils/longbits.js");
/* harmony import */ var _utf8_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utf8.js */ "./node_modules/protons-runtime/dist/src/utils/utf8.js");
/* istanbul ignore next */
function indexOutOfRange(reader, writeLength) {
return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`);
}
function readFixed32End(buf, end) {
return (buf[end - 4] |
buf[end - 3] << 8 |
buf[end - 2] << 16 |
buf[end - 1] << 24) >>> 0;
}
/**
* Constructs a new reader instance using the specified buffer.
*/
class Uint8ArrayReader {
buf;
pos;
len;
_slice = Uint8Array.prototype.subarray;
constructor(buffer) {
/**
* Read buffer
*/
this.buf = buffer;
/**
* Read buffer position
*/
this.pos = 0;
/**
* Read buffer length
*/
this.len = buffer.length;
}
/**
* Reads a varint as an unsigned 32 bit value
*/
uint32() {
let value = 4294967295;
value = (this.buf[this.pos] & 127) >>> 0;
if (this.buf[this.pos++] < 128)
return value;
value = (value | (this.buf[this.pos] & 127) << 7) >>> 0;
if (this.buf[this.pos++] < 128)
return value;
value = (value | (this.buf[this.pos] & 127) << 14) >>> 0;
if (this.buf[this.pos++] < 128)
return value;
value = (value | (this.buf[this.pos] & 127) << 21) >>> 0;
if (this.buf[this.pos++] < 128)
return value;
value = (value | (this.buf[this.pos] & 15) << 28) >>> 0;
if (this.buf[this.pos++] < 128)
return value;
if ((this.pos += 5) > this.len) {
this.pos = this.len;
throw indexOutOfRange(this, 10);
}
return value;
}
/**
* Reads a varint as a signed 32 bit value
*/
int32() {
return this.uint32() | 0;
}
/**
* Reads a zig-zag encoded varint as a signed 32 bit value
*/
sint32() {
const value = this.uint32();
return value >>> 1 ^ -(value & 1) | 0;
}
/**
* Reads a varint as a boolean
*/
bool() {
return this.uint32() !== 0;
}
/**
* Reads fixed 32 bits as an unsigned 32 bit integer
*/
fixed32() {
if (this.pos + 4 > this.len) {
throw indexOutOfRange(this, 4);
}
const res = readFixed32End(this.buf, this.pos += 4);
return res;
}
/**
* Reads fixed 32 bits as a signed 32 bit integer
*/
sfixed32() {
if (this.pos + 4 > this.len) {
throw indexOutOfRange(this, 4);
}
const res = readFixed32End(this.buf, this.pos += 4) | 0;
return res;
}
/**
* Reads a float (32 bit) as a number
*/
float() {
if (this.pos + 4 > this.len) {
throw indexOutOfRange(this, 4);
}
const value = (0,_float_js__WEBPACK_IMPORTED_MODULE_1__.readFloatLE)(this.buf, this.pos);
this.pos += 4;
return value;
}
/**
* Reads a double (64 bit float) as a number
*/
double() {
/* istanbul ignore if */
if (this.pos + 8 > this.len) {
throw indexOutOfRange(this, 4);
}
const value = (0,_float_js__WEBPACK_IMPORTED_MODULE_1__.readDoubleLE)(this.buf, this.pos);
this.pos += 8;
return value;
}
/**
* Reads a sequence of bytes preceded by its length as a varint
*/
bytes() {
const length = this.uint32();
const start = this.pos;
const end = this.pos + length;
/* istanbul ignore if */
if (end > this.len) {
throw indexOutOfRange(this, length);
}
this.pos += length;
return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1
? new Uint8Array(0)
: this.buf.subarray(start, end);
}
/**
* Reads a string preceded by its byte length as a varint
*/
string() {
const bytes = this.bytes();
return _utf8_js__WEBPACK_IMPORTED_MODULE_3__.read(bytes, 0, bytes.length);
}
/**
* Skips the specified number of bytes if specified, otherwise skips a varint
*/
skip(length) {
if (typeof length === 'number') {
/* istanbul ignore if */
if (this.pos + length > this.len) {
throw indexOutOfRange(this, length);
}
this.pos += length;
}
else {
do {
/* istanbul ignore if */
if (this.pos >= this.len) {
throw indexOutOfRange(this);
}
} while ((this.buf[this.pos++] & 128) !== 0);
}
return this;
}
/**
* Skips the next element of the specified wire type
*/
skipType(wireType) {
switch (wireType) {
case 0:
this.skip();
break;
case 1:
this.skip(8);
break;
case 2:
this.skip(this.uint32());
break;
case 3:
while ((wireType = this.uint32() & 7) !== 4) {
this.skipType(wireType);
}
break;
case 5:
this.skip(4);
break;
/* istanbul ignore next */
default:
throw Error(`invalid wire type ${wireType} at offset ${this.pos}`);
}
return this;
}
readLongVarint() {
// tends to deopt with local vars for octet etc.
const bits = new _longbits_js__WEBPACK_IMPORTED_MODULE_2__.LongBits(0, 0);
let i = 0;
if (this.len - this.pos > 4) { // fast route (lo)
for (; i < 4; ++i) {
// 1st..4th
bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
if (this.buf[this.pos++] < 128) {
return bits;
}
}
// 5th
bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
if (this.buf[this.pos++] < 128) {
return bits;
}
i = 0;
}
else {
for (; i < 3; ++i) {
/* istanbul ignore if */
if (this.pos >= this.len) {
throw indexOutOfRange(this);
}
// 1st..3th
bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
if (this.buf[this.pos++] < 128) {
return bits;
}
}
// 4th
bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
return bits;
}
if (this.len - this.pos > 4) { // fast route (hi)
for (; i < 5; ++i) {
// 6th..10th
bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
if (this.buf[this.pos++] < 128) {
return bits;
}
}
}
else {
for (; i < 5; ++i) {
if (this.pos >= this.len) {
throw indexOutOfRange(this);
}
// 6th..10th
bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
if (this.buf[this.pos++] < 128) {
return bits;
}
}
}
throw Error('invalid varint encoding');
}
readFixed64() {
if (this.pos + 8 > this.len) {
throw indexOutOfRange(this, 8);
}
const lo = readFixed32End(this.buf, this.pos += 4);
const hi = readFixed32End(this.buf, this.pos += 4);
return new _longbits_js__WEBPACK_IMPORTED_MODULE_2__.LongBits(lo, hi);
}
/**
* Reads a varint as a signed 64 bit value
*/
int64() {
return this.readLongVarint().toBigInt();
}
/**
* Reads a varint as a signed 64 bit value returned as a possibly unsafe
* JavaScript number
*/
int64Number() {
return this.readLongVarint().toNumber();
}
/**
* Reads a varint as a signed 64 bit value returned as a string
*/
int64String() {
return this.readLongVarint().toString();
}
/**
* Reads a varint as an unsigned 64 bit value
*/
uint64() {
return this.readLongVarint().toBigInt(true);
}
/**
* Reads a varint as an unsigned 64 bit value returned as a possibly unsafe
* JavaScript number
*/
uint64Number() {
const value = (0,uint8_varint__WEBPACK_IMPORTED_MODULE_0__.decodeUint8Array)(this.buf, this.pos);
this.pos += (0,uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encodingLength)(value);
return value;
}
/**
* Reads a varint as an unsigned 64 bit value returned as a string
*/
uint64String() {
return this.readLongVarint().toString(true);
}
/**
* Reads a zig-zag encoded varint as a signed 64 bit value
*/
sint64() {
return this.readLongVarint().zzDecode().toBigInt();
}
/**
* Reads a zig-zag encoded varint as a signed 64 bit value returned as a
* possibly unsafe JavaScript number
*/
sint64Number() {
return this.readLongVarint().zzDecode().toNumber();
}
/**
* Reads a zig-zag encoded varint as a signed 64 bit value returned as a
* string
*/
sint64String() {
return this.readLongVarint().zzDecode().toString();
}
/**
* Reads fixed 64 bits
*/
fixed64() {
return this.readFixed64().toBigInt();
}
/**
* Reads fixed 64 bits returned as a possibly unsafe JavaScript number
*/
fixed64Number() {
return this.readFixed64().toNumber();
}
/**
* Reads fixed 64 bits returned as a string
*/
fixed64String() {
return this.readFixed64().toString();
}
/**
* Reads zig-zag encoded fixed 64 bits
*/
sfixed64() {
return this.readFixed64().toBigInt();
}
/**
* Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe
* JavaScript number
*/
sfixed64Number() {
return this.readFixed64().toNumber();
}
/**
* Reads zig-zag encoded fixed 64 bits returned as a string
*/
sfixed64String() {
return this.readFixed64().toString();
}
}
function createReader(buf) {
return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray());
}
//# sourceMappingURL=reader.js.map
/***/ }),
/***/ "./node_modules/protons-runtime/dist/src/utils/utf8.js":
/*!*************************************************************!*\
!*** ./node_modules/protons-runtime/dist/src/utils/utf8.js ***!
\*************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ length: () => (/* binding */ length),
/* harmony export */ read: () => (/* binding */ read),
/* harmony export */ write: () => (/* binding */ write)
/* harmony export */ });
/**
* Calculates the UTF8 byte length of a string
*/
function length(string) {
let len = 0;
let c = 0;
for (let i = 0; i < string.length; ++i) {
c = string.charCodeAt(i);
if (c < 128) {
len += 1;
}
else if (c < 2048) {
len += 2;
}
else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
++i;
len += 4;
}
else {
len += 3;
}
}
return len;
}
/**
* Reads UTF8 bytes as a string
*/
function read(buffer, start, end) {
const len = end - start;
if (len < 1) {
return '';
}
let parts;
const chunk = [];
let i = 0; // char offset
let t; // temporary
while (start < end) {
t = buffer[start++];
if (t < 128) {
chunk[i++] = t;
}
else if (t > 191 && t < 224) {
chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;
}
else if (t > 239 && t < 365) {
t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;
chunk[i++] = 0xD800 + (t >> 10);
chunk[i++] = 0xDC00 + (t & 1023);
}
else {
chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
}
if (i > 8191) {
(parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk));
i = 0;
}
}
if (parts != null) {
if (i > 0) {
parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
}
return parts.join('');
}
return String.fromCharCode.apply(String, chunk.slice(0, i));
}
/**
* Writes a string as UTF8 bytes
*/
function write(string, buffer, offset) {
const start = offset;
let c1; // character 1
let c2; // character 2
for (let i = 0; i < string.length; ++i) {
c1 = string.charCodeAt(i);
if (c1 < 128) {
buffer[offset++] = c1;
}
else if (c1 < 2048) {
buffer[offset++] = c1 >> 6 | 192;
buffer[offset++] = c1 & 63 | 128;
}
else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
++i;
buffer[offset++] = c1 >> 18 | 240;
buffer[offset++] = c1 >> 12 & 63 | 128;
buffer[offset++] = c1 >> 6 & 63 | 128;
buffer[offset++] = c1 & 63 | 128;
}
else {
buffer[offset++] = c1 >> 12 | 224;
buffer[offset++] = c1 >> 6 & 63 | 128;
buffer[offset++] = c1 & 63 | 128;
}
}
return offset - start;
}
//# sourceMappingURL=utf8.js.map
/***/ }),
/***/ "./node_modules/protons-runtime/dist/src/utils/writer.js":
/*!***************************************************************!*\
!*** ./node_modules/protons-runtime/dist/src/utils/writer.js ***!
\***************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ createWriter: () => (/* binding */ createWriter)
/* harmony export */ });
/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8-varint */ "./node_modules/uint8-varint/dist/src/index.js");
/* harmony import */ var uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/alloc */ "./node_modules/uint8arrays/dist/src/alloc.js");
/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/from-string */ "./node_modules/uint8arrays/dist/src/from-string.js");
/* harmony import */ var _float_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./float.js */ "./node_modules/protons-runtime/dist/src/utils/float.js");
/* harmony import */ var _longbits_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./longbits.js */ "./node_modules/protons-runtime/dist/src/utils/longbits.js");
/* harmony import */ var _pool_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./pool.js */ "./node_modules/protons-runtime/dist/src/utils/pool.js");
/* harmony import */ var _utf8_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utf8.js */ "./node_modules/protons-runtime/dist/src/utils/utf8.js");
/**
* Constructs a new writer operation instance.
*
* @classdesc Scheduled writer operation
*/
class Op {
/**
* Function to call
*/
fn;
/**
* Value byte length
*/
len;
/**
* Next operation
*/
next;
/**
* Value to write
*/
val;
constructor(fn, len, val) {
this.fn = fn;
this.len = len;
this.next = undefined;
this.val = val; // type varies
}
}
/* istanbul ignore next */
function noop() { } // eslint-disable-line no-empty-function
/**
* Constructs a new writer state instance
*/
class State {
/**
* Current head
*/
head;
/**
* Current tail
*/
tail;
/**
* Current buffer length
*/
len;
/**
* Next state
*/
next;
constructor(writer) {
this.head = writer.head;
this.tail = writer.tail;
this.len = writer.len;
this.next = writer.states;
}
}
const bufferPool = (0,_pool_js__WEBPACK_IMPORTED_MODULE_5__["default"])();
/**
* Allocates a buffer of the specified size
*/
function alloc(size) {
if (globalThis.Buffer != null) {
return (0,uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_1__.allocUnsafe)(size);
}
return bufferPool(size);
}
/**
* When a value is written, the writer calculates its byte length and puts it into a linked
* list of operations to perform when finish() is called. This both allows us to allocate
* buffers of the exact required size and reduces the amount of work we have to do compared
* to first calculating over objects and then encoding over objects. In our case, the encoding
* part is just a linked list walk calling operations with already prepared values.
*/
class Uint8ArrayWriter {
/**
* Current length
*/
len;
/**
* Operations head
*/
head;
/**
* Operations tail
*/
tail;
/**
* Linked forked states
*/
states;
constructor() {
this.len = 0;
this.head = new Op(noop, 0, 0);
this.tail = this.head;
this.states = null;
}
/**
* Pushes a new operation to the queue
*/
_push(fn, len, val) {
this.tail = this.tail.next = new Op(fn, len, val);
this.len += len;
return this;
}
/**
* Writes an unsigned 32 bit value as a varint
*/
uint32(value) {
// here, the call to this.push has been inlined and a varint specific Op subclass is used.
// uint32 is by far the most frequently used operation and benefits significantly from this.
this.len += (this.tail = this.tail.next = new VarintOp((value = value >>> 0) <
128
? 1
: value < 16384
? 2
: value < 2097152
? 3
: value < 268435456
? 4
: 5, value)).len;
return this;
}
/**
* Writes a signed 32 bit value as a varint`
*/
int32(value) {
return value < 0
? this._push(writeVarint64, 10, _longbits_js__WEBPACK_IMPORTED_MODULE_4__.LongBits.fromNumber(value)) // 10 bytes per spec
: this.uint32(value);
}
/**
* Writes a 32 bit value as a varint, zig-zag encoded
*/
sint32(value) {
return this.uint32((value << 1 ^ value >> 31) >>> 0);
}
/**
* Writes an unsigned 64 bit value as a varint
*/
uint64(value) {
const bits = _longbits_js__WEBPACK_IMPORTED_MODULE_4__.LongBits.fromBigInt(value);
return this._push(writeVarint64, bits.length(), bits);
}
/**
* Writes an unsigned 64 bit value as a varint
*/
uint64Number(value) {
return this._push(uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encodeUint8Array, (0,uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encodingLength)(value), value);
}
/**
* Writes an unsigned 64 bit value as a varint
*/
uint64String(value) {
return this.uint64(BigInt(value));
}
/**
* Writes a signed 64 bit value as a varint
*/
int64(value) {
return this.uint64(value);
}
/**
* Writes a signed 64 bit value as a varint
*/
int64Number(value) {
return this.uint64Number(value);
}
/**
* Writes a signed 64 bit value as a varint
*/
int64String(value) {
return this.uint64String(value);
}
/**
* Writes a signed 64 bit value as a varint, zig-zag encoded
*/
sint64(value) {
const bits = _longbits_js__WEBPACK_IMPORTED_MODULE_4__.LongBits.fromBigInt(value).zzEncode();
return this._push(writeVarint64, bits.length(), bits);
}
/**
* Writes a signed 64 bit value as a varint, zig-zag encoded
*/
sint64Number(value) {
const bits = _longbits_js__WEBPACK_IMPORTED_MODULE_4__.LongBits.fromNumber(value).zzEncode();
return this._push(writeVarint64, bits.length(), bits);
}
/**
* Writes a signed 64 bit value as a varint, zig-zag encoded
*/
sint64String(value) {
return this.sint64(BigInt(value));
}
/**
* Writes a boolish value as a varint
*/
bool(value) {
return this._push(writeByte, 1, value ? 1 : 0);
}
/**
* Writes an unsigned 32 bit value as fixed 32 bits
*/
fixed32(value) {
return this._push(writeFixed32, 4, value >>> 0);
}
/**
* Writes a signed 32 bit value as fixed 32 bits
*/
sfixed32(value) {
return this.fixed32(value);
}
/**
* Writes an unsigned 64 bit value as fixed 64 bits
*/
fixed64(value) {
const bits = _longbits_js__WEBPACK_IMPORTED_MODULE_4__.LongBits.fromBigInt(value);
return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
}
/**
* Writes an unsigned 64 bit value as fixed 64 bits
*/
fixed64Number(value) {
const bits = _longbits_js__WEBPACK_IMPORTED_MODULE_4__.LongBits.fromNumber(value);
return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
}
/**
* Writes an unsigned 64 bit value as fixed 64 bits
*/
fixed64String(value) {
return this.fixed64(BigInt(value));
}
/**
* Writes a signed 64 bit value as fixed 64 bits
*/
sfixed64(value) {
return this.fixed64(value);
}
/**
* Writes a signed 64 bit value as fixed 64 bits
*/
sfixed64Number(value) {
return this.fixed64Number(value);
}
/**
* Writes a signed 64 bit value as fixed 64 bits
*/
sfixed64String(value) {
return this.fixed64String(value);
}
/**
* Writes a float (32 bit)
*/
float(value) {
return this._push(_float_js__WEBPACK_IMPORTED_MODULE_3__.writeFloatLE, 4, value);
}
/**
* Writes a double (64 bit float).
*
* @function
* @param {number} value - Value to write
* @returns {Writer} `this`
*/
double(value) {
return this._push(_float_js__WEBPACK_IMPORTED_MODULE_3__.writeDoubleLE, 8, value);
}
/**
* Writes a sequence of bytes
*/
bytes(value) {
const len = value.length >>> 0;
if (len === 0) {
return this._push(writeByte, 1, 0);
}
return this.uint32(len)._push(writeBytes, len, value);
}
/**
* Writes a string
*/
string(value) {
const len = _utf8_js__WEBPACK_IMPORTED_MODULE_6__.length(value);
return len !== 0
? this.uint32(len)._push(_utf8_js__WEBPACK_IMPORTED_MODULE_6__.write, len, value)
: this._push(writeByte, 1, 0);
}
/**
* Forks this writer's state by pushing it to a stack.
* Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
*/
fork() {
this.states = new State(this);
this.head = this.tail = new Op(noop, 0, 0);
this.len = 0;
return this;
}
/**
* Resets this instance to the last state
*/
reset() {
if (this.states != null) {
this.head = this.states.head;
this.tail = this.states.tail;
this.len = this.states.len;
this.states = this.states.next;
}
else {
this.head = this.tail = new Op(noop, 0, 0);
this.len = 0;
}
return this;
}
/**
* Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
*/
ldelim() {
const head = this.head;
const tail = this.tail;
const len = this.len;
this.reset().uint32(len);
if (len !== 0) {
this.tail.next = head.next; // skip noop
this.tail = tail;
this.len += len;
}
return this;
}
/**
* Finishes the write operation
*/
finish() {
let head = this.head.next; // skip noop
const buf = alloc(this.len);
let pos = 0;
while (head != null) {
head.fn(head.val, buf, pos);
pos += head.len;
head = head.next;
}
// this.head = this.tail = null;
return buf;
}
}
function writeByte(val, buf, pos) {
buf[pos] = val & 255;
}
function writeVarint32(val, buf, pos) {
while (val > 127) {
buf[pos++] = val & 127 | 128;
val >>>= 7;
}
buf[pos] = val;
}
/**
* Constructs a new varint writer operation instance.
*
* @classdesc Scheduled varint writer operation
*/
class VarintOp extends Op {
next;
constructor(len, val) {
super(writeVarint32, len, val);
this.next = undefined;
}
}
function writeVarint64(val, buf, pos) {
while (val.hi !== 0) {
buf[pos++] = val.lo & 127 | 128;
val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;
val.hi >>>= 7;
}
while (val.lo > 127) {
buf[pos++] = val.lo & 127 | 128;
val.lo = val.lo >>> 7;
}
buf[pos++] = val.lo;
}
function writeFixed32(val, buf, pos) {
buf[pos] = val & 255;
buf[pos + 1] = val >>> 8 & 255;
buf[pos + 2] = val >>> 16 & 255;
buf[pos + 3] = val >>> 24;
}
function writeBytes(val, buf, pos) {
buf.set(val, pos);
}
if (globalThis.Buffer != null) {
Uint8ArrayWriter.prototype.bytes = function (value) {
const len = value.length >>> 0;
this.uint32(len);
if (len > 0) {
this._push(writeBytesBuffer, len, value);
}
return this;
};
Uint8ArrayWriter.prototype.string = function (value) {
const len = globalThis.Buffer.byteLength(value);
this.uint32(len);
if (len > 0) {
this._push(writeStringBuffer, len, value);
}
return this;
};
}
function writeBytesBuffer(val, buf, pos) {
buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
// also works for plain array values
}
function writeStringBuffer(val, buf, pos) {
if (val.length < 40) {
// plain js is faster for short strings (probably due to redundant assertions)
_utf8_js__WEBPACK_IMPORTED_MODULE_6__.write(val, buf, pos);
// @ts-expect-error buf isn't a Uint8Array?
}
else if (buf.utf8Write != null) {
// @ts-expect-error buf isn't a Uint8Array?
buf.utf8Write(val, pos);
}
else {
buf.set((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__.fromString)(val), pos);
}
}
/**
* Creates a new writer
*/
function createWriter() {
return new Uint8ArrayWriter();
}
//# sourceMappingURL=writer.js.map
/***/ }),
/***/ "./node_modules/uint8-varint/dist/src/index.js":
/*!*****************************************************!*\
!*** ./node_modules/uint8-varint/dist/src/index.js ***!
\*****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ decodeUint8Array: () => (/* binding */ decodeUint8Array),
/* harmony export */ decodeUint8ArrayList: () => (/* binding */ decodeUint8ArrayList),
/* harmony export */ encode: () => (/* binding */ encode),
/* harmony export */ encodeUint8Array: () => (/* binding */ encodeUint8Array),
/* harmony export */ encodeUint8ArrayList: () => (/* binding */ encodeUint8ArrayList),
/* harmony export */ encodingLength: () => (/* binding */ encodingLength)
/* harmony export */ });
/* harmony import */ var uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/alloc */ "./node_modules/uint8arrays/dist/src/alloc.js");
/* eslint-disable no-fallthrough */
const N1 = Math.pow(2, 7);
const N2 = Math.pow(2, 14);
const N3 = Math.pow(2, 21);
const N4 = Math.pow(2, 28);
const N5 = Math.pow(2, 35);
const N6 = Math.pow(2, 42);
const N7 = Math.pow(2, 49);
/** Most significant bit of a byte */
const MSB = 0x80;
/** Rest of the bits in a byte */
const REST = 0x7f;
function encodingLength(value) {
if (value < N1) {
return 1;
}
if (value < N2) {
return 2;
}
if (value < N3) {
return 3;
}
if (value < N4) {
return 4;
}
if (value < N5) {
return 5;
}
if (value < N6) {
return 6;
}
if (value < N7) {
return 7;
}
if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {
throw new RangeError('Could not encode varint');
}
return 8;
}
function encodeUint8Array(value, buf, offset = 0) {
switch (encodingLength(value)) {
case 8: {
buf[offset++] = (value & 0xFF) | MSB;
value /= 128;
}
case 7: {
buf[offset++] = (value & 0xFF) | MSB;
value /= 128;
}
case 6: {
buf[offset++] = (value & 0xFF) | MSB;
value /= 128;
}
case 5: {
buf[offset++] = (value & 0xFF) | MSB;
value /= 128;
}
case 4: {
buf[offset++] = (value & 0xFF) | MSB;
value >>>= 7;
}
case 3: {
buf[offset++] = (value & 0xFF) | MSB;
value >>>= 7;
}
case 2: {
buf[offset++] = (value & 0xFF) | MSB;
value >>>= 7;
}
case 1: {
buf[offset++] = (value & 0xFF);
value >>>= 7;
break;
}
default: throw new Error('unreachable');
}
return buf;
}
function encodeUint8ArrayList(value, buf, offset = 0) {
switch (encodingLength(value)) {
case 8: {
buf.set(offset++, (value & 0xFF) | MSB);
value /= 128;
}
case 7: {
buf.set(offset++, (value & 0xFF) | MSB);
value /= 128;
}
case 6: {
buf.set(offset++, (value & 0xFF) | MSB);
value /= 128;
}
case 5: {
buf.set(offset++, (value & 0xFF) | MSB);
value /= 128;
}
case 4: {
buf.set(offset++, (value & 0xFF) | MSB);
value >>>= 7;
}
case 3: {
buf.set(offset++, (value & 0xFF) | MSB);
value >>>= 7;
}
case 2: {
buf.set(offset++, (value & 0xFF) | MSB);
value >>>= 7;
}
case 1: {
buf.set(offset++, (value & 0xFF));
value >>>= 7;
break;
}
default: throw new Error('unreachable');
}
return buf;
}
function decodeUint8Array(buf, offset) {
let b = buf[offset];
let res = 0;
res += b & REST;
if (b < MSB) {
return res;
}
b = buf[offset + 1];
res += (b & REST) << 7;
if (b < MSB) {
return res;
}
b = buf[offset + 2];
res += (b & REST) << 14;
if (b < MSB) {
return res;
}
b = buf[offset + 3];
res += (b & REST) << 21;
if (b < MSB) {
return res;
}
b = buf[offset + 4];
res += (b & REST) * N4;
if (b < MSB) {
return res;
}
b = buf[offset + 5];
res += (b & REST) * N5;
if (b < MSB) {
return res;
}
b = buf[offset + 6];
res += (b & REST) * N6;
if (b < MSB) {
return res;
}
b = buf[offset + 7];
res += (b & REST) * N7;
if (b < MSB) {
return res;
}
throw new RangeError('Could not decode varint');
}
function decodeUint8ArrayList(buf, offset) {
let b = buf.get(offset);
let res = 0;
res += b & REST;
if (b < MSB) {
return res;
}
b = buf.get(offset + 1);
res += (b & REST) << 7;
if (b < MSB) {
return res;
}
b = buf.get(offset + 2);
res += (b & REST) << 14;
if (b < MSB) {
return res;
}
b = buf.get(offset + 3);
res += (b & REST) << 21;
if (b < MSB) {
return res;
}
b = buf.get(offset + 4);
res += (b & REST) * N4;
if (b < MSB) {
return res;
}
b = buf.get(offset + 5);
res += (b & REST) * N5;
if (b < MSB) {
return res;
}
b = buf.get(offset + 6);
res += (b & REST) * N6;
if (b < MSB) {
return res;
}
b = buf.get(offset + 7);
res += (b & REST) * N7;
if (b < MSB) {
return res;
}
throw new RangeError('Could not decode varint');
}
function encode(value, buf, offset = 0) {
if (buf == null) {
buf = (0,uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_0__.allocUnsafe)(encodingLength(value));
}
if (buf instanceof Uint8Array) {
return encodeUint8Array(value, buf, offset);
}
else {
return encodeUint8ArrayList(value, buf, offset);
}
}
function decode(buf, offset = 0) {
if (buf instanceof Uint8Array) {
return decodeUint8Array(buf, offset);
}
else {
return decodeUint8ArrayList(buf, offset);
}
}
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/dist/src/alloc.js":
/*!****************************************************!*\
!*** ./node_modules/uint8arrays/dist/src/alloc.js ***!
\****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ alloc: () => (/* binding */ alloc),
/* harmony export */ allocUnsafe: () => (/* binding */ allocUnsafe)
/* harmony export */ });
/**
* Returns a `Uint8Array` of the requested size. Referenced memory will
* be initialized to 0.
*/
function alloc(size = 0) {
return new Uint8Array(size);
}
/**
* Where possible returns a Uint8Array of the requested size that references
* uninitialized memory. Only use if you are certain you will immediately
* overwrite every value in the returned `Uint8Array`.
*/
function allocUnsafe(size = 0) {
return new Uint8Array(size);
}
//# sourceMappingURL=alloc.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/dist/src/compare.js":
/*!******************************************************!*\
!*** ./node_modules/uint8arrays/dist/src/compare.js ***!
\******************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ compare: () => (/* binding */ compare)
/* harmony export */ });
/**
* Can be used with Array.sort to sort and array with Uint8Array entries
*/
function compare(a, b) {
for (let i = 0; i < a.byteLength; i++) {
if (a[i] < b[i]) {
return -1;
}
if (a[i] > b[i]) {
return 1;
}
}
if (a.byteLength > b.byteLength) {
return 1;
}
if (a.byteLength < b.byteLength) {
return -1;
}
return 0;
}
//# sourceMappingURL=compare.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/dist/src/concat.js":
/*!*****************************************************!*\
!*** ./node_modules/uint8arrays/dist/src/concat.js ***!
\*****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ concat: () => (/* binding */ concat)
/* harmony export */ });
/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! #alloc */ "./node_modules/uint8arrays/dist/src/alloc.js");
/* harmony import */ var _util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #util/as-uint8array */ "./node_modules/uint8arrays/dist/src/util/as-uint8array.js");
/**
* Returns a new Uint8Array created by concatenating the passed Uint8Arrays
*/
function concat(arrays, length) {
if (length == null) {
length = arrays.reduce((acc, curr) => acc + curr.length, 0);
}
const output = (0,_alloc__WEBPACK_IMPORTED_MODULE_0__.allocUnsafe)(length);
let offset = 0;
for (const arr of arrays) {
output.set(arr, offset);
offset += arr.length;
}
return (0,_util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__.asUint8Array)(output);
}
//# sourceMappingURL=concat.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/dist/src/equals.js":
/*!*****************************************************!*\
!*** ./node_modules/uint8arrays/dist/src/equals.js ***!
\*****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ equals: () => (/* binding */ equals)
/* harmony export */ });
/**
* Returns true if the two passed Uint8Arrays have the same content
*/
function equals(a, b) {
if (a === b) {
return true;
}
if (a.byteLength !== b.byteLength) {
return false;
}
for (let i = 0; i < a.byteLength; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
//# sourceMappingURL=equals.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/dist/src/from-string.js":
/*!**********************************************************!*\
!*** ./node_modules/uint8arrays/dist/src/from-string.js ***!
\**********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ fromString: () => (/* binding */ fromString)
/* harmony export */ });
/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/bases.js */ "./node_modules/uint8arrays/dist/src/util/bases.js");
/**
* Create a `Uint8Array` from the passed string
*
* Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.
*
* Also `ascii` which is similar to node's 'binary' encoding.
*/
function fromString(string, encoding = 'utf8') {
const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__["default"][encoding];
if (base == null) {
throw new Error(`Unsupported encoding "${encoding}"`);
}
// add multibase prefix
return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions
}
//# sourceMappingURL=from-string.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/dist/src/to-string.js":
/*!********************************************************!*\
!*** ./node_modules/uint8arrays/dist/src/to-string.js ***!
\********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ toString: () => (/* binding */ toString)
/* harmony export */ });
/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/bases.js */ "./node_modules/uint8arrays/dist/src/util/bases.js");
/**
* Turns a `Uint8Array` into a string.
*
* Supports `utf8`, `utf-8` and any encoding supported by the multibase module.
*
* Also `ascii` which is similar to node's 'binary' encoding.
*/
function toString(array, encoding = 'utf8') {
const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__["default"][encoding];
if (base == null) {
throw new Error(`Unsupported encoding "${encoding}"`);
}
// strip multibase prefix
return base.encoder.encode(array).substring(1);
}
//# sourceMappingURL=to-string.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/dist/src/util/as-uint8array.js":
/*!*****************************************************************!*\
!*** ./node_modules/uint8arrays/dist/src/util/as-uint8array.js ***!
\*****************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ asUint8Array: () => (/* binding */ asUint8Array)
/* harmony export */ });
/**
* To guarantee Uint8Array semantics, convert nodejs Buffers
* into vanilla Uint8Arrays
*/
function asUint8Array(buf) {
return buf;
}
//# sourceMappingURL=as-uint8array.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/dist/src/util/bases.js":
/*!*********************************************************!*\
!*** ./node_modules/uint8arrays/dist/src/util/bases.js ***!
\*********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/basics */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/basics.js");
/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #alloc */ "./node_modules/uint8arrays/dist/src/alloc.js");
function createCodec(name, prefix, encode, decode) {
return {
name,
prefix,
encoder: {
name,
prefix,
encode
},
decoder: {
decode
}
};
}
const string = createCodec('utf8', 'u', (buf) => {
const decoder = new TextDecoder('utf8');
return 'u' + decoder.decode(buf);
}, (str) => {
const encoder = new TextEncoder();
return encoder.encode(str.substring(1));
});
const ascii = createCodec('ascii', 'a', (buf) => {
let string = 'a';
for (let i = 0; i < buf.length; i++) {
string += String.fromCharCode(buf[i]);
}
return string;
}, (str) => {
str = str.substring(1);
const buf = (0,_alloc__WEBPACK_IMPORTED_MODULE_1__.allocUnsafe)(str.length);
for (let i = 0; i < str.length; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
});
const BASES = {
utf8: string,
'utf-8': string,
hex: multiformats_basics__WEBPACK_IMPORTED_MODULE_0__.bases.base16,
latin1: ascii,
ascii,
binary: ascii,
...multiformats_basics__WEBPACK_IMPORTED_MODULE_0__.bases
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (BASES);
//# sourceMappingURL=bases.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base.js":
/*!***********************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base.js ***!
\***********************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Codec: () => (/* binding */ Codec),
/* harmony export */ baseX: () => (/* binding */ baseX),
/* harmony export */ from: () => (/* binding */ from),
/* harmony export */ or: () => (/* binding */ or),
/* harmony export */ rfc4648: () => (/* binding */ rfc4648)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/vendor/base-x.js");
/**
* Class represents both BaseEncoder and MultibaseEncoder meaning it
* can be used to encode to multibase or base encode without multibase
* prefix.
*/
class Encoder {
name;
prefix;
baseEncode;
constructor(name, prefix, baseEncode) {
this.name = name;
this.prefix = prefix;
this.baseEncode = baseEncode;
}
encode(bytes) {
if (bytes instanceof Uint8Array) {
return `${this.prefix}${this.baseEncode(bytes)}`;
}
else {
throw Error('Unknown type, must be binary type');
}
}
}
/**
* Class represents both BaseDecoder and MultibaseDecoder so it could be used
* to decode multibases (with matching prefix) or just base decode strings
* with corresponding base encoding.
*/
class Decoder {
name;
prefix;
baseDecode;
prefixCodePoint;
constructor(name, prefix, baseDecode) {
this.name = name;
this.prefix = prefix;
/* c8 ignore next 3 */
if (prefix.codePointAt(0) === undefined) {
throw new Error('Invalid prefix character');
}
this.prefixCodePoint = prefix.codePointAt(0);
this.baseDecode = baseDecode;
}
decode(text) {
if (typeof text === 'string') {
if (text.codePointAt(0) !== this.prefixCodePoint) {
throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
}
return this.baseDecode(text.slice(this.prefix.length));
}
else {
throw Error('Can only multibase decode strings');
}
}
or(decoder) {
return or(this, decoder);
}
}
class ComposedDecoder {
decoders;
constructor(decoders) {
this.decoders = decoders;
}
or(decoder) {
return or(this, decoder);
}
decode(input) {
const prefix = input[0];
const decoder = this.decoders[prefix];
if (decoder != null) {
return decoder.decode(input);
}
else {
throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
}
}
}
function or(left, right) {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return new ComposedDecoder({
...(left.decoders ?? { [left.prefix]: left }),
...(right.decoders ?? { [right.prefix]: right })
});
}
class Codec {
name;
prefix;
baseEncode;
baseDecode;
encoder;
decoder;
constructor(name, prefix, baseEncode, baseDecode) {
this.name = name;
this.prefix = prefix;
this.baseEncode = baseEncode;
this.baseDecode = baseDecode;
this.encoder = new Encoder(name, prefix, baseEncode);
this.decoder = new Decoder(name, prefix, baseDecode);
}
encode(input) {
return this.encoder.encode(input);
}
decode(input) {
return this.decoder.decode(input);
}
}
function from({ name, prefix, encode, decode }) {
return new Codec(name, prefix, encode, decode);
}
function baseX({ name, prefix, alphabet }) {
const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__["default"])(alphabet, name);
return from({
prefix,
name,
encode,
decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))
});
}
function decode(string, alphabet, bitsPerChar, name) {
// Build the character lookup table:
const codes = {};
for (let i = 0; i < alphabet.length; ++i) {
codes[alphabet[i]] = i;
}
// Count the padding bytes:
let end = string.length;
while (string[end - 1] === '=') {
--end;
}
// Allocate the output:
const out = new Uint8Array((end * bitsPerChar / 8) | 0);
// Parse the data:
let bits = 0; // Number of bits currently in the buffer
let buffer = 0; // Bits waiting to be written out, MSB first
let written = 0; // Next byte to write
for (let i = 0; i < end; ++i) {
// Read one character from the string:
const value = codes[string[i]];
if (value === undefined) {
throw new SyntaxError(`Non-${name} character`);
}
// Append the bits to the buffer:
buffer = (buffer << bitsPerChar) | value;
bits += bitsPerChar;
// Write out some bits if the buffer has a byte's worth:
if (bits >= 8) {
bits -= 8;
out[written++] = 0xff & (buffer >> bits);
}
}
// Verify that we have received just enough bits:
if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
throw new SyntaxError('Unexpected end of data');
}
return out;
}
function encode(data, alphabet, bitsPerChar) {
const pad = alphabet[alphabet.length - 1] === '=';
const mask = (1 << bitsPerChar) - 1;
let out = '';
let bits = 0; // Number of bits currently in the buffer
let buffer = 0; // Bits waiting to be written out, MSB first
for (let i = 0; i < data.length; ++i) {
// Slurp data into the buffer:
buffer = (buffer << 8) | data[i];
bits += 8;
// Write out as much as we can:
while (bits > bitsPerChar) {
bits -= bitsPerChar;
out += alphabet[mask & (buffer >> bits)];
}
}
// Partial character:
if (bits !== 0) {
out += alphabet[mask & (buffer << (bitsPerChar - bits))];
}
// Add padding characters until we hit a byte boundary:
if (pad) {
while (((out.length * bitsPerChar) & 7) !== 0) {
out += '=';
}
}
return out;
}
/**
* RFC4648 Factory
*/
function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
return from({
prefix,
name,
encode(input) {
return encode(input, alphabet, bitsPerChar);
},
decode(input) {
return decode(input, alphabet, bitsPerChar, name);
}
});
}
//# sourceMappingURL=base.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base10.js":
/*!*************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base10.js ***!
\*************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base10: () => (/* binding */ base10)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base.js");
const base10 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
prefix: '9',
name: 'base10',
alphabet: '0123456789'
});
//# sourceMappingURL=base10.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base16.js":
/*!*************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base16.js ***!
\*************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base16: () => (/* binding */ base16),
/* harmony export */ base16upper: () => (/* binding */ base16upper)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base.js");
const base16 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'f',
name: 'base16',
alphabet: '0123456789abcdef',
bitsPerChar: 4
});
const base16upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'F',
name: 'base16upper',
alphabet: '0123456789ABCDEF',
bitsPerChar: 4
});
//# sourceMappingURL=base16.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base2.js":
/*!************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base2.js ***!
\************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base2: () => (/* binding */ base2)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base.js");
const base2 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: '0',
name: 'base2',
alphabet: '01',
bitsPerChar: 1
});
//# sourceMappingURL=base2.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base256emoji.js":
/*!*******************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base256emoji.js ***!
\*******************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base256emoji: () => (/* binding */ base256emoji)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base.js");
const alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');
const alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));
const alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));
function encode(data) {
return data.reduce((p, c) => {
p += alphabetBytesToChars[c];
return p;
}, '');
}
function decode(str) {
const byts = [];
for (const char of str) {
const byt = alphabetCharsToBytes[char.codePointAt(0)];
if (byt === undefined) {
throw new Error(`Non-base256emoji character: ${char}`);
}
byts.push(byt);
}
return new Uint8Array(byts);
}
const base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({
prefix: '🚀',
name: 'base256emoji',
encode,
decode
});
//# sourceMappingURL=base256emoji.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base32.js":
/*!*************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base32.js ***!
\*************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base32: () => (/* binding */ base32),
/* harmony export */ base32hex: () => (/* binding */ base32hex),
/* harmony export */ base32hexpad: () => (/* binding */ base32hexpad),
/* harmony export */ base32hexpadupper: () => (/* binding */ base32hexpadupper),
/* harmony export */ base32hexupper: () => (/* binding */ base32hexupper),
/* harmony export */ base32pad: () => (/* binding */ base32pad),
/* harmony export */ base32padupper: () => (/* binding */ base32padupper),
/* harmony export */ base32upper: () => (/* binding */ base32upper),
/* harmony export */ base32z: () => (/* binding */ base32z)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base.js");
const base32 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'b',
name: 'base32',
alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
bitsPerChar: 5
});
const base32upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'B',
name: 'base32upper',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
bitsPerChar: 5
});
const base32pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'c',
name: 'base32pad',
alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
bitsPerChar: 5
});
const base32padupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'C',
name: 'base32padupper',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
bitsPerChar: 5
});
const base32hex = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'v',
name: 'base32hex',
alphabet: '0123456789abcdefghijklmnopqrstuv',
bitsPerChar: 5
});
const base32hexupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'V',
name: 'base32hexupper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
bitsPerChar: 5
});
const base32hexpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 't',
name: 'base32hexpad',
alphabet: '0123456789abcdefghijklmnopqrstuv=',
bitsPerChar: 5
});
const base32hexpadupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'T',
name: 'base32hexpadupper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
bitsPerChar: 5
});
const base32z = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'h',
name: 'base32z',
alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
bitsPerChar: 5
});
//# sourceMappingURL=base32.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base36.js":
/*!*************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base36.js ***!
\*************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base36: () => (/* binding */ base36),
/* harmony export */ base36upper: () => (/* binding */ base36upper)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base.js");
const base36 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
prefix: 'k',
name: 'base36',
alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
const base36upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
prefix: 'K',
name: 'base36upper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base58.js":
/*!*************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base58.js ***!
\*************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base58btc: () => (/* binding */ base58btc),
/* harmony export */ base58flickr: () => (/* binding */ base58flickr)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base.js");
const base58btc = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
name: 'base58btc',
prefix: 'z',
alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
const base58flickr = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({
name: 'base58flickr',
prefix: 'Z',
alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base64.js":
/*!*************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base64.js ***!
\*************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base64: () => (/* binding */ base64),
/* harmony export */ base64pad: () => (/* binding */ base64pad),
/* harmony export */ base64url: () => (/* binding */ base64url),
/* harmony export */ base64urlpad: () => (/* binding */ base64urlpad)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base.js");
const base64 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'm',
name: 'base64',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
bitsPerChar: 6
});
const base64pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'M',
name: 'base64pad',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
bitsPerChar: 6
});
const base64url = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'u',
name: 'base64url',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
bitsPerChar: 6
});
const base64urlpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: 'U',
name: 'base64urlpad',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
bitsPerChar: 6
});
//# sourceMappingURL=base64.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base8.js":
/*!************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base8.js ***!
\************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ base8: () => (/* binding */ base8)
/* harmony export */ });
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base.js");
const base8 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({
prefix: '7',
name: 'base8',
alphabet: '01234567',
bitsPerChar: 3
});
//# sourceMappingURL=base8.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/identity.js":
/*!***************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/identity.js ***!
\***************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ identity: () => (/* binding */ identity)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base.js");
const identity = (0,_base_js__WEBPACK_IMPORTED_MODULE_1__.from)({
prefix: '\x00',
name: 'identity',
encode: (buf) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.toString)(buf),
decode: (str) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.fromString)(str)
});
//# sourceMappingURL=identity.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/interface.js":
/*!****************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/interface.js ***!
\****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
// Base encoders / decoders just base encode / decode between binary and
// textual representation. They are unaware of multibase.
//# sourceMappingURL=interface.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/basics.js":
/*!*******************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/basics.js ***!
\*******************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CID: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.CID),
/* harmony export */ bases: () => (/* binding */ bases),
/* harmony export */ bytes: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.bytes),
/* harmony export */ codecs: () => (/* binding */ codecs),
/* harmony export */ digest: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.digest),
/* harmony export */ hasher: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.hasher),
/* harmony export */ hashes: () => (/* binding */ hashes),
/* harmony export */ varint: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.varint)
/* harmony export */ });
/* harmony import */ var _bases_base10_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base10.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base10.js");
/* harmony import */ var _bases_base16_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base16.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base16.js");
/* harmony import */ var _bases_base2_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base2.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base2.js");
/* harmony import */ var _bases_base256emoji_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bases/base256emoji.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base256emoji.js");
/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./bases/base32.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base32.js");
/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./bases/base36.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base36.js");
/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./bases/base58.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base58.js");
/* harmony import */ var _bases_base64_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./bases/base64.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base64.js");
/* harmony import */ var _bases_base8_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./bases/base8.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base8.js");
/* harmony import */ var _bases_identity_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./bases/identity.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/identity.js");
/* harmony import */ var _codecs_json_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./codecs/json.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/codecs/json.js");
/* harmony import */ var _codecs_raw_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./codecs/raw.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/codecs/raw.js");
/* harmony import */ var _hashes_identity_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./hashes/identity.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/identity.js");
/* harmony import */ var _hashes_sha2_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./hashes/sha2.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/sha2-browser.js");
/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./index.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/index.js");
const bases = { ..._bases_identity_js__WEBPACK_IMPORTED_MODULE_9__, ..._bases_base2_js__WEBPACK_IMPORTED_MODULE_2__, ..._bases_base8_js__WEBPACK_IMPORTED_MODULE_8__, ..._bases_base10_js__WEBPACK_IMPORTED_MODULE_0__, ..._bases_base16_js__WEBPACK_IMPORTED_MODULE_1__, ..._bases_base32_js__WEBPACK_IMPORTED_MODULE_4__, ..._bases_base36_js__WEBPACK_IMPORTED_MODULE_5__, ..._bases_base58_js__WEBPACK_IMPORTED_MODULE_6__, ..._bases_base64_js__WEBPACK_IMPORTED_MODULE_7__, ..._bases_base256emoji_js__WEBPACK_IMPORTED_MODULE_3__ };
const hashes = { ..._hashes_sha2_js__WEBPACK_IMPORTED_MODULE_13__, ..._hashes_identity_js__WEBPACK_IMPORTED_MODULE_12__ };
const codecs = { raw: _codecs_raw_js__WEBPACK_IMPORTED_MODULE_11__, json: _codecs_json_js__WEBPACK_IMPORTED_MODULE_10__ };
//# sourceMappingURL=basics.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/block/interface.js":
/*!****************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/block/interface.js ***!
\****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
//# sourceMappingURL=interface.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bytes.js":
/*!******************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/bytes.js ***!
\******************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ coerce: () => (/* binding */ coerce),
/* harmony export */ empty: () => (/* binding */ empty),
/* harmony export */ equals: () => (/* binding */ equals),
/* harmony export */ fromHex: () => (/* binding */ fromHex),
/* harmony export */ fromString: () => (/* binding */ fromString),
/* harmony export */ isBinary: () => (/* binding */ isBinary),
/* harmony export */ toHex: () => (/* binding */ toHex),
/* harmony export */ toString: () => (/* binding */ toString)
/* harmony export */ });
const empty = new Uint8Array(0);
function toHex(d) {
return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
function fromHex(hex) {
const hexes = hex.match(/../g);
return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
function equals(aa, bb) {
if (aa === bb)
return true;
if (aa.byteLength !== bb.byteLength) {
return false;
}
for (let ii = 0; ii < aa.byteLength; ii++) {
if (aa[ii] !== bb[ii]) {
return false;
}
}
return true;
}
function coerce(o) {
if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')
return o;
if (o instanceof ArrayBuffer)
return new Uint8Array(o);
if (ArrayBuffer.isView(o)) {
return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
}
throw new Error('Unknown type, must be binary type');
}
function isBinary(o) {
return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
function fromString(str) {
return new TextEncoder().encode(str);
}
function toString(b) {
return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/cid.js":
/*!****************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/cid.js ***!
\****************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CID: () => (/* binding */ CID),
/* harmony export */ format: () => (/* binding */ format),
/* harmony export */ fromJSON: () => (/* binding */ fromJSON),
/* harmony export */ toJSON: () => (/* binding */ toJSON)
/* harmony export */ });
/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base32.js");
/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/base58.js");
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/digest.js");
/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/varint.js");
/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/link/interface.js");
// This way TS will also expose all the types from module
function format(link, base) {
const { bytes, version } = link;
switch (version) {
case 0:
return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);
default:
return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));
}
}
function toJSON(link) {
return {
'/': format(link)
};
}
function fromJSON(json) {
return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
const baseCache = cache.get(cid);
if (baseCache == null) {
const baseCache = new Map();
cache.set(cid, baseCache);
return baseCache;
}
return baseCache;
}
class CID {
code;
version;
multihash;
bytes;
'/';
/**
* @param version - Version of the CID
* @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
* @param multihash - (Multi)hash of the of the content.
*/
constructor(version, code, multihash, bytes) {
this.code = code;
this.version = version;
this.multihash = multihash;
this.bytes = bytes;
// flag to serializers that this is a CID and
// should be treated specially
this['/'] = bytes;
}
/**
* Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
* please either use `CID.asCID(cid)` or switch to new signalling mechanism
*
* @deprecated
*/
get asCID() {
return this;
}
// ArrayBufferView
get byteOffset() {
return this.bytes.byteOffset;
}
// ArrayBufferView
get byteLength() {
return this.bytes.byteLength;
}
toV0() {
switch (this.version) {
case 0: {
return this;
}
case 1: {
const { code, multihash } = this;
if (code !== DAG_PB_CODE) {
throw new Error('Cannot convert a non dag-pb CID to CIDv0');
}
// sha2-256
if (multihash.code !== SHA_256_CODE) {
throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
}
return (CID.createV0(multihash));
}
default: {
throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
}
}
}
toV1() {
switch (this.version) {
case 0: {
const { code, digest } = this.multihash;
const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);
return (CID.createV1(this.code, multihash));
}
case 1: {
return this;
}
default: {
throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
}
}
}
equals(other) {
return CID.equals(this, other);
}
static equals(self, other) {
const unknown = other;
return (unknown != null &&
self.code === unknown.code &&
self.version === unknown.version &&
_hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));
}
toString(base) {
return format(this, base);
}
toJSON() {
return { '/': format(this) };
}
link() {
return this;
}
[Symbol.toStringTag] = 'CID';
// Legacy
[Symbol.for('nodejs.util.inspect.custom')]() {
return `CID(${this.toString()})`;
}
/**
* Takes any input `value` and returns a `CID` instance if it was
* a `CID` otherwise returns `null`. If `value` is instanceof `CID`
* it will return value back. If `value` is not instance of this CID
* class, but is compatible CID it will return new instance of this
* `CID` class. Otherwise returns null.
*
* This allows two different incompatible versions of CID library to
* co-exist and interop as long as binary interface is compatible.
*/
static asCID(input) {
if (input == null) {
return null;
}
const value = input;
if (value instanceof CID) {
// If value is instance of CID then we're all set.
return value;
}
else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
// If value isn't instance of this CID class but `this.asCID === this` or
// `value['/'] === value.bytes` is true it is CID instance coming from a
// different implementation (diff version or duplicate). In that case we
// rebase it to this `CID` implementation so caller is guaranteed to get
// instance with expected API.
const { version, code, multihash, bytes } = value;
return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
}
else if (value[cidSymbol] === true) {
// If value is a CID from older implementation that used to be tagged via
// symbol we still rebase it to the this `CID` implementation by
// delegating that to a constructor.
const { version, multihash, code } = value;
const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);
return CID.create(version, code, digest);
}
else {
// Otherwise value is not a CID (or an incompatible version of it) in
// which case we return `null`.
return null;
}
}
/**
* @param version - Version of the CID
* @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
* @param digest - (Multi)hash of the of the content.
*/
static create(version, code, digest) {
if (typeof code !== 'number') {
throw new Error('String codecs are no longer supported');
}
if (!(digest.bytes instanceof Uint8Array)) {
throw new Error('Invalid digest');
}
switch (version) {
case 0: {
if (code !== DAG_PB_CODE) {
throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
}
else {
return new CID(version, code, digest, digest.bytes);
}
}
case 1: {
const bytes = encodeCID(version, code, digest.bytes);
return new CID(version, code, digest, bytes);
}
default: {
throw new Error('Invalid version');
}
}
}
/**
* Simplified version of `create` for CIDv0.
*/
static createV0(digest) {
return CID.create(0, DAG_PB_CODE, digest);
}
/**
* Simplified version of `create` for CIDv1.
*
* @param code - Content encoding format code.
* @param digest - Multihash of the content.
*/
static createV1(code, digest) {
return CID.create(1, code, digest);
}
/**
* Decoded a CID from its binary representation. The byte array must contain
* only the CID with no additional bytes.
*
* An error will be thrown if the bytes provided do not contain a valid
* binary representation of a CID.
*/
static decode(bytes) {
const [cid, remainder] = CID.decodeFirst(bytes);
if (remainder.length !== 0) {
throw new Error('Incorrect length');
}
return cid;
}
/**
* Decoded a CID from its binary representation at the beginning of a byte
* array.
*
* Returns an array with the first element containing the CID and the second
* element containing the remainder of the original byte array. The remainder
* will be a zero-length byte array if the provided bytes only contained a
* binary CID representation.
*/
static decodeFirst(bytes) {
const specs = CID.inspectBytes(bytes);
const prefixSize = specs.size - specs.multihashSize;
const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
if (multihashBytes.byteLength !== specs.multihashSize) {
throw new Error('Incorrect length');
}
const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
const cid = specs.version === 0
? CID.createV0(digest)
: CID.createV1(specs.codec, digest);
return [cid, bytes.subarray(specs.size)];
}
/**
* Inspect the initial bytes of a CID to determine its properties.
*
* Involves decoding up to 4 varints. Typically this will require only 4 to 6
* bytes but for larger multicodec code values and larger multihash digest
* lengths these varints can be quite large. It is recommended that at least
* 10 bytes be made available in the `initialBytes` argument for a complete
* inspection.
*/
static inspectBytes(initialBytes) {
let offset = 0;
const next = () => {
const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));
offset += length;
return i;
};
let version = next();
let codec = DAG_PB_CODE;
if (version === 18) {
// CIDv0
version = 0;
offset = 0;
}
else {
codec = next();
}
if (version !== 0 && version !== 1) {
throw new RangeError(`Invalid CID version ${version}`);
}
const prefixSize = offset;
const multihashCode = next(); // multihash code
const digestSize = next(); // multihash length
const size = offset + digestSize;
const multihashSize = size - prefixSize;
return { version, codec, multihashCode, digestSize, multihashSize, size };
}
/**
* Takes cid in a string representation and creates an instance. If `base`
* decoder is not provided will use a default from the configuration. It will
* throw an error if encoding of the CID is not compatible with supplied (or
* a default decoder).
*/
static parse(source, base) {
const [prefix, bytes] = parseCIDtoBytes(source, base);
const cid = CID.decode(bytes);
if (cid.version === 0 && source[0] !== 'Q') {
throw Error('Version 0 CID string must not include multibase prefix');
}
// Cache string representation to avoid computing it on `this.toString()`
baseCache(cid).set(prefix, source);
return cid;
}
}
function parseCIDtoBytes(source, base) {
switch (source[0]) {
// CIDv0 is parsed differently
case 'Q': {
const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;
return [
_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,
decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)
];
}
case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {
const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;
return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];
}
case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {
const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;
return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];
}
default: {
if (base == null) {
throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');
}
return [source[0], base.decode(source)];
}
}
}
function toStringV0(bytes, cache, base) {
const { prefix } = base;
if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {
throw Error(`Cannot string encode V0 in ${base.name} encoding`);
}
const cid = cache.get(prefix);
if (cid == null) {
const cid = base.encode(bytes).slice(1);
cache.set(prefix, cid);
return cid;
}
else {
return cid;
}
}
function toStringV1(bytes, cache, base) {
const { prefix } = base;
const cid = cache.get(prefix);
if (cid == null) {
const cid = base.encode(bytes);
cache.set(prefix, cid);
return cid;
}
else {
return cid;
}
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);
const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);
const bytes = new Uint8Array(hashOffset + multihash.byteLength);
_varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);
_varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);
bytes.set(multihash, hashOffset);
return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/codecs/interface.js":
/*!*****************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/codecs/interface.js ***!
\*****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
//# sourceMappingURL=interface.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/codecs/json.js":
/*!************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/codecs/json.js ***!
\************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ code: () => (/* binding */ code),
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ encode: () => (/* binding */ encode),
/* harmony export */ name: () => (/* binding */ name)
/* harmony export */ });
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
const name = 'json';
const code = 0x0200;
function encode(node) {
return textEncoder.encode(JSON.stringify(node));
}
function decode(data) {
return JSON.parse(textDecoder.decode(data));
}
//# sourceMappingURL=json.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/codecs/raw.js":
/*!***********************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/codecs/raw.js ***!
\***********************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ code: () => (/* binding */ code),
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ encode: () => (/* binding */ encode),
/* harmony export */ name: () => (/* binding */ name)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bytes.js");
const name = 'raw';
const code = 0x55;
function encode(node) {
return (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(node);
}
function decode(data) {
return (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(data);
}
//# sourceMappingURL=raw.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/digest.js":
/*!**************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/digest.js ***!
\**************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Digest: () => (/* binding */ Digest),
/* harmony export */ create: () => (/* binding */ create),
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ equals: () => (/* binding */ equals)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/varint.js");
/**
* Creates a multihash digest.
*/
function create(code, digest) {
const size = digest.byteLength;
const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);
const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);
const bytes = new Uint8Array(digestOffset + size);
_varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);
_varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);
bytes.set(digest, digestOffset);
return new Digest(code, size, digest, bytes);
}
/**
* Turns bytes representation of multihash digest into an instance.
*/
function decode(multihash) {
const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);
const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);
const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));
const digest = bytes.subarray(sizeOffset + digestOffset);
if (digest.byteLength !== size) {
throw new Error('Incorrect length');
}
return new Digest(code, size, digest, bytes);
}
function equals(a, b) {
if (a === b) {
return true;
}
else {
const data = b;
return (a.code === data.code &&
a.size === data.size &&
data.bytes instanceof Uint8Array &&
(0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));
}
}
/**
* Represents a multihash digest which carries information about the
* hashing algorithm and an actual hash digest.
*/
class Digest {
code;
size;
digest;
bytes;
/**
* Creates a multihash digest.
*/
constructor(code, size, digest, bytes) {
this.code = code;
this.size = size;
this.digest = digest;
this.bytes = bytes;
}
}
//# sourceMappingURL=digest.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/hasher.js":
/*!**************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/hasher.js ***!
\**************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Hasher: () => (/* binding */ Hasher),
/* harmony export */ from: () => (/* binding */ from)
/* harmony export */ });
/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./digest.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/digest.js");
function from({ name, code, encode }) {
return new Hasher(name, code, encode);
}
/**
* Hasher represents a hashing algorithm implementation that produces as
* `MultihashDigest`.
*/
class Hasher {
name;
code;
encode;
constructor(name, code, encode) {
this.name = name;
this.code = code;
this.encode = encode;
}
digest(input) {
if (input instanceof Uint8Array) {
const result = this.encode(input);
return result instanceof Uint8Array
? _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, result)
/* c8 ignore next 1 */
: result.then(digest => _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, digest));
}
else {
throw Error('Unknown type, must be binary type');
/* c8 ignore next 1 */
}
}
}
//# sourceMappingURL=hasher.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/identity.js":
/*!****************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/identity.js ***!
\****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ identity: () => (/* binding */ identity)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./digest.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/digest.js");
const code = 0x0;
const name = 'identity';
const encode = _bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce;
function digest(input) {
return _digest_js__WEBPACK_IMPORTED_MODULE_1__.create(code, encode(input));
}
const identity = { code, name, encode, digest };
//# sourceMappingURL=identity.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/interface.js":
/*!*****************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/interface.js ***!
\*****************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
// # Multihash
//# sourceMappingURL=interface.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/sha2-browser.js":
/*!********************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/sha2-browser.js ***!
\********************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ sha256: () => (/* binding */ sha256),
/* harmony export */ sha512: () => (/* binding */ sha512)
/* harmony export */ });
/* harmony import */ var _hasher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hasher.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/hasher.js");
/* global crypto */
function sha(name) {
return async (data) => new Uint8Array(await crypto.subtle.digest(name, data));
}
const sha256 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({
name: 'sha2-256',
code: 0x12,
encode: sha('SHA-256')
});
const sha512 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({
name: 'sha2-512',
code: 0x13,
encode: sha('SHA-512')
});
//# sourceMappingURL=sha2-browser.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/index.js":
/*!******************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/index.js ***!
\******************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CID: () => (/* reexport safe */ _cid_js__WEBPACK_IMPORTED_MODULE_1__.CID),
/* harmony export */ bytes: () => (/* reexport module object */ _bytes_js__WEBPACK_IMPORTED_MODULE_0__),
/* harmony export */ digest: () => (/* reexport module object */ _hashes_digest_js__WEBPACK_IMPORTED_MODULE_2__),
/* harmony export */ hasher: () => (/* reexport module object */ _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__),
/* harmony export */ varint: () => (/* reexport module object */ _varint_js__WEBPACK_IMPORTED_MODULE_4__)
/* harmony export */ });
/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bytes.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bytes.js");
/* harmony import */ var _cid_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cid.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/cid.js");
/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./hashes/digest.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/digest.js");
/* harmony import */ var _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/hasher.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/hasher.js");
/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/varint.js");
/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./interface.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/interface.js");
/**
* @packageDocumentation
*
* This library defines common interfaces and low level building blocks for various interrelated multiformat technologies (multicodec, multihash, multibase, and CID). They can be used to implement custom base encoders / decoders / codecs, codec encoders /decoders and multihash hashers that comply to the interface that layers above assume.
*
* This library provides implementations for most basics and many others can be found in linked repositories.
*
* ```TypeScript
* import { CID } from 'multiformats/cid'
* import * as json from 'multiformats/codecs/json'
* import { sha256 } from 'multiformats/hashes/sha2'
*
* const bytes = json.encode({ hello: 'world' })
*
* const hash = await sha256.digest(bytes)
* const cid = CID.create(1, json.code, hash)
* //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)
* ```
*
* ## Creating Blocks
*
* ```TypeScript
* import * as Block from 'multiformats/block'
* import * as codec from '@ipld/dag-cbor'
* import { sha256 as hasher } from 'multiformats/hashes/sha2'
*
* const value = { hello: 'world' }
*
* // encode a block
* let block = await Block.encode({ value, codec, hasher })
*
* block.value // { hello: 'world' }
* block.bytes // Uint8Array
* block.cid // CID() w/ sha2-256 hash address and dag-cbor codec
*
* // you can also decode blocks from their binary state
* block = await Block.decode({ bytes: block.bytes, codec, hasher })
*
* // if you have the cid you can also verify the hash on decode
* block = await Block.create({ bytes: block.bytes, cid: block.cid, codec, hasher })
* ```
*
* ## Multibase Encoders / Decoders / Codecs
*
* CIDs can be serialized to string representation using multibase encoders that implement [`MultibaseEncoder`](https://github.com/multiformats/js-multiformats/blob/master/src/bases/interface.ts) interface. This library provides quite a few implementations that can be imported:
*
* ```TypeScript
* import { base64 } from "multiformats/bases/base64"
* cid.toString(base64.encoder)
* //> 'mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA'
* ```
*
* Parsing CID string serialized CIDs requires multibase decoder that implements [`MultibaseDecoder`](https://github.com/multiformats/js-multiformats/blob/master/src/bases/interface.ts) interface. This library provides a decoder for every encoder it provides:
*
* ```TypeScript
* CID.parse('mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA', base64.decoder)
* //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)
* ```
*
* Dual of multibase encoder & decoder is defined as multibase codec and it exposes
* them as `encoder` and `decoder` properties. For added convenience codecs also
* implement `MultibaseEncoder` and `MultibaseDecoder` interfaces so they could be
* used as either or both:
*
* ```TypeScript
* cid.toString(base64)
* CID.parse(cid.toString(base64), base64)
* ```
*
* **Note:** CID implementation comes bundled with `base32` and `base58btc`
* multibase codecs so that CIDs can be base serialized to (version specific)
* default base encoding and parsed without having to supply base encoders/decoders:
*
* ```TypeScript
* const v1 = CID.parse('bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea')
* v1.toString()
* //> 'bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea'
*
* const v0 = CID.parse('QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n')
* v0.toString()
* //> 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'
* v0.toV1().toString()
* //> 'bafybeihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku'
* ```
*
* ## Multicodec Encoders / Decoders / Codecs
*
* This library defines [`BlockEncoder`, `BlockDecoder` and `BlockCodec` interfaces](https://github.com/multiformats/js-multiformats/blob/master/src/codecs/interface.ts).
* Codec implementations should conform to the `BlockCodec` interface which implements both `BlockEncoder` and `BlockDecoder`.
* Here is an example implementation of JSON `BlockCodec`.
*
* ```TypeScript
* export const { name, code, encode, decode } = {
* name: 'json',
* code: 0x0200,
* encode: json => new TextEncoder().encode(JSON.stringify(json)),
* decode: bytes => JSON.parse(new TextDecoder().decode(bytes))
* }
* ```
*
* ## Multihash Hashers
*
* This library defines [`MultihashHasher` and `MultihashDigest` interfaces](https://github.com/multiformats/js-multiformats/blob/master/src/hashes/interface.ts) and convinient function for implementing them:
*
* ```TypeScript
* import * as hasher from 'multiformats/hashes/hasher'
*
* const sha256 = hasher.from({
* // As per multiformats table
* // https://github.com/multiformats/multicodec/blob/master/table.csv#L9
* name: 'sha2-256',
* code: 0x12,
*
* encode: (input) => new Uint8Array(crypto.createHash('sha256').update(input).digest())
* })
*
* const hash = await sha256.digest(json.encode({ hello: 'world' }))
* CID.create(1, json.code, hash)
*
* //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)
* ```
*
* ## Traversal
*
* This library contains higher-order functions for traversing graphs of data easily.
*
* `walk()` walks through the links in each block of a DAG calling a user-supplied loader function for each one, in depth-first order with no duplicate block visits. The loader should return a `Block` object and can be used to inspect and collect block ordering for a full DAG walk. The loader should `throw` on error, and return `null` if a block should be skipped by `walk()`.
*
* ```TypeScript
* import { walk } from 'multiformats/traversal'
* import * as Block from 'multiformats/block'
* import * as codec from 'multiformats/codecs/json'
* import { sha256 as hasher } from 'multiformats/hashes/sha2'
*
* // build a DAG (a single block for this simple example)
* const value = { hello: 'world' }
* const block = await Block.encode({ value, codec, hasher })
* const { cid } = block
* console.log(cid)
* //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)
*
* // create a loader function that also collects CIDs of blocks in
* // their traversal order
* const load = (cid, blocks) => async (cid) => {
* // fetch a block using its cid
* // e.g.: const block = await fetchBlockByCID(cid)
* blocks.push(cid)
* return block
* }
*
* // collect blocks in this DAG starting from the root `cid`
* const blocks = []
* await walk({ cid, load: load(cid, blocks) })
*
* console.log(blocks)
* //> [CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)]
* ```
*
* ## Legacy interface
*
* [`blockcodec-to-ipld-format`](https://github.com/ipld/js-blockcodec-to-ipld-format) converts a multiformats [`BlockCodec`](https://github.com/multiformats/js-multiformats/blob/master/src/codecs/interface.ts#L21) into an
* [`interface-ipld-format`](https://github.com/ipld/interface-ipld-format) for use with the [`ipld`](https://github.com/ipld/ipld) package. This can help bridge IPLD codecs implemented using the structure and interfaces defined here to existing code that assumes, or requires `interface-ipld-format`. This bridge also includes the relevant TypeScript definitions.
*
* ## Implementations
*
* By default, no base encodings (other than base32 & base58btc), hash functions,
* or codec implementations are exposed by `multiformats`, you need to
* import the ones you need yourself.
*
* ### Multibase codecs
*
* | bases | import | repo |
* | ------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------- |
* | `base16` | `multiformats/bases/base16` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |
* | `base32`, `base32pad`, `base32hex`, `base32hexpad`, `base32z` | `multiformats/bases/base32` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |
* | `base64`, `base64pad`, `base64url`, `base64urlpad` | `multiformats/bases/base64` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |
* | `base58btc`, `base58flick4` | `multiformats/bases/base58` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |
*
* Other (less useful) bases implemented in [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) include: `base2`, `base8`, `base10`, `base36` and `base256emoji`.
*
* ### Multihash hashers
*
* | hashes | import | repo |
* | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
* | `sha2-256`, `sha2-512` | `multiformats/hashes/sha2` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/hashes) |
* | `sha3-224`, `sha3-256`, `sha3-384`,`sha3-512`, `shake-128`, `shake-256`, `keccak-224`, `keccak-256`, `keccak-384`, `keccak-512` | `@multiformats/sha3` | [multiformats/js-sha3](https://github.com/multiformats/js-sha3) |
* | `identity` | `multiformats/hashes/identity` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/hashes/identity.js) |
* | `murmur3-128`, `murmur3-32` | `@multiformats/murmur3` | [multiformats/js-murmur3](https://github.com/multiformats/js-murmur3) |
* | `blake2b-*`, `blake2s-*` | `@multiformats/blake2` | [multiformats/js-blake2](https://github.com/multiformats/js-blake2) |
*
* ### IPLD codecs (multicodec)
*
* | codec | import | repo |
* | ---------- | -------------------------- | ------------------------------------------------------------------------------------------------------ |
* | `raw` | `multiformats/codecs/raw` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/codecs) |
* | `json` | `multiformats/codecs/json` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/codecs) |
* | `dag-cbor` | `@ipld/dag-cbor` | [ipld/js-dag-cbor](https://github.com/ipld/js-dag-cbor) |
* | `dag-json` | `@ipld/dag-json` | [ipld/js-dag-json](https://github.com/ipld/js-dag-json) |
* | `dag-pb` | `@ipld/dag-pb` | [ipld/js-dag-pb](https://github.com/ipld/js-dag-pb) |
* | `dag-jose` | `dag-jose` | [ceramicnetwork/js-dag-jose](https://github.com/ceramicnetwork/js-dag-jose) |
*/
// This way TS will also expose all the types from module
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/interface.js":
/*!**********************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/interface.js ***!
\**********************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _bases_interface_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/interface.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/bases/interface.js");
/* harmony import */ var _hashes_interface_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hashes/interface.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/hashes/interface.js");
/* harmony import */ var _codecs_interface_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./codecs/interface.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/codecs/interface.js");
/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./link/interface.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/link/interface.js");
/* harmony import */ var _block_interface_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./block/interface.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/block/interface.js");
//# sourceMappingURL=interface.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/link/interface.js":
/*!***************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/link/interface.js ***!
\***************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* eslint-disable @typescript-eslint/no-unnecessary-type-constraint */
/* eslint-disable no-use-before-define */
//# sourceMappingURL=interface.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/varint.js":
/*!*******************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/varint.js ***!
\*******************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decode: () => (/* binding */ decode),
/* harmony export */ encodeTo: () => (/* binding */ encodeTo),
/* harmony export */ encodingLength: () => (/* binding */ encodingLength)
/* harmony export */ });
/* harmony import */ var _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vendor/varint.js */ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/vendor/varint.js");
function decode(data, offset = 0) {
const code = _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].decode(data, offset);
return [code, _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].decode.bytes];
}
function encodeTo(int, target, offset = 0) {
_vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].encode(int, target, offset);
return target;
}
function encodingLength(int) {
return _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__["default"].encodingLength(int);
}
//# sourceMappingURL=varint.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/vendor/base-x.js":
/*!**************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/vendor/base-x.js ***!
\**************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
* @param {string} ALPHABET
* @param {any} name
*/
function base(ALPHABET, name) {
if (ALPHABET.length >= 255) {
throw new TypeError('Alphabet too long');
}
var BASE_MAP = new Uint8Array(256);
for (var j = 0; j < BASE_MAP.length; j++) {
BASE_MAP[j] = 255;
}
for (var i = 0; i < ALPHABET.length; i++) {
var x = ALPHABET.charAt(i);
var xc = x.charCodeAt(0);
if (BASE_MAP[xc] !== 255) {
throw new TypeError(x + ' is ambiguous');
}
BASE_MAP[xc] = i;
}
var BASE = ALPHABET.length;
var LEADER = ALPHABET.charAt(0);
var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
/**
* @param {any[] | Iterable<number>} source
*/
function encode(source) {
// @ts-ignore
if (source instanceof Uint8Array)
;
else if (ArrayBuffer.isView(source)) {
source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
}
else if (Array.isArray(source)) {
source = Uint8Array.from(source);
}
if (!(source instanceof Uint8Array)) {
throw new TypeError('Expected Uint8Array');
}
if (source.length === 0) {
return '';
}
// Skip & count leading zeroes.
var zeroes = 0;
var length = 0;
var pbegin = 0;
var pend = source.length;
while (pbegin !== pend && source[pbegin] === 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
var b58 = new Uint8Array(size);
// Process the bytes.
while (pbegin !== pend) {
var carry = source[pbegin];
// Apply "b58 = b58 * 256 + ch".
var i = 0;
for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
carry += (256 * b58[it1]) >>> 0;
b58[it1] = (carry % BASE) >>> 0;
carry = (carry / BASE) >>> 0;
}
if (carry !== 0) {
throw new Error('Non-zero carry');
}
length = i;
pbegin++;
}
// Skip leading zeroes in base58 result.
var it2 = size - length;
while (it2 !== size && b58[it2] === 0) {
it2++;
}
// Translate the result into a string.
var str = LEADER.repeat(zeroes);
for (; it2 < size; ++it2) {
str += ALPHABET.charAt(b58[it2]);
}
return str;
}
/**
* @param {string | string[]} source
*/
function decodeUnsafe(source) {
if (typeof source !== 'string') {
throw new TypeError('Expected String');
}
if (source.length === 0) {
return new Uint8Array();
}
var psz = 0;
// Skip leading spaces.
if (source[psz] === ' ') {
return;
}
// Skip and count leading '1's.
var zeroes = 0;
var length = 0;
while (source[psz] === LEADER) {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
var b256 = new Uint8Array(size);
// Process the characters.
while (source[psz]) {
// Decode character
var carry = BASE_MAP[source.charCodeAt(psz)];
// Invalid character
if (carry === 255) {
return;
}
var i = 0;
for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
carry += (BASE * b256[it3]) >>> 0;
b256[it3] = (carry % 256) >>> 0;
carry = (carry / 256) >>> 0;
}
if (carry !== 0) {
throw new Error('Non-zero carry');
}
length = i;
psz++;
}
// Skip trailing spaces.
if (source[psz] === ' ') {
return;
}
// Skip leading zeroes in b256.
var it4 = size - length;
while (it4 !== size && b256[it4] === 0) {
it4++;
}
var vch = new Uint8Array(zeroes + (size - it4));
var j = zeroes;
while (it4 !== size) {
vch[j++] = b256[it4++];
}
return vch;
}
/**
* @param {string | string[]} string
*/
function decode(string) {
var buffer = decodeUnsafe(string);
if (buffer) {
return buffer;
}
throw new Error(`Non-${name} character`);
}
return {
encode: encode,
decodeUnsafe: decodeUnsafe,
decode: decode
};
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp__multiformats_scope_baseX);
//# sourceMappingURL=base-x.js.map
/***/ }),
/***/ "./node_modules/uint8arrays/node_modules/multiformats/dist/src/vendor/varint.js":
/*!**************************************************************************************!*\
!*** ./node_modules/uint8arrays/node_modules/multiformats/dist/src/vendor/varint.js ***!
\**************************************************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
* @param {number} num
* @param {number[]} out
* @param {number} offset
*/
function encode(num, out, offset) {
out = out || [];
offset = offset || 0;
var oldOffset = offset;
while (num >= INT) {
out[offset++] = (num & 0xFF) | MSB;
num /= 128;
}
while (num & MSBALL) {
out[offset++] = (num & 0xFF) | MSB;
num >>>= 7;
}
out[offset] = num | 0;
// @ts-ignore
encode.bytes = offset - oldOffset + 1;
return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
* @param {string | any[]} buf
* @param {number} offset
*/
function read(buf, offset) {
var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
do {
if (counter >= l) {
// @ts-ignore
read.bytes = 0;
throw new RangeError('Could not decode varint');
}
b = buf[counter++];
res += shift < 28
? (b & REST$1) << shift
: (b & REST$1) * Math.pow(2, shift);
shift += 7;
} while (b >= MSB$1);
// @ts-ignore
read.bytes = counter - offset;
return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
return (value < N1 ? 1
: value < N2 ? 2
: value < N3 ? 3
: value < N4 ? 4
: value < N5 ? 5
: value < N6 ? 6
: value < N7 ? 7
: value < N8 ? 8
: value < N9 ? 9
: 10);
};
var varint = {
encode: encode_1,
decode: decode,
encodingLength: length
};
var _brrp_varint = varint;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp_varint);
//# sourceMappingURL=varint.js.map
/***/ }),
/***/ "./src/access-controllers/index.js":
/*!*****************************************!*\
!*** ./src/access-controllers/index.js ***!
\*****************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ IPFSAccessController: () => (/* reexport safe */ _ipfs_js__WEBPACK_IMPORTED_MODULE_0__["default"]),
/* harmony export */ OrbitDBAccessController: () => (/* reexport safe */ _orbitdb_js__WEBPACK_IMPORTED_MODULE_1__["default"]),
/* harmony export */ getAccessController: () => (/* binding */ getAccessController),
/* harmony export */ useAccessController: () => (/* binding */ useAccessController)
/* harmony export */ });
/* harmony import */ var _ipfs_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ipfs.js */ "./src/access-controllers/ipfs.js");
/* harmony import */ var _orbitdb_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./orbitdb.js */ "./src/access-controllers/orbitdb.js");
/**
* @module AccessControllers
* @description
* Provides a system for managing access controllers. Supported access
* controllers can be added and removed from the access controller list, and
* can load the associated module if they are supported.
*/
const accessControllers = {}
/**
* Gets an access controller module specified by type.
* @param {string} type A valid access controller type.
* @return {AccessController} The access controller module.
* @private
*/
const getAccessController = (type) => {
if (!accessControllers[type]) {
throw new Error(`AccessController type '${type}' is not supported`)
}
return accessControllers[type]
}
/**
* Adds an access controller module to the list of supported access controller.
* @param {AccessController} accessController A compatible access controller
* module.
* @throws AccessController does not contain required field \'type\'.
* @throws AccessController '${accessController.type}' already added.
* @static
*/
const useAccessController = (accessController) => {
if (!accessController.type) {
throw new Error('AccessController does not contain required field \'type\'.')
}
accessControllers[accessController.type] = accessController
}
useAccessController(_ipfs_js__WEBPACK_IMPORTED_MODULE_0__["default"])
useAccessController(_orbitdb_js__WEBPACK_IMPORTED_MODULE_1__["default"])
/***/ }),
/***/ "./src/access-controllers/ipfs.js":
/*!****************************************!*\
!*** ./src/access-controllers/ipfs.js ***!
\****************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _storage_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../storage/index.js */ "./src/storage/index.js");
/* harmony import */ var multiformats_block__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/block */ "./node_modules/multiformats/src/block.js");
/* harmony import */ var _ipld_dag_cbor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @ipld/dag-cbor */ "./node_modules/@ipld/dag-cbor/src/index.js");
/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/sha2 */ "./node_modules/multiformats/src/hashes/sha2-browser.js");
/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/bases/base58 */ "./node_modules/multiformats/src/bases/base58.js");
/* harmony import */ var _utils_path_join_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/path-join.js */ "./src/utils/path-join.js");
/**
* @namespace AccessControllers-IPFS
* @memberof module:AccessControllers
*/
const codec = _ipld_dag_cbor__WEBPACK_IMPORTED_MODULE_2__
const hasher = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_3__.sha256
const hashStringEncoding = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_4__.base58btc
const AccessControlList = async ({ storage, type, params }) => {
const manifest = {
type,
...params
}
const { cid, bytes } = await multiformats_block__WEBPACK_IMPORTED_MODULE_1__.encode({ value: manifest, codec, hasher })
const hash = cid.toString(hashStringEncoding)
await storage.put(hash, bytes)
return hash
}
const type = 'ipfs'
/**
* Creates an instance of IPFSAccessController.
* @callback IPFSAccessController
* @param {Object} params Various parameters for configuring the access
* controller.
* @param {module:OrbitDB} params.orbitdb An OrbitDB instance.
* @param {module:Identities} params.identities An Identities instance.
* @param {string} [params.address] The address of the database.
* @function
* @instance
* @async
* @memberof module:AccessControllers.AccessControllers-IPFS
* @private
*/
/**
* Defines an IPFS access controller.
* @param {Object} options Various options for configuring the
* IPFSAccessController.
* @param {Array} [params.write] An array of identity ids who can write to the
* database.
* @param {module:Storage} [params.storage] An instance of a compatible storage.
* @return {module:AccessControllers.AccessControllers-IPFS} An
* IPFSAccessController function.
* @memberof module:AccessControllers
*/
const IPFSAccessController = ({ write, storage } = {}) => async ({ orbitdb, identities, address }) => {
storage = storage || await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_0__.ComposedStorage)(
await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_0__.LRUStorage)({ size: 1000 }),
await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_0__.IPFSBlockStorage)({ ipfs: orbitdb.ipfs, pin: true })
)
write = write || [orbitdb.identity.id]
if (address) {
const manifestBytes = await storage.get(address.replaceAll('/ipfs/', ''))
const { value } = await multiformats_block__WEBPACK_IMPORTED_MODULE_1__.decode({ bytes: manifestBytes, codec, hasher })
write = value.write
} else {
address = await AccessControlList({ storage, type, params: { write } })
address = (0,_utils_path_join_js__WEBPACK_IMPORTED_MODULE_5__["default"])('/', type, address)
}
/**
* Verifies the write permission of an entry.
* @param {module:Log~Entry} entry An entry to verify.
* @return {boolean} True if the entry's identity has write permission,
* false otherwise.
* @memberof module:AccessControllers.AccessControllers-IPFS
*/
const canAppend = async (entry) => {
const writerIdentity = await identities.getIdentity(entry.identity)
if (!writerIdentity) {
return false
}
const { id } = writerIdentity
// Allow if the write access list contain the writer's id or is '*'
if (write.includes(id) || write.includes('*')) {
// Check that the identity is valid
return await identities.verifyIdentity(writerIdentity)
}
return false
}
return {
type,
address,
write,
canAppend
}
}
IPFSAccessController.type = type
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (IPFSAccessController);
/***/ }),
/***/ "./src/access-controllers/orbitdb.js":
/*!*******************************************!*\
!*** ./src/access-controllers/orbitdb.js ***!
\*******************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _ipfs_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ipfs.js */ "./src/access-controllers/ipfs.js");
/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/index.js */ "./src/utils/index.js");
/**
* @namespace AccessControllers-OrbitDB
* @memberof module:AccessControllers
*/
const type = 'orbitdb'
/**
* Creates an instance of OrbitDBAccessController.
* @callback OrbitDBAccessController
* @param {Object} params Various parameters for configuring the access
* controller.
* @param {module:OrbitDB} params.orbitdb An OrbitDB instance.
* @param {module:Identities} params.identities An Identities instance.
* @param {string} [params.address] The address of the database.
* @function
* @instance
* @async
* @memberof module:AccessControllers.AccessControllers-OrbitDB
* @private
*/
/**
* Defines an OrbitDB access controller.
* @param {Object} options Various options for configuring the
* IPFSAccessController.
* @param {Array} [params.write] An array of ids of identities who can write to the
* database.
* @return {module:AccessControllers.AccessControllers-OrbitDB} An
* IPFSAccessController function.
* @memberof module:AccessControllers
*/
const OrbitDBAccessController = ({ write } = {}) => async ({ orbitdb, identities, address, name }) => {
address = address || name || await (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.createId)(64)
write = write || [orbitdb.identity.id]
// Open the database used for access information
const db = await orbitdb.open(address, { type: 'keyvalue', AccessController: (0,_ipfs_js__WEBPACK_IMPORTED_MODULE_0__["default"])({ write }) })
address = db.address
/**
* Verifies the write permission of an entry.
* @param {module:Log~Entry} entry An entry to verify.
* @return {boolean} True if the entry's identity has write permission,
* false otherwise.
* @memberof module:AccessControllers.AccessControllers-OrbitDB
* @instance
*/
const canAppend = async (entry) => {
const writerIdentity = await identities.getIdentity(entry.identity)
if (!writerIdentity) {
return false
}
const { id } = writerIdentity
// If the ACL contains the writer's public key or it contains '*'
const hasWriteAccess = await hasCapability('write', id) || await hasCapability('admin', id)
if (hasWriteAccess) {
return await identities.verifyIdentity(writerIdentity)
}
return false
}
/**
* Gets the access capabilities of the OrbitDB access controller.
*
* The returned capabilities will be a mixture of admin and write access
* addresses.
* @return {Array} A list of ids of identities with admin and write access.
* @memberof module:AccessControllers.AccessControllers-OrbitDB
* @instance
*/
const capabilities = async () => {
const _capabilities = []
for await (const entry of db.iterator()) {
_capabilities[entry.key] = entry.value
}
const toSet = (e) => {
const key = e[0]
_capabilities[key] = new Set([...(_capabilities[key] || []), ...e[1]])
}
// Merge with the access controller of the database
// and make sure all values are Sets
Object.entries({
..._capabilities,
// Add the root access controller's 'write' access list
// as admins on this controller
...{ admin: new Set([...(_capabilities.admin || []), ...db.access.write]) }
}).forEach(toSet)
return _capabilities
}
/**
* Gets a list of identities with the specified capability.
* @param {string} capability A capability (e.g. write).
* @return {Array} One or more addresses with the spcified capability.
* @memberof module:AccessControllers.AccessControllers-OrbitDB
* @instance
*/
const get = async (capability) => {
const _capabilities = await capabilities()
return _capabilities[capability] || new Set([])
}
/**
* Close the underlying access control database.
* @memberof module:AccessControllers.AccessControllers-OrbitDB
* @instance
*/
const close = async () => {
await db.close()
}
/**
* Drop the underlying access control database.
* @memberof module:AccessControllers.AccessControllers-OrbitDB
* @instance
*/
const drop = async () => {
await db.drop()
}
/**
* Checks whether an identity has a capability.
* @param {string} capability A capability (e.g. write).
* @param {string} key An id of an identity.
* @return {boolean} True if the identity has the capability, false
* otherwise.
* @memberof module:AccessControllers.AccessControllers-OrbitDB
* @instance
*/
const hasCapability = async (capability, key) => {
// Write keys and admins keys are allowed
const access = new Set(await get(capability))
return access.has(key) || access.has('*')
}
/**
* Grants a capability to an identity, storing it to the access control
* database.
* @param {string} capability A capability (e.g. write).
* @param {string} key An id of an identity.
* @memberof module:AccessControllers.AccessControllers-OrbitDB
* @instance
*/
const grant = async (capability, key) => {
// Merge current keys with the new key
const capabilities = new Set([...(await db.get(capability) || []), ...[key]])
await db.put(capability, Array.from(capabilities.values()))
}
/**
* Revokes a capability from an identity, removing it from the access control
* database.
* @param {string} capability A capability (e.g. write).
* @param {string} key An id of an identity.
* @memberof module:AccessControllers.AccessControllers-OrbitDB
* @instance
*/
const revoke = async (capability, key) => {
const capabilities = new Set(await db.get(capability) || [])
capabilities.delete(key)
if (capabilities.size > 0) {
await db.put(capability, Array.from(capabilities.values()))
} else {
await db.del(capability)
}
}
return {
type,
address,
write,
canAppend,
capabilities,
get,
grant,
revoke,
close,
drop,
events: db.events
}
}
OrbitDBAccessController.type = type
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (OrbitDBAccessController);
/***/ }),
/***/ "./src/address.js":
/*!************************!*\
!*** ./src/address.js ***!
\************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ OrbitDBAddress),
/* harmony export */ isValidAddress: () => (/* binding */ isValidAddress),
/* harmony export */ parseAddress: () => (/* binding */ parseAddress)
/* harmony export */ });
/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/cid */ "./node_modules/multiformats/src/cid.js");
/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/bases/base58 */ "./node_modules/multiformats/src/bases/base58.js");
/* harmony import */ var _utils_path_join_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/path-join.js */ "./src/utils/path-join.js");
/**
* @module Address
* @description OrbitDB database address verification.
*/
/**
* Validates an OrbitDB database address.
* @function
* @param {module:Address~OrbitDBAddress|string} address An OrbitDB database address.
* @return {boolean} True if the address is a valid OrbitDB database address,
* false otherwise.
* @static
*/
const isValidAddress = (address) => {
address = address.toString()
if (!address.startsWith('/orbitdb') && !address.startsWith('\\orbitdb')) {
return false
}
address = address.replaceAll('/orbitdb/', '')
address = address.replaceAll('\\orbitdb\\', '')
address = address.replaceAll('/', '')
address = address.replaceAll('\\', '')
let cid
try {
cid = multiformats_cid__WEBPACK_IMPORTED_MODULE_0__.CID.parse(address, multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_1__.base58btc)
} catch (e) {
return false
}
return cid !== undefined
}
/**
* Parses an OrbitDB database address.
* @function
* @param {module:Address~OrbitDBAddress|string} address A valid OrbitDB database address.
* @return {module:Address~OrbitDBAddress} An instance of OrbitDBAddress.
* @throws Not a valid OrbitDB address if no address if provided.
* @throws Not a valid OrbitDB address if address is invalid.
* @static
*/
const parseAddress = (address) => {
if (!address) {
throw new Error(`Not a valid OrbitDB address: ${address}`)
}
if (!isValidAddress(address)) {
throw new Error(`Not a valid OrbitDB address: ${address}`)
}
return OrbitDBAddress(address)
}
/**
* @typedef {Object} OrbitDBAddress
* @property {string} protocol Protocol prefix "/orbitdb/".
* @property {string} hash The hash of the database manifest.
* @property {string} address The full database address.
*/
const OrbitDBAddress = (address) => {
if (address && address.protocol === 'orbitdb' && address.hash) {
return address
}
const protocol = 'orbitdb'
const hash = address.replace('/orbitdb/', '').replace('\\orbitdb\\', '')
/**
* Returns address as a string.
* @typedef {Function} toString
* @returns {string} Address as a string.
*/
const toString = () => {
return (0,_utils_path_join_js__WEBPACK_IMPORTED_MODULE_2__.posixJoin)('/', protocol, hash)
}
return {
protocol,
hash,
address,
toString
}
}
/***/ }),
/***/ "./src/database.js":
/*!*************************!*\
!*** ./src/database.js ***!
\*************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! events */ "./node_modules/events/events.js");
/* harmony import */ var p_queue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! p-queue */ "./node_modules/p-queue/dist/index.js");
/* harmony import */ var _sync_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./sync.js */ "./src/sync.js");
/* harmony import */ var _oplog_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./oplog/index.js */ "./src/oplog/index.js");
/* harmony import */ var _storage_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./storage/index.js */ "./src/storage/index.js");
/* harmony import */ var _utils_path_join_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/path-join.js */ "./src/utils/path-join.js");
/**
* @module Database
* @description
* Database is the base class for OrbitDB data stores and handles all lower
* level add operations and database sync-ing using IPFS.
*/
const defaultReferencesCount = 16
const defaultCacheSize = 1000
/**
* Creates an instance of Database.
* @function
* @param {Object} params One or more parameters for configuring Database.
* @param {IPFS} params.ipfs An IPFS instance.
* @param {Identity} [params.identity] An Identity instance.
* @param {string} [params.address] The address of the database.
* @param {string} [params.name] The name of the database.
* @param {module:AccessControllers} [params.access] An AccessController
* instance.
* @param {string} [params.directory] A location for storing Database-related
* data. Defaults to ./orbitdb/[params.address].
* @param {*} [params.meta={}] The database's metadata.
* @param {module:Storage} [params.headsStorage] A compatible storage
* instance for storing log heads. Defaults to ComposedStorage.
* @param {module:Storage} [params.entryStorage] A compatible storage instance
* for storing log entries. Defaults to ComposedStorage.
* @param {module:Storage} [params.indexStorage] A compatible storage
* instance for storing an index of log entries. Defaults to ComposedStorage.
* @param {number} [params.referencesCount=16] The maximum distance between
* references to other entries.
* @param {boolean} [params.syncAutomatically=false] If true, sync databases
* automatically. Otherwise, false.
* @param {function} [params.onUpdate] A function callback. Fired when an
* entry is added to the oplog.
* @return {module:Databases~Database} An instance of Database.
* @instance
*/
const Database = async ({ ipfs, identity, address, name, access, directory, meta, headsStorage, entryStorage, indexStorage, referencesCount, syncAutomatically, onUpdate }) => {
/**
* @namespace module:Databases~Database
* @description The instance returned by {@link module:Database~Database}.
*/
/**
* Event fired when an update occurs.
* @event module:Databases~Database#update
* @param {module:Entry} entry An entry.
* @example
* database.events.on('update', (entry) => ...)
*/
/**
* Event fired when a close occurs.
* @event module:Databases~Database#close
* @example
* database.events.on('close', () => ...)
*/
/**
* Event fired when a drop occurs.
* @event module:Databases~Database#drop
* @example
* database.events.on('drop', () => ...)
*/
/** Events inherited from Sync */
/**
* Event fired when when a peer has connected to the database.
* @event module:Databases~Database#join
* @param {PeerID} peerId PeerID of the peer who connected
* @param {Entry[]} heads An array of Log entries
* @example
* database.events.on('join', (peerID, heads) => ...)
*/
/**
* Event fired when a peer has disconnected from the database.
* @event module:Databases~Database#leave
* @param {PeerID} peerId PeerID of the peer who disconnected
* @example
* database.events.on('leave', (peerID) => ...)
*/
directory = (0,_utils_path_join_js__WEBPACK_IMPORTED_MODULE_4__["default"])(directory || './orbitdb', `./${address}/`)
meta = meta || {}
referencesCount = Number(referencesCount) > -1 ? referencesCount : defaultReferencesCount
entryStorage = entryStorage || await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.ComposedStorage)(
await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.LRUStorage)({ size: defaultCacheSize }),
await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.IPFSBlockStorage)({ ipfs, pin: true })
)
headsStorage = headsStorage || await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.ComposedStorage)(
await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.LRUStorage)({ size: defaultCacheSize }),
await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.LevelStorage)({ path: (0,_utils_path_join_js__WEBPACK_IMPORTED_MODULE_4__["default"])(directory, '/log/_heads/') })
)
indexStorage = indexStorage || await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.ComposedStorage)(
await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.LRUStorage)({ size: defaultCacheSize }),
await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.LevelStorage)({ path: (0,_utils_path_join_js__WEBPACK_IMPORTED_MODULE_4__["default"])(directory, '/log/_index/') })
)
const log = await (0,_oplog_index_js__WEBPACK_IMPORTED_MODULE_2__.Log)(identity, { logId: address, access, entryStorage, headsStorage, indexStorage })
const events = new events__WEBPACK_IMPORTED_MODULE_0__.EventEmitter()
const queue = new p_queue__WEBPACK_IMPORTED_MODULE_5__["default"]({ concurrency: 1 })
/**
* Adds an operation to the oplog.
* @function addOperation
* @param {*} op Some operation to add to the oplog.
* @return {string} The hash of the operation.
* @memberof module:Databases~Database
* @instance
* @async
*/
const addOperation = async (op) => {
const task = async () => {
const entry = await log.append(op, { referencesCount })
await sync.add(entry)
if (onUpdate) {
await onUpdate(log, entry)
}
events.emit('update', entry)
return entry.hash
}
const hash = await queue.add(task)
await queue.onIdle()
return hash
}
const applyOperation = async (bytes) => {
const task = async () => {
const entry = await _oplog_index_js__WEBPACK_IMPORTED_MODULE_2__.Entry.decode(bytes)
if (entry) {
const updated = await log.joinEntry(entry)
if (updated) {
if (onUpdate) {
await onUpdate(log, entry)
}
events.emit('update', entry)
}
}
}
await queue.add(task)
}
/**
* Closes the database, stopping sync and closing the oplog.
* @memberof module:Databases~Database
* @instance
* @async
*/
const close = async () => {
await sync.stop()
await queue.onIdle()
await log.close()
if (access && access.close) {
await access.close()
}
events.emit('close')
}
/**
* Drops the database, clearing the oplog.
* @memberof module:Databases~Database
* @instance
* @async
*/
const drop = async () => {
await queue.onIdle()
await log.clear()
if (access && access.drop) {
await access.drop()
}
events.emit('drop')
}
const sync = await (0,_sync_js__WEBPACK_IMPORTED_MODULE_1__["default"])({ ipfs, log, events, onSynced: applyOperation, start: syncAutomatically })
return {
/**
* The address of the database.
* @†ype string
* @memberof module:Databases~Database
* @instance
*/
address,
/**
* The name of the database.
* @†ype string
* @memberof module:Databases~Database
* @instance
*/
name,
identity,
meta,
close,
drop,
addOperation,
/**
* The underlying [operations log]{@link module:Log~Log} of the database.
* @†ype {module:Log~Log}
* @memberof module:Databases~Database
* @instance
*/
log,
/**
* A [sync]{@link module:Sync~Sync} instance of the database.
* @†ype {module:Sync~Sync}
* @memberof module:Databases~Database
* @instance
*/
sync,
/**
* Set of currently connected peers for this Database instance.
* @†ype Set
* @memberof module:Databases~Database
* @instance
*/
peers: sync.peers,
/**
* Event emitter that emits Database changes. See Events section for details.
* @†ype EventEmitter
* @memberof module:Databases~Database
* @instance
*/
events,
/**
* The [access controller]{@link module:AccessControllers} instance of the database.
* @memberof module:Databases~Database
* @instance
*/
access
}
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Database);
/***/ }),
/***/ "./src/databases/documents.js":
/*!************************************!*\
!*** ./src/databases/documents.js ***!
\************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _database_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../database.js */ "./src/database.js");
/**
* @namespace Databases-Documents
* @memberof module:Databases
* @description Documents database.
* @example <caption>Create documents db with custom index</caption>
* import { createHelia } from 'helia'
* import { createOrbitDB, Documents } from 'orbitdb'
*
* const ipfs = createHelia()
* const orbitdb = await createOrbitDB({ ipfs })
* const db = await orbitdb.open('my-docs', { Database: Documents({ indexBy: 'myCustomId'} ) }
*
* @augments module:Databases~Database
*/
const type = 'documents'
const DefaultOptions = { indexBy: '_id' }
/**
* Defines a Documents database.
* @param {Object} options Various options for configuring the Document store.
* @param {string} [options.indexBy=_id] An index.
* @return {module:Databases.Databases-Documents} A Documents function.
* @memberof module:Databases
*/
const Documents = ({ indexBy } = DefaultOptions) => async ({ ipfs, identity, address, name, access, directory, meta, headsStorage, entryStorage, indexStorage, referencesCount, syncAutomatically, onUpdate }) => {
const database = await (0,_database_js__WEBPACK_IMPORTED_MODULE_0__["default"])({ ipfs, identity, address, name, access, directory, meta, headsStorage, entryStorage, indexStorage, referencesCount, syncAutomatically })
const { addOperation, log } = database
/**
* Stores a document to the store.
* @function
* @param {Object} doc An object representing a key/value list of fields.
* @return {string} The hash of the new oplog entry.
* @memberof module:Databases.Databases-Documents
* @instance
*/
const put = async (doc) => {
const key = doc[indexBy]
if (!key) { throw new Error(`The provided document doesn't contain field '${indexBy}'`) }
return addOperation({ op: 'PUT', key, value: doc })
}
/**
* Deletes a document from the store.
* @function
* @param {string} key The key of the doc to delete.
* @return {string} The hash of the new oplog entry.
* @memberof module:Databases.Databases-Documents
* @instance
*/
const del = async (key) => {
if (!await get(key)) { throw new Error(`No document with key '${key}' in the database`) }
return addOperation({ op: 'DEL', key, value: null })
}
/**
* Gets a document from the store by key.
* @function
* @param {string} key The key of the doc to get.
* @return {Object} The doc corresponding to key or null.
* @memberof module:Databases.Databases-Documents
* @instance
*/
const get = async (key) => {
for await (const doc of iterator()) {
if (key === doc.key) {
return doc
}
}
}
/**
* Queries the document store for documents matching mapper filters.
* @function
* @param {function(Object)} findFn A function for querying for specific
* results.
*
* The findFn function's signature takes the form `function(doc)` where doc
* is a document's value property. The function should return true if the
* document should be included in the results, false otherwise.
* @return {Array} Found documents.
* @memberof module:Databases.Databases-Documents
* @instance
*/
const query = async (findFn) => {
const results = []
for await (const doc of iterator()) {
if (findFn(doc.value)) {
results.push(doc.value)
}
}
return results
}
/**
* Iterates over documents.
* @function
* @param {Object} [filters={}] Various filters to apply to the iterator.
* @param {string} [filters.amount=-1] The number of results to fetch.
* @yields [string, string, string] The next document as hash/key/value.
* @memberof module:Databases.Databases-Documents
* @instance
*/
const iterator = async function * ({ amount } = {}) {
const keys = {}
let count = 0
for await (const entry of log.iterator()) {
const { op, key, value } = entry.payload
if (op === 'PUT' && !keys[key]) {
keys[key] = true
count++
const hash = entry.hash
yield { hash, key, value }
} else if (op === 'DEL' && !keys[key]) {
keys[key] = true
}
if (count >= amount) {
break
}
}
}
/**
* Returns all documents.
* @function
* @return [][string, string, string] An array of documents as hash/key
* value entries.
* @memberof module:Databases.Databases-Documents
* @instance
*/
const all = async () => {
const values = []
for await (const entry of iterator()) {
values.unshift(entry)
}
return values
}
return {
...database,
type,
put,
del,
get,
iterator,
query,
indexBy,
all
}
}
Documents.type = type
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Documents);
/***/ }),
/***/ "./src/databases/events.js":
/*!*********************************!*\
!*** ./src/databases/events.js ***!
\*********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _database_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../database.js */ "./src/database.js");
/**
* @namespace Databases-Events
* @memberof module:Databases
* @description
* Events database is an immutable, append-only event log database.
*
* @augments module:Databases~Database
*/
const type = 'events'
/**
* Defines an Events database.
* @return {module:Databases.Databases-Events} A Events function.
* @memberof module:Databases
*/
const Events = () => async ({ ipfs, identity, address, name, access, directory, meta, headsStorage, entryStorage, indexStorage, referencesCount, syncAutomatically, onUpdate }) => {
const database = await (0,_database_js__WEBPACK_IMPORTED_MODULE_0__["default"])({ ipfs, identity, address, name, access, directory, meta, headsStorage, entryStorage, indexStorage, referencesCount, syncAutomatically, onUpdate })
const { addOperation, log } = database
/**
* Adds an event to the store.
* @function
* @param {*} value The event to be added.
* @return {string} The hash of the new oplog entry.
* @memberof module:Databases.Databases-Events
* @instance
*/
const add = async (value) => {
return addOperation({ op: 'ADD', key: null, value })
}
/**
* Gets an event from the store by hash.
* @function
* @param {string} hash The hash of the event to get.
* @return {*} The value corresponding to hash or null.
* @memberof module:Databases.Databases-Events
* @instance
*/
const get = async (hash) => {
const entry = await log.get(hash)
return entry.payload.value
}
/**
* Iterates over events.
* @function
* @param {Object} [filters={}] Various filters to apply to the iterator.
* @param {string} [filters.gt] All events which are greater than the
* given hash.
* @param {string} [filters.gte] All events which are greater than or equal
* to the given hash.
* @param {string} [filters.lt] All events which are less than the given
* hash.
* @param {string} [filters.lte] All events which are less than or equal to
* the given hash.
* @param {string} [filters.amount=-1] The number of results to fetch.
* @yields [string, string] The next event as hash/value.
* @memberof module:Databases.Databases-Events
* @instance
*/
const iterator = async function * ({ gt, gte, lt, lte, amount } = {}) {
const it = log.iterator({ gt, gte, lt, lte, amount })
for await (const event of it) {
const hash = event.hash
const value = event.payload.value
yield { hash, value }
}
}
/**
* Returns all events.
* @function
* @return [][string, string] An array of events as hash/value entries.
* @memberof module:Databases.Databases-Events
* @instance
*/
const all = async () => {
const values = []
for await (const entry of iterator()) {
values.unshift(entry)
}
return values
}
return {
...database,
type,
add,
get,
iterator,
all
}
}
Events.type = type
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Events);
/***/ }),
/***/ "./src/databases/index.js":
/*!********************************!*\
!*** ./src/databases/index.js ***!
\********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Documents: () => (/* reexport safe */ _documents_js__WEBPACK_IMPORTED_MODULE_0__["default"]),
/* harmony export */ Events: () => (/* reexport safe */ _events_js__WEBPACK_IMPORTED_MODULE_1__["default"]),
/* harmony export */ KeyValue: () => (/* reexport safe */ _keyvalue_js__WEBPACK_IMPORTED_MODULE_2__["default"]),
/* harmony export */ KeyValueIndexed: () => (/* reexport safe */ _keyvalue_indexed_js__WEBPACK_IMPORTED_MODULE_3__["default"]),
/* harmony export */ getDatabaseType: () => (/* binding */ getDatabaseType),
/* harmony export */ useDatabaseType: () => (/* binding */ useDatabaseType)
/* harmony export */ });
/* harmony import */ var _documents_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./documents.js */ "./src/databases/documents.js");
/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./events.js */ "./src/databases/events.js");
/* harmony import */ var _keyvalue_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./keyvalue.js */ "./src/databases/keyvalue.js");
/* harmony import */ var _keyvalue_indexed_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./keyvalue-indexed.js */ "./src/databases/keyvalue-indexed.js");
/**
* @module Databases
* @description
* Provides various database structures for storing data.
*/
/**
* An array of available database types.
* @name databaseTypes
* @†ype []
* @return [] An array of database types.
* @memberof module:Databases
*/
const databaseTypes = {}
/**
* Add a new database type.
* @example
* import { useDatabaseType } from 'orbitdb'
* const CustomDBTypeModule = async (params) => {
* const database = await Database(...params)
* ...
* }
* useDatabaseType(CustomDBTypeModule)
* @function useDatabaseType
* @param {module:Databases} database A Database-compatible module.
* @throws Database type does not contain required field \'type\'.
* @throws Database type '${store.type}' already added.
* @memberof module:Databases
*/
const useDatabaseType = (database) => {
if (!database.type) {
throw new Error('Database type does not contain required field \'type\'.')
}
databaseTypes[database.type] = database
}
const getDatabaseType = (type) => {
if (!type) {
throw new Error('Type not specified')
}
if (!databaseTypes[type]) {
throw new Error(`Unsupported database type: '${type}'`)
}
return databaseTypes[type]
}
useDatabaseType(_events_js__WEBPACK_IMPORTED_MODULE_1__["default"])
useDatabaseType(_documents_js__WEBPACK_IMPORTED_MODULE_0__["default"])
useDatabaseType(_keyvalue_js__WEBPACK_IMPORTED_MODULE_2__["default"])
/***/ }),
/***/ "./src/databases/keyvalue-indexed.js":
/*!*******************************************!*\
!*** ./src/databases/keyvalue-indexed.js ***!
\*******************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _keyvalue_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./keyvalue.js */ "./src/databases/keyvalue.js");
/* harmony import */ var _storage_level_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../storage/level.js */ "./src/storage/level.js");
/* harmony import */ var _utils_path_join_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/path-join.js */ "./src/utils/path-join.js");
/**
* @namespace Databases-KeyValueIndexed
* @memberof module:Databases
* @description
* Key-Value database that uses an index in order to provide fast queries.
*
* Key-value pairs are stored to the configured storage.
* @example <caption>Specify a custom storage</caption>
* import { createHelia } from 'helia'
* import { createOrbitDB, KeyValueIndexed, IPFSBlockStorage } from 'orbitdb'
*
* const ipfs = createHelia()
* const storage = await IPFSBlockStorage({ ipfs })
* const orbitdb = await createOrbitDB({ ipfs })
* const db = await orbitdb.open('my-kv', { Database: KeyValueIndexed({ storage }) })
*
* @augments module:Databases~Database
* @augments module:Databases.Databases-KeyValue
*/
const valueEncoding = 'json'
/**
* Defines an index for a KeyValue database.
* @param {string} [directory] A location for storing the index-related data
* @return {Index} A Index function.
*/
const Index = ({ directory } = {}) => async () => {
const index = await (0,_storage_level_js__WEBPACK_IMPORTED_MODULE_1__["default"])({ path: directory, valueEncoding })
const indexedEntries = await (0,_storage_level_js__WEBPACK_IMPORTED_MODULE_1__["default"])({ path: (0,_utils_path_join_js__WEBPACK_IMPORTED_MODULE_2__["default"])(directory, '/_indexedEntries/'), valueEncoding })
const update = async (log, entry) => {
const keys = new Set()
const toBeIndexed = new Set()
const latest = entry.hash
// Function to check if a hash is in the entry index
const isIndexed = async (hash) => (await indexedEntries.get(hash)) === true
const isNotIndexed = async (hash) => !(await isIndexed(hash))
// Function to decide when the log traversal should be stopped
const shoudStopTraverse = async (entry) => {
// Go through the nexts of an entry and if any is not yet
// indexed, add it to the list of entries-to-be-indexed
for await (const hash of entry.next) {
if (await isNotIndexed(hash)) {
toBeIndexed.add(hash)
}
}
// If the latest entry and all its nexts are indexed and to-be-indexed list is empty,
// we don't have anything more to process, so return true to stop the traversal
return await isIndexed(latest) && toBeIndexed.size === 0
}
// Traverse the log and stop when everything has been processed
for await (const entry of log.traverse(null, shoudStopTraverse)) {
const { hash, payload } = entry
// If an entry is not yet indexed, process it
if (await isNotIndexed(hash)) {
const { op, key } = payload
if (op === 'PUT' && !keys.has(key)) {
keys.add(key)
await index.put(key, entry)
await indexedEntries.put(hash, true)
} else if (op === 'DEL' && !keys.has(key)) {
keys.add(key)
await index.del(key)
await indexedEntries.put(hash, true)
}
// Remove the entry (hash) from the list of to-be-indexed entries
toBeIndexed.delete(hash)
}
}
}
/**
* Closes the index and its storages.
*/
const close = async () => {
await index.close()
await indexedEntries.close()
}
/**
* Drops all records from the index and its storages.
*/
const drop = async () => {
await index.clear()
await indexedEntries.clear()
}
return {
get: index.get,
iterator: index.iterator,
update,
close,
drop
}
}
/**
* Defines a KeyValueIndexed database.
* @param {module:Storage} [storage=LevelStorage] A compatible storage where
* the key/value pairs are indexed.
* @return {module:Databases.Databases-KeyValueIndexed} A KeyValueIndexed
* function.
* @memberof module:Databases
*/
const KeyValueIndexed = () => async ({ ipfs, identity, address, name, access, directory, meta, headsStorage, entryStorage, indexStorage, referencesCount, syncAutomatically, onUpdate }) => {
// Set up the directory for an index
directory = (0,_utils_path_join_js__WEBPACK_IMPORTED_MODULE_2__["default"])(directory || './orbitdb', `./${address}/_index/`)
// Set up the index
const index = await Index({ directory })()
// Set up the underlying KeyValue database
const keyValueStore = await (0,_keyvalue_js__WEBPACK_IMPORTED_MODULE_0__["default"])()({ ipfs, identity, address, name, access, directory, meta, headsStorage, entryStorage, indexStorage, referencesCount, syncAutomatically, onUpdate: index.update })
/**
* Gets a value from the store by key.
* @function
* @param {string} key The key of the value to get.
* @return {*} The value corresponding to key or null.
* @memberof module:Databases.Databases-KeyValueIndexed
* @instance
*/
const get = async (key) => {
const entry = await index.get(key)
if (entry) {
return entry.payload.value
}
}
/**
* Iterates over keyvalue pairs.
* @function
* @param {Object} [filters={}] Various filters to apply to the iterator.
* @param {string} [filters.amount=-1] The number of results to fetch.
* @yields [string, string, string] The next key/value as key/value/hash.
* @memberof module:Databases.Databases-KeyValueIndexed
* @instance
*/
const iterator = async function * ({ amount } = {}) {
const it = index.iterator({ amount, reverse: true })
for await (const record of it) {
// 'index' is a LevelStorage that returns a [key, value] pair
const entry = record[1]
const { key, value } = entry.payload
const hash = entry.hash
yield { key, value, hash }
}
}
/**
* Closes the index and underlying storage.
*/
const close = async () => {
await keyValueStore.close()
await index.close()
}
/**
* Drops all records from the index and underlying storage.
*/
const drop = async () => {
await keyValueStore.drop()
await index.drop()
}
return {
...keyValueStore,
get,
iterator,
close,
drop
}
}
KeyValueIndexed.type = 'keyvalue'
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (KeyValueIndexed);
/***/ }),
/***/ "./src/databases/keyvalue.js":
/*!***********************************!*\
!*** ./src/databases/keyvalue.js ***!
\***********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _database_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../database.js */ "./src/database.js");
/**
* @namespace Databases-KeyValue
* @memberof module:Databases
* @description
* Key-Value database.
*
* @augments module:Databases~Database
*/
const type = 'keyvalue'
/**
* Defines a KeyValue database.
* @return {module:Databases.Databases-KeyValue} A KeyValue function.
* @memberof module:Databases
*/
const KeyValue = () => async ({ ipfs, identity, address, name, access, directory, meta, headsStorage, entryStorage, indexStorage, referencesCount, syncAutomatically, onUpdate }) => {
const database = await (0,_database_js__WEBPACK_IMPORTED_MODULE_0__["default"])({ ipfs, identity, address, name, access, directory, meta, headsStorage, entryStorage, indexStorage, referencesCount, syncAutomatically, onUpdate })
const { addOperation, log } = database
/**
* Stores a key/value pair to the store.
* @function
* @param {string} key The key to store.
* @param {*} value The value to store.
* @return {string} The hash of the new oplog entry.
* @memberof module:Databases.Databases-KeyValue
* @instance
*/
const put = async (key, value) => {
return addOperation({ op: 'PUT', key, value })
}
/**
* Deletes a key/value pair from the store.
* @function
* @param {string} key The key of the key/value pair to delete.
* @memberof module:Databases.Databases-KeyValue
* @instance
*/
const del = async (key) => {
return addOperation({ op: 'DEL', key, value: null })
}
/**
* Gets a value from the store by key.
* @function
* @param {string} key The key of the value to get.
* @return {*} The value corresponding to key or null.
* @memberof module:Databases.Databases-KeyValue
* @instance
*/
const get = async (key) => {
for await (const entry of log.traverse()) {
const { op, key: k, value } = entry.payload
if (op === 'PUT' && k === key) {
return value
} else if (op === 'DEL' && k === key) {
return
}
}
}
/**
* Iterates over keyvalue pairs.
* @function
* @param {Object} [filters={}] Various filters to apply to the iterator.
* @param {string} [filters.amount=-1] The number of results to fetch.
* @yields [string, string, string] The next key/value as key/value/hash.
* @memberof module:Databases.Databases-KeyValue
* @instance
*/
const iterator = async function * ({ amount } = {}) {
const keys = {}
let count = 0
for await (const entry of log.traverse()) {
const { op, key, value } = entry.payload
if (op === 'PUT' && !keys[key]) {
keys[key] = true
count++
const hash = entry.hash
yield { key, value, hash }
} else if (op === 'DEL' && !keys[key]) {
keys[key] = true
}
if (count >= amount) {
break
}
}
}
/**
* Returns all key/value pairs.
* @function
* @return [][string, string, string] An array of key/value pairs as
* key/value/hash entries.
* @memberof module:Databases.Databases-KeyValue
* @instance
*/
const all = async () => {
const values = []
for await (const entry of iterator()) {
values.unshift(entry)
}
return values
}
return {
...database,
type,
put,
set: put, // Alias for put()
del,
get,
iterator,
all
}
}
KeyValue.type = type
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (KeyValue);
/***/ }),
/***/ "./src/identities/identities.js":
/*!**************************************!*\
!*** ./src/identities/identities.js ***!
\**************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ Identities)
/* harmony export */ });
/* harmony import */ var _identity_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./identity.js */ "./src/identities/identity.js");
/* harmony import */ var _providers_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./providers/index.js */ "./src/identities/providers/index.js");
/* harmony import */ var _key_store_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../key-store.js */ "./src/key-store.js");
/* harmony import */ var _storage_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../storage/index.js */ "./src/storage/index.js");
/* harmony import */ var _utils_path_join_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/path-join.js */ "./src/utils/path-join.js");
/**
* @module Identities
* @description
* Identities provides a framework for generating and managing identity
* details and providers.
*/
// import DIDIdentityProvider from './identity-providers/did.js'
// import EthIdentityProvider from './identity-providers/ethereum.js'
const DefaultIdentityKeysPath = (0,_utils_path_join_js__WEBPACK_IMPORTED_MODULE_4__["default"])('./orbitdb', 'identities')
/**
* Creates an instance of Identities.
* @function
* @param {Object} params One or more parameters for configuring Identities.
* @param {module:KeyStore} [params.keystore] A preconfigured KeyStore.
* A KeyStore will be created in the path defined by the path param. If neither
* Keystore nor path are defined, a new KeyStore is stored in ./orbitdb
* identities.
* @param {string} [params.path] The path to a KeyStore. If no path is
* provided, the default is ./orbitdb/identities.
* @param {module:Storage} [params.storage] An instance of a compatible storage
* module.
* @param {IPFS} [params.ipfs] An instance of IPFS. This param is not required
* if storage is provided.
* @return {module:Identities~Identities} An instance of Identities.
* @instance
*/
const Identities = async ({ keystore, path, storage, ipfs } = {}) => {
/**
* @namespace module:Identities~Identities
* @description The instance returned by {@link module:Identities}.
*/
keystore = keystore || await (0,_key_store_js__WEBPACK_IMPORTED_MODULE_2__["default"])({ path: path || DefaultIdentityKeysPath })
if (!storage) {
storage = ipfs
? await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.ComposedStorage)(await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.LRUStorage)({ size: 1000 }), await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.IPFSBlockStorage)({ ipfs, pin: true }))
: await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.MemoryStorage)()
}
const verifiedIdentitiesCache = await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_3__.LRUStorage)({ size: 1000 })
/**
* Gets an identity by hash.
* @param {string} hash An identity hash.
* @return {module:Identities~Identity} An instance of identity.
* @memberof module:Identities~Identities
* @instance
*/
const getIdentity = async (hash) => {
const bytes = await storage.get(hash)
if (bytes) {
return (0,_identity_js__WEBPACK_IMPORTED_MODULE_0__.decodeIdentity)(bytes)
}
}
/**
* Creates an identity, adding it to storage.
* @param {Object} options Various options for configuring a new identity.
* @param {Function} [options.provider=PublicKeyIdentityProvider()] An instance of the Provider to use for generating an identity, e.g. PublicKeyIdentityProvider({ keystore })
* @return {module:Identities~Identity} An instance of identity.
* @memberof module:Identities~Identities
* @instance
*/
const createIdentity = async (options = {}) => {
options.keystore = keystore
const DefaultIdentityProvider = (0,_providers_index_js__WEBPACK_IMPORTED_MODULE_1__.getIdentityProvider)('publickey')
const identityProviderInit = options.provider || DefaultIdentityProvider({ keystore })
const identityProvider = await identityProviderInit()
if (!(0,_providers_index_js__WEBPACK_IMPORTED_MODULE_1__.getIdentityProvider)(identityProvider.type)) {
throw new Error('Identity provider is unknown. Use useIdentityProvider(provider) to register the identity provider')
}
const id = await identityProvider.getId(options)
const privateKey = await keystore.getKey(id) || await keystore.createKey(id)
const publicKey = keystore.getPublic(privateKey)
const idSignature = await (0,_key_store_js__WEBPACK_IMPORTED_MODULE_2__.signMessage)(privateKey, id)
const publicKeyAndIdSignature = await identityProvider.signIdentity(publicKey + idSignature, options)
const signatures = {
id: idSignature,
publicKey: publicKeyAndIdSignature
}
const identity = await (0,_identity_js__WEBPACK_IMPORTED_MODULE_0__["default"])({ id, publicKey, signatures, type: identityProvider.type, sign, verify })
await storage.put(identity.hash, identity.bytes)
return identity
}
/**
* Verifies an identity using the identity's provider.
* @param {module:Identities~Identity} identity The identity to verify.
* @return {boolean} True the identity is valid, false otherwise.
* @memberof module:Identities~Identities
*/
const verifyIdentity = async (identity) => {
if (!(0,_identity_js__WEBPACK_IMPORTED_MODULE_0__.isIdentity)(identity)) {
return false
}
const { id, publicKey, signatures } = identity
const idSignatureVerified = await verify(signatures.id, publicKey, id)
if (!idSignatureVerified) {
return false
}
const verifiedIdentity = await verifiedIdentitiesCache.get(signatures.id)
if (verifiedIdentity) {
return (0,_identity_js__WEBPACK_IMPORTED_MODULE_0__.isEqual)(identity, verifiedIdentity)
}
const Provider = (0,_providers_index_js__WEBPACK_IMPORTED_MODULE_1__.getIdentityProvider)(identity.type)
const identityVerified = await Provider.verifyIdentity(identity)
if (identityVerified) {
await verifiedIdentitiesCache.put(signatures.id, identity)
}
return identityVerified
}
/**
* Signs data using an identity.
* @param {module:Identities~Identity} identity The identity to use for
* signing.
* @param {string} data The data to sign.
* @return {string} The signed data.
* @throws Private signing key not found from KeyStore when no signing key can
* be retrieved.
* @memberof module:Identities~Identities
* @instance
* @private
*/
const sign = async (identity, data) => {
const signingKey = await keystore.getKey(identity.id)
if (!signingKey) {
throw new Error('Private signing key not found from KeyStore')
}
return await (0,_key_store_js__WEBPACK_IMPORTED_MODULE_2__.signMessage)(signingKey, data)
}
/**
* Verifies data using a valid signature and publicKey.
* @param {string} signature A signature.
* @param {string} publicKey A public key.
* @param {string} data The data to be verified.
* @return {boolean} True if the the data is signed by the publicKey, false
* otherwise.
* @memberof module:Identities~Identities
* @instance
* @private
*/
const verify = async (signature, publicKey, data) => {
return await (0,_key_store_js__WEBPACK_IMPORTED_MODULE_2__.verifyMessage)(signature, publicKey, data)
}
return {
createIdentity,
verifyIdentity,
getIdentity,
sign,
verify,
keystore
}
}
/***/ }),
/***/ "./src/identities/identity.js":
/*!************************************!*\
!*** ./src/identities/identity.js ***!
\************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decodeIdentity: () => (/* binding */ decodeIdentity),
/* harmony export */ "default": () => (/* binding */ Identity),
/* harmony export */ isEqual: () => (/* binding */ isEqual),
/* harmony export */ isIdentity: () => (/* binding */ isIdentity)
/* harmony export */ });
/* harmony import */ var multiformats_block__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/block */ "./node_modules/multiformats/src/block.js");
/* harmony import */ var _ipld_dag_cbor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @ipld/dag-cbor */ "./node_modules/@ipld/dag-cbor/src/index.js");
/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/hashes/sha2 */ "./node_modules/multiformats/src/hashes/sha2-browser.js");
/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/bases/base58 */ "./node_modules/multiformats/src/bases/base58.js");
const codec = _ipld_dag_cbor__WEBPACK_IMPORTED_MODULE_1__
const hasher = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_2__.sha256
const hashStringEncoding = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_3__.base58btc
/**
* @typedef {Object} module:Identities~Identity
* @property {string} id A unique identifer for the identity.
* @property {object} publicKey A public key.
* @property {object} signatures A signed identity id and public key.
* @property {string} type The type of identity provider.
* @property {function} sign A sign function to sign data using this identity.
* @property {function} verify A verify function to verify data signed by this identity.
*/
const Identity = async ({ id, publicKey, signatures, type, sign, verify } = {}) => {
/**
* @description The Identity instance. Returned by
* [Identities.createIdentity()]{@link module:Identities~Identities#createIdentity}.
*/
if (!id) throw new Error('Identity id is required')
if (!publicKey) throw new Error('Invalid public key')
if (!signatures) throw new Error('Signatures object is required')
if (!signatures.id) throw new Error('Signature of id is required')
if (!signatures.publicKey) throw new Error('Signature of publicKey+id is required')
if (!type) throw new Error('Identity type is required')
signatures = Object.assign({}, signatures)
const identity = {
id,
publicKey,
signatures,
type,
sign,
verify
}
const { hash, bytes } = await _encodeIdentity(identity)
identity.hash = hash
identity.bytes = bytes
return identity
}
const _encodeIdentity = async (identity) => {
const { id, publicKey, signatures, type } = identity
const value = { id, publicKey, signatures, type }
const { cid, bytes } = await multiformats_block__WEBPACK_IMPORTED_MODULE_0__.encode({ value, codec, hasher })
const hash = cid.toString(hashStringEncoding)
return { hash, bytes: Uint8Array.from(bytes) }
}
const decodeIdentity = async (bytes) => {
const { value } = await multiformats_block__WEBPACK_IMPORTED_MODULE_0__.decode({ bytes, codec, hasher })
return Identity({ ...value })
}
/**
* Verifies whether an identity is valid.
* @param {Identity} identity The identity to verify.
* @return {boolean} True if the identity is valid, false otherwise.
* @static
* @private
*/
const isIdentity = (identity) => {
return Boolean(identity.id &&
identity.hash &&
identity.bytes &&
identity.publicKey &&
identity.signatures &&
identity.signatures.id &&
identity.signatures.publicKey &&
identity.type)
}
/**
* Evaluates whether two identities are equal.
* @param {Identity} a First identity.
* @param {Identity} b Second identity.
* @return {boolean} True if identity a and b are equal, false otherwise.
* @static
* @private
*/
const isEqual = (a, b) => {
return a.id === b.id &&
a.hash === b.hash &&
a.type === b.type &&
a.publicKey === b.publicKey &&
a.signatures.id === b.signatures.id &&
a.signatures.publicKey === b.signatures.publicKey
}
/***/ }),
/***/ "./src/identities/index.js":
/*!*********************************!*\
!*** ./src/identities/index.js ***!
\*********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Identities: () => (/* reexport safe */ _identities_js__WEBPACK_IMPORTED_MODULE_0__["default"]),
/* harmony export */ Identity: () => (/* reexport safe */ _identity_js__WEBPACK_IMPORTED_MODULE_1__["default"]),
/* harmony export */ PublicKeyIdentityProvider: () => (/* reexport safe */ _providers_index_js__WEBPACK_IMPORTED_MODULE_2__.PublicKeyIdentityProvider),
/* harmony export */ getIdentityProvider: () => (/* reexport safe */ _providers_index_js__WEBPACK_IMPORTED_MODULE_2__.getIdentityProvider),
/* harmony export */ isEqual: () => (/* reexport safe */ _identity_js__WEBPACK_IMPORTED_MODULE_1__.isEqual),
/* harmony export */ isIdentity: () => (/* reexport safe */ _identity_js__WEBPACK_IMPORTED_MODULE_1__.isIdentity),
/* harmony export */ useIdentityProvider: () => (/* reexport safe */ _providers_index_js__WEBPACK_IMPORTED_MODULE_2__.useIdentityProvider)
/* harmony export */ });
/* harmony import */ var _identities_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./identities.js */ "./src/identities/identities.js");
/* harmony import */ var _identity_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./identity.js */ "./src/identities/identity.js");
/* harmony import */ var _providers_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./providers/index.js */ "./src/identities/providers/index.js");
/***/ }),
/***/ "./src/identities/providers/index.js":
/*!*******************************************!*\
!*** ./src/identities/providers/index.js ***!
\*******************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ PublicKeyIdentityProvider: () => (/* reexport safe */ _publickey_js__WEBPACK_IMPORTED_MODULE_0__["default"]),
/* harmony export */ getIdentityProvider: () => (/* binding */ getIdentityProvider),
/* harmony export */ useIdentityProvider: () => (/* binding */ useIdentityProvider)
/* harmony export */ });
/* harmony import */ var _publickey_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./publickey.js */ "./src/identities/providers/publickey.js");
const identityProviders = {}
const isProviderSupported = (type) => {
return Object.keys(identityProviders).includes(type)
}
const getIdentityProvider = (type) => {
if (!isProviderSupported(type)) {
throw new Error(`IdentityProvider type '${type}' is not supported`)
}
return identityProviders[type]
}
/**
* Adds an identity provider.
* @param {IdentityProvider} identityProvider The identity provider to add.
* @throws Given IdentityProvider doesn\'t have a field \'type\'.
* @throws Given IdentityProvider doesn\'t have a function \'verifyIdentity\'.
* @throws IdentityProvider ${IdentityProvider.type} already added.
* @static
* @memberof module:Identities
*/
const useIdentityProvider = (identityProvider) => {
if (!identityProvider.type ||
typeof identityProvider.type !== 'string') {
throw new Error('Given IdentityProvider doesn\'t have a field \'type\'.')
}
if (!identityProvider.verifyIdentity) {
throw new Error('Given IdentityProvider doesn\'t have a function \'verifyIdentity\'.')
}
identityProviders[identityProvider.type] = identityProvider
}
useIdentityProvider(_publickey_js__WEBPACK_IMPORTED_MODULE_0__["default"])
/***/ }),
/***/ "./src/identities/providers/publickey.js":
/*!***********************************************!*\
!*** ./src/identities/providers/publickey.js ***!
\***********************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/to-string */ "./node_modules/uint8arrays/dist/src/to-string.js");
/* harmony import */ var _key_store_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../key-store.js */ "./src/key-store.js");
/**
* @memberof module:IdentityProviders
* @description
* The PublicKey Identity Provider signs and verifies an identity using the
* public key of a private/public key pair.
*/
const type = 'publickey'
/**
* Verifies an identity using the identity's id.
* @param {module:Identity} identity
* @return {boolean} True if the identity is valid, false otherwise.
* @static
* @private
*/
const verifyIdentity = async identity => {
const { id, publicKey, signatures } = identity
return (0,_key_store_js__WEBPACK_IMPORTED_MODULE_1__.verifyMessage)(signatures.publicKey, id, publicKey + signatures.id)
}
/**
* Instantiates the publickey identity provider.
* @return {module:IdentityProviders.IdentityProvider-PublicKey} A public key
* identity provider function.
* @private
*/
const PublicKeyIdentityProvider = ({ keystore }) => async () => {
/**
* @namespace module:IdentityProviders.IdentityProvider-PublicKey
* @memberof module:IdentityProviders
* @description The instance returned by {@link module:IdentityProviders.IdentityProvider-PublicKey}.
* @private
*/
if (!keystore) {
throw new Error('PublicKeyIdentityProvider requires a keystore parameter')
}
/**
* Gets the id.
* @memberof module:IdentityProviders.IdentityProvider-PublicKey
* @param {string} id The id to retrieve.
* @return {string} The identity's id.
* @instance
*/
const getId = async ({ id } = {}) => {
if (!id) {
throw new Error('id is required')
}
const key = await keystore.getKey(id) || await keystore.createKey(id)
return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_0__.toString)(key.publicKey.raw, 'base16')
}
/**
* Signs an identity using the identity's id.
* @memberof module:IdentityProviders.IdentityProvider-PublicKey
* @param {*} data The identity data to sign.
* @param {Object} params One or more parameters for configuring Database.
* @param {string} [params.id] The identity's id.
* @return {string} A signature.
* @instance
*/
const signIdentity = async (data, { id } = {}) => {
if (!id) {
throw new Error('id is required')
}
const key = await keystore.getKey(id)
if (!key) {
throw new Error(`Signing key for '${id}' not found`)
}
return (0,_key_store_js__WEBPACK_IMPORTED_MODULE_1__.signMessage)(key, data)
}
return {
type,
getId,
signIdentity
}
}
PublicKeyIdentityProvider.verifyIdentity = verifyIdentity
PublicKeyIdentityProvider.type = type
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (PublicKeyIdentityProvider);
/***/ }),
/***/ "./src/key-store.js":
/*!**************************!*\
!*** ./src/key-store.js ***!
\**************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ KeyStore),
/* harmony export */ signMessage: () => (/* binding */ signMessage),
/* harmony export */ verifyMessage: () => (/* binding */ verifyMessage)
/* harmony export */ });
/* harmony import */ var _libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/crypto/keys */ "./node_modules/@libp2p/crypto/dist/src/keys/index.js");
/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/from-string */ "./node_modules/uint8arrays/dist/src/from-string.js");
/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/to-string */ "./node_modules/uint8arrays/dist/src/to-string.js");
/* harmony import */ var uint8arrays_compare__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/compare */ "./node_modules/uint8arrays/dist/src/compare.js");
/* harmony import */ var _storage_composed_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./storage/composed.js */ "./src/storage/composed.js");
/* harmony import */ var _storage_level_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./storage/level.js */ "./src/storage/level.js");
/* harmony import */ var _storage_lru_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./storage/lru.js */ "./src/storage/lru.js");
/**
* @module KeyStore
* @description
* Provides a local key manager for OrbitDB.
* @example <caption>Create a keystore with defaults.</caption>
* const keystore = await KeyStore()
* @example <caption>Create a keystore with custom storage.</caption>
* const storage = await MemoryStorage()
* const keystore = await KeyStore({ storage })
*/
const verifySignature = async (signature, publicKey, data) => {
if (!signature) {
throw new Error('No signature given')
}
if (!publicKey) {
throw new Error('Given publicKey was undefined')
}
if (!data) {
throw new Error('Given input data was undefined')
}
if (!(data instanceof Uint8Array)) {
data = typeof data === 'string' ? (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(data) : new Uint8Array(data)
}
const isValid = (key, msg, sig) => key.verify(msg, sig)
let res = false
try {
const pubKey = (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__.publicKeyFromRaw)((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(publicKey, 'base16'))
res = await isValid(pubKey, data, (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(signature, 'base16'))
} catch (e) {
// Catch error: sig length wrong
}
return Promise.resolve(res)
}
/**
* Signs data using a key pair.
* @param {Secp256k1PrivateKey} key The key to use for signing data.
* @param {string|Uint8Array} data The data to sign.
* @return {string} A signature.
* @throws No signing key given if no key is provided.
* @throws Given input data was undefined if no data is provided.
* @static
* @private
*/
const signMessage = async (key, data) => {
if (!key) {
throw new Error('No signing key given')
}
if (!data) {
throw new Error('Given input data was undefined')
}
if (!(data instanceof Uint8Array)) {
data = typeof data === 'string' ? (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(data) : new Uint8Array(data)
}
return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_1__.toString)(await key.sign(data), 'base16')
}
const verifiedCachePromise = (0,_storage_lru_js__WEBPACK_IMPORTED_MODULE_5__["default"])({ size: 1000 })
/**
* Verifies input data against a cached version of the signed message.
* @param {string} signature The generated signature.
* @param {string} publicKey The derived public key of the key pair.
* @param {string} data The data to be verified.
* @return {boolean} True if the the data and cache match, false otherwise.
* @static
* @private
*/
const verifyMessage = async (signature, publicKey, data) => {
const verifiedCache = await verifiedCachePromise
const cached = await verifiedCache.get(signature)
let res = false
if (!cached) {
const verified = await verifySignature(signature, publicKey, data)
res = verified
if (verified) {
await verifiedCache.put(signature, { publicKey, data })
}
} else {
const compare = (cached, data) => {
const match = data instanceof Uint8Array ? (0,uint8arrays_compare__WEBPACK_IMPORTED_MODULE_2__.compare)(cached, data) === 0 : cached.toString() === data.toString()
return match
}
res = cached.publicKey === publicKey && compare(cached.data, data)
}
return res
}
const defaultPath = './keystore'
/**
* Creates an instance of KeyStore.
* @param {Object} params One or more parameters for configuring KeyStore.
* @param {Object} [params.storage] An instance of a storage class. Can be one
* of ComposedStorage, IPFSBlockStorage, LevelStorage, etc. Defaults to
* ComposedStorage.
* @param {string} [params.path=./keystore] The path to a valid storage.
* @return {module:KeyStore~KeyStore} An instance of KeyStore.
* @instance
*/
const KeyStore = async ({ storage, path } = {}) => {
/**
* @namespace module:KeyStore~KeyStore
* @description The instance returned by {@link module:KeyStore}.
*/
// Persistent storage for keys
storage = storage || await (0,_storage_composed_js__WEBPACK_IMPORTED_MODULE_3__["default"])(await (0,_storage_lru_js__WEBPACK_IMPORTED_MODULE_5__["default"])({ size: 1000 }), await (0,_storage_level_js__WEBPACK_IMPORTED_MODULE_4__["default"])({ path: path || defaultPath }))
// Cache for deserialized/unmarshaled keys
const keyCache = await (0,_storage_lru_js__WEBPACK_IMPORTED_MODULE_5__["default"])({ size: 1000 })
/**
* Closes the KeyStore's underlying storage.
* @memberof module:KeyStore~KeyStore
* @async
* @instance
*/
const close = async () => {
await storage.close()
await keyCache.close()
}
/**
* Clears the KeyStore's underlying storage.
* @memberof module:KeyStore~KeyStore
* @async
* @instance
*/
const clear = async () => {
await storage.clear()
await keyCache.clear()
}
/**
* Checks if a key exists in the key store .
* @param {string} id The id of an [Identity]{@link module:Identities~Identity} to check the key for.
* @return {boolean} True if the key exists, false otherwise.
* @throws id needed to check a key if no id is specified.
* @memberof module:KeyStore~KeyStore
* @async
* @instance
*/
const hasKey = async (id) => {
if (!id) {
throw new Error('id needed to check a key')
}
let hasKey = false
let key = await keyCache.get(id)
if (key) {
hasKey = true
} else {
try {
key = await storage.get('private_' + id)
hasKey = key !== undefined && key !== null
} catch (e) {
// Catches 'Error: ENOENT: no such file or directory, open <path>'
console.error('Error: ENOENT: no such file or directory')
}
}
return hasKey
}
/**
* Adds a private key to the keystore.
* @param {string} id An id of the [Identity]{@link module:Identities~Identity} to whom the key belongs to.
* @param {Uint8Array} key The private key to store.
* @memberof module:KeyStore~KeyStore
* @async
* @instance
*/
const addKey = async (id, key) => {
const { privateKey } = key
await storage.put('private_' + id, privateKey)
// Unmarshal the key and add it to the cache
const unmarshaledPrivateKey = (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__.privateKeyFromRaw)(privateKey)
await keyCache.put(id, unmarshaledPrivateKey)
}
/**
* Creates a key pair and stores it to the keystore.
* @param {string} id An id of the [Identity]{@link module:Identities~Identity} to generate the key pair for.
* @throws id needed to create a key if no id is specified.
* @memberof module:KeyStore~KeyStore
* @async
* @instance
*/
const createKey = async (id) => {
if (!id) {
throw new Error('id needed to create a key')
}
// Generate a private key
const keyPair = await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__.generateKeyPair)('secp256k1')
const key = {
publicKey: keyPair.publicKey.raw,
privateKey: keyPair.raw
}
await addKey(id, key)
return keyPair
}
/**
* Gets a key from keystore.
* @param {string} id An id of the [Identity]{@link module:Identities~Identity} whose key to retrieve.
* @return {Uint8Array} The key specified by id.
* @throws id needed to get a key if no id is specified.
* @memberof module:KeyStore~KeyStore
* @async
* @instance
*/
const getKey = async (id) => {
if (!id) {
throw new Error('id needed to get a key')
}
let key = await keyCache.get(id)
if (!key) {
let storedKey
try {
storedKey = await storage.get('private_' + id)
} catch (e) {
// ignore ENOENT error
}
if (!storedKey) {
return
}
key = (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__.privateKeyFromRaw)(storedKey)
await keyCache.put(id, key)
}
return key
}
/**
* Gets the serialized public key from a key pair.
* @param {*} keys A key pair.
* @param {Object} options One or more options.
* @param {Object} [options.format=hex] The format the public key should be
* returned in.
* @return {Uint8Array|String} The public key.
* @throws Supported formats are `hex` and `buffer` if an invalid format is
* passed in options.
* @memberof module:KeyStore~KeyStore
* @async
* @instance
*/
const getPublic = (keys, options = {}) => {
const formats = ['hex', 'buffer']
const format = options.format || 'hex'
if (formats.indexOf(format) === -1) {
throw new Error('Supported formats are `hex` and `buffer`')
}
const pubKey = keys.publicKey.raw
return format === 'buffer' ? pubKey : (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_1__.toString)(pubKey, 'base16')
}
return {
clear,
close,
hasKey,
addKey,
createKey,
getKey,
getPublic
}
}
/***/ }),
/***/ "./src/manifest-store.js":
/*!*******************************!*\
!*** ./src/manifest-store.js ***!
\*******************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var multiformats_block__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/block */ "./node_modules/multiformats/src/block.js");
/* harmony import */ var _ipld_dag_cbor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @ipld/dag-cbor */ "./node_modules/@ipld/dag-cbor/src/index.js");
/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/hashes/sha2 */ "./node_modules/multiformats/src/hashes/sha2-browser.js");
/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/bases/base58 */ "./node_modules/multiformats/src/bases/base58.js");
/* harmony import */ var _storage_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./storage/index.js */ "./src/storage/index.js");
const codec = _ipld_dag_cbor__WEBPACK_IMPORTED_MODULE_1__
const hasher = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_2__.sha256
const hashStringEncoding = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_3__.base58btc
const ManifestStore = async ({ ipfs, storage } = {}) => {
/**
* @namespace module:Manifest~Manifest
* @description The instance returned by {@link module:Manifest~Manifest}.
* @private
*/
storage = storage || await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_4__.ComposedStorage)(
await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_4__.LRUStorage)({ size: 100000 }),
await (0,_storage_index_js__WEBPACK_IMPORTED_MODULE_4__.IPFSBlockStorage)({ ipfs, pin: true })
)
const get = async (address) => {
const bytes = await storage.get(address)
const { value } = await multiformats_block__WEBPACK_IMPORTED_MODULE_0__.decode({ bytes, codec, hasher })
if (value) {
// Write to storage to make sure it gets pinned on IPFS
await storage.put(address, bytes)
}
return value
}
const create = async ({ name, type, accessController, meta }) => {
if (!name) throw new Error('name is required')
if (!type) throw new Error('type is required')
if (!accessController) throw new Error('accessController is required')
const manifest = Object.assign(
{
name,
type,
accessController
},
// meta field is only added to manifest if meta parameter is defined
meta !== undefined ? { meta } : {}
)
const { cid, bytes } = await multiformats_block__WEBPACK_IMPORTED_MODULE_0__.encode({ value: manifest, codec, hasher })
const hash = cid.toString(hashStringEncoding)
await storage.put(hash, bytes)
return {
hash,
manifest
}
}
const close = async () => {
await storage.close()
}
return {
get,
create,
close
}
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ManifestStore);
/***/ }),
/***/ "./src/oplog/clock.js":
/*!****************************!*\
!*** ./src/oplog/clock.js ***!
\****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ compareClocks: () => (/* binding */ compareClocks),
/* harmony export */ "default": () => (/* binding */ Clock),
/* harmony export */ tickClock: () => (/* binding */ tickClock)
/* harmony export */ });
/**
* @namespace module:Log~Clock
* @memberof module:Log
* @description
* The lamport clock.
* @private
*/
/**
* Compares two clocks by time and then, time is the same, by id.
*
* compareClocks should never return zero (0). If it does, a and b refer to the
* same clock.
* @param {module:Clock} a The first clock.
* @param {module:Clock} b The second clock.
* @return {number} Returns a negative integer if clock a is less than clock b
* otherwise a positive integer is returned.
* @memberof module:Log~Clock
*/
const compareClocks = (a, b) => {
// Calculate the "distance" based on the clock, ie. lower or greater
const dist = a.time - b.time
// If the sequence number is the same (concurrent events),
// and the IDs are different, take the one with a "lower" id
if (dist === 0 && a.id !== b.id) return a.id < b.id ? -1 : 1
return dist
}
/**
* Advances a clock's time by 1, returning a new instance of Clock.
* @param {module:Clock} clock The clock to advance.
* @return {module:Clock} A new instance of clock with time advanced by 1.
* @memberof module:Log~Clock
*/
const tickClock = (clock) => {
return Clock(clock.id, ++clock.time)
}
/**
* Creates an instance of Clock.
* @function
* @param {string} id A unique identifier.
* @param {number} [time=0] A natural number (including 0).
* @memberof module:Log~Clock
* @instance
*/
const Clock = (id, time) => {
time = time || 0
return {
id,
time
}
}
/***/ }),
/***/ "./src/oplog/conflict-resolution.js":
/*!******************************************!*\
!*** ./src/oplog/conflict-resolution.js ***!
\******************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _clock_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./clock.js */ "./src/oplog/clock.js");
/**
* Sort two entries as Last-Write-Wins (LWW).
*
* Last Write Wins is a conflict resolution strategy for sorting elements
* where the element with a greater clock (latest) is chosen as the winner.
*
* @param {Entry} a First entry
* @param {Entry} b Second entry
* @return {number} 1 if a is latest, -1 if b is latest
* @private
*/
function LastWriteWins (a, b) {
// Ultimate conflict resolution (take the first/left arg)
const First = (a, b) => a
// Sort two entries by their clock id, if the same always take the first
const sortById = (a, b) => SortByClockId(a, b, First)
// Sort two entries by their clock time, if concurrent,
// determine sorting using provided conflict resolution function
const sortByEntryClocks = (a, b) => SortByClocks(a, b, sortById)
// Sort entries by clock time as the primary sort criteria
return sortByEntryClocks(a, b)
}
/**
* Sort two entries by their clock time.
* @param {Entry} a First entry to compare
* @param {Entry} b Second entry to compare
* @param {function(a, b)} resolveConflict A function to call if entries are
* concurrent (happened at the same time). The function should take in two
* entries and return 1 if the first entry should be chosen and -1 if the
* second entry should be chosen.
* @return {number} 1 if a is greater, -1 if b is greater
* @private
*/
function SortByClocks (a, b, resolveConflict) {
// Compare the clocks
const diff = (0,_clock_js__WEBPACK_IMPORTED_MODULE_0__.compareClocks)(a.clock, b.clock)
// If the clocks are concurrent, use the provided
// conflict resolution function to determine which comes first
return diff === 0 ? resolveConflict(a, b) : diff
}
/**
* Sort two entries by their clock id.
* @param {Entry} a First entry to compare
* @param {Entry} b Second entry to compare
* @param {function(a, b)} resolveConflict A function to call if the clocks ids
* are the same. The function should take in two entries and return 1 if the
* first entry should be chosen and -1 if the second entry should be chosen.
* @return {number} 1 if a is greater, -1 if b is greater
* @private
*/
function SortByClockId (a, b, resolveConflict) {
// Sort by ID if clocks are concurrent,
// take the entry with a "greater" clock id
return a.clock.id === b.clock.id
? resolveConflict(a, b)
: a.clock.id < b.clock.id ? -1 : 1
}
/**
* A wrapper function to throw an error if the results of a passed function
* return zero
* @param {function(a, b)} [tiebreaker] The tiebreaker function to validate.
* @return {function(a, b)} 1 if a is greater, -1 if b is greater
* @throws {Error} if func ever returns 0
* @private
*/
function NoZeroes (func) {
const msg = `Your log's tiebreaker function, ${func.name}, has returned zero and therefore cannot be`
const comparator = (a, b) => {
// Validate by calling the function
const result = func(a, b)
if (result === 0) { throw Error(msg) }
return result
}
return comparator
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
SortByClocks,
SortByClockId,
LastWriteWins,
NoZeroes
});
/***/ }),
/***/ "./src/oplog/entry.js":
/*!****************************!*\
!*** ./src/oplog/entry.js ***!
\****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _clock_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./clock.js */ "./src/oplog/clock.js");
/* harmony import */ var multiformats_block__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/block */ "./node_modules/multiformats/src/block.js");
/* harmony import */ var _ipld_dag_cbor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @ipld/dag-cbor */ "./node_modules/@ipld/dag-cbor/src/index.js");
/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/sha2 */ "./node_modules/multiformats/src/hashes/sha2-browser.js");
/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/bases/base58 */ "./node_modules/multiformats/src/bases/base58.js");
const codec = _ipld_dag_cbor__WEBPACK_IMPORTED_MODULE_2__
const hasher = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_3__.sha256
const hashStringEncoding = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_4__.base58btc
/**
* @typedef {Object} module:Log~Entry
* @property {string} id A string linking multiple entries together.
* @property {*} payload An arbitrary chunk of data.
* @property {Array<string>} next One or more hashes pointing to the next entries in a chain of
* entries.
* @property {Array<string>} refs One or more hashes which reference other entries in the chain.
* @property {Clock} clock A logical clock. See {@link module:Log~Clock}.
* @property {integer} v The version of the entry.
* @property {string} key The public key of the identity.
* @property {string} identity The identity of the entry's owner.
* @property {string} sig The signature of the entry signed by the owner.
*/
/**
* Creates an Entry.
* @param {module:Identities~Identity} identity The identity instance
* @param {string} logId The unique identifier for this log
* @param {*} data Data of the entry to be added. Can be any JSON.stringifyable
* data.
* @param {module:Log~Clock} [clock] The clock
* @param {Array<string|Entry>} [next=[]] An array of CIDs as base58btc encoded
* strings which point to the next entries in a chain of entries.
* @param {Array<string|module:Log~Entry>} [refs=[]] An array of CIDs as
* base58btc encoded strings pointing to various entries which come before
* this entry.
* @return {Promise<module:Log~Entry>} A promise which contains an instance of
* Entry.
* Entry consists of the following properties:
*
* - id: A string linking multiple entries together,
* - payload: An arbitrary chunk of data,
* - next: One or more hashes pointing to the next entries in a chain of
* entries,
* - refs: One or more hashes which reference other entries in the chain,
* - clock: A logical clock. See {@link module:Log~Clock},
* - v: The version of the entry,
* - key: The public key of the identity,
* - identity: The identity of the entry's owner,
* - sig: The signature of the entry signed by the owner.
* @memberof module:Log~Entry
* @example
* const entry = await Entry.create(identity, 'log1', 'hello')
* console.log(entry)
* // { payload: "hello", next: [], ... }
* @private
*/
const create = async (identity, id, payload, clock = null, next = [], refs = []) => {
if (identity == null) throw new Error('Identity is required, cannot create entry')
if (id == null) throw new Error('Entry requires an id')
if (payload == null) throw new Error('Entry requires a payload')
if (next == null || !Array.isArray(next)) throw new Error("'next' argument is not an array")
clock = clock || (0,_clock_js__WEBPACK_IMPORTED_MODULE_0__["default"])(identity.publicKey)
const entry = {
id, // For determining a unique chain
payload, // Can be any dag-cbor encodeable data
next, // Array of strings of CIDs
refs, // Array of strings of CIDs
clock, // Clock
v: 2 // To tag the version of this data structure
}
const { bytes } = await multiformats_block__WEBPACK_IMPORTED_MODULE_1__.encode({ value: entry, codec, hasher })
const signature = await identity.sign(identity, bytes)
entry.key = identity.publicKey
entry.identity = identity.hash
entry.sig = signature
return encode(entry)
}
/**
* Verifies an entry signature.
* @param {Identities} identities Identities system to use
* @param {module:Log~Entry} entry The entry being verified
* @return {Promise<boolean>} A promise that resolves to a boolean value indicating if
* the signature is valid.
* @memberof module:Log~Entry
* @private
*/
const verify = async (identities, entry) => {
if (!identities) throw new Error('Identities is required, cannot verify entry')
if (!isEntry(entry)) throw new Error('Invalid Log entry')
if (!entry.key) throw new Error("Entry doesn't have a key")
if (!entry.sig) throw new Error("Entry doesn't have a signature")
const value = {
id: entry.id,
payload: entry.payload,
next: entry.next,
refs: entry.refs,
clock: entry.clock,
v: entry.v
}
const { bytes } = await multiformats_block__WEBPACK_IMPORTED_MODULE_1__.encode({ value, codec, hasher })
return identities.verify(entry.sig, entry.key, bytes)
}
/**
* Checks if an object is an Entry.
* @param {module:Log~Entry} obj
* @return {boolean}
* @memberof module:Log~Entry
* @private
*/
const isEntry = (obj) => {
return obj && obj.id !== undefined &&
obj.next !== undefined &&
obj.payload !== undefined &&
obj.v !== undefined &&
obj.clock !== undefined &&
obj.refs !== undefined
}
/**
* Determines whether two entries are equal.
* @param {module:Log~Entry} a An entry to compare.
* @param {module:Log~Entry} b An entry to compare.
* @return {boolean} True if a and b are equal, false otherwise.
* @memberof module:Log~Entry
* @private
*/
const isEqual = (a, b) => {
return a && b && a.hash === b.hash
}
/**
* Decodes a serialized Entry from bytes
* @param {Uint8Array} bytes
* @return {module:Log~Entry}
* @memberof module:Log~Entry
* @private
*/
const decode = async (bytes) => {
const { cid, value } = await multiformats_block__WEBPACK_IMPORTED_MODULE_1__.decode({ bytes, codec, hasher })
const hash = cid.toString(hashStringEncoding)
return {
...value,
hash,
bytes
}
}
/**
* Encodes an Entry and adds bytes field to it
* @param {Entry} entry
* @return {module:Log~Entry}
* @memberof module:Log~Entry
* @private
*/
const encode = async (entry) => {
const { cid, bytes } = await multiformats_block__WEBPACK_IMPORTED_MODULE_1__.encode({ value: entry, codec, hasher })
const hash = cid.toString(hashStringEncoding)
const clock = (0,_clock_js__WEBPACK_IMPORTED_MODULE_0__["default"])(entry.clock.id, entry.clock.time)
return {
...entry,
clock,
hash,
bytes
}
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
create,
verify,
decode,
encode,
isEntry,
isEqual
});
/***/ }),
/***/ "./src/oplog/heads.js":
/*!****************************!*\
!*** ./src/oplog/heads.js ***!
\****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _entry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./entry.js */ "./src/oplog/entry.js");
/* harmony import */ var _storage_memory_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../storage/memory.js */ "./src/storage/memory.js");
/**
* @namespace module:Log~Heads
* @memberof module:Log
* @description The log's heads.
* @private
*/
const DefaultStorage = _storage_memory_js__WEBPACK_IMPORTED_MODULE_1__["default"]
const Heads = async ({ storage, heads }) => {
storage = storage || await DefaultStorage()
const put = async (heads) => {
heads = findHeads(heads)
for (const head of heads) {
await storage.put(head.hash, head.bytes)
}
}
const set = async (heads) => {
await storage.clear()
await put(heads)
}
const add = async (head) => {
const currentHeads = await all()
if (currentHeads.find(e => _entry_js__WEBPACK_IMPORTED_MODULE_0__["default"].isEqual(e, head))) {
return
}
const newHeads = findHeads([...currentHeads, head])
await set(newHeads)
return newHeads
}
const remove = async (hash) => {
const currentHeads = await all()
const newHeads = currentHeads.filter(e => e.hash !== hash)
await set(newHeads)
}
const iterator = async function * () {
const it = storage.iterator()
for await (const [, bytes] of it) {
const head = await _entry_js__WEBPACK_IMPORTED_MODULE_0__["default"].decode(bytes)
yield head
}
}
const all = async () => {
const values = []
for await (const head of iterator()) {
values.push(head)
}
return values
}
const clear = async () => {
await storage.clear()
}
const close = async () => {
await storage.close()
}
// Initialize the heads if given as parameter
await put(heads || [])
return {
put,
set,
add,
remove,
iterator,
all,
clear,
close
}
}
/**
* Find heads from a collection of entries.
*
* Finds entries that are the heads of this collection,
* ie. entries that are not referenced by other entries.
*
* This function is private and not exposed in the Log API
*
* @param {Array<Entry>} entries Entries to search heads from
* @return {Array<Entry>}
* @private
*/
const findHeads = (entries) => {
entries = new Set(entries)
const items = {}
for (const entry of entries) {
for (const next of entry.next) {
items[next] = entry.hash
}
}
const res = []
for (const entry of entries) {
if (!items[entry.hash]) {
res.push(entry)
}
}
return res
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Heads);
/***/ }),
/***/ "./src/oplog/index.js":
/*!****************************!*\
!*** ./src/oplog/index.js ***!
\****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Clock: () => (/* reexport safe */ _clock_js__WEBPACK_IMPORTED_MODULE_2__["default"]),
/* harmony export */ ConflictResolution: () => (/* reexport safe */ _conflict_resolution_js__WEBPACK_IMPORTED_MODULE_3__["default"]),
/* harmony export */ DefaultAccessController: () => (/* reexport safe */ _log_js__WEBPACK_IMPORTED_MODULE_0__.DefaultAccessController),
/* harmony export */ Entry: () => (/* reexport safe */ _entry_js__WEBPACK_IMPORTED_MODULE_1__["default"]),
/* harmony export */ Log: () => (/* reexport safe */ _log_js__WEBPACK_IMPORTED_MODULE_0__["default"])
/* harmony export */ });
/* harmony import */ var _log_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./log.js */ "./src/oplog/log.js");
/* harmony import */ var _entry_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./entry.js */ "./src/oplog/entry.js");
/* harmony import */ var _clock_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./clock.js */ "./src/oplog/clock.js");
/* harmony import */ var _conflict_resolution_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./conflict-resolution.js */ "./src/oplog/conflict-resolution.js");
/***/ }),
/***/ "./src/oplog/log.js":
/*!**************************!*\
!*** ./src/oplog/log.js ***!
\**************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Clock: () => (/* reexport safe */ _clock_js__WEBPACK_IMPORTED_MODULE_2__["default"]),
/* harmony export */ DefaultAccessController: () => (/* binding */ DefaultAccessController),
/* harmony export */ "default": () => (/* binding */ Log)
/* harmony export */ });
/* harmony import */ var lru__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lru */ "./node_modules/lru/index.js");
/* harmony import */ var p_queue__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! p-queue */ "./node_modules/p-queue/dist/index.js");
/* harmony import */ var _entry_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./entry.js */ "./src/oplog/entry.js");
/* harmony import */ var _clock_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./clock.js */ "./src/oplog/clock.js");
/* harmony import */ var _heads_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./heads.js */ "./src/oplog/heads.js");
/* harmony import */ var _conflict_resolution_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./conflict-resolution.js */ "./src/oplog/conflict-resolution.js");
/* harmony import */ var _storage_memory_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../storage/memory.js */ "./src/storage/memory.js");
/**
* @module Log
* @description
* Log is a verifiable, append-only log CRDT.
*
* Implemented as a Merkle-CRDT as per the paper
* ["Merkle-CRDTs: Merkle-DAGs meet CRDTs"]{@link https://arxiv.org/abs/2004.00107}
*/
const { LastWriteWins, NoZeroes } = _conflict_resolution_js__WEBPACK_IMPORTED_MODULE_4__["default"]
const randomId = () => new Date().getTime().toString()
const maxClockTimeReducer = (res, acc) => Math.max(res, acc.clock.time)
// Default storage for storing the Log and its entries. Default: Memory. Options: Memory, LRU, IPFS.
const DefaultStorage = _storage_memory_js__WEBPACK_IMPORTED_MODULE_5__["default"]
// Default AccessController for the Log.
// Default policy is that anyone can write to the Log.
// Signature of an entry will always be verified regardless of AccessController policy.
// Any object that implements the function `canAppend()` that returns true|false can be
// used as an AccessController.
const DefaultAccessController = async () => {
// An AccessController may do any async initialization stuff here...
return {
canAppend: async (entry) => true
}
}
/**
* Create a new Log instance
* @function
* @param {IPFS} ipfs An IPFS instance
* @param {Object} identity Identity.
* @param {Object} options
* @param {string} options.logId ID of the log
* @param {Array<Entry>} options.logHeads Set the heads of the log
* @param {Object} options.access AccessController (./default-access-controller)
* @param {Array<Entry>} options.entries An Array of Entries from which to create the log
* @param {module:Storage} [options.entryStorage] A compatible storage instance
* for storing log entries. Defaults to MemoryStorage.
* @param {module:Storage} [options.headsStorage] A compatible storage
* instance for storing log heads. Defaults to MemoryStorage.
* @param {module:Storage} [options.indexStorage] A compatible storage
* instance for storing an index of log entries. Defaults to MemoryStorage.
* @param {Function} options.sortFn The sort function - by default LastWriteWins
* @return {module:Log~Log} sync An instance of Log
* @memberof module:Log
* @instance
*/
const Log = async (identity, { logId, logHeads, access, entryStorage, headsStorage, indexStorage, sortFn } = {}) => {
/**
* @namespace Log
* @description The instance returned by {@link module:Log}
*/
if (identity == null) {
throw new Error('Identity is required')
}
if (logHeads != null && !Array.isArray(logHeads)) {
throw new Error('\'logHeads\' argument must be an array')
}
// Set Log's id
const id = logId || randomId()
// Access Controller
access = access || await DefaultAccessController()
// Oplog entry storage
const _entries = entryStorage || await DefaultStorage()
// Entry index for keeping track which entries are already in the log
const _index = indexStorage || await DefaultStorage()
// Heads storage
headsStorage = headsStorage || await DefaultStorage()
// Add heads to the state storage, ie. init the log state
const _heads = await (0,_heads_js__WEBPACK_IMPORTED_MODULE_3__["default"])({ storage: headsStorage, heads: logHeads })
// Conflict-resolution sorting function
sortFn = NoZeroes(sortFn || LastWriteWins)
// Internal queues for processing appends and joins in their call-order
const appendQueue = new p_queue__WEBPACK_IMPORTED_MODULE_6__["default"]({ concurrency: 1 })
const joinQueue = new p_queue__WEBPACK_IMPORTED_MODULE_6__["default"]({ concurrency: 1 })
/**
* Returns the clock of the log.
* @return {module:Clock}
* @memberof module:Log~Log
* @instance
*/
const clock = async () => {
// Find the latest clock from the heads
const maxTime = Math.max(0, (await heads()).reduce(maxClockTimeReducer, 0))
return (0,_clock_js__WEBPACK_IMPORTED_MODULE_2__["default"])(identity.publicKey, maxTime)
}
/**
* Returns the current heads of the log
*
* @return {Array<module:Log~Entry>}
* @memberof module:Log~Log
* @instance
*/
const heads = async () => {
const res = await _heads.all()
return res.sort(sortFn).reverse()
}
/**
* Returns all entries in the log
*
* @return {Array<module:Log~Entry>}
* @memberof module:Log~Log
* @instance
*/
const values = async () => {
const values = []
for await (const entry of traverse()) {
values.unshift(entry)
}
return values
}
/**
* Retrieve an entry
*
* @param {string} hash The hash of the entry to retrieve
* @return {module:Log~Entry}
* @memberof module:Log~Log
* @instance
*/
const get = async (hash) => {
const bytes = await _entries.get(hash)
if (bytes) {
const entry = await _entry_js__WEBPACK_IMPORTED_MODULE_1__["default"].decode(bytes)
return entry
}
}
const has = async (hash) => {
const entry = await _index.get(hash)
return entry != null
}
/**
* Append an new entry to the log
*
* @param {data} data Payload to add to the entry
* @param {Object} options
* @param {number} options.referencesCount TODO
* @return {module:Log~Entry} Entry that was appended
* @memberof module:Log~Log
* @instance
*/
const append = async (data, options = { referencesCount: 0 }) => {
const task = async () => {
// 1. Prepare entry
// 2. Authorize entry
// 3. Store entry
// 4. return Entry
// Get current heads of the log
const heads_ = await heads()
// Create the next pointers from heads
const nexts = heads_.map(entry => entry.hash)
// Get references (pointers) to multiple entries in the past
// (skips the heads which are covered by the next field)
const refs = await getReferences(heads_, options.referencesCount + heads_.length)
// Create the entry
const entry = await _entry_js__WEBPACK_IMPORTED_MODULE_1__["default"].create(
identity,
id,
data,
(0,_clock_js__WEBPACK_IMPORTED_MODULE_2__.tickClock)(await clock()),
nexts,
refs
)
// Authorize the entry
const canAppend = await access.canAppend(entry)
if (!canAppend) {
throw new Error(`Could not append entry:\nKey "${identity.hash}" is not allowed to write to the log`)
}
// The appended entry is now the latest head
await _heads.set([entry])
// Add entry to the entry storage
await _entries.put(entry.hash, entry.bytes)
// Add entry to the entry index
await _index.put(entry.hash, true)
// Return the appended entry
return entry
}
return appendQueue.add(task)
}
/**
* Join two logs.
*
* Joins another log into this one.
*
* @param {module:Log~Log} log Log to join with this Log
*
* @example
*
* await log1.join(log2)
*
* @memberof module:Log~Log
* @instance
*/
const join = async (log) => {
if (!log) {
throw new Error('Log instance not defined')
}
if (!isLog(log)) {
throw new Error('Given argument is not an instance of Log')
}
if (_entries.merge) {
await _entries.merge(log.storage)
}
const heads = await log.heads()
for (const entry of heads) {
await joinEntry(entry)
}
}
/**
* Join an entry into a log.
*
* @param {module:Log~Entry} entry Entry to join with this Log
*
* @example
*
* await log.joinEntry(entry)
*
* @memberof module:Log~Log
* @instance
*/
const joinEntry = async (entry) => {
const task = async () => {
/* 1. Check if the entry is already in the log and return early if it is */
const isAlreadyInTheLog = await has(entry.hash)
if (isAlreadyInTheLog) {
return false
}
const verifyEntry = async (entry) => {
// Check that the Entry belongs to this Log
if (entry.id !== id) {
throw new Error(`Entry's id (${entry.id}) doesn't match the log's id (${id}).`)
}
// Verify if entry is allowed to be added to the log
const canAppend = await access.canAppend(entry)
if (!canAppend) {
throw new Error(`Could not append entry:\nKey "${entry.identity}" is not allowed to write to the log`)
}
// Verify signature for the entry
const isValid = await _entry_js__WEBPACK_IMPORTED_MODULE_1__["default"].verify(identity, entry)
if (!isValid) {
throw new Error(`Could not validate signature for entry "${entry.hash}"`)
}
}
/* 2. Verify the entry */
await verifyEntry(entry)
/* 3. Find missing entries and connections (=path in the DAG) to the current heads */
const headsHashes = (await heads()).map(e => e.hash)
const hashesToAdd = new Set([entry.hash])
const hashesToGet = new Set([...entry.next, ...entry.refs])
const connectedHeads = new Set()
const traverseAndVerify = async () => {
const getEntries = Array.from(hashesToGet.values()).filter(has).map(get)
const entries = await Promise.all(getEntries)
for (const e of entries) {
hashesToGet.delete(e.hash)
await verifyEntry(e)
hashesToAdd.add(e.hash)
for (const hash of [...e.next, ...e.refs]) {
const isInTheLog = await has(hash)
if (!isInTheLog && !hashesToAdd.has(hash)) {
hashesToGet.add(hash)
} else if (headsHashes.includes(hash)) {
connectedHeads.add(hash)
}
}
}
if (hashesToGet.size > 0) {
await traverseAndVerify()
}
}
await traverseAndVerify()
/* 4. Add missing entries to the index (=to the log) */
for (const hash of hashesToAdd.values()) {
await _index.put(hash, true)
}
/* 5. Remove heads which new entries are connect to */
for (const hash of connectedHeads.values()) {
await _heads.remove(hash)
}
/* 6. Add new entry to entries (for pinning) */
await _entries.put(entry.hash, entry.bytes)
/* 6. Add the new entry to heads (=union with current heads) */
await _heads.add(entry)
return true
}
return joinQueue.add(task)
}
/**
* TODO
* @memberof module:Log~Log
* @instance
*/
const traverse = async function * (rootEntries, shouldStopFn) {
// By default, we don't stop traversal and traverse
// until the end of the log
const defaultStopFn = () => false
shouldStopFn = shouldStopFn || defaultStopFn
// Start traversal from given entries or from current heads
rootEntries = rootEntries || (await heads())
// Sort the given given root entries and use as the starting stack
let stack = rootEntries.sort(sortFn)
// Keep a record of all the hashes of entries we've traversed and yielded
const traversed = {}
// Keep a record of all the hashes we are fetching or have already fetched
let toFetch = []
const fetched = {}
// A function to check if we've seen a hash
const notIndexed = (hash) => !(traversed[hash] || fetched[hash])
// Current entry during traversal
let entry
// Start traversal and process stack until it's empty (traversed the full log)
while (stack.length > 0) {
stack = stack.sort(sortFn)
// Get the next entry from the stack
entry = stack.pop()
if (entry) {
const { hash, next } = entry
// If we have an entry that we haven't traversed yet, process it
if (!traversed[hash]) {
// Yield the current entry
yield entry
// If we should stop traversing, stop here
const done = await shouldStopFn(entry)
if (done === true) {
break
}
// Add to the hash indices
traversed[hash] = true
fetched[hash] = true
// Add the next and refs hashes to the list of hashes to fetch next,
// filter out traversed and fetched hashes
toFetch = [...toFetch, ...next].filter(notIndexed)
// Function to fetch an entry and making sure it's not a duplicate (check the hash indices)
const fetchEntries = (hash) => {
if (!traversed[hash] && !fetched[hash]) {
fetched[hash] = true
return get(hash)
}
}
// Fetch the next/reference entries
const nexts = await Promise.all(toFetch.map(fetchEntries))
// Add the next and refs fields from the fetched entries to the next round
toFetch = nexts
.filter(e => e !== null && e !== undefined)
.reduce((res, acc) => Array.from(new Set([...res, ...acc.next])), [])
.filter(notIndexed)
// Add the fetched entries to the stack to be processed
stack = [...nexts, ...stack]
}
}
}
}
/**
* Async iterator over the log entries
*
* @param {Object} options
* @param {amount} options.amount Number of entried to return. Default: return all entries.
* @param {string} options.gt Beginning hash of the iterator, non-inclusive
* @param {string} options.gte Beginning hash of the iterator, inclusive
* @param {string} options.lt Ending hash of the iterator, non-inclusive
* @param {string} options.lte Ending hash of the iterator, inclusive
* @return {Symbol.asyncIterator} Iterator object of log entries
*
* @examples
*
* (async () => {
* log = await Log(testIdentity, { logId: 'X' })
*
* for (let i = 0; i <= 100; i++) {
* await log.append('entry' + i)
* }
*
* let it = log.iterator({
* lte: 'zdpuApFd5XAPkCTmSx7qWQmQzvtdJPtx2K5p9to6ytCS79bfk',
* amount: 10
* })
*
* for await (let entry of it) {
* console.log(entry.payload) // 'entry100', 'entry99', ..., 'entry91'
* }
* })()
*
* @memberof module:Log~Log
* @instance
*/
const iterator = async function * ({ amount = -1, gt, gte, lt, lte } = {}) {
// TODO: write comments on how the iterator algorithm works
if (amount === 0) {
return
}
if (typeof lte === 'string') {
lte = [await get(lte)]
}
if (typeof lt === 'string') {
const entry = await get(lt)
const nexts = await Promise.all(entry.next.map(n => get(n)))
lt = nexts
}
if (lt != null && !Array.isArray(lt)) throw new Error('lt must be a string or an array of Entries')
if (lte != null && !Array.isArray(lte)) throw new Error('lte must be a string or an array of Entries')
const start = (lt || (lte || await heads())).filter(i => i != null)
const end = (gt || gte) ? await get(gt || gte) : null
const amountToIterate = (end || amount === -1) ? -1 : amount
let count = 0
const shouldStopTraversal = async (entry) => {
count++
if (!entry) {
return false
}
if (count >= amountToIterate && amountToIterate !== -1) {
return true
}
if (end && _entry_js__WEBPACK_IMPORTED_MODULE_1__["default"].isEqual(entry, end)) {
return true
}
return false
}
const useBuffer = end && amount !== -1 && !lt && !lte
const buffer = useBuffer ? new lru__WEBPACK_IMPORTED_MODULE_0__(amount + 2) : null
let index = 0
const it = traverse(start, shouldStopTraversal)
for await (const entry of it) {
const skipFirst = (lt && _entry_js__WEBPACK_IMPORTED_MODULE_1__["default"].isEqual(entry, start))
const skipLast = (gt && _entry_js__WEBPACK_IMPORTED_MODULE_1__["default"].isEqual(entry, end))
const skip = skipFirst || skipLast
if (!skip) {
if (useBuffer) {
buffer.set(index++, entry.hash)
} else {
yield entry
}
}
}
if (useBuffer) {
const endIndex = buffer.keys.length
const startIndex = endIndex > amount ? endIndex - amount : 0
const keys = buffer.keys.slice(startIndex, endIndex)
for (const key of keys) {
const hash = buffer.get(key)
const entry = await get(hash)
yield entry
}
}
}
/**
* Clear all entries from the log and the underlying storages
* @memberof module:Log~Log
* @instance
*/
const clear = async () => {
await _index.clear()
await _heads.clear()
await _entries.clear()
}
/**
* Close the log and underlying storages
* @memberof module:Log~Log
* @instance
*/
const close = async () => {
await _index.close()
await _heads.close()
await _entries.close()
}
/**
* Check if an object is a Log.
* @param {Log} obj
* @return {boolean}
* @memberof module:Log~Log
* @instance
*/
const isLog = (obj) => {
return obj && obj.id !== undefined &&
obj.clock !== undefined &&
obj.heads !== undefined &&
obj.values !== undefined &&
obj.access !== undefined &&
obj.identity !== undefined &&
obj.storage !== undefined
}
/**
* Get an array of references to multiple entries in the past.
* @param {Array<Entry>} heads An array of Log heads starting rom which the references are collected from.
* @param {number} amount The number of references to return.
* @return {Array<string>}
* @private
*/
const getReferences = async (heads, amount = 0) => {
let refs = []
const shouldStopTraversal = async (entry) => {
return refs.length >= amount && amount !== -1
}
for await (const { hash } of traverse(heads, shouldStopTraversal)) {
refs.push(hash)
}
refs = refs.slice(heads.length + 1, amount)
return refs
}
return {
id,
clock,
heads,
values,
all: values, // Alias for values()
get,
has,
append,
join,
joinEntry,
traverse,
iterator,
clear,
close,
access,
identity,
storage: _entries
}
}
/***/ }),
/***/ "./src/orbitdb.js":
/*!************************!*\
!*** ./src/orbitdb.js ***!
\************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ OrbitDBAddress: () => (/* reexport safe */ _address_js__WEBPACK_IMPORTED_MODULE_3__["default"]),
/* harmony export */ "default": () => (/* binding */ OrbitDB)
/* harmony export */ });
/* harmony import */ var _databases_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./databases/index.js */ "./src/databases/index.js");
/* harmony import */ var _key_store_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./key-store.js */ "./src/key-store.js");
/* harmony import */ var _identities_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./identities/index.js */ "./src/identities/index.js");
/* harmony import */ var _address_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./address.js */ "./src/address.js");
/* harmony import */ var _manifest_store_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./manifest-store.js */ "./src/manifest-store.js");
/* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/index.js */ "./src/utils/index.js");
/* harmony import */ var _utils_path_join_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/path-join.js */ "./src/utils/path-join.js");
/* harmony import */ var _access_controllers_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./access-controllers/index.js */ "./src/access-controllers/index.js");
/* harmony import */ var _access_controllers_ipfs_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./access-controllers/ipfs.js */ "./src/access-controllers/ipfs.js");
/**
* @module OrbitDB
* @description Provides an interface for users to interact with OrbitDB.
*/
const DefaultDatabaseType = 'events'
const DefaultAccessController = _access_controllers_ipfs_js__WEBPACK_IMPORTED_MODULE_8__["default"]
/**
* Creates an instance of OrbitDB.
* @function createOrbitDB
* @param {Object} params One or more parameters for configuring OrbitDB.
* @param {IPFS} params.ipfs An IPFS instance.
* @param {string} [params.id] The id of the identity to use for this OrbitDB instance.
* @param {module:Identity|Object} [params.identity] An identity instance or an object containing an Identity Provider instance and any additional params required to create the identity using the specified provider.
* @param {Function} [params.identity.provider] An initialized identity provider.
* @param {module:Identities} [params.identities] An Identities system instance.
* @param {string} [params.directory] A location for storing OrbitDB data.
* @return {module:OrbitDB~OrbitDB} An instance of OrbitDB.
* @throws "IPFS instance is required argument" if no IPFS instance is provided.
* @instance
*/
const OrbitDB = async ({ ipfs, id, identity, identities, directory } = {}) => {
/**
* @namespace module:OrbitDB~OrbitDB
* @description The instance returned by {@link module:OrbitDB}.
*/
if (ipfs == null) {
throw new Error('IPFS instance is a required argument.')
}
id = id || await (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_5__.createId)()
const peerId = ipfs.libp2p.peerId
directory = directory || './orbitdb'
let keystore
if (identities) {
keystore = identities.keystore
} else {
keystore = await (0,_key_store_js__WEBPACK_IMPORTED_MODULE_1__["default"])({ path: (0,_utils_path_join_js__WEBPACK_IMPORTED_MODULE_6__["default"])(directory, './keystore') })
identities = await (0,_identities_index_js__WEBPACK_IMPORTED_MODULE_2__.Identities)({ ipfs, keystore })
}
if (identity) {
if (identity.provider) {
identity = await identities.createIdentity({ ...identity })
}
} else {
identity = await identities.createIdentity({ id })
}
const manifestStore = await (0,_manifest_store_js__WEBPACK_IMPORTED_MODULE_4__["default"])({ ipfs })
let databases = {}
/**
* Open a database or create one if it does not already exist.
*
* By default, OrbitDB will create a database of type [DefaultDatabaseType]{@link module:OrbitDB~DefaultDatabaseType}:
* ```
* const mydb = await orbitdb.open('mydb')
* ```
* To create a database of a different type, specify the type param:
* ```
* const mydb = await orbitdb.open('mydb', {type: 'documents'})
* ```
* The type must be listed in [databaseTypes]{@link module:OrbitDB.databaseTypes} or an error is thrown.
* To open an existing database, pass its address to the `open` function:
* ```
* const existingDB = await orbitdb.open(dbAddress)
* ```
* The address of a newly created database can be retrieved using
* `db.address`.
* @function
* @param {string} address The address of an existing database to open, or
* the name of a new database.
* @param {Object} params One or more database configuration parameters.
* @param {string} [params.type=events] The database's type.
* @param {*} [params.meta={}] The database's metadata. Only applies when
* creating a database and is not used when opening an existing database.
* @param {boolean} [params.sync=true] If true, sync databases automatically.
* Otherwise, false.
* @param {module:Database} [params.Database=[Events]{@link module:Database.Database-Events}] A Database-compatible
* module.
* @param {module:AccessControllers}
* [params.AccessController=[IPFSAccessController]{@link module:AccessControllers.AccessControllers-IPFS}]
* An AccessController-compatible module.
* @param {module:Storage} [params.headsStorage=[ComposedStorage]{@link module:Storage.Storage-Composed}] A compatible storage instance for storing
* log heads. Defaults to ComposedStorage(LRUStorage, LevelStorage).
* @param {module:Storage} [params.entryStorage=[ComposedStorage]{@link module:Storage.Storage-Composed}] A compatible storage instance for storing
* log entries. Defaults to ComposedStorage(LRUStorage, IPFSBlockStorage).
* @param {module:Storage} [params.indexStorage=[ComposedStorage]{@link module:Storage.Storage-Composed}] A compatible storage instance for storing an " index of log entries. Defaults to ComposedStorage(LRUStorage, LevelStorage).
* @param {number} [params.referencesCount] The number of references to
* use for [Log]{@link module:Log} entries.
* @memberof module:OrbitDB
* @return {module:Database} A database instance.
* @throws "Unsupported database type" if the type specified is not in the list
* of known databaseTypes.
* @memberof module:OrbitDB~OrbitDB
* @instance
* @async
*/
const open = async (address, { type, meta, sync, Database, AccessController, headsStorage, entryStorage, indexStorage, referencesCount } = {}) => {
let name, manifest, accessController
if (databases[address]) {
return databases[address]
}
if ((0,_address_js__WEBPACK_IMPORTED_MODULE_3__.isValidAddress)(address)) {
// If the address given was a valid OrbitDB address, eg. '/orbitdb/zdpuAuK3BHpS7NvMBivynypqciYCuy2UW77XYBPUYRnLjnw13'
const addr = (0,_address_js__WEBPACK_IMPORTED_MODULE_3__["default"])(address)
manifest = await manifestStore.get(addr.hash)
const acType = manifest.accessController.split('/', 2).pop()
AccessController = (0,_access_controllers_index_js__WEBPACK_IMPORTED_MODULE_7__.getAccessController)(acType)()
accessController = await AccessController({ orbitdb: { open, identity, ipfs }, identities, address: manifest.accessController })
name = manifest.name
type = type || manifest.type
meta = manifest.meta
} else {
// If the address given was not valid, eg. just the name of the database
type = type || DefaultDatabaseType
AccessController = AccessController || DefaultAccessController()
accessController = await AccessController({ orbitdb: { open, identity, ipfs }, identities, name: address })
const m = await manifestStore.create({ name: address, type, accessController: accessController.address, meta })
manifest = m.manifest
address = (0,_address_js__WEBPACK_IMPORTED_MODULE_3__["default"])(m.hash)
name = manifest.name
meta = manifest.meta
// Check if we already have the database open and return if it is
if (databases[address]) {
return databases[address]
}
}
Database = Database || (0,_databases_index_js__WEBPACK_IMPORTED_MODULE_0__.getDatabaseType)(type)()
if (!Database) {
throw new Error(`Unsupported database type: '${type}'`)
}
address = address.toString()
const db = await Database({ ipfs, identity, address, name, access: accessController, directory, meta, syncAutomatically: sync, headsStorage, entryStorage, indexStorage, referencesCount })
db.events.on('close', onDatabaseClosed(address))
databases[address] = db
return db
}
const onDatabaseClosed = (address) => () => {
delete databases[address]
}
/**
* Stops OrbitDB, closing the underlying keystore and manifest store.
* @function stop
* @memberof module:OrbitDB~OrbitDB
* @instance
* @async
*/
const stop = async () => {
for (const db of Object.values(databases)) {
await db.close()
}
if (keystore) {
await keystore.close()
}
if (manifestStore) {
await manifestStore.close()
}
databases = {}
}
return {
id,
open,
stop,
ipfs,
directory,
keystore,
identities,
identity,
peerId
}
}
/***/ }),
/***/ "./src/storage/composed.js":
/*!*********************************!*\
!*** ./src/storage/composed.js ***!
\*********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/**
* @namespace Storage-Composed
* @memberof module:Storage
* @description
* ComposedStorage stores data to multiple storage backends.
* @example <caption>Store to LRU and Level</caption>
* await ComposedStorage(await LRUStorage(), await LevelStorage())
* @example <caption>Store to memory and IPFS</caption>
* await ComposedStorage(await MemoryStorage(), await IPFSBlockStorage())
* @example <caption>Store to LRU and a nested ComposedStorage</caption>
* const storage1 = await ComposedStorage(await LRUStorage(), await LevelStorage())
* await ComposedStorage(storage1, await IPFSBlockStorage())
*/
/**
* Creates an instance of ComposedStorage.
* @function
* @param {module:Storage} storage1 A storage instance.
* @param {module:Storage} storage2 A storage instance.
* @return {module:Storage.Storage-Composed} An instance of ComposedStorage.
* @memberof module:Storage
* @instance
*/
const ComposedStorage = async (storage1, storage2) => {
/**
* Puts data to all configured storages.
* @function
* @param {string} hash The hash of the data to put.
* @param {*} data The data to store.
* @memberof module:Storage.Storage-Composed
* @instance
*/
const put = async (hash, data) => {
await storage1.put(hash, data)
await storage2.put(hash, data)
}
/**
* Gets data from the composed storage.
*
* Get will fetch the data from storage1 first. If no value is found, an
* attempt is made to fetch the data from storage2. If data exists in
* storage2 but not in storage1, the data is added to storage1.
* @function
* @param {string} hash The hash of the data to get.
* @memberof module:Storage.Storage-Composed
* @instance
*/
const get = async (hash) => {
let value = await storage1.get(hash)
if (!value) {
value = await storage2.get(hash)
if (value) {
await storage1.put(hash, value)
}
}
return value
}
/**
* Deletes a value from storage.
* @function
* @param {string} hash The hash of the value to delete.
* @memberof module:Storage.Storage-Composed
* @instance
*/
const del = async (hash) => {
await storage1.del(hash)
await storage2.del(hash)
}
/**
* Iterates over records stored in both storages.
* @function
* @yields [string, string] The next key/value pair from all storages.
* @memberof module:Storage.Storage-Composed
* @instance
*/
const iterator = async function * ({ amount, reverse } = {}) {
const keys = []
const iteratorOptions = { amount: amount || -1, reverse: reverse || false }
for (const storage of [storage1, storage2]) {
for await (const [key, value] of storage.iterator(iteratorOptions)) {
if (!keys[key]) {
keys[key] = true
yield [key, value]
}
}
}
}
/**
* Merges data from another source into each of the composed storages.
* @function
* @param {module:Storage} other Another storage instance.
* @memberof module:Storage.Storage-Composed
* @instance
*/
const merge = async (other) => {
await storage1.merge(other)
await storage2.merge(other)
await other.merge(storage1)
await other.merge(storage2)
}
/**
* Calls clear on each of the composed storages.
* @function
* @memberof module:Storage.Storage-Composed
* @instance
*/
const clear = async () => {
await storage1.clear()
await storage2.clear()
}
/**
* Calls close on each of the composed storages.
* @function
* @memberof module:Storage.Storage-Composed
* @instance
*/
const close = async () => {
await storage1.close()
await storage2.close()
}
return {
put,
get,
del,
iterator,
merge,
clear,
close
}
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ComposedStorage);
/***/ }),
/***/ "./src/storage/index.js":
/*!******************************!*\
!*** ./src/storage/index.js ***!
\******************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ComposedStorage: () => (/* reexport safe */ _composed_js__WEBPACK_IMPORTED_MODULE_0__["default"]),
/* harmony export */ IPFSBlockStorage: () => (/* reexport safe */ _ipfs_block_js__WEBPACK_IMPORTED_MODULE_1__["default"]),
/* harmony export */ LRUStorage: () => (/* reexport safe */ _lru_js__WEBPACK_IMPORTED_MODULE_3__["default"]),
/* harmony export */ LevelStorage: () => (/* reexport safe */ _level_js__WEBPACK_IMPORTED_MODULE_2__["default"]),
/* harmony export */ MemoryStorage: () => (/* reexport safe */ _memory_js__WEBPACK_IMPORTED_MODULE_4__["default"])
/* harmony export */ });
/* harmony import */ var _composed_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./composed.js */ "./src/storage/composed.js");
/* harmony import */ var _ipfs_block_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ipfs-block.js */ "./src/storage/ipfs-block.js");
/* harmony import */ var _level_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./level.js */ "./src/storage/level.js");
/* harmony import */ var _lru_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./lru.js */ "./src/storage/lru.js");
/* harmony import */ var _memory_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./memory.js */ "./src/storage/memory.js");
/**
* @module Storage
* @description
* Storage backends for OrbitDB.
*/
/***/ }),
/***/ "./src/storage/ipfs-block.js":
/*!***********************************!*\
!*** ./src/storage/ipfs-block.js ***!
\***********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/cid */ "./node_modules/multiformats/src/cid.js");
/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/bases/base58 */ "./node_modules/multiformats/src/bases/base58.js");
/* harmony import */ var timeout_abort_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! timeout-abort-controller */ "./node_modules/timeout-abort-controller/index.js");
/* harmony import */ var it_drain__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! it-drain */ "./node_modules/it-drain/dist/src/index.js");
/**
* @namespace Storage-IPFS
* @memberof module:Storage
* @description
* IPFSBlockStorage uses IPFS to store data as raw blocks.
*/
const DefaultTimeout = 30000 // 30 seconds
/**
* Creates an instance of IPFSBlockStorage.
* @function
* @param {Object} params One or more parameters for configuring
* IPFSBlockStorage.
* @param {IPFS} params.ipfs An IPFS instance.
* @param {boolean} [params.pin=false] True, if the block should be pinned,
* false otherwise.
* @param {number} [params.timeout=defaultTimeout] A timeout in ms.
* @return {module:Storage.Storage-IPFS} An instance of IPFSBlockStorage.
* @memberof module:Storage
* @throw An instance of ipfs is required if params.ipfs is not specified.
* @instance
*/
const IPFSBlockStorage = async ({ ipfs, pin, timeout } = {}) => {
if (!ipfs) throw new Error('An instance of ipfs is required.')
/**
* Puts data to an IPFS block.
* @function
* @param {string} hash The hash of the block to put.
* @param {*} data The data to store in the IPFS block.
* @memberof module:Storage.Storage-IPFS
* @instance
*/
const put = async (hash, data) => {
const cid = multiformats_cid__WEBPACK_IMPORTED_MODULE_0__.CID.parse(hash, multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_1__.base58btc)
const { signal } = new timeout_abort_controller__WEBPACK_IMPORTED_MODULE_2__.TimeoutController(timeout || DefaultTimeout)
await ipfs.blockstore.put(cid, data, { signal })
if (pin && !(await ipfs.pins.isPinned(cid))) {
await (0,it_drain__WEBPACK_IMPORTED_MODULE_3__["default"])(ipfs.pins.add(cid))
}
}
const del = async (hash) => {}
/**
* Gets data from an IPFS block.
* @function
* @param {string} hash The hash of the block to get.
* @return {Uint8Array} The block.
* @memberof module:Storage.Storage-IPFS
* @instance
*/
const get = async (hash) => {
const cid = multiformats_cid__WEBPACK_IMPORTED_MODULE_0__.CID.parse(hash, multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_1__.base58btc)
const { signal } = new timeout_abort_controller__WEBPACK_IMPORTED_MODULE_2__.TimeoutController(timeout || DefaultTimeout)
const block = await ipfs.blockstore.get(cid, { signal })
if (block) {
return block
}
}
const iterator = async function * () {}
const merge = async (other) => {}
const clear = async () => {}
const close = async () => {}
return {
put,
del,
get,
iterator,
merge,
clear,
close
}
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (IPFSBlockStorage);
/***/ }),
/***/ "./src/storage/level.js":
/*!******************************!*\
!*** ./src/storage/level.js ***!
\******************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var level__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! level */ "./node_modules/level/browser.js");
/**
* @namespace Storage-Level
* @memberof module:Storage
* @description
* LevelStorage stores data to a Level-compatible database.
*
* To learn more about Level, see {@link https://github.com/Level/level}.
*/
const defaultPath = './level'
const defaultValueEncoding = 'view'
/**
* Creates an instance of LevelStorage.
* @function
* @param {Object} [params={}] One or more parameters for configuring
* LevelStorage.
* @param {string} [params.path=defaultPath] The Level path.
* @param {string} [params.valueEncoding=defaultValueEncoding] Value encoding.
* @return {module:Storage.Storage-Level} An instance of LevelStorage.
* @memberof module:Storage
* @instance
*/
const LevelStorage = async ({ path, valueEncoding } = {}) => {
path = path || defaultPath
valueEncoding = valueEncoding || defaultValueEncoding
const db = new level__WEBPACK_IMPORTED_MODULE_0__.Level(path, { valueEncoding, passive: true })
await db.open()
/**
* Puts data to Level.
* @function
* @param {string} hash The hash of the data to put.
* @param {*} data The data to store.
* @memberof module:Storage.Storage-Level
* @instance
*/
const put = async (hash, value) => {
await db.put(hash, value)
}
/**
* Deletes data from Level.
* @function
* @param {string} hash The hash of the data to delete.
* @param {*} data The data to store.
* @memberof module:Storage.Storage-Level
* @instance
*/
const del = async (hash) => {
await db.del(hash)
}
/**
* Gets data from Level.
* @function
* @param {string} hash The hash of the data to get.
* @memberof module:Storage.Storage-Level
* @instance
*/
const get = async (hash) => {
try {
const value = await db.get(hash)
if (value) {
return value
}
} catch (e) {
// LEVEL_NOT_FOUND (ie. key not found)
}
}
/**
* Iterates over records stored in Level.
* @function
* @yields [string, string] The next key/value pair from Level.
* @memberof module:Storage.Storage-Level
* @instance
*/
const iterator = async function * ({ amount, reverse } = {}) {
const iteratorOptions = { limit: amount || -1, reverse: reverse || false }
for await (const [key, value] of db.iterator(iteratorOptions)) {
yield [key, value]
}
}
const merge = async (other) => {}
/**
* Clears the contents of the Level db.
* @function
* @memberof module:Storage.Storage-Level
* @instance
*/
const clear = async () => {
await db.clear()
}
/**
* Closes the Level db.
* @function
* @memberof module:Storage.Storage-Level
* @instance
*/
const close = async () => {
await db.close()
}
return {
put,
del,
get,
iterator,
merge,
clear,
close
}
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (LevelStorage);
/***/ }),
/***/ "./src/storage/lru.js":
/*!****************************!*\
!*** ./src/storage/lru.js ***!
\****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var lru__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lru */ "./node_modules/lru/index.js");
/**
* @namespace Storage-LRU
* @memberof module:Storage
* @description
* LRUStorage stores data in a Least Recently Used (LRU) cache.
*/
const defaultSize = 1000000
/**
* Creates an instance of LRUStorage.
* @function
* @param {Object} [params={}] One or more parameters for configuring
* LRUStorage.
* @param {string} [params.size=defaultSize] The number of elements to store.
* @return {module:Storage.Storage-LRU} An instance of LRUStorage.
* @memberof module:Storage
* @instance
*/
const LRUStorage = async ({ size } = {}) => {
let lru = new lru__WEBPACK_IMPORTED_MODULE_0__(size || defaultSize)
/**
* Puts data to the LRU cache.
* @function
* @param {string} hash The hash of the data to put.
* @param {*} data The data to store.
* @memberof module:Storage.Storage-LRU
* @instance
*/
const put = async (hash, data) => {
lru.set(hash, data)
}
/**
* Deletes data from the LRU cache.
* @function
* @param {string} hash The hash of the data to delete.
* @memberof module:Storage.Storage-LRU
* @instance
*/
const del = async (hash) => {
lru.remove(hash)
}
/**
* Gets data from the LRU cache.
* @function
* @param {string} hash The hash of the data to get.
* @memberof module:Storage.Storage-LRU
* @instance
*/
const get = async (hash) => {
return lru.get(hash)
}
/**
* Iterates over records stored in the LRU cache.
* @function
* @yields [string, string] The next key/value pair from the LRU cache.
* @memberof module:Storage.Storage-LRU
* @instance
*/
const iterator = async function * () {
for await (const key of lru.keys) {
const value = lru.get(key)
yield [key, value]
}
}
/**
* Merges data from another source into the LRU cache.
* @function
* @param {module:Storage} other Another storage instance.
* @memberof module:Storage.Storage-LRU
* @instance
*/
const merge = async (other) => {
if (other) {
for await (const [key, value] of other.iterator()) {
lru.set(key, value)
}
}
}
/**
* Clears the contents of the LRU cache.
* @function
* @memberof module:Storage.Storage-LRU
* @instance
*/
const clear = async () => {
lru = new lru__WEBPACK_IMPORTED_MODULE_0__(size || defaultSize)
}
const close = async () => {}
return {
put,
del,
get,
iterator,
merge,
clear,
close
}
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (LRUStorage);
/***/ }),
/***/ "./src/storage/memory.js":
/*!*******************************!*\
!*** ./src/storage/memory.js ***!
\*******************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/**
* @namespace Storage-Memory
* @memberof module:Storage
* @description
* MemoryStorage stores data in memory.
*/
/**
* Creates an instance of MemoryStorage.
* @function
* @return {module:Storage.Storage-Memory} An instance of MemoryStorage.
* @memberof module:Storage
* @instance
*/
const MemoryStorage = async () => {
let memory = {}
/**
* Puts data to memory.
* @function
* @param {string} hash The hash of the data to put.
* @param {*} data The data to store.
* @memberof module:Storage.Storage-Memory
* @instance
*/
const put = async (hash, data) => {
memory[hash] = data
}
/**
* Deletes data from memory.
* @function
* @param {string} hash The hash of the data to delete.
* @memberof module:Storage.Storage-Memory
* @instance
*/
const del = async (hash) => {
delete memory[hash]
}
/**
* Gets data from memory.
* @function
* @param {string} hash The hash of the data to get.
* @memberof module:Storage.Storage-Memory
* @instance
*/
const get = async (hash) => {
return memory[hash]
}
/**
* Iterates over records stored in memory.
* @function
* @yields [string, string] The next key/value pair from memory.
* @memberof module:Storage.Storage-Memory
* @instance
*/
const iterator = async function * () {
for await (const [key, value] of Object.entries(memory)) {
yield [key, value]
}
}
/**
* Merges data from another source into memory.
* @function
* @param {module:Storage} other Another storage instance.
* @memberof module:Storage.Storage-Memory
* @instance
*/
const merge = async (other) => {
if (other) {
for await (const [key, value] of other.iterator()) {
put(key, value)
}
}
}
/**
* Clears the contents of memory.
* @function
* @memberof module:Storage.Storage-Memory
* @instance
*/
const clear = async () => {
memory = {}
}
const close = async () => {}
return {
put,
del,
get,
iterator,
merge,
clear,
close
}
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (MemoryStorage);
/***/ }),
/***/ "./src/sync.js":
/*!*********************!*\
!*** ./src/sync.js ***!
\*********************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ Sync)
/* harmony export */ });
/* harmony import */ var it_pipe__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-pipe */ "./node_modules/it-pipe/dist/src/index.js");
/* harmony import */ var p_queue__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! p-queue */ "./node_modules/p-queue/dist/index.js");
/* harmony import */ var events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! events */ "./node_modules/events/events.js");
/* harmony import */ var timeout_abort_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! timeout-abort-controller */ "./node_modules/timeout-abort-controller/index.js");
/* harmony import */ var _utils_path_join_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/path-join.js */ "./src/utils/path-join.js");
const DefaultTimeout = 30000 // 30 seconds
/**
* @module Sync
* @description
* The Sync Protocol for OrbitDB synchronizes the database operations {@link module:Log} between multiple peers.
*
* The Sync Protocol sends and receives heads between multiple peers,
* both when opening a database and when a database is updated, ie.
* new entries are appended to the log.
*
* When Sync is started, a peer subscribes to a pubsub topic of the log's id.
* Upon subscribing to the topic, peers already connected to the topic receive
* the subscription message and "dial" the subscribing peer using a libp2p
* custom protocol. Once connected to the subscribing peer on a direct
* peer-to-peer connection, the dialing peer and the subscribing peer exchange
* the heads of the Log each peer currently has. Once completed, the peers have
* the same "local state".
*
* Once the initial sync has completed, peers notify one another of updates to
* the log, ie. updates to the database, using the initially opened pubsub
* topic subscription. A peer with new heads broadcasts changes to other peers
* by publishing the updated heads to the pubsub topic. Peers subscribed to the
* same topic will then receive the update and will update their log's state,
* the heads, accordingly.
*
* The Sync Protocol is eventually consistent. It guarantees that once all
* messages have been sent and received, peers will observe the same log state
* and values. The Sync Protocol does not guarantee the order in which messages
* are received or even that a message is recieved at all, nor any timing on
* when messages are received.
*
* @example
* // Using defaults
* const sync = await Sync({ ipfs, log, onSynced: (peerId, heads) => ... })
*
* @example
* // Using all parameters
* const sync = await Sync({ ipfs, log, events, onSynced: (peerId, heads) => ..., start: false })
* sync.events.on('join', (peerId, heads) => ...)
* sync.events.on('leave', (peerId) => ...)
* sync.events.on('error', (err) => ...)
* await sync.start()
*/
/**
* Creates a Sync instance for sychronizing logs between multiple peers.
*
* @function
* @param {Object} params One or more parameters for configuring Sync.
* @param {IPFS} params.ipfs An IPFS instance.
* @param {Log} params.log The log instance to sync.
* @param {EventEmitter} [params.events] An event emitter to use. Events
* emitted are 'join', 'leave' and 'error'. If the parameter is not provided,
* an EventEmitter will be created.
* @param {onSynced} [params.onSynced] A callback function that is called after
* the peer has received heads from another peer.
* @param {Boolean} [params.start] True if sync should start automatically,
* false otherwise. Defaults to true.
* @return {module:Sync~Sync} sync An instance of the Sync Protocol.
* @memberof module:Sync
* @instance
*/
const Sync = async ({ ipfs, log, events, onSynced, start, timeout }) => {
/**
* @namespace module:Sync~Sync
* @description The instance returned by {@link module:Sync}.
*/
/**
* Callback function when new heads have been received from other peers.
* @callback module:Sync~Sync#onSynced
* @param {PeerID} peerId PeerID of the peer who we received heads from
* @param {Entry[]} heads An array of Log entries
*/
/**
* Event fired when when a peer has connected and the exchange of
* heads has been completed.
* @event module:Sync~Sync#join
* @param {PeerID} peerId PeerID of the peer who we received heads from
* @param {Entry[]} heads An array of Log entries
* @example
* sync.events.on('join', (peerID, heads) => ...)
*/
/**
* Event fired when a peer leaves the sync protocol.
* @event module:Sync~Sync#leave
* @param {PeerID} peerId PeerID of the peer who left
* @example
* sync.events.on('leave', (peerID) => ...)
*/
/**
* Event fired when an error occurs.
* @event module:Sync~Sync#error
* @param {Error} error The error that occured
* @example
* sync.events.on('error', (error) => ...)
*/
if (!ipfs) throw new Error('An instance of ipfs is required.')
if (!log) throw new Error('An instance of log is required.')
const libp2p = ipfs.libp2p
const pubsub = ipfs.libp2p.services.pubsub
const address = log.id
const headsSyncAddress = (0,_utils_path_join_js__WEBPACK_IMPORTED_MODULE_3__["default"])('/orbitdb/heads/', address)
const queue = new p_queue__WEBPACK_IMPORTED_MODULE_4__["default"]({ concurrency: 1 })
/**
* Set of currently connected peers for the log for this Sync instance.
* @name peers
* @†ype Set
* @memberof module:Sync~Sync
* @instance
*/
const peers = new Set()
/**
* Event emitter that emits Sync changes. See Events section for details.
* @†ype EventEmitter
* @memberof module:Sync~Sync
* @instance
*/
events = events || new events__WEBPACK_IMPORTED_MODULE_1__.EventEmitter()
timeout = timeout || DefaultTimeout
let started = false
const onPeerJoined = async (peerId) => {
const heads = await log.heads()
events.emit('join', peerId, heads)
}
const sendHeads = (source) => {
return (async function * () {
const heads = await log.heads()
for await (const { bytes } of heads) {
yield bytes
}
})()
}
const receiveHeads = (peerId) => async (source) => {
for await (const value of source) {
const headBytes = value.subarray()
if (headBytes && onSynced) {
await onSynced(headBytes)
}
}
if (started) {
await onPeerJoined(peerId)
}
}
const handleReceiveHeads = async ({ connection, stream }) => {
const peerId = String(connection.remotePeer)
try {
peers.add(peerId)
await (0,it_pipe__WEBPACK_IMPORTED_MODULE_0__.pipe)(stream, receiveHeads(peerId), sendHeads, stream)
} catch (e) {
peers.delete(peerId)
events.emit('error', e)
}
}
const handlePeerSubscribed = async (event) => {
const task = async () => {
const { peerId: remotePeer, subscriptions } = event.detail
const peerId = String(remotePeer)
const subscription = subscriptions.find(e => e.topic === address)
if (!subscription) {
return
}
if (subscription.subscribe) {
if (peers.has(peerId)) {
return
}
const timeoutController = new timeout_abort_controller__WEBPACK_IMPORTED_MODULE_2__.TimeoutController(timeout)
const { signal } = timeoutController
try {
peers.add(peerId)
const stream = await libp2p.dialProtocol(remotePeer, headsSyncAddress, { signal })
await (0,it_pipe__WEBPACK_IMPORTED_MODULE_0__.pipe)(sendHeads, stream, receiveHeads(peerId))
} catch (e) {
peers.delete(peerId)
if (e.name === 'UnsupportedProtocolError') {
// Skip peer, they don't have this database currently
} else {
events.emit('error', e)
}
} finally {
if (timeoutController) {
timeoutController.clear()
}
}
} else {
peers.delete(peerId)
events.emit('leave', peerId)
}
}
queue.add(task)
}
const handleUpdateMessage = async message => {
const { topic, data } = message.detail
const task = async () => {
try {
if (data && onSynced) {
await onSynced(data)
}
} catch (e) {
events.emit('error', e)
}
}
if (topic === address) {
queue.add(task)
}
}
const handlePeerDisconnected = async event => {
peers.delete(event.detail.toString())
}
/**
* Add a log entry to the Sync Protocol to be sent to peers.
* @function add
* @param {Entry} entry Log entry
* @memberof module:Sync~Sync
* @instance
*/
const add = async (entry) => {
if (started) {
await pubsub.publish(address, entry.bytes)
}
}
/**
* Stop the Sync Protocol.
* @function stop
* @memberof module:Sync~Sync
* @instance
*/
const stopSync = async () => {
if (started) {
started = false
await queue.onIdle()
pubsub.removeEventListener('subscription-change', handlePeerSubscribed)
pubsub.removeEventListener('message', handleUpdateMessage)
await libp2p.unhandle(headsSyncAddress)
await pubsub.unsubscribe(address)
libp2p.removeEventListener('peer:disconnect', handlePeerDisconnected)
peers.clear()
}
}
/**
* Start the Sync Protocol.
* @function start
* @memberof module:Sync~Sync
* @instance
*/
const startSync = async () => {
if (!started) {
// Exchange head entries with peers when connected
await libp2p.handle(headsSyncAddress, handleReceiveHeads)
pubsub.addEventListener('subscription-change', handlePeerSubscribed)
pubsub.addEventListener('message', handleUpdateMessage)
// Subscribe to the pubsub channel for this database through which updates are sent
await pubsub.subscribe(address)
// Remove disconnected peers from `peers`, as otherwise they will not resync heads on reconnection
libp2p.addEventListener('peer:disconnect', handlePeerDisconnected)
started = true
}
}
// Start Sync automatically
if (start !== false) {
await startSync()
}
return {
add,
stop: stopSync,
start: startSync,
events,
peers
}
}
/***/ }),
/***/ "./src/utils/create-id.js":
/*!********************************!*\
!*** ./src/utils/create-id.js ***!
\********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
const createId = async (length = 32) => {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
let result = ''
let counter = 0
while (counter < length) {
result += characters.charAt(Math.floor(Math.random() * characters.length))
counter += 1
}
return result
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (createId);
/***/ }),
/***/ "./src/utils/index.js":
/*!****************************!*\
!*** ./src/utils/index.js ***!
\****************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ createId: () => (/* reexport safe */ _create_id_js__WEBPACK_IMPORTED_MODULE_0__["default"])
/* harmony export */ });
/* harmony import */ var _create_id_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./create-id.js */ "./src/utils/create-id.js");
/***/ }),
/***/ "./src/utils/path-join.js":
/*!********************************!*\
!*** ./src/utils/path-join.js ***!
\********************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */ join: () => (/* binding */ join),
/* harmony export */ posixJoin: () => (/* binding */ posixJoin),
/* harmony export */ win32Join: () => (/* binding */ win32Join)
/* harmony export */ });
const posixJoin = (...paths) => paths
.join('/')
.replace(/((?<=\/)\/+)|(^\.\/)|((?<=\/)\.\/)/g, '') || '.'
const win32Join = (...paths) => paths
.join('\\')
.replace(/\//g, '\\')
.replace(/((?<=\\)\\+)|(^\.\\)|((?<=\\)\.\\)/g, '') || '.'
const join = posixJoin
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (posixJoin);
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/global */
/******/ (() => {
/******/ __webpack_require__.g = (function() {
/******/ if (typeof globalThis === 'object') return globalThis;
/******/ try {
/******/ return this || new Function('return this')();
/******/ } catch (e) {
/******/ if (typeof window === 'object') return window;
/******/ }
/******/ })();
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
/*!**********************!*\
!*** ./src/index.js ***!
\**********************/
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ComposedStorage: () => (/* reexport safe */ _storage_index_js__WEBPACK_IMPORTED_MODULE_8__.ComposedStorage),
/* harmony export */ Database: () => (/* reexport safe */ _database_js__WEBPACK_IMPORTED_MODULE_4__["default"]),
/* harmony export */ DefaultAccessController: () => (/* reexport safe */ _oplog_index_js__WEBPACK_IMPORTED_MODULE_3__.DefaultAccessController),
/* harmony export */ Documents: () => (/* reexport safe */ _databases_index_js__WEBPACK_IMPORTED_MODULE_1__.Documents),
/* harmony export */ Entry: () => (/* reexport safe */ _oplog_index_js__WEBPACK_IMPORTED_MODULE_3__.Entry),
/* harmony export */ Events: () => (/* reexport safe */ _databases_index_js__WEBPACK_IMPORTED_MODULE_1__.Events),
/* harmony export */ IPFSAccessController: () => (/* reexport safe */ _access_controllers_index_js__WEBPACK_IMPORTED_MODULE_6__.IPFSAccessController),
/* harmony export */ IPFSBlockStorage: () => (/* reexport safe */ _storage_index_js__WEBPACK_IMPORTED_MODULE_8__.IPFSBlockStorage),
/* harmony export */ Identities: () => (/* reexport safe */ _identities_index_js__WEBPACK_IMPORTED_MODULE_7__.Identities),
/* harmony export */ KeyStore: () => (/* reexport safe */ _key_store_js__WEBPACK_IMPORTED_MODULE_5__["default"]),
/* harmony export */ KeyValue: () => (/* reexport safe */ _databases_index_js__WEBPACK_IMPORTED_MODULE_1__.KeyValue),
/* harmony export */ KeyValueIndexed: () => (/* reexport safe */ _databases_index_js__WEBPACK_IMPORTED_MODULE_1__.KeyValueIndexed),
/* harmony export */ LRUStorage: () => (/* reexport safe */ _storage_index_js__WEBPACK_IMPORTED_MODULE_8__.LRUStorage),
/* harmony export */ LevelStorage: () => (/* reexport safe */ _storage_index_js__WEBPACK_IMPORTED_MODULE_8__.LevelStorage),
/* harmony export */ Log: () => (/* reexport safe */ _oplog_index_js__WEBPACK_IMPORTED_MODULE_3__.Log),
/* harmony export */ MemoryStorage: () => (/* reexport safe */ _storage_index_js__WEBPACK_IMPORTED_MODULE_8__.MemoryStorage),
/* harmony export */ OrbitDBAccessController: () => (/* reexport safe */ _access_controllers_index_js__WEBPACK_IMPORTED_MODULE_6__.OrbitDBAccessController),
/* harmony export */ PublicKeyIdentityProvider: () => (/* reexport safe */ _identities_index_js__WEBPACK_IMPORTED_MODULE_7__.PublicKeyIdentityProvider),
/* harmony export */ createOrbitDB: () => (/* reexport safe */ _orbitdb_js__WEBPACK_IMPORTED_MODULE_0__["default"]),
/* harmony export */ isIdentity: () => (/* reexport safe */ _identities_index_js__WEBPACK_IMPORTED_MODULE_7__.isIdentity),
/* harmony export */ isValidAddress: () => (/* reexport safe */ _address_js__WEBPACK_IMPORTED_MODULE_2__.isValidAddress),
/* harmony export */ parseAddress: () => (/* reexport safe */ _address_js__WEBPACK_IMPORTED_MODULE_2__.parseAddress),
/* harmony export */ useAccessController: () => (/* reexport safe */ _access_controllers_index_js__WEBPACK_IMPORTED_MODULE_6__.useAccessController),
/* harmony export */ useDatabaseType: () => (/* reexport safe */ _databases_index_js__WEBPACK_IMPORTED_MODULE_1__.useDatabaseType),
/* harmony export */ useIdentityProvider: () => (/* reexport safe */ _identities_index_js__WEBPACK_IMPORTED_MODULE_7__.useIdentityProvider)
/* harmony export */ });
/* harmony import */ var _orbitdb_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./orbitdb.js */ "./src/orbitdb.js");
/* harmony import */ var _databases_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./databases/index.js */ "./src/databases/index.js");
/* harmony import */ var _address_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./address.js */ "./src/address.js");
/* harmony import */ var _oplog_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./oplog/index.js */ "./src/oplog/index.js");
/* harmony import */ var _database_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./database.js */ "./src/database.js");
/* harmony import */ var _key_store_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./key-store.js */ "./src/key-store.js");
/* harmony import */ var _access_controllers_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./access-controllers/index.js */ "./src/access-controllers/index.js");
/* harmony import */ var _identities_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./identities/index.js */ "./src/identities/index.js");
/* harmony import */ var _storage_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./storage/index.js */ "./src/storage/index.js");
})();
OrbitDB = __webpack_exports__;
/******/ })()
;
//# sourceMappingURL=orbitdb.js.map