@wovin/core 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/applog/applog-helpers.d.ts +5 -6
  2. package/dist/applog/applog-helpers.d.ts.map +1 -1
  3. package/dist/applog/applog-utils.d.ts +2 -1
  4. package/dist/applog/applog-utils.d.ts.map +1 -1
  5. package/dist/applog/datom-types.d.ts +34 -2
  6. package/dist/applog/datom-types.d.ts.map +1 -1
  7. package/dist/applog.min.js +90 -1
  8. package/dist/chunk-2J7BWXZ3.min.js +4373 -0
  9. package/dist/{chunk-G3GOAFHU.min.js.map → chunk-2J7BWXZ3.min.js.map} +1 -1
  10. package/dist/chunk-5MMGBK2U.min.js +1 -0
  11. package/dist/chunk-5MMGBK2U.min.js.map +1 -0
  12. package/dist/chunk-6BFNER6K.min.js +120 -0
  13. package/dist/chunk-6BFNER6K.min.js.map +1 -0
  14. package/dist/chunk-KRQZ6V4Y.min.js +36 -0
  15. package/dist/chunk-KRQZ6V4Y.min.js.map +1 -0
  16. package/dist/chunk-N4QMZPZF.min.js +10844 -0
  17. package/dist/chunk-N4QMZPZF.min.js.map +1 -0
  18. package/dist/chunk-ORHJN4G2.min.js +1425 -0
  19. package/dist/chunk-ORHJN4G2.min.js.map +1 -0
  20. package/dist/chunk-PTGUFZ3Q.min.js +1555 -0
  21. package/dist/chunk-PTGUFZ3Q.min.js.map +1 -0
  22. package/dist/chunk-YOCP7FGE.min.js +66 -0
  23. package/dist/chunk-YOCP7FGE.min.js.map +1 -0
  24. package/dist/index.d.ts +0 -1
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.min.js +252 -1
  27. package/dist/index.min.js.map +1 -1
  28. package/dist/ipfs/car.d.ts +2 -0
  29. package/dist/ipfs/car.d.ts.map +1 -1
  30. package/dist/ipfs.min.js +32 -1
  31. package/dist/mobx/mobx-utils.d.ts +7 -6
  32. package/dist/mobx/mobx-utils.d.ts.map +1 -1
  33. package/dist/pubsub.min.js +21 -1
  34. package/dist/query/basic.d.ts +11 -28
  35. package/dist/query/basic.d.ts.map +1 -1
  36. package/dist/query/divergences.d.ts +2 -2
  37. package/dist/query/divergences.d.ts.map +1 -1
  38. package/dist/query/query-steps.d.ts +4 -0
  39. package/dist/query/query-steps.d.ts.map +1 -0
  40. package/dist/query/types.d.ts +29 -0
  41. package/dist/query/types.d.ts.map +1 -0
  42. package/dist/query.d.ts +1 -0
  43. package/dist/query.d.ts.map +1 -1
  44. package/dist/query.min.js +71 -1
  45. package/dist/thread/basic.d.ts +12 -6
  46. package/dist/thread/basic.d.ts.map +1 -1
  47. package/dist/thread/filters.d.ts +7 -5
  48. package/dist/thread/filters.d.ts.map +1 -1
  49. package/dist/thread/mapped.d.ts +3 -4
  50. package/dist/thread/mapped.d.ts.map +1 -1
  51. package/dist/thread/writeable.d.ts +3 -2
  52. package/dist/thread/writeable.d.ts.map +1 -1
  53. package/dist/thread.min.js +37 -1
  54. package/dist/types/typescript-utils.d.ts +6 -2
  55. package/dist/types/typescript-utils.d.ts.map +1 -1
  56. package/dist/types.min.js +30 -1
  57. package/package.json +2 -2
  58. package/dist/chunk-5O6HLH5H.min.js +0 -2
  59. package/dist/chunk-5O6HLH5H.min.js.map +0 -1
  60. package/dist/chunk-6WLDICQ6.min.js +0 -2
  61. package/dist/chunk-6WLDICQ6.min.js.map +0 -1
  62. package/dist/chunk-G3GOAFHU.min.js +0 -8
  63. package/dist/chunk-J5PGGKKW.min.js +0 -2
  64. package/dist/chunk-J5PGGKKW.min.js.map +0 -1
  65. package/dist/chunk-O7KDPKK2.min.js +0 -2
  66. package/dist/chunk-O7KDPKK2.min.js.map +0 -1
  67. package/dist/chunk-XQUJRFOK.min.js +0 -45
  68. package/dist/chunk-XQUJRFOK.min.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/encode.js","../../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/decode.js","../../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/length.js","../../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/index.js","../../../../node_modules/.pnpm/@ipld+dag-cbor@9.0.6/node_modules/@ipld/dag-cbor/src/index.js","../../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/decoder-common.js","../../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/header-validator.js","../../../../node_modules/.pnpm/cborg@4.0.3/node_modules/cborg/lib/length.js","../../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/buffer-writer.js","../../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/decoder.js","../../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/indexer.js","../../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/iterator.js","../../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/encoder.js","../../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/iterator-channel.js","../../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/writer-browser.js","../src/ipfs/car.ts"],"sourcesContent":["module.exports = encode\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31)\n\nfunction encode(num, out, offset) {\n if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) {\n encode.bytes = 0\n throw new RangeError('Could not encode varint')\n }\n out = out || []\n offset = offset || 0\n var oldOffset = offset\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB\n num /= 128\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB\n num >>>= 7\n }\n out[offset] = num | 0\n \n encode.bytes = offset - oldOffset + 1\n \n return out\n}\n","module.exports = read\n\nvar MSB = 0x80\n , REST = 0x7F\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length\n\n do {\n if (counter >= l || shift > 49) {\n read.bytes = 0\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++]\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift)\n shift += 7\n } while (b >= MSB)\n\n read.bytes = counter - offset\n\n return res\n}\n","\nvar N1 = Math.pow(2, 7)\nvar N2 = Math.pow(2, 14)\nvar N3 = Math.pow(2, 21)\nvar N4 = Math.pow(2, 28)\nvar N5 = Math.pow(2, 35)\nvar N6 = Math.pow(2, 42)\nvar N7 = Math.pow(2, 49)\nvar N8 = Math.pow(2, 56)\nvar N9 = Math.pow(2, 63)\n\nmodule.exports = function (value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n}\n","module.exports = {\n encode: require('./encode.js')\n , decode: require('./decode.js')\n , encodingLength: require('./length.js')\n}\n","import * as cborg from 'cborg'\nimport { CID } from 'multiformats/cid'\n\n// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692\nconst CID_CBOR_TAG = 42\n\n/**\n * @template T\n * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView\n */\n\n/**\n * cidEncoder will receive all Objects during encode, it needs to filter out\n * anything that's not a CID and return `null` for that so it's encoded as\n * normal.\n *\n * @param {any} obj\n * @returns {cborg.Token[]|null}\n */\nfunction cidEncoder (obj) {\n if (obj.asCID !== obj && obj['/'] !== obj.bytes) {\n return null // any other kind of object\n }\n const cid = CID.asCID(obj)\n /* c8 ignore next 4 */\n // very unlikely case, and it'll probably throw a recursion error in cborg\n if (!cid) {\n return null\n }\n const bytes = new Uint8Array(cid.bytes.byteLength + 1)\n bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons\n return [\n new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),\n new cborg.Token(cborg.Type.bytes, bytes)\n ]\n}\n\n// eslint-disable-next-line jsdoc/require-returns-check\n/**\n * Intercept all `undefined` values from an object walk and reject the entire\n * object if we find one.\n *\n * @returns {null}\n */\nfunction undefinedEncoder () {\n throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')\n}\n\n/**\n * Intercept all `number` values from an object walk and reject the entire\n * object if we find something that doesn't fit the IPLD data model (NaN &\n * Infinity).\n *\n * @param {number} num\n * @returns {null}\n */\nfunction numberEncoder (num) {\n if (Number.isNaN(num)) {\n throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')\n }\n if (num === Infinity || num === -Infinity) {\n throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')\n }\n return null\n}\n\nconst encodeOptions = {\n float64: true,\n typeEncoders: {\n Object: cidEncoder,\n undefined: undefinedEncoder,\n number: numberEncoder\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {CID}\n */\nfunction cidDecoder (bytes) {\n if (bytes[0] !== 0) {\n throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')\n }\n return CID.decode(bytes.subarray(1)) // ignore leading 0x00\n}\n\nconst decodeOptions = {\n allowIndefinite: false,\n coerceUndefinedToNull: true,\n allowNaN: false,\n allowInfinity: false,\n allowBigInt: true, // this will lead to BigInt for ints outside of\n // safe-integer range, which may surprise users\n strict: true,\n useMaps: false,\n rejectDuplicateMapKeys: true,\n /** @type {import('cborg').TagDecoder[]} */\n tags: []\n}\ndecodeOptions.tags[CID_CBOR_TAG] = cidDecoder\n\nexport const name = 'dag-cbor'\nexport const code = 0x71\n\n/**\n * @template T\n * @param {T} node\n * @returns {ByteView<T>}\n */\nexport const encode = (node) => cborg.encode(node, encodeOptions)\n\n/**\n * @template T\n * @param {ByteView<T>} data\n * @returns {T}\n */\nexport const decode = (data) => cborg.decode(data, decodeOptions)\n","import varint from 'varint'\n\nexport const CIDV0_BYTES = {\n SHA2_256: 0x12,\n LENGTH: 0x20,\n DAG_PB: 0x70\n}\n\nexport const V2_HEADER_LENGTH = /* characteristics */ 16 /* v1 offset */ + 8 /* v1 size */ + 8 /* index offset */ + 8\n\n/**\n * Decodes varint and seeks the buffer\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.upTo(8) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n * @param {import('./coding').Seekable} seeker\n * @returns {number}\n */\nexport function decodeVarint (bytes, seeker) {\n if (!bytes.length) {\n throw new Error('Unexpected end of data')\n }\n const i = varint.decode(bytes)\n seeker.seek(/** @type {number} */(varint.decode.bytes))\n return i\n}\n\n/**\n * Decode v2 header\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.exactly(V2_HEADER_LENGTH, true) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n * @returns {import('./coding').CarV2FixedHeader}\n */\nexport function decodeV2Header (bytes) {\n const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n let offset = 0\n const header = {\n version: 2,\n /** @type {[bigint, bigint]} */\n characteristics: [\n dv.getBigUint64(offset, true),\n dv.getBigUint64(offset += 8, true)\n ],\n dataOffset: Number(dv.getBigUint64(offset += 8, true)),\n dataSize: Number(dv.getBigUint64(offset += 8, true)),\n indexOffset: Number(dv.getBigUint64(offset += 8, true))\n }\n return header\n}\n\n/**\n * Checks the length of the multihash to be read afterwards\n *\n * ```js\n * // needs bytes to be read first\n * const bytes = reader.upTo(8) // maybe async\n * ```\n *\n * @param {Uint8Array} bytes\n */\nexport function getMultihashLength (bytes) {\n // | code | length | .... |\n // where both code and length are varints, so we have to decode\n // them first before we can know total length\n\n varint.decode(bytes) // code\n const codeLength = /** @type {number} */(varint.decode.bytes)\n const length = varint.decode(bytes.subarray(varint.decode.bytes))\n const lengthLength = /** @type {number} */(varint.decode.bytes)\n const mhLength = codeLength + lengthLength + length\n\n return mhLength\n}\n","/** Auto-generated with @ipld/schema@v4.2.0 at Thu Sep 14 2023 from IPLD Schema:\n *\n * # CarV1HeaderOrV2Pragma is a more relaxed form, and can parse {version:x} where\n * # roots are optional. This is typically useful for the {verison:2} CARv2\n * # pragma.\n *\n * type CarV1HeaderOrV2Pragma struct {\n * \troots optional [&Any]\n * \t# roots is _not_ optional for CarV1 but we defer that check within code to\n * \t# gracefully handle the V2 case where it's just {version:X}\n * \tversion Int\n * }\n *\n * # CarV1Header is the strict form of the header, and requires roots to be\n * # present. This is compatible with the CARv1 specification.\n *\n * # type CarV1Header struct {\n * # \troots [&Any]\n * # \tversion Int\n * # }\n *\n */\n\nconst Kinds = {\n Null: /** @returns {undefined|null} */ (/** @type {any} */ obj) => obj === null ? obj : undefined,\n Int: /** @returns {undefined|number} */ (/** @type {any} */ obj) => Number.isInteger(obj) ? obj : undefined,\n Float: /** @returns {undefined|number} */ (/** @type {any} */ obj) => typeof obj === 'number' && Number.isFinite(obj) ? obj : undefined,\n String: /** @returns {undefined|string} */ (/** @type {any} */ obj) => typeof obj === 'string' ? obj : undefined,\n Bool: /** @returns {undefined|boolean} */ (/** @type {any} */ obj) => typeof obj === 'boolean' ? obj : undefined,\n Bytes: /** @returns {undefined|Uint8Array} */ (/** @type {any} */ obj) => obj instanceof Uint8Array ? obj : undefined,\n Link: /** @returns {undefined|object} */ (/** @type {any} */ obj) => obj !== null && typeof obj === 'object' && obj.asCID === obj ? obj : undefined,\n List: /** @returns {undefined|Array<any>} */ (/** @type {any} */ obj) => Array.isArray(obj) ? obj : undefined,\n Map: /** @returns {undefined|object} */ (/** @type {any} */ obj) => obj !== null && typeof obj === 'object' && obj.asCID !== obj && !Array.isArray(obj) && !(obj instanceof Uint8Array) ? obj : undefined\n}\n/** @type {{ [k in string]: (obj:any)=>undefined|any}} */\nconst Types = {\n 'CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)': Kinds.Link,\n 'CarV1HeaderOrV2Pragma > roots (anon)': /** @returns {undefined|any} */ (/** @type {any} */ obj) => {\n if (Kinds.List(obj) === undefined) {\n return undefined\n }\n for (let i = 0; i < obj.length; i++) {\n let v = obj[i]\n v = Types['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n if (v !== obj[i]) {\n const ret = obj.slice(0, i)\n for (let j = i; j < obj.length; j++) {\n let v = obj[j]\n v = Types['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n ret.push(v)\n }\n return ret\n }\n }\n return obj\n },\n Int: Kinds.Int,\n CarV1HeaderOrV2Pragma: /** @returns {undefined|any} */ (/** @type {any} */ obj) => {\n if (Kinds.Map(obj) === undefined) {\n return undefined\n }\n const entries = Object.entries(obj)\n /** @type {{[k in string]: any}} */\n let ret = obj\n let requiredCount = 1\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i]\n switch (key) {\n case 'roots':\n {\n const v = Types['CarV1HeaderOrV2Pragma > roots (anon)'](obj[key])\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.roots = v\n }\n }\n break\n case 'version':\n {\n requiredCount--\n const v = Types.Int(obj[key])\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.version = v\n }\n }\n break\n default:\n return undefined\n }\n }\n\n if (requiredCount > 0) {\n return undefined\n }\n return ret\n }\n}\n/** @type {{ [k in string]: (obj:any)=>undefined|any}} */\nconst Reprs = {\n 'CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)': Kinds.Link,\n 'CarV1HeaderOrV2Pragma > roots (anon)': /** @returns {undefined|any} */ (/** @type {any} */ obj) => {\n if (Kinds.List(obj) === undefined) {\n return undefined\n }\n for (let i = 0; i < obj.length; i++) {\n let v = obj[i]\n v = Reprs['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n if (v !== obj[i]) {\n const ret = obj.slice(0, i)\n for (let j = i; j < obj.length; j++) {\n let v = obj[j]\n v = Reprs['CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)'](v)\n if (v === undefined) {\n return undefined\n }\n ret.push(v)\n }\n return ret\n }\n }\n return obj\n },\n Int: Kinds.Int,\n CarV1HeaderOrV2Pragma: /** @returns {undefined|any} */ (/** @type {any} */ obj) => {\n if (Kinds.Map(obj) === undefined) {\n return undefined\n }\n const entries = Object.entries(obj)\n /** @type {{[k in string]: any}} */\n let ret = obj\n let requiredCount = 1\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i]\n switch (key) {\n case 'roots':\n {\n const v = Reprs['CarV1HeaderOrV2Pragma > roots (anon)'](value)\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.roots = v\n }\n }\n break\n case 'version':\n {\n requiredCount--\n const v = Reprs.Int(value)\n if (v === undefined) {\n return undefined\n }\n if (v !== value || ret !== obj) {\n if (ret === obj) {\n /** @type {{[k in string]: any}} */\n ret = {}\n for (let j = 0; j < i; j++) {\n ret[entries[j][0]] = entries[j][1]\n }\n }\n ret.version = v\n }\n }\n break\n default:\n return undefined\n }\n }\n if (requiredCount > 0) {\n return undefined\n }\n return ret\n }\n}\n\nexport const CarV1HeaderOrV2Pragma = {\n toTyped: Types.CarV1HeaderOrV2Pragma,\n toRepresentation: Reprs.CarV1HeaderOrV2Pragma\n}\n","import { makeCborEncoders, objectToTokens } from './encode.js'\nimport { quickEncodeToken } from './jump.js'\n\n/**\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../interface').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface').TokenOrNestedTokens} TokenOrNestedTokens\n */\n\nconst cborEncoders = makeCborEncoders()\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n quickEncodeToken\n}\n\n/**\n * Calculate the byte length of the given data when encoded as CBOR with the\n * options provided.\n * This calculation will be accurate if the same options are used as when\n * performing a normal encode. Some encode options can change the encoding\n * output length.\n *\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {number}\n */\nexport function encodedLength (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n options.mapSorter = undefined // won't change the length\n const tokens = objectToTokens(data, options)\n return tokensToLength(tokens, cborEncoders, options)\n}\n\n/**\n * Calculate the byte length of the data as represented by the given tokens when\n * encoded as CBOR with the options provided.\n * This function is for advanced users and would not normally be called\n * directly. See `encodedLength()` for appropriate use.\n *\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} [encoders]\n * @param {EncodeOptions} [options]\n */\nexport function tokensToLength (tokens, encoders = cborEncoders, options = defaultEncodeOptions) {\n if (Array.isArray(tokens)) {\n let len = 0\n for (const token of tokens) {\n len += tokensToLength(token, encoders, options)\n }\n return len\n } else {\n const encoder = encoders[tokens.type.major]\n /* c8 ignore next 3 */\n if (encoder.encodedSize === undefined || typeof encoder.encodedSize !== 'function') {\n throw new Error(`Encoder for ${tokens.type.name} does not have an encodedSize()`)\n }\n return encoder.encodedSize(tokens, options)\n }\n}\n","import * as CBOR from '@ipld/dag-cbor'\nimport { Token, Type } from 'cborg'\nimport { tokensToLength } from 'cborg/length'\nimport varint from 'varint'\n\n/**\n * @typedef {import('./api').CID} CID\n * @typedef {import('./api').Block} Block\n * @typedef {import('./api').CarBufferWriter} Writer\n * @typedef {import('./api').CarBufferWriterOptions} Options\n * @typedef {import('./coding').CarEncoder} CarEncoder\n */\n\n/**\n * A simple CAR writer that writes to a pre-allocated buffer.\n *\n * @class\n * @name CarBufferWriter\n * @implements {Writer}\n */\nclass CarBufferWriter {\n /**\n * @param {Uint8Array} bytes\n * @param {number} headerSize\n */\n constructor (bytes, headerSize) {\n /** @readonly */\n this.bytes = bytes\n this.byteOffset = headerSize\n\n /**\n * @readonly\n * @type {CID[]}\n */\n this.roots = []\n this.headerSize = headerSize\n }\n\n /**\n * Add a root to this writer, to be used to create a header when the CAR is\n * finalized with {@link CarBufferWriter.close `close()`}\n *\n * @param {CID} root\n * @param {{resize?:boolean}} [options]\n * @returns {CarBufferWriter}\n */\n addRoot (root, options) {\n addRoot(this, root, options)\n return this\n }\n\n /**\n * Write a `Block` (a `{ cid:CID, bytes:Uint8Array }` pair) to the archive.\n * Throws if there is not enough capacity.\n *\n * @param {Block} block - A `{ cid:CID, bytes:Uint8Array }` pair.\n * @returns {CarBufferWriter}\n */\n write (block) {\n addBlock(this, block)\n return this\n }\n\n /**\n * Finalize the CAR and return it as a `Uint8Array`.\n *\n * @param {object} [options]\n * @param {boolean} [options.resize]\n * @returns {Uint8Array}\n */\n close (options) {\n return close(this, options)\n }\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {CID} root\n * @param {{resize?:boolean}} [options]\n */\nexport const addRoot = (writer, root, options = {}) => {\n const { resize = false } = options\n const { bytes, headerSize, byteOffset, roots } = writer\n writer.roots.push(root)\n const size = headerLength(writer)\n // If there is not enough space for the new root\n if (size > headerSize) {\n // Check if we root would fit if we were to resize the head.\n if (size - headerSize + byteOffset < bytes.byteLength) {\n // If resize is enabled resize head\n if (resize) {\n resizeHeader(writer, size)\n // otherwise remove head and throw an error suggesting to resize\n } else {\n roots.pop()\n throw new RangeError(`Header of size ${headerSize} has no capacity for new root ${root}.\n However there is a space in the buffer and you could call addRoot(root, { resize: root }) to resize header to make a space for this root.`)\n }\n // If head would not fit even with resize pop new root and throw error\n } else {\n roots.pop()\n throw new RangeError(`Buffer has no capacity for a new root ${root}`)\n }\n }\n}\n\n/**\n * Calculates number of bytes required for storing given block in CAR. Useful in\n * estimating size of an `ArrayBuffer` for the `CarBufferWriter`.\n *\n * @name CarBufferWriter.blockLength(Block)\n * @param {Block} block\n * @returns {number}\n */\nexport const blockLength = ({ cid, bytes }) => {\n const size = cid.bytes.byteLength + bytes.byteLength\n return varint.encodingLength(size) + size\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {Block} block\n */\nexport const addBlock = (writer, { cid, bytes }) => {\n const byteLength = cid.bytes.byteLength + bytes.byteLength\n const size = varint.encode(byteLength)\n if (writer.byteOffset + size.length + byteLength > writer.bytes.byteLength) {\n throw new RangeError('Buffer has no capacity for this block')\n } else {\n writeBytes(writer, size)\n writeBytes(writer, cid.bytes)\n writeBytes(writer, bytes)\n }\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {object} [options]\n * @param {boolean} [options.resize]\n */\nexport const close = (writer, options = {}) => {\n const { resize = false } = options\n const { roots, bytes, byteOffset, headerSize } = writer\n\n const headerBytes = CBOR.encode({ version: 1, roots })\n const varintBytes = varint.encode(headerBytes.length)\n\n const size = varintBytes.length + headerBytes.byteLength\n const offset = headerSize - size\n\n // If header size estimate was accurate we just write header and return\n // view into buffer.\n if (offset === 0) {\n writeHeader(writer, varintBytes, headerBytes)\n return bytes.subarray(0, byteOffset)\n // If header was overestimated and `{resize: true}` is passed resize header\n } else if (resize) {\n resizeHeader(writer, size)\n writeHeader(writer, varintBytes, headerBytes)\n return bytes.subarray(0, writer.byteOffset)\n } else {\n throw new RangeError(`Header size was overestimated.\nYou can use close({ resize: true }) to resize header`)\n }\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {number} byteLength\n */\nexport const resizeHeader = (writer, byteLength) => {\n const { bytes, headerSize } = writer\n // Move data section to a new offset\n bytes.set(bytes.subarray(headerSize, writer.byteOffset), byteLength)\n // Update header size & byteOffset\n writer.byteOffset += byteLength - headerSize\n writer.headerSize = byteLength\n}\n\n/**\n * @param {CarBufferWriter} writer\n * @param {number[]|Uint8Array} bytes\n */\n\nconst writeBytes = (writer, bytes) => {\n writer.bytes.set(bytes, writer.byteOffset)\n writer.byteOffset += bytes.length\n}\n/**\n * @param {{bytes:Uint8Array}} writer\n * @param {number[]} varint\n * @param {Uint8Array} header\n */\nconst writeHeader = ({ bytes }, varint, header) => {\n bytes.set(varint)\n bytes.set(header, varint.length)\n}\n\nconst headerPreludeTokens = [\n new Token(Type.map, 2),\n new Token(Type.string, 'version'),\n new Token(Type.uint, 1),\n new Token(Type.string, 'roots')\n]\n\nconst CID_TAG = new Token(Type.tag, 42)\n\n/**\n * Calculates header size given the array of byteLength for roots.\n *\n * @name CarBufferWriter.calculateHeaderLength(rootLengths)\n * @param {number[]} rootLengths\n * @returns {number}\n */\nexport const calculateHeaderLength = (rootLengths) => {\n const tokens = [...headerPreludeTokens]\n tokens.push(new Token(Type.array, rootLengths.length))\n for (const rootLength of rootLengths) {\n tokens.push(CID_TAG)\n tokens.push(new Token(Type.bytes, { length: rootLength + 1 }))\n }\n const length = tokensToLength(tokens) // no options needed here because we have simple tokens\n return varint.encodingLength(length) + length\n}\n\n/**\n * Calculates header size given the array of roots.\n *\n * @name CarBufferWriter.headerLength({ roots })\n * @param {object} options\n * @param {CID[]} options.roots\n * @returns {number}\n */\nexport const headerLength = ({ roots }) =>\n calculateHeaderLength(roots.map(cid => cid.bytes.byteLength))\n\n/**\n * Estimates header size given a count of the roots and the expected byte length\n * of the root CIDs. The default length works for a standard CIDv1 with a\n * single-byte multihash code, such as SHA2-256 (i.e. the most common CIDv1).\n *\n * @name CarBufferWriter.estimateHeaderLength(rootCount[, rootByteLength])\n * @param {number} rootCount\n * @param {number} [rootByteLength]\n * @returns {number}\n */\nexport const estimateHeaderLength = (rootCount, rootByteLength = 36) =>\n calculateHeaderLength(new Array(rootCount).fill(rootByteLength))\n\n/**\n * Creates synchronous CAR writer that can be used to encode blocks into a given\n * buffer. Optionally you could pass `byteOffset` and `byteLength` to specify a\n * range inside buffer to write into. If car file is going to have `roots` you\n * need to either pass them under `options.roots` (from which header size will\n * be calculated) or provide `options.headerSize` to allocate required space\n * in the buffer. You may also provide known `roots` and `headerSize` to\n * allocate space for the roots that may not be known ahead of time.\n *\n * Note: Incorrect `headerSize` may lead to copying bytes inside a buffer\n * which will have a negative impact on performance.\n *\n * @name CarBufferWriter.createWriter(buffer[, options])\n * @param {ArrayBuffer} buffer\n * @param {object} [options]\n * @param {CID[]} [options.roots]\n * @param {number} [options.byteOffset]\n * @param {number} [options.byteLength]\n * @param {number} [options.headerSize]\n * @returns {CarBufferWriter}\n */\nexport const createWriter = (buffer, options = {}) => {\n const {\n roots = [],\n byteOffset = 0,\n byteLength = buffer.byteLength,\n headerSize = headerLength({ roots })\n } = options\n const bytes = new Uint8Array(buffer, byteOffset, byteLength)\n\n const writer = new CarBufferWriter(bytes, headerSize)\n for (const root of roots) {\n writer.addRoot(root)\n }\n\n return writer\n}\n","import { decode as decodeDagCbor } from '@ipld/dag-cbor'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { CIDV0_BYTES, decodeV2Header, decodeVarint, getMultihashLength, V2_HEADER_LENGTH } from './decoder-common.js'\nimport { CarV1HeaderOrV2Pragma } from './header-validator.js'\n\n/**\n * @typedef {import('./api').Block} Block\n * @typedef {import('./api').BlockHeader} BlockHeader\n * @typedef {import('./api').BlockIndex} BlockIndex\n * @typedef {import('./coding').BytesReader} BytesReader\n * @typedef {import('./coding').CarHeader} CarHeader\n * @typedef {import('./coding').CarV2Header} CarV2Header\n * @typedef {import('./coding').CarV2FixedHeader} CarV2FixedHeader\n * @typedef {import('./coding').CarDecoder} CarDecoder\n */\n\n/**\n * Reads header data from a `BytesReader`. The header may either be in the form\n * of a `CarHeader` or `CarV2Header` depending on the CAR being read.\n *\n * @name async decoder.readHeader(reader)\n * @param {BytesReader} reader\n * @param {number} [strictVersion]\n * @returns {Promise<CarHeader|CarV2Header>}\n */\nexport async function readHeader (reader, strictVersion) {\n const length = decodeVarint(await reader.upTo(8), reader)\n if (length === 0) {\n throw new Error('Invalid CAR header (zero length)')\n }\n const header = await reader.exactly(length, true)\n const block = decodeDagCbor(header)\n if (CarV1HeaderOrV2Pragma.toTyped(block) === undefined) {\n throw new Error('Invalid CAR header format')\n }\n if ((block.version !== 1 && block.version !== 2) || (strictVersion !== undefined && block.version !== strictVersion)) {\n throw new Error(`Invalid CAR version: ${block.version}${strictVersion !== undefined ? ` (expected ${strictVersion})` : ''}`)\n }\n if (block.version === 1) {\n // CarV1HeaderOrV2Pragma makes roots optional, let's make it mandatory\n if (!Array.isArray(block.roots)) {\n throw new Error('Invalid CAR header format')\n }\n return block\n }\n // version 2\n if (block.roots !== undefined) {\n throw new Error('Invalid CAR header format')\n }\n const v2Header = decodeV2Header(await reader.exactly(V2_HEADER_LENGTH, true))\n reader.seek(v2Header.dataOffset - reader.pos)\n const v1Header = await readHeader(reader, 1)\n return Object.assign(v1Header, v2Header)\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise<CID>}\n */\nasync function readCid (reader) {\n const first = await reader.exactly(2, false)\n if (first[0] === CIDV0_BYTES.SHA2_256 && first[1] === CIDV0_BYTES.LENGTH) {\n // cidv0 32-byte sha2-256\n const bytes = await reader.exactly(34, true)\n const multihash = Digest.decode(bytes)\n return CID.create(0, CIDV0_BYTES.DAG_PB, multihash)\n }\n\n const version = decodeVarint(await reader.upTo(8), reader)\n if (version !== 1) {\n throw new Error(`Unexpected CID version (${version})`)\n }\n const codec = decodeVarint(await reader.upTo(8), reader)\n const bytes = await reader.exactly(getMultihashLength(await reader.upTo(8)), true)\n const multihash = Digest.decode(bytes)\n return CID.create(version, codec, multihash)\n}\n\n/**\n * Reads the leading data of an individual block from CAR data from a\n * `BytesReader`. Returns a `BlockHeader` object which contains\n * `{ cid, length, blockLength }` which can be used to either index the block\n * or read the block binary data.\n *\n * @name async decoder.readBlockHead(reader)\n * @param {BytesReader} reader\n * @returns {Promise<BlockHeader>}\n */\nexport async function readBlockHead (reader) {\n // length includes a CID + Binary, where CID has a variable length\n // we have to deal with\n const start = reader.pos\n let length = decodeVarint(await reader.upTo(8), reader)\n if (length === 0) {\n throw new Error('Invalid CAR section (zero length)')\n }\n length += (reader.pos - start)\n const cid = await readCid(reader)\n const blockLength = length - Number(reader.pos - start) // subtract CID length\n\n return { cid, length, blockLength }\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise<Block>}\n */\nasync function readBlock (reader) {\n const { cid, blockLength } = await readBlockHead(reader)\n const bytes = await reader.exactly(blockLength, true)\n return { bytes, cid }\n}\n\n/**\n * @param {BytesReader} reader\n * @returns {Promise<BlockIndex>}\n */\nasync function readBlockIndex (reader) {\n const offset = reader.pos\n const { cid, length, blockLength } = await readBlockHead(reader)\n const index = { cid, length, blockLength, offset, blockOffset: reader.pos }\n reader.seek(index.blockLength)\n return index\n}\n\n/**\n * Creates a `CarDecoder` from a `BytesReader`. The `CarDecoder` is as async\n * interface that will consume the bytes from the `BytesReader` to yield a\n * `header()` and either `blocks()` or `blocksIndex()` data.\n *\n * @name decoder.createDecoder(reader)\n * @param {BytesReader} reader\n * @returns {CarDecoder}\n */\nexport function createDecoder (reader) {\n const headerPromise = (async () => {\n const header = await readHeader(reader)\n if (header.version === 2) {\n const v1length = reader.pos - header.dataOffset\n reader = limitReader(reader, header.dataSize - v1length)\n }\n return header\n })()\n\n return {\n header: () => headerPromise,\n\n async * blocks () {\n await headerPromise\n while ((await reader.upTo(8)).length > 0) {\n yield await readBlock(reader)\n }\n },\n\n async * blocksIndex () {\n await headerPromise\n while ((await reader.upTo(8)).length > 0) {\n yield await readBlockIndex(reader)\n }\n }\n }\n}\n\n/**\n * Creates a `BytesReader` from a `Uint8Array`.\n *\n * @name decoder.bytesReader(bytes)\n * @param {Uint8Array} bytes\n * @returns {BytesReader}\n */\nexport function bytesReader (bytes) {\n let pos = 0\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n const out = bytes.subarray(pos, pos + Math.min(length, bytes.length - pos))\n return out\n },\n\n async exactly (length, seek = false) {\n if (length > bytes.length - pos) {\n throw new Error('Unexpected end of data')\n }\n const out = bytes.subarray(pos, pos + length)\n if (seek) {\n pos += length\n }\n return out\n },\n\n seek (length) {\n pos += length\n },\n\n get pos () {\n return pos\n }\n }\n}\n\n/**\n * @ignore\n * reusable reader for streams and files, we just need a way to read an\n * additional chunk (of some undetermined size) and a way to close the\n * reader when finished\n * @param {() => Promise<Uint8Array|null>} readChunk\n * @returns {BytesReader}\n */\nexport function chunkReader (readChunk /*, closer */) {\n let pos = 0\n let have = 0\n let offset = 0\n let currentChunk = new Uint8Array(0)\n\n const read = async (/** @type {number} */ length) => {\n have = currentChunk.length - offset\n const bufa = [currentChunk.subarray(offset)]\n while (have < length) {\n const chunk = await readChunk()\n if (chunk == null) {\n break\n }\n /* c8 ignore next 8 */\n // undo this ignore ^ when we have a fd implementation that can seek()\n if (have < 0) { // because of a seek()\n /* c8 ignore next 4 */\n // toohard to test the else\n if (chunk.length > have) {\n bufa.push(chunk.subarray(-have))\n } // else discard\n } else {\n bufa.push(chunk)\n }\n have += chunk.length\n }\n currentChunk = new Uint8Array(bufa.reduce((p, c) => p + c.length, 0))\n let off = 0\n for (const b of bufa) {\n currentChunk.set(b, off)\n off += b.length\n }\n offset = 0\n }\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n if (currentChunk.length - offset < length) {\n await read(length)\n }\n return currentChunk.subarray(offset, offset + Math.min(currentChunk.length - offset, length))\n },\n\n async exactly (length, seek = false) {\n if (currentChunk.length - offset < length) {\n await read(length)\n }\n if (currentChunk.length - offset < length) {\n throw new Error('Unexpected end of data')\n }\n const out = currentChunk.subarray(offset, offset + length)\n if (seek) {\n pos += length\n offset += length\n }\n return out\n },\n\n seek (length) {\n pos += length\n offset += length\n },\n\n get pos () {\n return pos\n }\n }\n}\n\n/**\n * Creates a `BytesReader` from an `AsyncIterable<Uint8Array>`, which allows for\n * consumption of CAR data from a streaming source.\n *\n * @name decoder.asyncIterableReader(asyncIterable)\n * @param {AsyncIterable<Uint8Array>} asyncIterable\n * @returns {BytesReader}\n */\nexport function asyncIterableReader (asyncIterable) {\n const iterator = asyncIterable[Symbol.asyncIterator]()\n\n async function readChunk () {\n const next = await iterator.next()\n if (next.done) {\n return null\n }\n return next.value\n }\n\n return chunkReader(readChunk)\n}\n\n/**\n * Wraps a `BytesReader` in a limiting `BytesReader` which limits maximum read\n * to `byteLimit` bytes. It _does not_ update `pos` of the original\n * `BytesReader`.\n *\n * @name decoder.limitReader(reader, byteLimit)\n * @param {BytesReader} reader\n * @param {number} byteLimit\n * @returns {BytesReader}\n */\nexport function limitReader (reader, byteLimit) {\n let bytesRead = 0\n\n /** @type {BytesReader} */\n return {\n async upTo (length) {\n let bytes = await reader.upTo(length)\n if (bytes.length + bytesRead > byteLimit) {\n bytes = bytes.subarray(0, byteLimit - bytesRead)\n }\n return bytes\n },\n\n async exactly (length, seek = false) {\n const bytes = await reader.exactly(length, seek)\n if (bytes.length + bytesRead > byteLimit) {\n throw new Error('Unexpected end of data')\n }\n if (seek) {\n bytesRead += length\n }\n return bytes\n },\n\n seek (length) {\n bytesRead += length\n reader.seek(length)\n },\n\n get pos () {\n return reader.pos\n }\n }\n}\n","import {\n asyncIterableReader,\n bytesReader,\n createDecoder\n} from './decoder.js'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('./api').Block} Block\n * @typedef {import('./api').RootsReader} RootsReader\n * @typedef {import('./api').BlockIndex} BlockIndex\n * @typedef {import('./coding').BytesReader} BytesReader\n */\n\n/**\n * Provides an iterator over all of the `Block`s in a CAR, returning their CIDs\n * and byte-location information. Implements an `AsyncIterable<BlockIndex>`.\n * Where a `BlockIndex` is a\n * `{ cid:CID, length:number, offset:number, blockLength:number, blockOffset:number }`.\n *\n * As an implementer of `AsyncIterable`, this class can be used directly in a\n * `for await (const blockIndex of iterator) {}` loop. Where the `iterator` is\n * constructed using {@link CarIndexer.fromBytes} or\n * {@link CarIndexer.fromIterable}.\n *\n * An iteration can only be performce _once_ per instantiation.\n *\n * `CarIndexer` also implements the `RootsReader` interface and provides\n * the {@link CarIndexer.getRoots `getRoots()`} method.\n *\n * Load this class with either\n * `import { CarIndexer } from '@ipld/car/indexer'`\n * (`const { CarIndexer } = require('@ipld/car/indexer')`). Or\n * `import { CarIndexer } from '@ipld/car'`\n * (`const { CarIndexer } = require('@ipld/car')`). The former will likely\n * result in smaller bundle sizes where this is important.\n *\n * @name CarIndexer\n * @class\n * @implements {RootsReader}\n * @implements {AsyncIterable<BlockIndex>}\n * @property {number} version The version number of the CAR referenced by this\n * reader (should be `1`).\n */\nexport class CarIndexer {\n /**\n * @param {number} version\n * @param {CID[]} roots\n * @param {AsyncGenerator<BlockIndex>} iterator\n */\n constructor (version, roots, iterator) {\n this._version = version\n this._roots = roots\n this._iterator = iterator\n }\n\n get version () {\n return this._version\n }\n\n /**\n * Get the list of roots defined by the CAR referenced by this indexer. May be\n * zero or more `CID`s.\n *\n * @function\n * @memberof CarIndexer\n * @instance\n * @async\n * @returns {Promise<CID[]>}\n */\n async getRoots () {\n return this._roots\n }\n\n /**\n * @returns {AsyncIterator<BlockIndex>}\n */\n [Symbol.asyncIterator] () {\n return this._iterator\n }\n\n /**\n * Instantiate a {@link CarIndexer} from a `Uint8Array` blob. Only the header\n * is decoded initially, the remainder is processed and emitted via the\n * iterator as it is consumed.\n *\n * @async\n * @static\n * @memberof CarIndexer\n * @param {Uint8Array} bytes\n * @returns {Promise<CarIndexer>}\n */\n static async fromBytes (bytes) {\n if (!(bytes instanceof Uint8Array)) {\n throw new TypeError('fromBytes() requires a Uint8Array')\n }\n return decodeIndexerComplete(bytesReader(bytes))\n }\n\n /**\n * Instantiate a {@link CarIndexer} from a `AsyncIterable<Uint8Array>`,\n * such as a [modern Node.js stream](https://nodejs.org/api/stream.html#stream_streams_compatibility_with_async_generators_and_async_iterators).\n * is decoded initially, the remainder is processed and emitted via the\n * iterator as it is consumed.\n *\n * @async\n * @static\n * @memberof CarIndexer\n * @param {AsyncIterable<Uint8Array>} asyncIterable\n * @returns {Promise<CarIndexer>}\n */\n static async fromIterable (asyncIterable) {\n if (!asyncIterable || !(typeof asyncIterable[Symbol.asyncIterator] === 'function')) {\n throw new TypeError('fromIterable() requires an async iterable')\n }\n return decodeIndexerComplete(asyncIterableReader(asyncIterable))\n }\n}\n\n/**\n * @private\n * @param {BytesReader} reader\n * @returns {Promise<CarIndexer>}\n */\nasync function decodeIndexerComplete (reader) {\n const decoder = createDecoder(reader)\n const { version, roots } = await decoder.header()\n\n return new CarIndexer(version, roots, decoder.blocksIndex())\n}\n","import {\n asyncIterableReader,\n bytesReader,\n createDecoder\n} from './decoder.js'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('./api').Block} Block\n * @typedef {import('./api').RootsReader} RootsReader\n * @typedef {import('./coding').BytesReader} BytesReader\n */\n\n/**\n * @class\n * @implements {RootsReader}\n * @property {number} version The version number of the CAR referenced by this reader (should be `1`).\n */\nexport class CarIteratorBase {\n /**\n * @param {number} version\n * @param {CID[]} roots\n * @param {AsyncIterable<Block>|void} iterable\n */\n constructor (version, roots, iterable) {\n this._version = version\n this._roots = roots\n this._iterable = iterable\n this._decoded = false\n }\n\n get version () {\n return this._version\n }\n\n /**\n * @returns {Promise<CID[]>}\n */\n async getRoots () {\n return this._roots\n }\n}\n\n/**\n * Provides an iterator over all of the `Block`s in a CAR. Implements a\n * `BlockIterator` interface, or `AsyncIterable<Block>`. Where a `Block` is\n * a `{ cid:CID, bytes:Uint8Array }` pair.\n *\n * As an implementer of `AsyncIterable`, this class can be used directly in a\n * `for await (const block of iterator) {}` loop. Where the `iterator` is\n * constructed using {@link CarBlockiterator.fromBytes} or\n * {@link CarBlockiterator.fromIterable}.\n *\n * An iteration can only be performce _once_ per instantiation.\n *\n * `CarBlockIterator` also implements the `RootsReader` interface and provides\n * the {@link CarBlockiterator.getRoots `getRoots()`} method.\n *\n * Load this class with either\n * `import { CarBlockIterator } from '@ipld/car/iterator'`\n * (`const { CarBlockIterator } = require('@ipld/car/iterator')`). Or\n * `import { CarBlockIterator } from '@ipld/car'`\n * (`const { CarBlockIterator } = require('@ipld/car')`).\n *\n * @name CarBlockIterator\n * @class\n * @implements {RootsReader}\n * @implements {AsyncIterable<Block>}\n * @property {number} version The version number of the CAR referenced by this\n * iterator (should be `1`).\n */\nexport class CarBlockIterator extends CarIteratorBase {\n // inherited method\n /**\n * Get the list of roots defined by the CAR referenced by this iterator. May be\n * zero or more `CID`s.\n *\n * @function getRoots\n * @memberof CarBlockIterator\n * @instance\n * @async\n * @returns {Promise<CID[]>}\n */\n\n /**\n * @returns {AsyncIterator<Block>}\n */\n [Symbol.asyncIterator] () {\n if (this._decoded) {\n throw new Error('Cannot decode more than once')\n }\n /* c8 ignore next 3 */\n if (!this._iterable) {\n throw new Error('Block iterable not found')\n }\n this._decoded = true\n return this._iterable[Symbol.asyncIterator]()\n }\n\n /**\n * Instantiate a {@link CarBlockIterator} from a `Uint8Array` blob. Rather\n * than decoding the entire byte array prior to returning the iterator, as in\n * {@link CarReader.fromBytes}, only the header is decoded and the remainder\n * of the CAR is parsed as the `Block`s as yielded.\n *\n * @async\n * @static\n * @memberof CarBlockIterator\n * @param {Uint8Array} bytes\n * @returns {Promise<CarBlockIterator>}\n */\n static async fromBytes (bytes) {\n const { version, roots, iterator } = await fromBytes(bytes)\n return new CarBlockIterator(version, roots, iterator)\n }\n\n /**\n * Instantiate a {@link CarBlockIterator} from a `AsyncIterable<Uint8Array>`,\n * such as a [modern Node.js stream](https://nodejs.org/api/stream.html#stream_streams_compatibility_with_async_generators_and_async_iterators).\n * Rather than decoding the entire byte array prior to returning the iterator,\n * as in {@link CarReader.fromIterable}, only the header is decoded and the\n * remainder of the CAR is parsed as the `Block`s as yielded.\n *\n * @async\n * @static\n * @param {AsyncIterable<Uint8Array>} asyncIterable\n * @returns {Promise<CarBlockIterator>}\n */\n static async fromIterable (asyncIterable) {\n const { version, roots, iterator } = await fromIterable(asyncIterable)\n return new CarBlockIterator(version, roots, iterator)\n }\n}\n\n/**\n * Provides an iterator over all of the `CID`s in a CAR. Implements a\n * `CIDIterator` interface, or `AsyncIterable<CID>`. Similar to\n * {@link CarBlockIterator} but only yields the CIDs in the CAR.\n *\n * As an implementer of `AsyncIterable`, this class can be used directly in a\n * `for await (const cid of iterator) {}` loop. Where the `iterator` is\n * constructed using {@link CarCIDiterator.fromBytes} or\n * {@link CarCIDiterator.fromIterable}.\n *\n * An iteration can only be performce _once_ per instantiation.\n *\n * `CarCIDIterator` also implements the `RootsReader` interface and provides\n * the {@link CarCIDiterator.getRoots `getRoots()`} method.\n *\n * Load this class with either\n * `import { CarCIDIterator } from '@ipld/car/iterator'`\n * (`const { CarCIDIterator } = require('@ipld/car/iterator')`). Or\n * `import { CarCIDIterator } from '@ipld/car'`\n * (`const { CarCIDIterator } = require('@ipld/car')`).\n *\n * @name CarCIDIterator\n * @class\n * @implements {RootsReader}\n * @implements {AsyncIterable<CID>}\n * @property {number} version The version number of the CAR referenced by this\n * iterator (should be `1`).\n */\nexport class CarCIDIterator extends CarIteratorBase {\n // inherited method\n /**\n * Get the list of roots defined by the CAR referenced by this iterator. May be\n * zero or more `CID`s.\n *\n * @function getRoots\n * @memberof CarCIDIterator\n * @instance\n * @async\n * @returns {Promise<CID[]>}\n */\n\n /**\n * @returns {AsyncIterator<CID>}\n */\n [Symbol.asyncIterator] () {\n if (this._decoded) {\n throw new Error('Cannot decode more than once')\n }\n /* c8 ignore next 3 */\n if (!this._iterable) {\n throw new Error('Block iterable not found')\n }\n this._decoded = true\n const iterable = this._iterable[Symbol.asyncIterator]()\n return {\n async next () {\n const next = await iterable.next()\n if (next.done) {\n return next\n }\n return { done: false, value: next.value.cid }\n }\n }\n }\n\n /**\n * Instantiate a {@link CarCIDIterator} from a `Uint8Array` blob. Rather\n * than decoding the entire byte array prior to returning the iterator, as in\n * {@link CarReader.fromBytes}, only the header is decoded and the remainder\n * of the CAR is parsed as the `CID`s as yielded.\n *\n * @async\n * @static\n * @memberof CarCIDIterator\n * @param {Uint8Array} bytes\n * @returns {Promise<CarCIDIterator>}\n */\n static async fromBytes (bytes) {\n const { version, roots, iterator } = await fromBytes(bytes)\n return new CarCIDIterator(version, roots, iterator)\n }\n\n /**\n * Instantiate a {@link CarCIDIterator} from a `AsyncIterable<Uint8Array>`,\n * such as a [modern Node.js stream](https://nodejs.org/api/stream.html#stream_streams_compatibility_with_async_generators_and_async_iterators).\n * Rather than decoding the entire byte array prior to returning the iterator,\n * as in {@link CarReader.fromIterable}, only the header is decoded and the\n * remainder of the CAR is parsed as the `CID`s as yielded.\n *\n * @async\n * @static\n * @memberof CarCIDIterator\n * @param {AsyncIterable<Uint8Array>} asyncIterable\n * @returns {Promise<CarCIDIterator>}\n */\n static async fromIterable (asyncIterable) {\n const { version, roots, iterator } = await fromIterable(asyncIterable)\n return new CarCIDIterator(version, roots, iterator)\n }\n}\n\n/**\n * @param {Uint8Array} bytes\n * @returns {Promise<{ version:number, roots:CID[], iterator:AsyncIterable<Block>}>}\n */\nasync function fromBytes (bytes) {\n if (!(bytes instanceof Uint8Array)) {\n throw new TypeError('fromBytes() requires a Uint8Array')\n }\n return decodeIterator(bytesReader(bytes))\n}\n\n/**\n * @param {AsyncIterable<Uint8Array>} asyncIterable\n * @returns {Promise<{ version:number, roots:CID[], iterator:AsyncIterable<Block>}>}\n */\nasync function fromIterable (asyncIterable) {\n if (!asyncIterable || !(typeof asyncIterable[Symbol.asyncIterator] === 'function')) {\n throw new TypeError('fromIterable() requires an async iterable')\n }\n return decodeIterator(asyncIterableReader(asyncIterable))\n}\n\n/**\n * @private\n * @param {BytesReader} reader\n * @returns {Promise<{ version:number, roots:CID[], iterator:AsyncIterable<Block>}>}\n */\nasync function decodeIterator (reader) {\n const decoder = createDecoder(reader)\n const { version, roots } = await decoder.header()\n return { version, roots, iterator: decoder.blocks() }\n}\n","import { encode as dagCborEncode } from '@ipld/dag-cbor'\nimport varint from 'varint'\n\n/**\n * @typedef {import('multiformats').CID} CID\n * @typedef {import('./api').Block} Block\n * @typedef {import('./coding').CarEncoder} CarEncoder\n * @typedef {import('./coding').IteratorChannel_Writer<Uint8Array>} IteratorChannel_Writer\n */\n\n/**\n * Create a header from an array of roots.\n *\n * @param {CID[]} roots\n * @returns {Uint8Array}\n */\nexport function createHeader (roots) {\n const headerBytes = dagCborEncode({ version: 1, roots })\n const varintBytes = varint.encode(headerBytes.length)\n const header = new Uint8Array(varintBytes.length + headerBytes.length)\n header.set(varintBytes, 0)\n header.set(headerBytes, varintBytes.length)\n return header\n}\n\n/**\n * @param {IteratorChannel_Writer} writer\n * @returns {CarEncoder}\n */\nfunction createEncoder (writer) {\n // none of this is wrapped in a mutex, that needs to happen above this to\n // avoid overwrites\n\n return {\n /**\n * @param {CID[]} roots\n * @returns {Promise<void>}\n */\n async setRoots (roots) {\n const bytes = createHeader(roots)\n await writer.write(bytes)\n },\n\n /**\n * @param {Block} block\n * @returns {Promise<void>}\n */\n async writeBlock (block) {\n const { cid, bytes } = block\n await writer.write(new Uint8Array(varint.encode(cid.bytes.length + bytes.length)))\n await writer.write(cid.bytes)\n if (bytes.length) {\n // zero-length blocks are valid, but it'd be safer if we didn't write them\n await writer.write(bytes)\n }\n },\n\n /**\n * @returns {Promise<void>}\n */\n async close () {\n await writer.end()\n }\n }\n}\n\nexport { createEncoder }\n","/**\n * @template {any} T\n * @typedef {import('./coding').IteratorChannel<T>} IteratorChannel\n */\n\nfunction noop () {}\n\n/**\n * @template {any} T\n * @returns {IteratorChannel<T>}\n */\nexport function create () {\n /** @type {T[]} */\n const chunkQueue = []\n /** @type {Promise<void> | null} */\n let drainer = null\n let drainerResolver = noop\n let ended = false\n /** @type {Promise<IteratorResult<T>> | null} */\n let outWait = null\n let outWaitResolver = noop\n\n const makeDrainer = () => {\n if (!drainer) {\n drainer = new Promise((resolve) => {\n drainerResolver = () => {\n drainer = null\n drainerResolver = noop\n resolve()\n }\n })\n }\n return drainer\n }\n\n /**\n * @returns {IteratorChannel<T>}\n */\n const writer = {\n /**\n * @param {T} chunk\n * @returns {Promise<void>}\n */\n write (chunk) {\n chunkQueue.push(chunk)\n const drainer = makeDrainer()\n outWaitResolver()\n return drainer\n },\n\n async end () {\n ended = true\n const drainer = makeDrainer()\n outWaitResolver()\n await drainer\n }\n }\n\n /** @type {AsyncIterator<T>} */\n const iterator = {\n /** @returns {Promise<IteratorResult<T>>} */\n async next () {\n const chunk = chunkQueue.shift()\n if (chunk) {\n if (chunkQueue.length === 0) {\n drainerResolver()\n }\n return { done: false, value: chunk }\n }\n\n if (ended) {\n drainerResolver()\n return { done: true, value: undefined }\n }\n\n if (!outWait) {\n outWait = new Promise((resolve) => {\n outWaitResolver = () => {\n outWait = null\n outWaitResolver = noop\n return resolve(iterator.next())\n }\n })\n }\n\n return outWait\n }\n }\n\n return { writer, iterator }\n}\n","import { CID } from 'multiformats/cid'\nimport { bytesReader, readHeader } from './decoder.js'\nimport { createEncoder, createHeader } from './encoder.js'\nimport { create as iteratorChannel } from './iterator-channel.js'\n\n/**\n * @typedef {import('./api').Block} Block\n * @typedef {import('./api').BlockWriter} BlockWriter\n * @typedef {import('./api').WriterChannel} WriterChannel\n * @typedef {import('./coding').CarEncoder} CarEncoder\n * @typedef {import('./coding').IteratorChannel<Uint8Array>} IteratorChannel\n */\n\n/**\n * Provides a writer interface for the creation of CAR files.\n *\n * Creation of a `CarWriter` involves the instatiation of an input / output pair\n * in the form of a `WriterChannel`, which is a\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }` pair. These two\n * components form what can be thought of as a stream-like interface. The\n * `writer` component (an instantiated `CarWriter`), has methods to\n * {@link CarWriter.put `put()`} new blocks and {@link CarWriter.put `close()`}\n * the writing operation (finalising the CAR archive). The `out` component is\n * an `AsyncIterable` that yields the bytes of the archive. This can be\n * redirected to a file or other sink. In Node.js, you can use the\n * [`Readable.from()`](https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options)\n * API to convert this to a standard Node.js stream, or it can be directly fed\n * to a\n * [`stream.pipeline()`](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback).\n *\n * The channel will provide a form of backpressure. The `Promise` from a\n * `write()` won't resolve until the resulting data is drained from the `out`\n * iterable.\n *\n * It is also possible to ignore the `Promise` from `write()` calls and allow\n * the generated data to queue in memory. This should be avoided for large CAR\n * archives of course due to the memory costs and potential for memory overflow.\n *\n * Load this class with either\n * `import { CarWriter } from '@ipld/car/writer'`\n * (`const { CarWriter } = require('@ipld/car/writer')`). Or\n * `import { CarWriter } from '@ipld/car'`\n * (`const { CarWriter } = require('@ipld/car')`). The former will likely\n * result in smaller bundle sizes where this is important.\n *\n * @name CarWriter\n * @class\n * @implements {BlockWriter}\n */\nexport class CarWriter {\n /**\n * @param {CID[]} roots\n * @param {CarEncoder} encoder\n */\n constructor (roots, encoder) {\n this._encoder = encoder\n /** @type {Promise<void>} */\n this._mutex = encoder.setRoots(roots)\n this._ended = false\n }\n\n /**\n * Write a `Block` (a `{ cid:CID, bytes:Uint8Array }` pair) to the archive.\n *\n * @function\n * @memberof CarWriter\n * @instance\n * @async\n * @param {Block} block - A `{ cid:CID, bytes:Uint8Array }` pair.\n * @returns {Promise<void>} The returned promise will only resolve once the\n * bytes this block generates are written to the `out` iterable.\n */\n async put (block) {\n if (!(block.bytes instanceof Uint8Array) || !block.cid) {\n throw new TypeError('Can only write {cid, bytes} objects')\n }\n if (this._ended) {\n throw new Error('Already closed')\n }\n const cid = CID.asCID(block.cid)\n if (!cid) {\n throw new TypeError('Can only write {cid, bytes} objects')\n }\n this._mutex = this._mutex.then(() => this._encoder.writeBlock({ cid, bytes: block.bytes }))\n return this._mutex\n }\n\n /**\n * Finalise the CAR archive and signal that the `out` iterable should end once\n * any remaining bytes are written.\n *\n * @function\n * @memberof CarWriter\n * @instance\n * @async\n * @returns {Promise<void>}\n */\n async close () {\n if (this._ended) {\n throw new Error('Already closed')\n }\n await this._mutex\n this._ended = true\n return this._encoder.close()\n }\n\n /**\n * Create a new CAR writer \"channel\" which consists of a\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }` pair.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @param {CID[] | CID | void} roots\n * @returns {WriterChannel} The channel takes the form of\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }`.\n */\n static create (roots) {\n roots = toRoots(roots)\n const { encoder, iterator } = encodeWriter()\n const writer = new CarWriter(roots, encoder)\n const out = new CarWriterOut(iterator)\n return { writer, out }\n }\n\n /**\n * Create a new CAR appender \"channel\" which consists of a\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }` pair.\n * This appender does not consider roots and does not produce a CAR header.\n * It is designed to append blocks to an _existing_ CAR archive. It is\n * expected that `out` will be concatenated onto the end of an existing\n * archive that already has a properly formatted header.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @returns {WriterChannel} The channel takes the form of\n * `{ writer:CarWriter, out:AsyncIterable<Uint8Array> }`.\n */\n static createAppender () {\n const { encoder, iterator } = encodeWriter()\n encoder.setRoots = () => Promise.resolve()\n const writer = new CarWriter([], encoder)\n const out = new CarWriterOut(iterator)\n return { writer, out }\n }\n\n /**\n * Update the list of roots in the header of an existing CAR as represented\n * in a Uint8Array.\n *\n * This operation is an _overwrite_, the total length of the CAR will not be\n * modified. A rejection will occur if the new header will not be the same\n * length as the existing header, in which case the CAR will not be modified.\n * It is the responsibility of the user to ensure that the roots being\n * replaced encode as the same length as the new roots.\n *\n * The byte array passed in an argument will be modified and also returned\n * upon successful modification.\n *\n * @async\n * @static\n * @memberof CarWriter\n * @param {Uint8Array} bytes\n * @param {CID[]} roots - A new list of roots to replace the existing list in\n * the CAR header. The new header must take up the same number of bytes as the\n * existing header, so the roots should collectively be the same byte length\n * as the existing roots.\n * @returns {Promise<Uint8Array>}\n */\n static async updateRootsInBytes (bytes, roots) {\n const reader = bytesReader(bytes)\n await readHeader(reader)\n const newHeader = createHeader(roots)\n if (Number(reader.pos) !== newHeader.length) {\n throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${reader.pos} bytes, new header is ${newHeader.length} bytes)`)\n }\n bytes.set(newHeader, 0)\n return bytes\n }\n}\n\n/**\n * @class\n * @implements {AsyncIterable<Uint8Array>}\n */\nexport class CarWriterOut {\n /**\n * @param {AsyncIterator<Uint8Array>} iterator\n */\n constructor (iterator) {\n this._iterator = iterator\n }\n\n [Symbol.asyncIterator] () {\n if (this._iterating) {\n throw new Error('Multiple iterator not supported')\n }\n this._iterating = true\n return this._iterator\n }\n}\n\nfunction encodeWriter () {\n /** @type {IteratorChannel} */\n const iw = iteratorChannel()\n const { writer, iterator } = iw\n const encoder = createEncoder(writer)\n return { encoder, iterator }\n}\n\n/**\n * @private\n * @param {CID[] | CID | void} roots\n * @returns {CID[]}\n */\nfunction toRoots (roots) {\n if (roots === undefined) {\n return []\n }\n\n if (!Array.isArray(roots)) {\n const cid = CID.asCID(roots)\n if (!cid) {\n throw new TypeError('roots must be a single CID or an array of CIDs')\n }\n return [cid]\n }\n\n const _roots = []\n for (const root of roots) {\n const _root = CID.asCID(root)\n if (!_root) {\n throw new TypeError('roots must be a single CID or an array of CIDs')\n }\n _roots.push(_root)\n }\n return _roots\n}\n\nexport const __browser = true\n","import { CarReader, CarWriter } from '@ipld/car'\nimport * as dagJson from '@ipld/dag-json'\nimport { Logger } from 'besonders-logger'\nimport { CID } from 'multiformats'\nimport { sortApplogsByTs } from '../applog/applog-utils'\nimport { Applog, CidString } from '../applog/datom-types'\n\nconst { WARN, LOG, DEBUG, VERBOSE, ERROR } = Logger.setup(Logger.INFO) // eslint-disable-line no-unused-vars\n\nexport type CIDForCar = Exclude<Parameters<(typeof CarWriter)['create']>[0], void>\nexport type BlockForCar = Parameters<CarWriter['put']>[0]\n\n/** Warning: unsorted & maybe encrypted */\nexport async function decodeCarToApplogs(car: CarReader) {\n\tconst { roots, blocks } = await decodeCar(car)\n\tif (!roots || !blocks) {\n\t\tthrow ERROR('decodeCar is funky', { roots, blocks })\n\t}\n\tif (roots.length !== 1) {\n\t\tWARN('Unexpected roots count:', roots)\n\t}\n\tconst root = blocks.get(roots[0])\n\tlet applogArr: any\n\tDEBUG(`root:`, root, { blocks })\n\tif (root.info) {\n\t\t// New(er) format\n\t\tapplogArr = blocks.get(root.applogs.toString()).logs // ? better map format possible\n\t\tDEBUG(`new format - infoLogs`, blocks.get(root.info.toString()))\n\t} else {\n\t\tapplogArr = root.applogs\n\t}\n\n\tlet applogs: Array<Applog | Uint8Array>\n\tapplogs = applogArr.map((cidOrLink: CID | { '/': string }) => {\n\t\tconst cid = (cidOrLink as any).toV1 ? (cidOrLink as CID).toV1().toString() : cidOrLink['/'] as string\n\t\tconst applog = blocks.get(cid)\n\t\tif (!applog) throw ERROR(`Could not find applog CID in Car file:`, cid, { root, blocks })\n\t\tif (applog.pv instanceof CID) applog.pv = applog.pv.toV1().toString()\n\t\treturn {\n\t\t\t...applog,\n\t\t\tcid: cid,\n\t\t}\n\t})\n\n\tDEBUG('Decoded car logs:', root, { roots, blocks, applogs })\n\treturn { applogs }\n}\n\nexport async function decodeCar(car: CarReader) {\n\tconst roots = (await car.getRoots()).map(c => c.toV1().toString() as CidString)\n\tconst blocks = new Map<CidString, any>()\n\tfor await (const { cid, bytes } of car.blocks()) {\n\t\tblocks.set(cid.toV1().toString(), dagJson.decode(bytes)) // HACK: tried using CID as map key, but because it's based on referential equality it's not working\n\t}\n\treturn { roots, blocks }\n}\n\n// make out in the car... been a while but also sounds nice\nexport async function makeCarOut(roots: CIDForCar, blocks: BlockForCar[]) {\n\tconst { writer, out } = CarWriter.create(Array.isArray(roots) ? roots : [roots])\n\n\t// add the blocks to the CAR and close it\n\tVERBOSE(`Writing ${blocks.length} blocks to CAR`, { roots, blocks })\n\tblocks.forEach(b => writer.put(b))\n\twriter.close()\n\t// VERBOSE(`Wrote ${blocks.length} blocks to CAR`, writer)\n\treturn out\n} /** create a new CarWriter, with the encoded block as the root */\n\n// export async function makeCarReader(roots: CIDForCar, blocks: BlockForCar[]) {\n// \tconst out = await makeCarOut(roots, blocks)\n\n// \t// create a new CarReader we can hand to web3.storage.putCar\n// \tconst reader = await CarReader.fromIterable(out)\n// \tVERBOSE(`CAR reader`, reader)\n// \treturn reader\n// } /** create a new CarWriter, with the encoded block as the root */\n\nexport async function makeCarBlob(roots: CIDForCar, blocks: BlockForCar[]) {\n\tconst carOut = await makeCarOut(roots, blocks)\n\tconst chunks = []\n\tfor await (const chunk of carOut) {\n\t\tchunks.push(chunk)\n\t}\n\tconst blob = new Blob(chunks)\n\treturn blob\n}\n"],"mappings":"kHAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAAAA,GAAO,QAAUC,EAEjB,IAAIC,EAAM,IACNC,GAAO,IACPC,GAAS,CAACD,GACVE,GAAM,KAAK,IAAI,EAAG,EAAE,EAExB,SAASJ,EAAOK,EAAKC,EAAKC,EAAQ,CAChC,GAAI,OAAO,kBAAoBF,EAAM,OAAO,iBAC1C,MAAAL,EAAO,MAAQ,EACT,IAAI,WAAW,yBAAyB,EAEhDM,EAAMA,GAAO,CAAC,EACdC,EAASA,GAAU,EAGnB,QAFIC,EAAYD,EAEVF,GAAOD,IACXE,EAAIC,GAAQ,EAAKF,EAAM,IAAQJ,EAC/BI,GAAO,IAET,KAAMA,EAAMF,IACVG,EAAIC,GAAQ,EAAKF,EAAM,IAAQJ,EAC/BI,KAAS,EAEX,OAAAC,EAAIC,CAAM,EAAIF,EAAM,EAEpBL,EAAO,MAAQO,EAASC,EAAY,EAE7BF,CACT,IC7BA,IAAAG,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAAAA,GAAO,QAAUC,EAEjB,IAAIC,GAAM,IACNC,GAAO,IAEX,SAASF,EAAKG,EAAKC,EAAQ,CACzB,IAAIC,EAAS,EACTD,EAASA,GAAU,EACnBE,EAAS,EACTC,EAAUH,EACVI,EACAC,EAAIN,EAAI,OAEZ,EAAG,CACD,GAAII,GAAWE,GAAKH,EAAQ,GAC1B,MAAAN,EAAK,MAAQ,EACP,IAAI,WAAW,yBAAyB,EAEhDQ,EAAIL,EAAII,GAAS,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ACR,CAWA,eAAsBG,GAAYlB,EAAkBC,EAAuB,CAC1E,IAAMkB,EAAS,MAAMN,GAAWb,EAAOC,CAAM,EACvCmB,EAAS,CAAC,EAChB,cAAiBC,KAASF,EACzBC,EAAO,KAAKC,CAAK,EAGlB,OADa,IAAI,KAAKD,CAAM,CAE7B","names":["require_encode","__commonJSMin","exports","module","encode","MSB","REST","MSBALL","INT","num","out","offset","oldOffset","require_decode","__commonJSMin","exports","module","read","MSB","REST","buf","offset","res","shift","counter","b","l","require_length","__commonJSMin","exports","module","N1","N2","N3","N4","N5","N6","N7","N8","N9","value","require_varint","__commonJSMin","exports","module","CID_CBOR_TAG","cidEncoder","obj","cid","CID","bytes","Token","Type","undefinedEncoder","numberEncoder","num","encodeOptions","cidDecoder","decodeOptions","encode","node","encodeOptions","decode","data","decodeOptions","import_varint","CIDV0_BYTES","V2_HEADER_LENGTH","decodeVarint","bytes","seeker","i","varint","decodeV2Header","dv","offset","getMultihashLength","codeLength","length","lengthLength","Kinds","obj","Types","i","v","ret","j","entries","requiredCount","key","value","Reprs","CarV1HeaderOrV2Pragma","cborEncoders","makeCborEncoders","import_varint","headerPreludeTokens","Token","Type","CID_TAG","readHeader","reader","strictVersion","length","decodeVarint","header","block","decode","CarV1HeaderOrV2Pragma","v2Header","decodeV2Header","V2_HEADER_LENGTH","v1Header","readCid","first","CIDV0_BYTES","bytes","multihash","CID","version","codec","getMultihashLength","readBlockHead","start","cid","blockLength","readBlock","readBlockIndex","offset","index","createDecoder","headerPromise","v1length","limitReader","bytesReader","pos","seek","out","chunkReader","readChunk","have","currentChunk","read","bufa","chunk","p","c","off","b","asyncIterableReader","asyncIterable","iterator","next","byteLimit","bytesRead","CarIndexer","version","roots","iterator","bytes","decodeIndexerComplete","bytesReader","asyncIterable","asyncIterableReader","reader","decoder","createDecoder","CarIteratorBase","version","roots","iterable","CarBlockIterator","_CarBlockIterator","bytes","iterator","fromBytes","asyncIterable","fromIterable","CarCIDIterator","_CarCIDIterator","next","decodeIterator","bytesReader","asyncIterableReader","reader","decoder","createDecoder","import_varint","createHeader","roots","headerBytes","encode","varintBytes","varint","header","createEncoder","writer","bytes","block","cid","noop","create","chunkQueue","drainer","drainerResolver","ended","outWait","outWaitResolver","makeDrainer","resolve","writer","chunk","iterator","CarWriter","_CarWriter","roots","encoder","block","cid","CID","toRoots","iterator","encodeWriter","writer","out","CarWriterOut","bytes","reader","bytesReader","readHeader","newHeader","createHeader","iw","create","createEncoder","_roots","root","_root","WARN","LOG","DEBUG","VERBOSE","ERROR","Logger","decodeCarToApplogs","car","roots","blocks","decodeCar","root","applogArr","applogs","cidOrLink","cid","applog","CID","c","bytes","decode","makeCarOut","writer","out","CarWriter","b","makeCarBlob","carOut","chunks","chunk"]}
@@ -1,2 +0,0 @@
1
- import{d as h}from"./chunk-J5PGGKKW.min.js";import{K as D,M as S,ia as T,v as w}from"./chunk-XQUJRFOK.min.js";import{c as f,l as C,q as c}from"./chunk-G3GOAFHU.min.js";var{WARN:O,LOG:H,DEBUG:i,VERBOSE:x,ERROR:m}=f.setup(f.DEBUG);async function M(t,n,o,p){let e=D(o),{sharedAgents:d,sharedKeyMap:l,sharedKey:s}=p??{},a=S(T(n),{en:t.ag,at:["agent/ecdh","agent/jwkd","agent/appAgent"]}).applogs;if(i("[preparePubForPush] agent logs:",a),!a.find(({at:r})=>r==="agent/appAgent"))throw m("[preparePubForPush] appThread missing agent/appAgent log");let u,y=async(r,P)=>{throw new Error("todo: enc")};i("[preparePubForPush] applogs ",e);let g;if(d){if(!s||!l)throw m("sharedAgents but no Keys/Map",{sharedAgents:d,sharedKeyMap:l,sharedKey:s});let r=[],P=[];for(let[A,I]of Array.from(l.entries()))P.push({ag:t.ag,en:A,at:"pub/sharedKey",vl:I});for(let A of e){x("[crypto] encrypting ",A);try{u=await y(A,s)}catch{}r.push(u)}g=r}else g=e;return U(t,g,a)}async function U(t,n,o){i("[encodePubAsCar] encoding",{agent:t,applogs:n,infoLogs:o});let{cids:p,encodedApplogs:e}=await b(o),{cids:d,encodedApplogs:l}=await b(n),s=await c({logs:p}),a=await c({logs:d}),u=await t.sign(s.bytes),y=await t.sign(a.bytes),g={info:s.cid,applogs:a.cid,infoSignature:u,applogsSignature:y};i("[encodePubAsCar] encoding root",{root:g,logCids:d,infoLogCids:p});let r=await c(g);return i("[encodePubAsCar] => root",{encodedRoot:r}),await h(r.cid,[r,s,a,...e,...l])}async function G(t){let{cids:n,encodedApplogs:o}=await b(t),e=await c({applogs:n});return i("[encodeApplogsAsCar] encoded root",{cids:n,encodedRoot:e}),await h(e.cid,[e,...o])}async function b(t){let n=t.map(e=>e instanceof Uint8Array?e:C(e)),o=await Promise.all(n.map(c));return i("[encodeApplogsAsIpld] encoded applogs",{encodedApplogs:o}),{cids:o.map(e=>{if(!e.cid)throw new m("[publish] no cid for encoded log:",e);return e.cid}),encodedApplogs:o}}function N(t){return t?.pk!==void 0&&t?.lastPush!==void 0}function V(t){return t?.lastPull!==void 0}function q(t){return w(t,31,7)}export{M as a,U as b,G as c,N as d,V as e,q as f};
2
- //# sourceMappingURL=chunk-O7KDPKK2.min.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/pubsub/publication.ts","../src/pubsub/pubsub-types.ts"],"sourcesContent":["import { Logger } from 'besonders-logger'\nimport { stringify } from 'safe-stable-stringify'\nimport { cyrb53hash } from '../applog/applog-utils'\nimport { Applog, ApplogForInsert, EntityID } from '../applog/datom-types'\nimport { makeCarBlob } from '../ipfs/car'\nimport { encodeBlockOriginal, prepareForPub } from '../ipfs/ipfs-utils'\nimport { lastWriteWins } from './../query/basic'\nimport { ApplogsOrThread, getLogsFromThread, Thread } from '../thread'\nimport { rollingFilter } from '../thread/filters'\nimport { AppAgent, IPublication } from './pubsub-types'\n\nconst { WARN, LOG, DEBUG, VERBOSE, ERROR } = Logger.setup(Logger.DEBUG) // eslint-disable-line no-unused-vars\n\n// export const neverEncryptAttrs = [\n// \t'agent/jwkd',\n// \t'agent/appAgent',\n// \t'pub/encryptedFor',\n// \t'pub/sharedKey',\n// ]\n\nexport async function preparePubForPush(\n\tagent: AppAgent,\n\tappThread: Thread,\n\tthreadToPublish: ApplogsOrThread,\n\tpublication: IPublication,\n) {\n\t// await initWasm()\n\t// const car_data = Wasm.make_car(applogs)\n\t// DEBUG('Car data:', car_data)\n\t// TODO prevent publish if there is no new info\n\tconst logsToPublish = getLogsFromThread(threadToPublish)\n\n\tconst { sharedAgents, sharedKeyMap, sharedKey } = publication ?? {}\n\t// TODO: publish all agents' info related to the logs we want to publish\n\tconst agentLogs = rollingFilter(lastWriteWins(appThread), {\n\t\ten: agent.ag,\n\t\tat: ['agent/ecdh', 'agent/jwkd', 'agent/appAgent'],\n\t}).applogs\n\tDEBUG(`[preparePubForPush] agent logs:`, agentLogs)\n\tif (!agentLogs.find(({ at }) => at === 'agent/appAgent')) throw ERROR(`[preparePubForPush] appThread missing agent/appAgent log`)\n\tlet encPayload\n\tconst encryptAndTestDecrypt = async (applog: Applog, keyToUse: CryptoKey): Promise<Uint8Array> => {\n\t\tthrow new Error(`todo: enc`) // TODO: ENC\n\t\t// const eachLog = prepareForPub(applog) // without cid\n\t\t// const enc = new TextEncoder()\n\t\t// const stringified = stringify(eachLog)\n\t\t// const stringifiedEncodedAppLogPayload = enc.encode(stringified) // TODO: consider encodeToDagJson instead\n\t\t// VERBOSE('[odd]', { eachLog, stringified, stringifiedEncodedAppLogPayload })\n\n\t\t// try {\n\t\t// \tencPayload = await agent.crypto?.aes.encrypt(stringifiedEncodedAppLogPayload, keyToUse, SymmAlg.AES_GCM)\n\t\t// } catch (err) {\n\t\t// \tthrow ERROR('FAILED TO ENC payload length:', stringifiedEncodedAppLogPayload.length, { err })\n\t\t// }\n\n\t\t// const decrypted = await decryptWithAesSharedKey(encPayload, keyToUse, 'string')\n\n\t\t// VERBOSE('[odd] encrypted length:', stringifiedEncodedAppLogPayload.length, { encPayload, decrypted })\n\t\t// return encPayload\n\t}\n\tDEBUG('[preparePubForPush] applogs ', logsToPublish)\n\n\tlet maybeEncryptedApplogs: Uint8Array[] | readonly Applog[]\n\tif (sharedAgents) { // encrypt all Applogs\n\t\tif (!sharedKey || !sharedKeyMap) {\n\t\t\tthrow ERROR('sharedAgents but no Keys/Map', { sharedAgents, sharedKeyMap, sharedKey })\n\t\t}\n\t\tconst encryptedApplogs = [] as Uint8Array[]\n\t\tconst agentSharedKeyLogs = []\n\t\tfor (const [eachAgent, eachEncKey] of Array.from(sharedKeyMap.entries())) {\n\t\t\tagentSharedKeyLogs.push({\n\t\t\t\tag: agent.ag,\n\t\t\t\ten: eachAgent,\n\t\t\t\tat: 'pub/sharedKey',\n\t\t\t\tvl: eachEncKey, // these are encrypted with the derived key from the local agent private and remote agent public keys\n\t\t\t})\n\t\t}\n\t\t// const encryptedForLogs = await insertApplogs(agentSharedKeyLogs)\n\t\t// DEBUG(`[publish] adding agentSharedKeyLogs:`, encryptedForLogs)\n\n\t\t// TODO ensure that all needed keys are in\n\t\tfor (const eachLog of logsToPublish) {\n\t\t\tVERBOSE('[crypto] encrypting ', eachLog)\n\t\t\t// if (neverEncryptAttrs.includes(eachLog.at)) {\n\t\t\t// \tencryptedApplogs.push(/* prepareForPub( */ eachLog /* ) */) // ? this seemed to double the below one - @gotjoshua?\n\t\t\t// \t// continue\n\t\t\t// }\n\t\t\ttry {\n\t\t\t\tencPayload = await encryptAndTestDecrypt(eachLog, sharedKey)\n\t\t\t} catch (err) {\n\t\t\t\t// its already traced in encryptAndTestDecrypt\n\t\t\t\t// continue\n\t\t\t}\n\t\t\tencryptedApplogs.push(encPayload)\n\t\t}\n\t\tmaybeEncryptedApplogs = encryptedApplogs\n\t} else {\n\t\tmaybeEncryptedApplogs = logsToPublish // publish nonEncrypted\n\t}\n\treturn encodePubAsCar(agent, maybeEncryptedApplogs, agentLogs)\n}\n\n/**\n * @param applogs Encrypted or plain applogs\n * @returns Car file\n */\nexport async function encodePubAsCar(\n\tagent: AppAgent,\n\tapplogs: readonly Uint8Array[] | readonly Applog[],\n\tinfoLogs: readonly Applog[],\n) {\n\tDEBUG(`[encodePubAsCar] encoding`, { agent, applogs, infoLogs })\n\tconst { cids: infoLogCids, encodedApplogs: encodedInfoLogs } = await encodeApplogsAsIPLD(infoLogs)\n\tconst { cids: logCids, encodedApplogs } = await encodeApplogsAsIPLD(applogs)\n\t// We need to wrap the array to get a CID\n\tconst infoLogsWrap = await encodeBlockOriginal({ logs: infoLogCids })\n\tconst applogsWrap = await encodeBlockOriginal({ logs: logCids })\n\tconst infoSignature = await agent.sign(infoLogsWrap.bytes)\n\tconst applogsSignature = await agent.sign(applogsWrap.bytes)\n\tconst root = {\n\t\tinfo: infoLogsWrap.cid,\n\t\tapplogs: applogsWrap.cid,\n\t\tinfoSignature,\n\t\tapplogsSignature,\n\t}\n\tDEBUG('[encodePubAsCar] encoding root', { root, logCids, infoLogCids })\n\tconst encodedRoot = await encodeBlockOriginal(root)\n\tDEBUG('[encodePubAsCar] => root', { encodedRoot })\n\n\treturn await makeCarBlob(encodedRoot.cid, [encodedRoot, infoLogsWrap, applogsWrap, ...encodedInfoLogs, ...encodedApplogs]) // TODO: create CarBuilder\n}\n\n/**\n * @param applogs Encrypted or plain applogs\n * @returns Car file\n */\nexport async function encodeApplogsAsCar(\n\tapplogs: readonly Uint8Array[] | readonly Applog[],\n) {\n\tconst { cids, encodedApplogs } = await encodeApplogsAsIPLD(applogs)\n\tconst root = { applogs: cids }\n\tconst encodedRoot = await encodeBlockOriginal(root)\n\tDEBUG('[encodeApplogsAsCar] encoded root', { cids, encodedRoot })\n\n\treturn await makeCarBlob(encodedRoot.cid, [encodedRoot, ...encodedApplogs])\n}\n\nasync function encodeApplogsAsIPLD(applogs: readonly Applog[] | readonly Uint8Array[]) {\n\tconst preppedLogs = applogs.map(log => log instanceof Uint8Array ? log : prepareForPub(log as Applog))\n\tconst encodedApplogs = await Promise.all(preppedLogs.map(encodeBlockOriginal))\n\tDEBUG('[encodeApplogsAsIpld] encoded applogs', { encodedApplogs })\n\n\tconst cids = encodedApplogs.map(b => {\n\t\tif (!b.cid) throw new ERROR(`[publish] no cid for encoded log:`, b)\n\t\treturn b.cid\n\t})\n\treturn { cids, encodedApplogs }\n}\n","import { cyrb53hash } from './../applog/applog-utils'\nimport { AgentHash, AgentID } from '../applog/datom-types'\nimport { Tagged } from '../types'\n\ntype AgentString = Tagged<string, 'AgentString'>\ntype DIDString = Tagged<string, 'DID'>\nexport type { AgentHash, AgentString, DIDString }\n\nexport interface AppAgent {\n\tag: AgentHash\n\tagentString: AgentString\n\tdid: DIDString\n\n\tsign(data: Uint8Array): Promise<Uint8Array>\n}\n\nexport interface IPublication {\n\tid?: string // string hash of pub (used as unique id in IDB) `W3Name.create().toString()` starts with k51qzi5uqu5d\n\tcreatedAt: string // ISO timestamp of creation\n\tname: string // nick name for the pub\n\tisDeleted?: boolean\n\n\tpk: Uint8Array // exported privatekey - needed to create WritableName for publishing //TODO: store as non-extractable / encrypted?\n\n\tautopush: boolean\n\tlastPush: string | null\n\tlastCID?: string\n\tlatestLogTs?: string\n\n\tpublishedBy: string // local user appAgent\n\tselectors?: string[] // to be used as a filter for which applogs to pub\n\tencryptedFor?: string | null // short agentHash\n\tencryptedWith?: CryptoKey | null // AES-GCM derived key from ECDH keys (local private and remote public)\n\n\t// HACK WIP #39 - shared encryption\n\tsharedKey?: CryptoKey | null // AES-GCM derived key from ECDH keys (local private and ipns public)\n\tsharedAgents?: AgentID[] | null // array of string EntityIDs for the chosen agents (we need public jwkd atoms for each of them)\n\tsharedKeyMap?: Map<AgentID, string> | null // uses public key from each agent to derive an aes key that is used to encrypt and btoa the sharedKey that is actually used to encrypt and decrypt the applogs\n}\nexport interface ISubscription {\n\tid: string // string hash of pub (used as unique id in IDB) `W3Name.create().toString()` starts with k51qzi5uqu5d\n\tcreatedAt: string // ISO timestamp of creation\n\tname: string // nick name for the pub\n\tisDeleted: boolean\n\n\tlastPull?: string | null\n\tlastPullAttempt?: string | null\n\tautopull: boolean\n\tlastCID?: string\n\tpublishedBy?: string // remote publisher short agentHash\n\tencryptedFor?: string | undefined // short agentHash\n\tencryptedWith?: CryptoKey | undefined // AES-GCM derived key from ECDH keys (local private and remote public)\n}\nexport function isPublication(obj: any): obj is IPublication {\n\treturn obj?.pk !== undefined && obj?.lastPush !== undefined\n}\nexport function isSubscription(obj: any): obj is ISubscription {\n\treturn obj?.lastPull !== undefined\n}\n\nexport type TSubPub = IPublication | ISubscription\n\nexport function agentToShortHash(agentString: string) {\n\treturn cyrb53hash(agentString, 31, 7) as string\n}\n"],"mappings":"wKAWA,GAAM,CAAE,KAAAA,EAAM,IAAAC,EAAK,MAAAC,EAAO,QAAAC,EAAS,MAAAC,CAAM,EAAIC,EAAO,MAAMA,EAAO,KAAK,EAStE,eAAsBC,EACrBC,EACAC,EACAC,EACAC,EACC,CAKD,IAAMC,EAAgBC,EAAkBH,CAAe,EAEjD,CAAE,aAAAI,EAAc,aAAAC,EAAc,UAAAC,CAAU,EAAIL,GAAe,CAAC,EAE5DM,EAAYC,EAAcC,EAAcV,CAAS,EAAG,CACzD,GAAID,EAAM,GACV,GAAI,CAAC,aAAc,aAAc,gBAAgB,CAClD,CAAC,EAAE,QAEH,GADAL,EAAM,kCAAmCc,CAAS,EAC9C,CAACA,EAAU,KAAK,CAAC,CAAE,GAAAG,CAAG,IAAMA,IAAO,gBAAgB,EAAG,MAAMf,EAAM,0DAA0D,EAChI,IAAIgB,EACEC,EAAwB,MAAOC,EAAgBC,IAA6C,CACjG,MAAM,IAAI,MAAM,WAAW,CAiB5B,EACArB,EAAM,+BAAgCS,CAAa,EAEnD,IAAIa,EACJ,GAAIX,EAAc,CACjB,GAAI,CAACE,GAAa,CAACD,EAClB,MAAMV,EAAM,+BAAgC,CAAE,aAAAS,EAAc,aAAAC,EAAc,UAAAC,CAAU,CAAC,EAEtF,IAAMU,EAAmB,CAAC,EACpBC,EAAqB,CAAC,EAC5B,OAAW,CAACC,EAAWC,CAAU,IAAK,MAAM,KAAKd,EAAa,QAAQ,CA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AAe,EAAI,MAAMF,EAAoBJ,CAAO,EAE5Da,EAAc,MAAML,EADb,CAAE,QAASQ,CAAK,CACqB,EAClD,OAAA7C,EAAM,oCAAqC,CAAE,KAAA6C,EAAM,YAAAH,CAAY,CAAC,EAEzD,MAAMC,EAAYD,EAAY,IAAK,CAACA,EAAa,GAAGP,CAAc,CAAC,CAC3E,CAEA,eAAeF,EAAoBJ,EAAoD,CACtF,IAAMiB,EAAcjB,EAAQ,IAAIkB,GAAOA,aAAe,WAAaA,EAAMC,EAAcD,CAAa,CAAC,EAC/FZ,EAAiB,MAAM,QAAQ,IAAIW,EAAY,IAAIT,CAAmB,CAAC,EAC7E,OAAArC,EAAM,wCAAyC,CAAE,eAAAmC,CAAe,CAAC,EAM1D,CAAE,KAJIA,EAAe,IAAIc,GAAK,CACpC,GAAI,CAACA,EAAE,IAAK,MAAM,IAAI/C,EAAM,oCAAqC+C,CAAC,EAClE,OAAOA,EAAE,GACV,CAAC,EACc,eAAAd,CAAe,CAC/B,CCxGO,SAASe,EAAcC,EAA+B,CAC5D,OAAOA,GAAK,KAAO,QAAaA,GAAK,WAAa,MACnD,CACO,SAASC,EAAeD,EAAgC,CAC9D,OAAOA,GAAK,WAAa,MAC1B,CAIO,SAASE,EAAiBC,EAAqB,CACrD,OAAOC,EAAWD,EAAa,GAAI,CAAC,CACrC","names":["WARN","LOG","DEBUG","VERBOSE","ERROR","Logger","preparePubForPush","agent","appThread","threadToPublish","publication","logsToPublish","getLogsFromThread","sharedAgents","sharedKeyMap","sharedKey","agentLogs","rollingFilter","lastWriteWins","at","encPayload","encryptAndTestDecrypt","applog","keyToUse","maybeEncryptedApplogs","encryptedApplogs","agentSharedKeyLogs","eachAgent","eachEncKey","eachLog","encodePubAsCar","applogs","infoLogs","infoLogCids","encodedInfoLogs","encodeApplogsAsIPLD","logCids","encodedApplogs","infoLogsWrap","encodeBlockOriginal","applogsWrap","infoSignature","applogsSignature","root","encodedRoot","makeCarBlob","encodeApplogsAsCar","cids","preppedLogs","log","prepareForPub","b","isPublication","obj","isSubscription","agentToShortHash","agentString","cyrb53hash"]}