@dxos/feed-store 0.8.4-main.72ec0f3 → 0.8.4-main.74a063c4e0

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.
@@ -25,7 +25,7 @@ var FeedWrapper = class {
25
25
  this._hypercore = hypercore2;
26
26
  invariant(this._key, void 0, {
27
27
  F: __dxlog_file,
28
- L: 41,
28
+ L: 40,
29
29
  S: this,
30
30
  A: [
31
31
  "this._key",
@@ -78,13 +78,13 @@ var FeedWrapper = class {
78
78
  seq: this._hypercore.length
79
79
  }, {
80
80
  F: __dxlog_file,
81
- L: 100,
81
+ L: 99,
82
82
  S: this,
83
83
  C: (f, a) => f(...a)
84
84
  });
85
85
  invariant(!this._closed, "Feed closed", {
86
86
  F: __dxlog_file,
87
- L: 101,
87
+ L: 100,
88
88
  S: this,
89
89
  A: [
90
90
  "!this._closed",
@@ -114,7 +114,7 @@ var FeedWrapper = class {
114
114
  const seq = await this.append(data);
115
115
  invariant(seq < this.length, "Invalid seq after write", {
116
116
  F: __dxlog_file,
117
- L: 132,
117
+ L: 131,
118
118
  S: this,
119
119
  A: [
120
120
  "seq < this.length",
@@ -126,7 +126,7 @@ var FeedWrapper = class {
126
126
  seq
127
127
  }, {
128
128
  F: __dxlog_file,
129
- L: 133,
129
+ L: 132,
130
130
  S: this,
131
131
  C: (f, a) => f(...a)
132
132
  });
@@ -178,7 +178,7 @@ var FeedWrapper = class {
178
178
  pendingWrites: Array.from(this._pendingWrites.values()).map((stack) => stack.getStack())
179
179
  }, {
180
180
  F: __dxlog_file,
181
- L: 187,
181
+ L: 186,
182
182
  S: this,
183
183
  C: (f, a) => f(...a)
184
184
  });
@@ -230,7 +230,7 @@ var FeedWrapper = class {
230
230
  async safeClear(from, to) {
231
231
  invariant(from >= 0 && from < to && to <= this.length, "Invalid range", {
232
232
  F: __dxlog_file,
233
- L: 250,
233
+ L: 249,
234
234
  S: this,
235
235
  A: [
236
236
  "from >= 0 && from < to && to <= this.length",
@@ -271,7 +271,7 @@ var BatchedReadStream = class extends Readable {
271
271
  });
272
272
  invariant(opts.live === true, "Only live mode supported", {
273
273
  F: __dxlog_file,
274
- L: 292,
274
+ L: 291,
275
275
  S: this,
276
276
  A: [
277
277
  "opts.live === true",
@@ -280,7 +280,7 @@ var BatchedReadStream = class extends Readable {
280
280
  });
281
281
  invariant(opts.batch !== void 0 && opts.batch > 1, void 0, {
282
282
  F: __dxlog_file,
283
- L: 293,
283
+ L: 292,
284
284
  S: this,
285
285
  A: [
286
286
  "opts.batch !== undefined && opts.batch > 1",
@@ -529,4 +529,4 @@ export {
529
529
  FeedFactory,
530
530
  FeedStore
531
531
  };
532
- //# sourceMappingURL=chunk-I36R5SR3.mjs.map
532
+ //# sourceMappingURL=chunk-5F4TNRQV.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/feed-wrapper.ts", "../../../src/feed-factory.ts", "../../../src/feed-store.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2022 DXOS.org\n//\n\nimport { inspect } from 'node:util';\nimport { promisify } from 'node:util';\nimport { Readable, Transform } from 'streamx';\n\nimport { Trigger } from '@dxos/async';\nimport { StackTrace, inspectObject } from '@dxos/debug';\nimport type { Hypercore, HypercoreProperties, ReadStreamOptions } from '@dxos/hypercore';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { type PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type Directory } from '@dxos/random-access-storage';\nimport { arrayToBuffer, rangeFromTo } from '@dxos/util';\nimport type { GetOptions, Proof } from '@dxos/vendor-hypercore/hypercore';\n\nimport { type FeedWriter, type WriteReceipt } from './feed-writer';\n\n/**\n * Async feed wrapper.\n */\nexport class FeedWrapper<T extends {}> {\n private _hypercore: Hypercore<T>;\n private readonly _pendingWrites = new Set<StackTrace>();\n\n // Pending while writes are happening. Resolves when there are no pending writes.\n private readonly _writeLock = new Trigger();\n\n private _closed = false;\n\n constructor(\n hypercore: Hypercore<T>,\n private _key: PublicKey, // TODO(burdon): Required since currently patching the key inside factory.\n private _storageDirectory: Directory,\n ) {\n assertArgument(hypercore, 'hypercore');\n this._hypercore = hypercore;\n invariant(this._key);\n this._writeLock.wake();\n }\n\n [inspect.custom](): string {\n return inspectObject(this);\n }\n\n toJSON(): { feedKey: PublicKey; length: number; opened: boolean; closed: boolean } {\n return {\n feedKey: this._key,\n length: this.properties.length,\n opened: this.properties.opened,\n closed: this.properties.closed,\n };\n }\n\n get key(): PublicKey {\n return this._key;\n }\n\n get core(): Hypercore<T> {\n return this._hypercore;\n }\n\n // TODO(burdon): Create proxy.\n get properties(): HypercoreProperties {\n return this._hypercore;\n }\n\n createReadableStream(opts?: ReadStreamOptions): Readable {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n const transform = new Transform({\n transform(data: any, cb: (err?: Error | null, data?: any) => void) {\n // Delay until write is complete.\n void self._writeLock.wait().then(() => {\n this.push(data);\n cb();\n });\n },\n });\n const readStream =\n opts?.batch !== undefined && opts?.batch > 1\n ? new BatchedReadStream(this._hypercore, opts)\n : this._hypercore.createReadStream(opts);\n\n readStream.pipe(transform, (err: any) => {\n // Ignore errors.\n // We might get \"Writable stream closed prematurely\" error.\n // Its okay since the pipeline is closed and does not expect more messages.\n });\n\n return transform;\n }\n\n createFeedWriter(): FeedWriter<T> {\n return {\n write: async (data: T, { afterWrite } = {}) => {\n log('write', { feed: this._key, seq: this._hypercore.length });\n invariant(!this._closed, 'Feed closed');\n const stackTrace = new StackTrace();\n\n try {\n // Pending writes pause the read stream.\n this._pendingWrites.add(stackTrace);\n if (this._pendingWrites.size === 1) {\n this._writeLock.reset();\n }\n\n const receipt = await this.appendWithReceipt(data);\n\n // TODO(dmaretskyi): Removing this will make user-intiated writes faster but might result in a data-loss.\n await this.flushToDisk();\n\n await afterWrite?.(receipt);\n\n return receipt;\n } finally {\n // Unblock the read stream after the write (and callback) is complete.\n this._pendingWrites.delete(stackTrace);\n if (this._pendingWrites.size === 0) {\n this._writeLock.wake();\n }\n }\n },\n };\n }\n\n async appendWithReceipt(data: T): Promise<WriteReceipt> {\n const seq = await this.append(data);\n invariant(seq < this.length, 'Invalid seq after write');\n log('write complete', { feed: this._key, seq });\n const receipt: WriteReceipt = {\n feedKey: this.key,\n seq,\n };\n return receipt;\n }\n\n /**\n * Flush pending changes to disk.\n * Calling this is not required unless you want to explicitly wait for data to be written.\n */\n async flushToDisk(): Promise<void> {\n await this._storageDirectory.flush();\n }\n\n get opened(): boolean {\n return this._hypercore.opened;\n }\n\n get closed(): boolean {\n return this._hypercore.closed;\n }\n\n get readable(): boolean {\n return this._hypercore.readable;\n }\n\n get length(): number {\n return this._hypercore.length;\n }\n\n get byteLength(): number {\n return this._hypercore.byteLength;\n }\n\n on(...args: any[]) {\n return (this._hypercore as any).on(...args);\n }\n\n off(...args: any[]) {\n return (this._hypercore as any).off(...args);\n }\n\n open(...args: Parameters<Hypercore<T>['open']>) {\n return promisify(this._hypercore.open.bind(this._hypercore) as any)(...args);\n }\n\n _close(...args: Parameters<Hypercore<T>['close']>) {\n return promisify(this._hypercore.close.bind(this._hypercore) as any)(...args);\n }\n\n close = async () => {\n if (this._pendingWrites.size) {\n log.warn('Closing feed with pending writes', {\n feed: this._key,\n count: this._pendingWrites.size,\n pendingWrites: Array.from(this._pendingWrites.values()).map((stack) => stack.getStack()),\n });\n }\n this._closed = true;\n await this.flushToDisk();\n await this._close();\n };\n\n has(start: number, end?: number) {\n return this._hypercore.has(start, end);\n }\n\n get(index: number, options?: GetOptions) {\n return promisify(this._hypercore.get.bind(this._hypercore) as any)(index, options);\n }\n\n // TODO(dmaretskyi): Type better\n append(data: any | any[]): Promise<number> {\n return promisify(this._hypercore.append.bind(this._hypercore))(data);\n }\n\n /**\n * Will not resolve if `end` parameter is not specified and the feed is not closed.\n */\n download(...args: Parameters<Hypercore<T>['download']>) {\n return this._hypercore.download(...args);\n }\n\n undownload(...args: Parameters<Hypercore<T>['undownload']>) {\n return this._hypercore.undownload(...args);\n }\n\n setDownloading(...args: Parameters<Hypercore<T>['setDownloading']>) {\n return this._hypercore.setDownloading(...args);\n }\n\n replicate(...args: Parameters<Hypercore<T>['replicate']>) {\n return this._hypercore.replicate(...args);\n }\n\n clear(start: number, end?: number) {\n return promisify(this._hypercore.clear.bind(this._hypercore))(start, end);\n }\n\n proof(index: number, options?: any) {\n return promisify(this._hypercore.proof.bind(this._hypercore))(index);\n }\n\n put(index: number, data: T, proof: Proof) {\n return promisify(this._hypercore.put.bind(this._hypercore))(index, data, proof);\n }\n\n putBuffer(index: number, data: Buffer | Uint8Array, proof: Proof, peer: null): Promise<void> {\n return promisify((this._hypercore as any)._putBuffer.bind(this._hypercore) as any)(index, data, proof, peer);\n }\n\n /**\n * Clear and check for integrity.\n */\n async safeClear(from: number, to: number): Promise<void> {\n invariant(from >= 0 && from < to && to <= this.length, 'Invalid range');\n\n const CHECK_MESSAGES = 20;\n const checkBegin = to;\n const checkEnd = Math.min(checkBegin + CHECK_MESSAGES, this.length);\n\n const messagesBefore = await Promise.all(\n rangeFromTo(checkBegin, checkEnd).map((idx) =>\n this.get(idx, {\n valueEncoding: { decode: (x: Uint8Array) => x } as any,\n }),\n ),\n );\n\n await this.clear(from, to);\n\n const messagesAfter = await Promise.all(\n rangeFromTo(checkBegin, checkEnd).map((idx) =>\n this.get(idx, {\n valueEncoding: { decode: (x: Uint8Array) => x } as any,\n }),\n ),\n );\n\n for (let i = 0; i < messagesBefore.length; i++) {\n const before = arrayToBuffer(messagesBefore[i]);\n const after = arrayToBuffer(messagesAfter[i]);\n if (!before.equals(after)) {\n throw new Error('Feed corruption on clear. There has likely been a data loss.');\n }\n }\n }\n}\n\nclass BatchedReadStream extends Readable {\n private readonly _feed: Hypercore<any>;\n private readonly _batch: number;\n private _cursor: number;\n private _reading = false;\n\n constructor(feed: Hypercore<any>, opts: ReadStreamOptions = {}) {\n super({ objectMode: true });\n invariant(opts.live === true, 'Only live mode supported');\n invariant(opts.batch !== undefined && opts.batch > 1);\n this._feed = feed;\n this._batch = opts.batch;\n this._cursor = opts.start ?? 0;\n }\n\n override _open(cb: (err: Error | null) => void): void {\n this._feed.ready(cb);\n }\n\n override _read(cb: (err: Error | null) => void): void {\n if (this._reading) {\n return;\n }\n\n if (this._feed.bitfield!.total(this._cursor, this._cursor + this._batch) === this._batch) {\n this._batchedRead(cb);\n } else {\n this._nonBatchedRead(cb);\n }\n }\n\n private _nonBatchedRead(cb: (err: Error | null) => void): void {\n this._feed.get(this._cursor, { wait: true }, (err, data) => {\n if (err) {\n cb(err);\n } else {\n this._cursor++;\n this._reading = false;\n this.push(data);\n cb(null);\n }\n });\n }\n\n private _batchedRead(cb: (err: Error | null) => void): void {\n this._feed.getBatch(this._cursor, this._cursor + this._batch, { wait: true }, (err, data) => {\n if (err) {\n cb(err);\n } else {\n this._cursor += data.length;\n this._reading = false;\n for (const item of data) {\n this.push(item);\n }\n cb(null);\n }\n });\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport defaultsDeep from 'lodash.defaultsdeep';\n\nimport { type Signer, subtleCrypto } from '@dxos/crypto';\nimport { failUndefined } from '@dxos/debug';\nimport type { HypercoreOptions } from '@dxos/hypercore';\nimport { createCrypto, hypercore } from '@dxos/hypercore';\nimport { type PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type Directory } from '@dxos/random-access-storage';\n\nimport { FeedWrapper } from './feed-wrapper';\n\nexport type FeedFactoryOptions = {\n root: Directory;\n signer?: Signer;\n hypercore?: HypercoreOptions;\n};\n\nexport type FeedOptions = HypercoreOptions & {\n writable?: boolean;\n /**\n * Optional hook called before data is written after being verified.\n * Called for writes done by this peer as well as for data replicated from other peers.\n * NOTE: The callback must be invoked to complete the write operation.\n * @param peer Always null in hypercore@9.12.0.\n */\n onwrite?: (index: number, data: any, peer: null, cb: (err: Error | null) => void) => void;\n};\n\n/**\n * Hypercore factory.\n */\nexport class FeedFactory<T extends {}> {\n private readonly _root: Directory;\n private readonly _signer?: Signer;\n private readonly _hypercoreOptions?: HypercoreOptions;\n\n constructor({ root, signer, hypercore }: FeedFactoryOptions) {\n log('FeedFactory', { options: hypercore });\n this._root = root ?? failUndefined();\n this._signer = signer;\n this._hypercoreOptions = hypercore;\n }\n\n get storageRoot() {\n return this._root;\n }\n\n async createFeed(publicKey: PublicKey, options?: FeedOptions): Promise<FeedWrapper<T>> {\n if (options?.writable && !this._signer) {\n throw new Error('Signer required to create writable feeds.');\n }\n if (options?.secretKey) {\n log.warn('Secret key ignored due to signer.');\n }\n\n // Required due to hypercore's 32-byte key limit.\n const key = await subtleCrypto.digest('SHA-256', Buffer.from(publicKey.toHex()));\n\n const opts = defaultsDeep(\n {\n // sparse: false,\n // stats: false,\n },\n this._hypercoreOptions,\n {\n secretKey: this._signer && options?.writable ? Buffer.from('secret') : undefined,\n crypto: this._signer ? createCrypto(this._signer, publicKey) : undefined,\n onwrite: options?.onwrite,\n noiseKeyPair: {}, // We're not using noise.\n },\n options,\n );\n\n const storageDir = this._root.createDirectory(publicKey.toHex());\n const makeStorage = (filename: string) => {\n const { type, native } = storageDir.getOrCreateFile(filename);\n log('created', {\n path: `${type}:${this._root.path}/${publicKey.truncate()}/${filename}`,\n });\n\n return native;\n };\n\n const core = hypercore(makeStorage, Buffer.from(key), opts);\n return new FeedWrapper(core, publicKey, storageDir);\n }\n}\n", "//\n// Copyright 2019 DXOS.org\n//\n\nimport { Event, Mutex } from '@dxos/async';\nimport { failUndefined } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, defaultMap } from '@dxos/util';\n\nimport { type FeedFactory, type FeedOptions } from './feed-factory';\nimport { type FeedWrapper } from './feed-wrapper';\n\nexport interface FeedStoreOptions<T extends {}> {\n factory: FeedFactory<T>;\n}\n\n/**\n * Persistent hypercore store.\n */\nexport class FeedStore<T extends {}> {\n private readonly _feeds: ComplexMap<PublicKey, FeedWrapper<T>> = new ComplexMap(PublicKey.hash);\n private readonly _mutexes = new ComplexMap<PublicKey, Mutex>(PublicKey.hash);\n private readonly _factory: FeedFactory<T>;\n\n private _closed = false;\n\n readonly feedOpened = new Event<FeedWrapper<T>>();\n\n constructor({ factory }: FeedStoreOptions<T>) {\n this._factory = factory ?? failUndefined();\n }\n\n get size() {\n return this._feeds.size;\n }\n\n get feeds() {\n return Array.from(this._feeds.values());\n }\n\n /**\n * Get the open feed if it exists.\n */\n getFeed(publicKey: PublicKey): FeedWrapper<T> | undefined {\n return this._feeds.get(publicKey);\n }\n\n /**\n * Gets or opens a feed.\n * The feed is readonly unless a secret key is provided.\n */\n async openFeed(feedKey: PublicKey, { writable, sparse }: FeedOptions = {}): Promise<FeedWrapper<T>> {\n log('opening feed', { feedKey });\n invariant(feedKey);\n invariant(!this._closed, 'Feed store is closed');\n\n const mutex = defaultMap(this._mutexes, feedKey, () => new Mutex());\n\n return mutex.executeSynchronized(async () => {\n let feed = this.getFeed(feedKey);\n if (feed) {\n // TODO(burdon): Need to check that there's another instance being used (create test and break this).\n // TODO(burdon): Remove from store if feed is closed externally? (remove wrapped open/close methods?)\n if (writable && !feed.properties.writable) {\n throw new Error(`Read-only feed is already open: ${feedKey.truncate()}`);\n } else if ((sparse ?? false) !== feed.properties.sparse) {\n throw new Error(\n `Feed already open with different sparse setting: ${feedKey.truncate()} [${sparse} !== ${\n feed.properties.sparse\n }]`,\n );\n } else {\n await feed.open();\n return feed;\n }\n }\n\n feed = await this._factory.createFeed(feedKey, { writable, sparse });\n this._feeds.set(feed.key, feed);\n\n await feed.open();\n this.feedOpened.emit(feed);\n log('opened', { feedKey });\n return feed;\n });\n }\n\n /**\n * Close all feeds.\n */\n async close(): Promise<void> {\n log('closing...');\n this._closed = true;\n await Promise.all(\n Array.from(this._feeds.values()).map(async (feed) => {\n await feed.close();\n invariant(feed.closed);\n // TODO(burdon): SpaceProxy still being initialized.\n // SpaceProxy.initialize => Database.createItem => ... => FeedWrapper.append\n // Uncaught Error: Closed [random-access-storage/index.js:181:38]\n // await sleep(100);\n }),\n );\n\n this._feeds.clear();\n log('closed');\n }\n}\n"],
5
+ "mappings": ";;;AAIA,SAASA,eAAe;AACxB,SAASC,iBAAiB;AAC1B,SAASC,UAAUC,iBAAiB;AAEpC,SAASC,eAAe;AACxB,SAASC,YAAYC,qBAAqB;AAE1C,SAASC,gBAAgBC,iBAAiB;AAE1C,SAASC,WAAW;AAEpB,SAASC,eAAeC,mBAAmB;;AAQpC,IAAMC,cAAN,MAAMA;;;EACHC;EACSC,iBAAiB,oBAAIC,IAAAA;;EAGrBC,aAAa,IAAIZ,QAAAA;EAE1Ba,UAAU;EAElB,YACEC,YACQC,MACAC,mBACR;SAFQD,OAAAA;SACAC,oBAAAA;AAERb,mBAAeW,YAAW,WAAA;AAC1B,SAAKL,aAAaK;AAClBV,cAAU,KAAKW,MAAI,QAAA;;;;;;;;;AACnB,SAAKH,WAAWK,KAAI;EACtB;EAEA,CAACrB,QAAQsB,MAAM,IAAY;AACzB,WAAOhB,cAAc,IAAI;EAC3B;EAEAiB,SAAmF;AACjF,WAAO;MACLC,SAAS,KAAKL;MACdM,QAAQ,KAAKC,WAAWD;MACxBE,QAAQ,KAAKD,WAAWC;MACxBC,QAAQ,KAAKF,WAAWE;IAC1B;EACF;EAEA,IAAIC,MAAiB;AACnB,WAAO,KAAKV;EACd;EAEA,IAAIW,OAAqB;AACvB,WAAO,KAAKjB;EACd;;EAGA,IAAIa,aAAkC;AACpC,WAAO,KAAKb;EACd;EAEAkB,qBAAqBC,MAAoC;AAEvD,UAAMC,OAAO;AACb,UAAMC,YAAY,IAAI/B,UAAU;MAC9B+B,UAAUC,MAAWC,IAA4C;AAE/D,aAAKH,KAAKjB,WAAWqB,KAAI,EAAGC,KAAK,MAAA;AAC/B,eAAKC,KAAKJ,IAAAA;AACVC,aAAAA;QACF,CAAA;MACF;IACF,CAAA;AACA,UAAMI,aACJR,MAAMS,UAAUC,UAAaV,MAAMS,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Q,GAAA;;;;;;AACxB,aAAOK;IACT,CAAA;EACF;;;;EAKA,MAAMS,QAAuB;AAC3BlC,IAAAA,KAAI,cAAA,QAAA;;;;;;AACJ,SAAKQ,UAAU;AACf,UAAM2B,QAAQC,IACZvB,MAAMC,KAAK,KAAKV,OAAOW,OAAM,CAAA,EAAIsB,IAAI,OAAOZ,SAAAA;AAC1C,YAAMA,KAAKS,MAAK;AAChBpC,MAAAA,WAAU2B,KAAKa,QAAM,QAAA;;;;;;;;;IAKvB,CAAA,CAAA;AAGF,SAAKlC,OAAOmC,MAAK;AACjBvC,IAAAA,KAAI,UAAA,QAAA;;;;;;EACN;AACF;",
6
+ "names": ["inspect", "promisify", "Readable", "Transform", "Trigger", "StackTrace", "inspectObject", "assertArgument", "invariant", "log", "arrayToBuffer", "rangeFromTo", "FeedWrapper", "_hypercore", "_pendingWrites", "Set", "_writeLock", "_closed", "hypercore", "_key", "_storageDirectory", "wake", "custom", "toJSON", "feedKey", "length", "properties", "opened", "closed", "key", "core", "createReadableStream", "opts", "self", "transform", "data", "cb", "wait", "then", "push", "readStream", "batch", "undefined", "BatchedReadStream", "createReadStream", "pipe", "err", "createFeedWriter", "write", "afterWrite", "feed", "seq", "stackTrace", "add", "size", "reset", "receipt", "appendWithReceipt", "flushToDisk", "delete", "append", "flush", "readable", "byteLength", "on", "args", "off", "open", "bind", "_close", "close", "warn", "count", "pendingWrites", "Array", "from", "values", "map", "stack", "getStack", "has", "start", "end", "get", "index", "options", "download", "undownload", "setDownloading", "replicate", "clear", "proof", "put", "putBuffer", "peer", "_putBuffer", "safeClear", "to", "CHECK_MESSAGES", "checkBegin", "checkEnd", "Math", "min", "messagesBefore", "Promise", "all", "idx", "valueEncoding", "decode", "x", "messagesAfter", "i", "before", "after", "equals", "Error", "_feed", "_batch", "_cursor", "_reading", "objectMode", "live", "_open", "ready", "_read", "bitfield", "total", "_batchedRead", "_nonBatchedRead", "getBatch", "item", "defaultsDeep", "subtleCrypto", "failUndefined", "createCrypto", "hypercore", "log", "FeedFactory", "_root", "_signer", "_hypercoreOptions", "root", "signer", "hypercore", "log", "options", "failUndefined", "storageRoot", "createFeed", "publicKey", "writable", "Error", "secretKey", "warn", "key", "subtleCrypto", "digest", "Buffer", "from", "toHex", "opts", "defaultsDeep", "undefined", "crypto", "createCrypto", "onwrite", "noiseKeyPair", "storageDir", "createDirectory", "makeStorage", "filename", "type", "native", "getOrCreateFile", "path", "truncate", "core", "FeedWrapper", "Event", "Mutex", "failUndefined", "invariant", "PublicKey", "log", "ComplexMap", "defaultMap", "FeedStore", "_feeds", "hash", "_mutexes", "_factory", "_closed", "feedOpened", "factory", "size", "feeds", "Array", "from", "values", "getFeed", "publicKey", "get", "openFeed", "feedKey", "writable", "sparse", "mutex", "executeSynchronized", "feed", "properties", "Error", "truncate", "open", "createFeed", "set", "key", "emit", "close", "Promise", "all", "map", "closed", "clear"]
7
+ }
@@ -3,7 +3,7 @@ import {
3
3
  FeedFactory,
4
4
  FeedStore,
5
5
  FeedWrapper
6
- } from "./chunk-I36R5SR3.mjs";
6
+ } from "./chunk-5F4TNRQV.mjs";
7
7
 
8
8
  // src/feed-iterator.ts
9
9
  import safeRace from "race-as-promised";
@@ -78,7 +78,7 @@ var FeedQueue = class {
78
78
  feedKey: this._feed.key
79
79
  }, {
80
80
  F: __dxlog_file,
81
- L: 93,
81
+ L: 92,
82
82
  S: this,
83
83
  C: (f, a) => f(...a)
84
84
  });
@@ -121,7 +121,7 @@ var FeedQueue = class {
121
121
  feedKey: this._feed.key
122
122
  }, {
123
123
  F: __dxlog_file,
124
- L: 138,
124
+ L: 137,
125
125
  S: this,
126
126
  C: (f, a) => f(...a)
127
127
  });
@@ -137,7 +137,7 @@ var FeedQueue = class {
137
137
  });
138
138
  log("opened", void 0, {
139
139
  F: __dxlog_file,
140
- L: 156,
140
+ L: 155,
141
141
  S: this,
142
142
  C: (f, a) => f(...a)
143
143
  });
@@ -149,7 +149,7 @@ var FeedQueue = class {
149
149
  if (this.isOpen) {
150
150
  invariant(this._feedConsumer, void 0, {
151
151
  F: __dxlog_file,
152
- L: 164,
152
+ L: 163,
153
153
  S: this,
154
154
  A: [
155
155
  "this._feedConsumer",
@@ -158,7 +158,7 @@ var FeedQueue = class {
158
158
  });
159
159
  invariant(!this._feed.properties.closed, void 0, {
160
160
  F: __dxlog_file,
161
- L: 165,
161
+ L: 164,
162
162
  S: this,
163
163
  A: [
164
164
  "!this._feed.properties.closed",
@@ -169,7 +169,7 @@ var FeedQueue = class {
169
169
  feedKey: this._feed.key
170
170
  }, {
171
171
  F: __dxlog_file,
172
- L: 167,
172
+ L: 166,
173
173
  S: this,
174
174
  C: (f, a) => f(...a)
175
175
  });
@@ -180,7 +180,7 @@ var FeedQueue = class {
180
180
  await closed();
181
181
  log("closed", void 0, {
182
182
  F: __dxlog_file,
183
- L: 173,
183
+ L: 172,
184
184
  S: this,
185
185
  C: (f, a) => f(...a)
186
186
  });
@@ -214,7 +214,7 @@ var FeedQueue = class {
214
214
  feedKey: this._feed.key
215
215
  }, {
216
216
  F: __dxlog_file,
217
- L: 206,
217
+ L: 205,
218
218
  S: this,
219
219
  C: (f, a) => f(...a)
220
220
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/feed-iterator.ts", "../../../src/feed-queue.ts", "../../../src/feed-set-iterator.ts", "../../../src/feed-writer.ts"],
4
- "sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport safeRace from 'race-as-promised';\n\nimport { Trigger } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { FeedQueue } from './feed-queue';\nimport { type FeedWrapper } from './feed-wrapper';\nimport { type FeedBlock } from './types';\n\n/**\n * Base class for an async iterable feed.\n */\nexport abstract class AbstractFeedIterator<T> implements AsyncIterable<FeedBlock<T>> {\n private readonly _stopTrigger = new Trigger();\n\n protected _open = false;\n protected _running = false;\n\n toJSON(): { open: boolean; running: boolean } {\n return {\n open: this.isOpen,\n running: this.isRunning,\n };\n }\n\n get isOpen() {\n return this._open;\n }\n\n get isRunning() {\n return this._running;\n }\n\n async open(): Promise<void> {\n if (!this._open) {\n log('opening...');\n await this._onOpen();\n this._open = true;\n\n await this.start();\n log('opened');\n }\n }\n\n async close(): Promise<void> {\n if (this._open) {\n log('closing...');\n await this.stop();\n\n await this._onClose();\n this._open = false;\n log('closed');\n }\n }\n\n async start(): Promise<void> {\n invariant(this._open);\n if (!this._running) {\n this._running = true;\n }\n }\n\n async stop(): Promise<void> {\n invariant(this._open);\n if (this._running) {\n this._running = false;\n this._stopTrigger.wake();\n }\n }\n\n //\n // AsyncIterable\n //\n\n [Symbol.asyncIterator]() {\n return this._generator();\n }\n\n async *_generator() {\n log('started');\n while (this._running) {\n // https://github.com/nodejs/node/issues/17469\n const block = await safeRace([this._stopTrigger.wait(), this._nextBlock()]);\n\n if (block === undefined) {\n break;\n }\n\n yield block;\n }\n\n log('stopped');\n }\n\n abstract _onOpen(): Promise<void>;\n abstract _onClose(): Promise<void>;\n abstract _nextBlock(): Promise<FeedBlock<T> | undefined>;\n}\n\n/**\n * Iterator that reads blocks from a single feed.\n */\nexport class FeedIterator<T extends {}> extends AbstractFeedIterator<T> {\n private readonly _queue: FeedQueue<T>;\n\n constructor(private readonly _feed: FeedWrapper<T>) {\n super();\n this._queue = new FeedQueue<T>(this._feed);\n }\n\n override async _onOpen(): Promise<void> {\n await this._queue.open();\n }\n\n override async _onClose(): Promise<void> {\n await this._queue.close();\n }\n\n override async _nextBlock(): Promise<FeedBlock<T> | undefined> {\n return this._queue.pop();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { inspect } from 'node:util';\n\nimport { Writable } from 'streamx';\n\nimport { Event, Trigger, latch } from '@dxos/async';\nimport { inspectObject } from '@dxos/debug';\nimport type { ReadStreamOptions } from '@dxos/hypercore';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type FeedWrapper } from './feed-wrapper';\nimport { type FeedBlock } from './types';\n\nexport const defaultReadStreamOptions: ReadStreamOptions = {\n live: true, // Keep reading until closed.\n batch: 1024, // Read in batches.\n};\n\nexport type FeedQueueOptions = {};\n\n/**\n * Async queue using an AsyncIterator created from a hypercore.\n */\nexport class FeedQueue<T extends {}> {\n public updated = new Event<FeedQueue<T>>();\n\n private readonly _messageTrigger = new Trigger<FeedBlock<T>>({\n autoReset: true,\n });\n\n private _feedConsumer?: Writable = undefined;\n private _next?: () => void;\n private _currentBlock?: FeedBlock<T> = undefined;\n private _index = -1;\n\n // prettier-ignore\n constructor(\n private readonly _feed: FeedWrapper<T>,\n private readonly _options: FeedQueueOptions = {},\n ) {}\n\n [inspect.custom](): string {\n return inspectObject(this);\n }\n\n toJSON() {\n return {\n feedKey: this._feed.key,\n index: this.index,\n length: this.length,\n open: this.isOpen,\n };\n }\n\n get feed() {\n return this._feed;\n }\n\n get isOpen(): boolean {\n return Boolean(this._feedConsumer);\n }\n\n get length(): number {\n return this._feed.properties.length;\n }\n\n /**\n * Index (seq) of the NEXT block to be read, or -1 if not open.\n */\n get index() {\n return this._index;\n }\n\n /**\n * Opens (or reopens) the queue.\n * @param options.start Starting index. First mutation to be read would have `seq == options.start`.\n */\n async open(options: ReadStreamOptions = {}): Promise<void> {\n if (this.isOpen) {\n // TODO(burdon): Warn if re-opening (e.g., with different starting point).\n return;\n }\n\n this._index = options.start ?? 0;\n // if (this._index !== 0) {\n // console.warn('Start index not yet supported.');\n // }\n\n log('opening', { feedKey: this._feed.key });\n\n // TODO(burdon): Open with starting range.\n const opts = Object.assign({}, defaultReadStreamOptions, options);\n const feedStream = this._feed.createReadableStream(opts);\n\n this._feedConsumer = new Writable({\n write: (data: any, next: () => void) => {\n this._next = () => {\n this._next = undefined;\n this._currentBlock = undefined;\n this._index++;\n next();\n };\n\n this._currentBlock = {\n feedKey: this._feed.key,\n seq: this._index,\n data,\n };\n\n this._messageTrigger.wake(this._currentBlock);\n this.updated.emit(this);\n },\n });\n\n const onClose = () => {\n this.feed.core.off('close', onClose);\n this._feedConsumer?.off('close', onClose);\n this._feedConsumer?.off('error', onError);\n\n this._destroyConsumer();\n };\n\n const onError = (err?: Error) => {\n if (!this.isOpen) {\n return;\n }\n if (!err) {\n return;\n }\n if (err.message === 'Writable stream closed prematurely' || err.message === 'Feed is closed') {\n return;\n }\n\n log.catch(err, { feedKey: this._feed.key });\n };\n\n // Called if feed is closed externally.\n this._feed.core.once('close', onClose);\n this._feedConsumer.on('error', onError);\n\n // Called when queue is closed. Throws exception if waiting for `pop`.\n this._feedConsumer.once('close', onClose);\n\n // Pipe readable stream into writable consumer.\n feedStream.pipe(this._feedConsumer, (err) => {\n if (err) {\n onError(err);\n }\n this._destroyConsumer();\n });\n\n log('opened');\n }\n\n /**\n * Closes the queue.\n */\n async close(): Promise<void> {\n if (this.isOpen) {\n invariant(this._feedConsumer);\n invariant(!this._feed.properties.closed);\n\n log('closing', { feedKey: this._feed.key });\n const [closed, setClosed] = latch();\n this._feedConsumer.once('close', setClosed);\n this._feedConsumer.destroy();\n this._next?.(); // Release any message currently in the queue (otherwise destroy will block).\n await closed();\n log('closed');\n }\n }\n\n /**\n * Get the block at the head of the queue without removing it.\n */\n peek(): FeedBlock<T> | undefined {\n return this._currentBlock;\n }\n\n /**\n * Pop block at the head of the queue.\n */\n async pop(): Promise<FeedBlock<T>> {\n if (!this.isOpen) {\n throw new Error(`Queue closed: ${this.feed.key.truncate()}`);\n }\n\n let block = this.peek();\n if (!block) {\n block = await this._messageTrigger.wait();\n }\n\n if (block) {\n this._next?.();\n }\n\n return block;\n }\n\n private _destroyConsumer(): void {\n if (this._feedConsumer) {\n log('queue closed', { feedKey: this._feed.key });\n this._feedConsumer = undefined;\n this._next = undefined;\n this._currentBlock = undefined;\n this._index = -1;\n }\n }\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport { inspect } from 'node:util';\n\nimport { Event, SubscriptionList, Trigger } from '@dxos/async';\nimport { inspectObject } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, isNonNullable } from '@dxos/util';\n\nimport { AbstractFeedIterator } from './feed-iterator';\nimport { FeedQueue } from './feed-queue';\nimport { type FeedWrapper } from './feed-wrapper';\nimport { type FeedBlock } from './types';\n\n/**\n * Select next block.\n */\nexport type FeedBlockSelector<T> = (blocks: FeedBlock<T>[]) => number | undefined;\n\nexport type FeedIndex = {\n feedKey: PublicKey;\n index: number;\n};\n\nexport type FeedSetIteratorOptions = {\n // TODO(burdon): Should we remove this and assume the feeds are positioned before adding?\n start?: FeedIndex[];\n stallTimeout?: number;\n};\n\nexport const defaultFeedSetIteratorOptions = {\n stallTimeout: 1000,\n};\n\n/**\n * Iterator that reads blocks from multiple feeds, ordering them based on a traversal callback.\n */\nexport class FeedSetIterator<T extends {}> extends AbstractFeedIterator<T> {\n private readonly _feedQueues = new ComplexMap<PublicKey, FeedQueue<T>>(PublicKey.hash);\n\n private readonly _trigger = new Trigger({ autoReset: true });\n private readonly _subscriptions = new SubscriptionList();\n\n public readonly stalled = new Event<FeedSetIterator<T>>();\n\n constructor(\n private readonly _selector: FeedBlockSelector<T>,\n public readonly options: FeedSetIteratorOptions = defaultFeedSetIteratorOptions,\n ) {\n super();\n invariant(_selector);\n invariant(options);\n }\n\n [inspect.custom](): string {\n return inspectObject(this);\n }\n\n override toJSON(): { open: boolean; running: boolean; indexes: FeedIndex[] } {\n return {\n open: this.isOpen,\n running: this.isRunning,\n indexes: this.indexes,\n };\n }\n\n get size() {\n return this._feedQueues.size;\n }\n\n get feeds(): FeedWrapper<T>[] {\n return Array.from(this._feedQueues.values()).map((feedQueue) => feedQueue.feed);\n }\n\n get indexes(): FeedIndex[] {\n return Array.from(this._feedQueues.values()).map((feedQueue) => ({\n feedKey: feedQueue.feed.key,\n index: feedQueue.index,\n }));\n }\n\n reiterateBlock(block: FeedBlock<T>): void {\n this._trigger.wake();\n }\n\n async addFeed(feed: FeedWrapper<T>): Promise<void> {\n invariant(!this._feedQueues.has(feed.key), `Feed already added: ${feed.key}`);\n invariant(feed.properties.opened);\n log('feed added', { feedKey: feed.key });\n\n // Create queue and listen for updates.\n const queue = new FeedQueue<T>(feed);\n this._feedQueues.set(feed.key, queue);\n this._subscriptions.add(\n queue.updated.on(() => {\n this._trigger.wake();\n }),\n );\n\n await queue.open({\n start: this.options.start?.find((index) => index.feedKey.equals(feed.key))?.index,\n });\n\n // Wake when feed added or queue updated.\n this._trigger.wake();\n }\n\n hasFeed(feedKey: PublicKey): boolean {\n return this._feedQueues.has(feedKey);\n }\n\n override async _onOpen(): Promise<void> {\n for (const queue of this._feedQueues.values()) {\n await queue.open();\n }\n }\n\n override async _onClose(): Promise<void> {\n this._subscriptions.clear();\n await Promise.all(Array.from(this._feedQueues.values()).map((queue) => queue.close()));\n\n // Wake when feed added or queue updated.\n this._trigger.wake();\n }\n\n /**\n * Gets the next block from the selected queue.\n */\n override async _nextBlock(): Promise<FeedBlock<T> | undefined> {\n let t: NodeJS.Timeout | undefined;\n\n while (this._running) {\n // Get blocks from the head of each queue.\n const queues = Array.from(this._feedQueues.values());\n const blocks = queues.map((queue) => queue.peek()).filter(isNonNullable);\n if (blocks.length) {\n // Get the selected block from candidates.\n const idx = this._selector(blocks);\n log('selected', { idx, blocks });\n if (idx === undefined) {\n // Timeout if all candidates are rejected.\n if (t === undefined) {\n t = setTimeout(() => {\n this.stalled.emit(this);\n this._trigger.wake();\n }, this.options.stallTimeout);\n }\n } else {\n if (t !== undefined) {\n clearTimeout(t);\n t = undefined;\n }\n if (idx >= blocks.length) {\n throw new Error(`Index out of bounds: ${idx} of ${blocks.length}`);\n }\n\n // Pop from queue.\n const queue = this._feedQueues.get(blocks[idx].feedKey)!;\n log('popping', queue.toJSON());\n try {\n const message = await queue.pop();\n invariant(message === blocks[idx]);\n return message;\n } catch (err) {\n // TODO(burdon): Same queue closed twice.\n log.warn('queue closed', { feedKey: queue.feed.key });\n // console.log(Array.from(this._feedQueues.values()));\n }\n }\n }\n\n // Wait until feed added, new block, or closing.\n await this._trigger.wait();\n }\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type PublicKey } from '@dxos/keys';\n\nexport type WriteReceipt = {\n feedKey: PublicKey;\n seq: number;\n};\n\nexport type WriteOptions = {\n /**\n * Called after the write is complete.\n * Runs and completes before the mutation is read from the pipeline.\n */\n afterWrite?: (receipt: WriteReceipt) => Promise<void>;\n};\n\nexport interface FeedWriter<T extends {}> {\n /**\n * Write data to the feed.\n * Awaits `afterWrite` before returning.\n */\n write(data: T, options?: WriteOptions): Promise<WriteReceipt>;\n}\n\nexport const createFeedWriter = <T extends {}>(cb: (data: T) => Promise<WriteReceipt>): FeedWriter<T> => ({\n write: async (data: T) => {\n return cb(data);\n },\n});\n\nexport const writeMessages = async <T extends {}>(writer: FeedWriter<T>, messages: T[]): Promise<WriteReceipt[]> => {\n const receipts: WriteReceipt[] = [];\n // NOTE: Write messages sequentially.\n for (const message of messages) {\n receipts.push(await writer.write(message));\n }\n return receipts;\n};\n"],
5
- "mappings": ";;;;;;;;AAIA,OAAOA,cAAc;AAErB,SAASC,WAAAA,gBAAe;AACxB,SAASC,aAAAA,kBAAiB;AAC1B,SAASC,OAAAA,YAAW;;;ACJpB,SAASC,eAAe;AAExB,SAASC,gBAAgB;AAEzB,SAASC,OAAOC,SAASC,aAAa;AACtC,SAASC,qBAAqB;AAE9B,SAASC,iBAAiB;AAC1B,SAASC,WAAW;;AAKb,IAAMC,2BAA8C;EACzDC,MAAM;EACNC,OAAO;AACT;AAOO,IAAMC,YAAN,MAAMA;;;EACJC,UAAU,IAAIV,MAAAA;EAEJW,kBAAkB,IAAIV,QAAsB;IAC3DW,WAAW;EACb,CAAA;EAEQC,gBAA2BC;EAC3BC;EACAC,gBAA+BF;EAC/BG,SAAS;;EAGjB,YACmBC,OACAC,WAA6B,CAAC,GAC/C;SAFiBD,QAAAA;SACAC,WAAAA;EAChB;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AA,OAAUL,OAAOI,MAAM,EAAE;UACnE;AAGA,gBAAMxB,QAAQ,KAAK1C,YAAYyE,IAAIX,OAAOK,GAAAA,EAAKpC,OAAO;AACtDU,UAAAA,KAAI,WAAWC,MAAMzB,OAAM,GAAA;;;;;;AAC3B,cAAI;AACF,kBAAMyD,UAAU,MAAMhC,MAAMiC,IAAG;AAC/B9D,YAAAA,WAAU6D,YAAYZ,OAAOK,GAAAA,GAAI,QAAA;;;;;;;;;AACjC,mBAAOO;UACT,SAASE,KAAK;AAEZnC,YAAAA,KAAIoC,KAAK,gBAAgB;cAAE9C,SAASW,MAAMZ,KAAKE;YAAI,GAAA;;;;;;UAErD;QACF;MACF;AAGA,YAAM,KAAK5B,SAAS0E,KAAI;IAC1B;EACF;AACF;;;ACxJO,IAAMC,mBAAmB,CAAeC,QAA2D;EACxGC,OAAO,OAAOC,SAAAA;AACZ,WAAOF,GAAGE,IAAAA;EACZ;AACF;AAEO,IAAMC,gBAAgB,OAAqBC,QAAuBC,aAAAA;AACvE,QAAMC,WAA2B,CAAA;AAEjC,aAAWC,WAAWF,UAAU;AAC9BC,aAASE,KAAK,MAAMJ,OAAOH,MAAMM,OAAAA,CAAAA;EACnC;AACA,SAAOD;AACT;",
4
+ "sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport safeRace from 'race-as-promised';\n\nimport { Trigger } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { FeedQueue } from './feed-queue';\nimport { type FeedWrapper } from './feed-wrapper';\nimport { type FeedBlock } from './types';\n\n/**\n * Base class for an async iterable feed.\n */\nexport abstract class AbstractFeedIterator<T> implements AsyncIterable<FeedBlock<T>> {\n private readonly _stopTrigger = new Trigger();\n\n protected _open = false;\n protected _running = false;\n\n toJSON(): { open: boolean; running: boolean } {\n return {\n open: this.isOpen,\n running: this.isRunning,\n };\n }\n\n get isOpen() {\n return this._open;\n }\n\n get isRunning() {\n return this._running;\n }\n\n async open(): Promise<void> {\n if (!this._open) {\n log('opening...');\n await this._onOpen();\n this._open = true;\n\n await this.start();\n log('opened');\n }\n }\n\n async close(): Promise<void> {\n if (this._open) {\n log('closing...');\n await this.stop();\n\n await this._onClose();\n this._open = false;\n log('closed');\n }\n }\n\n async start(): Promise<void> {\n invariant(this._open);\n if (!this._running) {\n this._running = true;\n }\n }\n\n async stop(): Promise<void> {\n invariant(this._open);\n if (this._running) {\n this._running = false;\n this._stopTrigger.wake();\n }\n }\n\n //\n // AsyncIterable\n //\n\n [Symbol.asyncIterator]() {\n return this._generator();\n }\n\n async *_generator() {\n log('started');\n while (this._running) {\n // https://github.com/nodejs/node/issues/17469\n const block = await safeRace([this._stopTrigger.wait(), this._nextBlock()]);\n\n if (block === undefined) {\n break;\n }\n\n yield block;\n }\n\n log('stopped');\n }\n\n abstract _onOpen(): Promise<void>;\n abstract _onClose(): Promise<void>;\n abstract _nextBlock(): Promise<FeedBlock<T> | undefined>;\n}\n\n/**\n * Iterator that reads blocks from a single feed.\n */\nexport class FeedIterator<T extends {}> extends AbstractFeedIterator<T> {\n private readonly _queue: FeedQueue<T>;\n\n constructor(private readonly _feed: FeedWrapper<T>) {\n super();\n this._queue = new FeedQueue<T>(this._feed);\n }\n\n override async _onOpen(): Promise<void> {\n await this._queue.open();\n }\n\n override async _onClose(): Promise<void> {\n await this._queue.close();\n }\n\n override async _nextBlock(): Promise<FeedBlock<T> | undefined> {\n return this._queue.pop();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { inspect } from 'node:util';\nimport { Writable } from 'streamx';\n\nimport { Event, Trigger, latch } from '@dxos/async';\nimport { inspectObject } from '@dxos/debug';\nimport type { ReadStreamOptions } from '@dxos/hypercore';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type FeedWrapper } from './feed-wrapper';\nimport { type FeedBlock } from './types';\n\nexport const defaultReadStreamOptions: ReadStreamOptions = {\n live: true, // Keep reading until closed.\n batch: 1024, // Read in batches.\n};\n\nexport type FeedQueueOptions = {};\n\n/**\n * Async queue using an AsyncIterator created from a hypercore.\n */\nexport class FeedQueue<T extends {}> {\n public updated = new Event<FeedQueue<T>>();\n\n private readonly _messageTrigger = new Trigger<FeedBlock<T>>({\n autoReset: true,\n });\n\n private _feedConsumer?: Writable = undefined;\n private _next?: () => void;\n private _currentBlock?: FeedBlock<T> = undefined;\n private _index = -1;\n\n // prettier-ignore\n constructor(\n private readonly _feed: FeedWrapper<T>,\n private readonly _options: FeedQueueOptions = {},\n ) {}\n\n [inspect.custom](): string {\n return inspectObject(this);\n }\n\n toJSON() {\n return {\n feedKey: this._feed.key,\n index: this.index,\n length: this.length,\n open: this.isOpen,\n };\n }\n\n get feed() {\n return this._feed;\n }\n\n get isOpen(): boolean {\n return Boolean(this._feedConsumer);\n }\n\n get length(): number {\n return this._feed.properties.length;\n }\n\n /**\n * Index (seq) of the NEXT block to be read, or -1 if not open.\n */\n get index() {\n return this._index;\n }\n\n /**\n * Opens (or reopens) the queue.\n * @param options.start Starting index. First mutation to be read would have `seq == options.start`.\n */\n async open(options: ReadStreamOptions = {}): Promise<void> {\n if (this.isOpen) {\n // TODO(burdon): Warn if re-opening (e.g., with different starting point).\n return;\n }\n\n this._index = options.start ?? 0;\n // if (this._index !== 0) {\n // console.warn('Start index not yet supported.');\n // }\n\n log('opening', { feedKey: this._feed.key });\n\n // TODO(burdon): Open with starting range.\n const opts = Object.assign({}, defaultReadStreamOptions, options);\n const feedStream = this._feed.createReadableStream(opts);\n\n this._feedConsumer = new Writable({\n write: (data: any, next: () => void) => {\n this._next = () => {\n this._next = undefined;\n this._currentBlock = undefined;\n this._index++;\n next();\n };\n\n this._currentBlock = {\n feedKey: this._feed.key,\n seq: this._index,\n data,\n };\n\n this._messageTrigger.wake(this._currentBlock);\n this.updated.emit(this);\n },\n });\n\n const onClose = () => {\n this.feed.core.off('close', onClose);\n this._feedConsumer?.off('close', onClose);\n this._feedConsumer?.off('error', onError);\n\n this._destroyConsumer();\n };\n\n const onError = (err?: Error) => {\n if (!this.isOpen) {\n return;\n }\n if (!err) {\n return;\n }\n if (err.message === 'Writable stream closed prematurely' || err.message === 'Feed is closed') {\n return;\n }\n\n log.catch(err, { feedKey: this._feed.key });\n };\n\n // Called if feed is closed externally.\n this._feed.core.once('close', onClose);\n this._feedConsumer.on('error', onError);\n\n // Called when queue is closed. Throws exception if waiting for `pop`.\n this._feedConsumer.once('close', onClose);\n\n // Pipe readable stream into writable consumer.\n feedStream.pipe(this._feedConsumer, (err) => {\n if (err) {\n onError(err);\n }\n this._destroyConsumer();\n });\n\n log('opened');\n }\n\n /**\n * Closes the queue.\n */\n async close(): Promise<void> {\n if (this.isOpen) {\n invariant(this._feedConsumer);\n invariant(!this._feed.properties.closed);\n\n log('closing', { feedKey: this._feed.key });\n const [closed, setClosed] = latch();\n this._feedConsumer.once('close', setClosed);\n this._feedConsumer.destroy();\n this._next?.(); // Release any message currently in the queue (otherwise destroy will block).\n await closed();\n log('closed');\n }\n }\n\n /**\n * Get the block at the head of the queue without removing it.\n */\n peek(): FeedBlock<T> | undefined {\n return this._currentBlock;\n }\n\n /**\n * Pop block at the head of the queue.\n */\n async pop(): Promise<FeedBlock<T>> {\n if (!this.isOpen) {\n throw new Error(`Queue closed: ${this.feed.key.truncate()}`);\n }\n\n let block = this.peek();\n if (!block) {\n block = await this._messageTrigger.wait();\n }\n\n if (block) {\n this._next?.();\n }\n\n return block;\n }\n\n private _destroyConsumer(): void {\n if (this._feedConsumer) {\n log('queue closed', { feedKey: this._feed.key });\n this._feedConsumer = undefined;\n this._next = undefined;\n this._currentBlock = undefined;\n this._index = -1;\n }\n }\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport { inspect } from 'node:util';\n\nimport { Event, SubscriptionList, Trigger } from '@dxos/async';\nimport { inspectObject } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, isNonNullable } from '@dxos/util';\n\nimport { AbstractFeedIterator } from './feed-iterator';\nimport { FeedQueue } from './feed-queue';\nimport { type FeedWrapper } from './feed-wrapper';\nimport { type FeedBlock } from './types';\n\n/**\n * Select next block.\n */\nexport type FeedBlockSelector<T> = (blocks: FeedBlock<T>[]) => number | undefined;\n\nexport type FeedIndex = {\n feedKey: PublicKey;\n index: number;\n};\n\nexport type FeedSetIteratorOptions = {\n // TODO(burdon): Should we remove this and assume the feeds are positioned before adding?\n start?: FeedIndex[];\n stallTimeout?: number;\n};\n\nexport const defaultFeedSetIteratorOptions = {\n stallTimeout: 1000,\n};\n\n/**\n * Iterator that reads blocks from multiple feeds, ordering them based on a traversal callback.\n */\nexport class FeedSetIterator<T extends {}> extends AbstractFeedIterator<T> {\n private readonly _feedQueues = new ComplexMap<PublicKey, FeedQueue<T>>(PublicKey.hash);\n\n private readonly _trigger = new Trigger({ autoReset: true });\n private readonly _subscriptions = new SubscriptionList();\n\n public readonly stalled = new Event<FeedSetIterator<T>>();\n\n constructor(\n private readonly _selector: FeedBlockSelector<T>,\n public readonly options: FeedSetIteratorOptions = defaultFeedSetIteratorOptions,\n ) {\n super();\n invariant(_selector);\n invariant(options);\n }\n\n [inspect.custom](): string {\n return inspectObject(this);\n }\n\n override toJSON(): { open: boolean; running: boolean; indexes: FeedIndex[] } {\n return {\n open: this.isOpen,\n running: this.isRunning,\n indexes: this.indexes,\n };\n }\n\n get size() {\n return this._feedQueues.size;\n }\n\n get feeds(): FeedWrapper<T>[] {\n return Array.from(this._feedQueues.values()).map((feedQueue) => feedQueue.feed);\n }\n\n get indexes(): FeedIndex[] {\n return Array.from(this._feedQueues.values()).map((feedQueue) => ({\n feedKey: feedQueue.feed.key,\n index: feedQueue.index,\n }));\n }\n\n reiterateBlock(block: FeedBlock<T>): void {\n this._trigger.wake();\n }\n\n async addFeed(feed: FeedWrapper<T>): Promise<void> {\n invariant(!this._feedQueues.has(feed.key), `Feed already added: ${feed.key}`);\n invariant(feed.properties.opened);\n log('feed added', { feedKey: feed.key });\n\n // Create queue and listen for updates.\n const queue = new FeedQueue<T>(feed);\n this._feedQueues.set(feed.key, queue);\n this._subscriptions.add(\n queue.updated.on(() => {\n this._trigger.wake();\n }),\n );\n\n await queue.open({\n start: this.options.start?.find((index) => index.feedKey.equals(feed.key))?.index,\n });\n\n // Wake when feed added or queue updated.\n this._trigger.wake();\n }\n\n hasFeed(feedKey: PublicKey): boolean {\n return this._feedQueues.has(feedKey);\n }\n\n override async _onOpen(): Promise<void> {\n for (const queue of this._feedQueues.values()) {\n await queue.open();\n }\n }\n\n override async _onClose(): Promise<void> {\n this._subscriptions.clear();\n await Promise.all(Array.from(this._feedQueues.values()).map((queue) => queue.close()));\n\n // Wake when feed added or queue updated.\n this._trigger.wake();\n }\n\n /**\n * Gets the next block from the selected queue.\n */\n override async _nextBlock(): Promise<FeedBlock<T> | undefined> {\n let t: NodeJS.Timeout | undefined;\n\n while (this._running) {\n // Get blocks from the head of each queue.\n const queues = Array.from(this._feedQueues.values());\n const blocks = queues.map((queue) => queue.peek()).filter(isNonNullable);\n if (blocks.length) {\n // Get the selected block from candidates.\n const idx = this._selector(blocks);\n log('selected', { idx, blocks });\n if (idx === undefined) {\n // Timeout if all candidates are rejected.\n if (t === undefined) {\n t = setTimeout(() => {\n this.stalled.emit(this);\n this._trigger.wake();\n }, this.options.stallTimeout);\n }\n } else {\n if (t !== undefined) {\n clearTimeout(t);\n t = undefined;\n }\n if (idx >= blocks.length) {\n throw new Error(`Index out of bounds: ${idx} of ${blocks.length}`);\n }\n\n // Pop from queue.\n const queue = this._feedQueues.get(blocks[idx].feedKey)!;\n log('popping', queue.toJSON());\n try {\n const message = await queue.pop();\n invariant(message === blocks[idx]);\n return message;\n } catch (err) {\n // TODO(burdon): Same queue closed twice.\n log.warn('queue closed', { feedKey: queue.feed.key });\n // console.log(Array.from(this._feedQueues.values()));\n }\n }\n }\n\n // Wait until feed added, new block, or closing.\n await this._trigger.wait();\n }\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type PublicKey } from '@dxos/keys';\n\nexport type WriteReceipt = {\n feedKey: PublicKey;\n seq: number;\n};\n\nexport type WriteOptions = {\n /**\n * Called after the write is complete.\n * Runs and completes before the mutation is read from the pipeline.\n */\n afterWrite?: (receipt: WriteReceipt) => Promise<void>;\n};\n\nexport interface FeedWriter<T extends {}> {\n /**\n * Write data to the feed.\n * Awaits `afterWrite` before returning.\n */\n write(data: T, options?: WriteOptions): Promise<WriteReceipt>;\n}\n\nexport const createFeedWriter = <T extends {}>(cb: (data: T) => Promise<WriteReceipt>): FeedWriter<T> => ({\n write: async (data: T) => {\n return cb(data);\n },\n});\n\nexport const writeMessages = async <T extends {}>(writer: FeedWriter<T>, messages: T[]): Promise<WriteReceipt[]> => {\n const receipts: WriteReceipt[] = [];\n // NOTE: Write messages sequentially.\n for (const message of messages) {\n receipts.push(await writer.write(message));\n }\n return receipts;\n};\n"],
5
+ "mappings": ";;;;;;;;AAIA,OAAOA,cAAc;AAErB,SAASC,WAAAA,gBAAe;AACxB,SAASC,aAAAA,kBAAiB;AAC1B,SAASC,OAAAA,YAAW;;;ACJpB,SAASC,eAAe;AACxB,SAASC,gBAAgB;AAEzB,SAASC,OAAOC,SAASC,aAAa;AACtC,SAASC,qBAAqB;AAE9B,SAASC,iBAAiB;AAC1B,SAASC,WAAW;;AAKb,IAAMC,2BAA8C;EACzDC,MAAM;EACNC,OAAO;AACT;AAOO,IAAMC,YAAN,MAAMA;;;EACJC,UAAU,IAAIV,MAAAA;EAEJW,kBAAkB,IAAIV,QAAsB;IAC3DW,WAAW;EACb,CAAA;EAEQC,gBAA2BC;EAC3BC;EACAC,gBAA+BF;EAC/BG,SAAS;;EAGjB,YACmBC,OACAC,WAA6B,CAAC,GAC/C;SAFiBD,QAAAA;SACAC,WAAAA;EAChB;EAEH,CAACrB,QAAQsB,MAAM,IAAY;AACzB,WAAOjB,cAAc,IAAI;EAC3B;EAEAkB,SAAS;AACP,WAAO;M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AA,EAAKpC,OAAO;AACtDU,UAAAA,KAAI,WAAWC,MAAMzB,OAAM,GAAA;;;;;;AAC3B,cAAI;AACF,kBAAMyD,UAAU,MAAMhC,MAAMiC,IAAG;AAC/B9D,YAAAA,WAAU6D,YAAYZ,OAAOK,GAAAA,GAAI,QAAA;;;;;;;;;AACjC,mBAAOO;UACT,SAASE,KAAK;AAEZnC,YAAAA,KAAIoC,KAAK,gBAAgB;cAAE9C,SAASW,MAAMZ,KAAKE;YAAI,GAAA;;;;;;UAErD;QACF;MACF;AAGA,YAAM,KAAK5B,SAAS0E,KAAI;IAC1B;EACF;AACF;;;ACxJO,IAAMC,mBAAmB,CAAeC,QAA2D;EACxGC,OAAO,OAAOC,SAAAA;AACZ,WAAOF,GAAGE,IAAAA;EACZ;AACF;AAEO,IAAMC,gBAAgB,OAAqBC,QAAuBC,aAAAA;AACvE,QAAMC,WAA2B,CAAA;AAEjC,aAAWC,WAAWF,UAAU;AAC9BC,aAASE,KAAK,MAAMJ,OAAOH,MAAMM,OAAAA,CAAAA;EACnC;AACA,SAAOD;AACT;",
6
6
  "names": ["safeRace", "Trigger", "invariant", "log", "inspect", "Writable", "Event", "Trigger", "latch", "inspectObject", "invariant", "log", "defaultReadStreamOptions", "live", "batch", "FeedQueue", "updated", "_messageTrigger", "autoReset", "_feedConsumer", "undefined", "_next", "_currentBlock", "_index", "_feed", "_options", "custom", "toJSON", "feedKey", "key", "index", "length", "open", "isOpen", "feed", "Boolean", "properties", "options", "start", "opts", "Object", "assign", "feedStream", "createReadableStream", "write", "data", "next", "seq", "wake", "emit", "onClose", "core", "off", "onError", "_destroyConsumer", "err", "message", "catch", "once", "on", "pipe", "close", "closed", "setClosed", "destroy", "peek", "pop", "Error", "truncate", "block", "wait", "AbstractFeedIterator", "_stopTrigger", "Trigger", "_open", "_running", "toJSON", "open", "isOpen", "running", "isRunning", "log", "_onOpen", "start", "close", "stop", "_onClose", "invariant", "wake", "Symbol", "asyncIterator", "_generator", "block", "safeRace", "wait", "_nextBlock", "undefined", "FeedIterator", "_queue", "_feed", "FeedQueue", "pop", "inspect", "Event", "SubscriptionList", "Trigger", "inspectObject", "invariant", "PublicKey", "log", "ComplexMap", "isNonNullable", "defaultFeedSetIteratorOptions", "stallTimeout", "FeedSetIterator", "AbstractFeedIterator", "_feedQueues", "ComplexMap", "PublicKey", "hash", "_trigger", "Trigger", "autoReset", "_subscriptions", "SubscriptionList", "stalled", "Event", "_selector", "options", "invariant", "inspect", "custom", "inspectObject", "toJSON", "open", "isOpen", "running", "isRunning", "indexes", "size", "feeds", "Array", "from", "values", "map", "feedQueue", "feed", "feedKey", "key", "index", "reiterateBlock", "block", "wake", "addFeed", "has", "properties", "opened", "log", "queue", "FeedQueue", "set", "add", "updated", "on", "start", "find", "equals", "hasFeed", "_onOpen", "_onClose", "clear", "Promise", "all", "close", "_nextBlock", "t", "_running", "queues", "blocks", "peek", "filter", "isNonNullable", "length", "idx", "undefined", "setTimeout", "emit", "clearTimeout", "Error", "get", "message", "pop", "err", "warn", "wait", "createFeedWriter", "cb", "write", "data", "writeMessages", "writer", "messages", "receipts", "message", "push"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"src/feed-wrapper.ts":{"bytes":35830,"imports":[{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"streamx","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/feed-factory.ts":{"bytes":9086,"imports":[{"path":"lodash.defaultsdeep","kind":"import-statement","external":true},{"path":"@dxos/crypto","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/hypercore","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"src/feed-wrapper.ts","kind":"import-statement","original":"./feed-wrapper"}],"format":"esm"},"src/feed-queue.ts":{"bytes":19592,"imports":[{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"streamx","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"src/feed-iterator.ts":{"bytes":10114,"imports":[{"path":"race-as-promised","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"src/feed-queue.ts","kind":"import-statement","original":"./feed-queue"}],"format":"esm"},"src/feed-set-iterator.ts":{"bytes":19967,"imports":[{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"src/feed-iterator.ts","kind":"import-statement","original":"./feed-iterator"},{"path":"src/feed-queue.ts","kind":"import-statement","original":"./feed-queue"}],"format":"esm"},"src/feed-store.ts":{"bytes":12102,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/feed-writer.ts":{"bytes":2625,"imports":[],"format":"esm"},"src/index.ts":{"bytes":1106,"imports":[{"path":"src/feed-factory.ts","kind":"import-statement","original":"./feed-factory"},{"path":"src/feed-iterator.ts","kind":"import-statement","original":"./feed-iterator"},{"path":"src/feed-set-iterator.ts","kind":"import-statement","original":"./feed-set-iterator"},{"path":"src/feed-queue.ts","kind":"import-statement","original":"./feed-queue"},{"path":"src/feed-store.ts","kind":"import-statement","original":"./feed-store"},{"path":"src/feed-wrapper.ts","kind":"import-statement","original":"./feed-wrapper"},{"path":"src/feed-writer.ts","kind":"import-statement","original":"./feed-writer"}],"format":"esm"},"src/testing/mocks.ts":{"bytes":3371,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true}],"format":"esm"},"src/testing/test-generator.ts":{"bytes":5521,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/hypercore","kind":"import-statement","external":true},{"path":"@dxos/random","kind":"import-statement","external":true}],"format":"esm"},"src/testing/test-builder.ts":{"bytes":9653,"imports":[{"path":"@dxos/keyring","kind":"import-statement","external":true},{"path":"@dxos/random-access-storage","kind":"import-statement","external":true},{"path":"src/feed-factory.ts","kind":"import-statement","original":"../feed-factory"},{"path":"src/feed-store.ts","kind":"import-statement","original":"../feed-store"},{"path":"src/testing/test-generator.ts","kind":"import-statement","original":"./test-generator"}],"format":"esm"},"src/testing/index.ts":{"bytes":660,"imports":[{"path":"src/testing/mocks.ts","kind":"import-statement","original":"./mocks"},{"path":"src/testing/test-builder.ts","kind":"import-statement","original":"./test-builder"},{"path":"src/testing/test-generator.ts","kind":"import-statement","original":"./test-generator"}],"format":"esm"}},"outputs":{"dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":24505},"dist/lib/browser/index.mjs":{"imports":[{"path":"dist/lib/browser/chunk-I36R5SR3.mjs","kind":"import-statement"},{"path":"race-as-promised","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"streamx","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["AbstractFeedIterator","FeedFactory","FeedIterator","FeedQueue","FeedSetIterator","FeedStore","FeedWrapper","createFeedWriter","defaultFeedSetIteratorOptions","defaultReadStreamOptions","writeMessages"],"entryPoint":"src/index.ts","inputs":{"src/index.ts":{"bytesInOutput":0},"src/feed-iterator.ts":{"bytesInOutput":2761},"src/feed-queue.ts":{"bytesInOutput":4963},"src/feed-set-iterator.ts":{"bytesInOutput":4938},"src/feed-writer.ts":{"bytesInOutput":273}},"bytes":13433},"dist/lib/browser/testing/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":9644},"dist/lib/browser/testing/index.mjs":{"imports":[{"path":"dist/lib/browser/chunk-I36R5SR3.mjs","kind":"import-statement"},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/keyring","kind":"import-statement","external":true},{"path":"@dxos/random-access-storage","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/hypercore","kind":"import-statement","external":true},{"path":"@dxos/random","kind":"import-statement","external":true}],"exports":["MockFeedWriter","TestBuilder","TestGenerator","TestItemBuilder","defaultCodec","defaultTestBlockGenerator","defaultTestGenerator","defaultValueEncoding"],"entryPoint":"src/testing/index.ts","inputs":{"src/testing/mocks.ts":{"bytesInOutput":768},"src/testing/index.ts":{"bytesInOutput":0},"src/testing/test-builder.ts":{"bytesInOutput":1800},"src/testing/test-generator.ts":{"bytesInOutput":967}},"bytes":3967},"dist/lib/browser/chunk-I36R5SR3.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":27830},"dist/lib/browser/chunk-I36R5SR3.mjs":{"imports":[{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"streamx","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"lodash.defaultsdeep","kind":"import-statement","external":true},{"path":"@dxos/crypto","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/hypercore","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["FeedFactory","FeedStore","FeedWrapper"],"inputs":{"src/feed-wrapper.ts":{"bytesInOutput":8770},"src/feed-factory.ts":{"bytesInOutput":2043},"src/feed-store.ts":{"bytesInOutput":3100}},"bytes":14115}}}
1
+ {"inputs":{"src/feed-wrapper.ts":{"bytes":35825,"imports":[{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"streamx","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/feed-factory.ts":{"bytes":9086,"imports":[{"path":"lodash.defaultsdeep","kind":"import-statement","external":true},{"path":"@dxos/crypto","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/hypercore","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"src/feed-wrapper.ts","kind":"import-statement","original":"./feed-wrapper"}],"format":"esm"},"src/feed-queue.ts":{"bytes":19588,"imports":[{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"streamx","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"src/feed-iterator.ts":{"bytes":10114,"imports":[{"path":"race-as-promised","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"src/feed-queue.ts","kind":"import-statement","original":"./feed-queue"}],"format":"esm"},"src/feed-set-iterator.ts":{"bytes":19967,"imports":[{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"src/feed-iterator.ts","kind":"import-statement","original":"./feed-iterator"},{"path":"src/feed-queue.ts","kind":"import-statement","original":"./feed-queue"}],"format":"esm"},"src/feed-store.ts":{"bytes":12102,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"src/feed-writer.ts":{"bytes":2625,"imports":[],"format":"esm"},"src/index.ts":{"bytes":1106,"imports":[{"path":"src/feed-factory.ts","kind":"import-statement","original":"./feed-factory"},{"path":"src/feed-iterator.ts","kind":"import-statement","original":"./feed-iterator"},{"path":"src/feed-set-iterator.ts","kind":"import-statement","original":"./feed-set-iterator"},{"path":"src/feed-queue.ts","kind":"import-statement","original":"./feed-queue"},{"path":"src/feed-store.ts","kind":"import-statement","original":"./feed-store"},{"path":"src/feed-wrapper.ts","kind":"import-statement","original":"./feed-wrapper"},{"path":"src/feed-writer.ts","kind":"import-statement","original":"./feed-writer"}],"format":"esm"},"src/testing/mocks.ts":{"bytes":3371,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true}],"format":"esm"},"src/testing/test-generator.ts":{"bytes":5529,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/hypercore","kind":"import-statement","external":true},{"path":"@dxos/random","kind":"import-statement","external":true}],"format":"esm"},"src/testing/test-builder.ts":{"bytes":9653,"imports":[{"path":"@dxos/keyring","kind":"import-statement","external":true},{"path":"@dxos/random-access-storage","kind":"import-statement","external":true},{"path":"src/feed-factory.ts","kind":"import-statement","original":"../feed-factory"},{"path":"src/feed-store.ts","kind":"import-statement","original":"../feed-store"},{"path":"src/testing/test-generator.ts","kind":"import-statement","original":"./test-generator"}],"format":"esm"},"src/testing/index.ts":{"bytes":660,"imports":[{"path":"src/testing/mocks.ts","kind":"import-statement","original":"./mocks"},{"path":"src/testing/test-builder.ts","kind":"import-statement","original":"./test-builder"},{"path":"src/testing/test-generator.ts","kind":"import-statement","original":"./test-generator"}],"format":"esm"}},"outputs":{"dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":24503},"dist/lib/browser/index.mjs":{"imports":[{"path":"dist/lib/browser/chunk-5F4TNRQV.mjs","kind":"import-statement"},{"path":"race-as-promised","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"streamx","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["AbstractFeedIterator","FeedFactory","FeedIterator","FeedQueue","FeedSetIterator","FeedStore","FeedWrapper","createFeedWriter","defaultFeedSetIteratorOptions","defaultReadStreamOptions","writeMessages"],"entryPoint":"src/index.ts","inputs":{"src/index.ts":{"bytesInOutput":0},"src/feed-iterator.ts":{"bytesInOutput":2761},"src/feed-queue.ts":{"bytesInOutput":4963},"src/feed-set-iterator.ts":{"bytesInOutput":4938},"src/feed-writer.ts":{"bytesInOutput":273}},"bytes":13433},"dist/lib/browser/testing/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":9649},"dist/lib/browser/testing/index.mjs":{"imports":[{"path":"dist/lib/browser/chunk-5F4TNRQV.mjs","kind":"import-statement"},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/keyring","kind":"import-statement","external":true},{"path":"@dxos/random-access-storage","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/hypercore","kind":"import-statement","external":true},{"path":"@dxos/random","kind":"import-statement","external":true}],"exports":["MockFeedWriter","TestBuilder","TestGenerator","TestItemBuilder","defaultCodec","defaultTestBlockGenerator","defaultTestGenerator","defaultValueEncoding"],"entryPoint":"src/testing/index.ts","inputs":{"src/testing/mocks.ts":{"bytesInOutput":768},"src/testing/index.ts":{"bytesInOutput":0},"src/testing/test-builder.ts":{"bytesInOutput":1800},"src/testing/test-generator.ts":{"bytesInOutput":971}},"bytes":3971},"dist/lib/browser/chunk-5F4TNRQV.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":27828},"dist/lib/browser/chunk-5F4TNRQV.mjs":{"imports":[{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"@dxos/node-std/util","kind":"import-statement","external":true},{"path":"streamx","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"lodash.defaultsdeep","kind":"import-statement","external":true},{"path":"@dxos/crypto","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/hypercore","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["FeedFactory","FeedStore","FeedWrapper"],"inputs":{"src/feed-wrapper.ts":{"bytesInOutput":8769},"src/feed-factory.ts":{"bytesInOutput":2043},"src/feed-store.ts":{"bytesInOutput":3100}},"bytes":14114}}}
@@ -2,7 +2,7 @@ import "@dxos/node-std/globals";
2
2
  import {
3
3
  FeedFactory,
4
4
  FeedStore
5
- } from "../chunk-I36R5SR3.mjs";
5
+ } from "../chunk-5F4TNRQV.mjs";
6
6
 
7
7
  // src/testing/mocks.ts
8
8
  import { Event, scheduleTask } from "@dxos/async";
@@ -43,16 +43,16 @@ import { StorageType, createStorage } from "@dxos/random-access-storage";
43
43
  // src/testing/test-generator.ts
44
44
  import { sleep } from "@dxos/async";
45
45
  import { createCodecEncoding } from "@dxos/hypercore";
46
- import { faker } from "@dxos/random";
46
+ import { random } from "@dxos/random";
47
47
  var defaultCodec = {
48
48
  encode: (obj) => Buffer.from(JSON.stringify(obj)),
49
49
  decode: (buffer) => JSON.parse(buffer.toString())
50
50
  };
51
51
  var defaultValueEncoding = createCodecEncoding(defaultCodec);
52
52
  var defaultTestBlockGenerator = (i) => ({
53
- id: faker.string.uuid(),
53
+ id: random.string.uuid(),
54
54
  index: i,
55
- value: faker.lorem.sentence()
55
+ value: random.lorem.sentence()
56
56
  });
57
57
  var TestGenerator = class {
58
58
  _generate;
@@ -65,7 +65,7 @@ var TestGenerator = class {
65
65
  const data = this._generate(this._count++);
66
66
  const receipt = await writer.write(data);
67
67
  if (delay) {
68
- await sleep(faker.number.int(delay));
68
+ await sleep(random.number.int(delay));
69
69
  }
70
70
  return receipt;
71
71
  }));
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/testing/mocks.ts", "../../../../src/testing/test-builder.ts", "../../../../src/testing/test-generator.ts"],
4
- "sourcesContent": ["//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event, scheduleTask } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\n\nimport type { FeedWriter, WriteOptions, WriteReceipt } from '../feed-writer';\n\n/**\n * Mock writer collects and emits messages.\n */\nexport class MockFeedWriter<T extends {}> implements FeedWriter<T> {\n public readonly written = new Event<[T, WriteReceipt]>();\n public readonly messages: T[] = [];\n\n constructor(readonly feedKey = PublicKey.random()) {}\n\n async write(data: T, { afterWrite }: WriteOptions = {}): Promise<WriteReceipt> {\n this.messages.push(data);\n\n const receipt: WriteReceipt = {\n feedKey: this.feedKey,\n seq: this.messages.length - 1,\n };\n\n await afterWrite?.(receipt);\n\n scheduleTask(new Context(), () => {\n this.written.emit([data, receipt]);\n });\n\n return receipt;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Keyring } from '@dxos/keyring';\nimport { type Directory, type Storage, StorageType, createStorage } from '@dxos/random-access-storage';\nimport type { ValueEncoding } from '@dxos/vendor-hypercore/hypercore';\n\nimport { FeedFactory } from '../feed-factory';\nimport { FeedStore } from '../feed-store';\n\nimport { type TestGenerator, type TestItem, defaultTestGenerator, defaultValueEncoding } from './test-generator';\n\nexport type TestBuilderOptions<T extends {}> = {\n storage?: Storage;\n root?: Directory;\n keyring?: Keyring;\n valueEncoding?: ValueEncoding<T>;\n generator?: TestGenerator<T>;\n};\n\ntype PropertyProvider<T extends {}, P> = (cb: TestBuilder<T>) => P;\n\nconst evaluate = <T extends {}, P>(builder: TestBuilder<T>, arg: P | PropertyProvider<T, P>) =>\n arg === 'function' ? (arg as Function)(builder) : arg;\n\n/**\n * The builder provides building blocks for tests with sensible defaults.\n * - Factory methods trigger the automatic generation of unset required properties.\n * - Avoids explosion of overly specific test functions that require and return large bags of properties.\n */\nexport class TestBuilder<T extends {}> {\n static readonly ROOT_DIR = 'feeds';\n\n constructor(public readonly _properties: TestBuilderOptions<T> = {}) {}\n\n /**\n * Creates a new builder with the current builder's properties.\n */\n clone(): TestBuilder<T> {\n return new TestBuilder<T>(Object.assign({}, this._properties));\n }\n\n get keyring(): Keyring {\n return (this._properties.keyring ??= new Keyring());\n }\n\n get storage(): Storage {\n return (this._properties.storage ??= createStorage({ type: StorageType.RAM }));\n }\n\n get root(): Directory {\n return (this._properties.root ??= this.storage.createDirectory(TestBuilder.ROOT_DIR));\n }\n\n setKeyring(keyring: Keyring | PropertyProvider<T, Keyring>): this {\n this._properties.keyring = evaluate(this, keyring);\n return this;\n }\n\n setStorage(storage: Storage, root?: string): this {\n this._properties.storage = evaluate(this, storage);\n if (root) {\n this._properties.root = this.storage.createDirectory(root);\n }\n\n return this;\n }\n\n setRoot(root: Directory): this {\n this._properties.root = evaluate(this, root);\n return this;\n }\n\n createFeedFactory(): FeedFactory<T> {\n return new FeedFactory<T>({\n root: this.root,\n signer: this.keyring,\n hypercore: {\n valueEncoding: this._properties.valueEncoding,\n },\n });\n }\n\n createFeedStore(): FeedStore<T> {\n return new FeedStore<T>({\n factory: this.createFeedFactory(),\n });\n }\n}\n\n/**\n * Builder with default encoder and generator.\n */\nexport class TestItemBuilder extends TestBuilder<TestItem> {\n constructor() {\n super({\n valueEncoding: defaultValueEncoding,\n generator: defaultTestGenerator,\n });\n }\n\n get valueEncoding() {\n return this._properties.valueEncoding!;\n }\n\n get generator() {\n return this._properties.generator!;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { sleep } from '@dxos/async';\nimport { type Codec } from '@dxos/codec-protobuf';\nimport { createCodecEncoding } from '@dxos/hypercore';\nimport { faker } from '@dxos/random';\nimport type { AbstractValueEncoding } from '@dxos/vendor-hypercore/hypercore';\n\nimport { type FeedWriter } from '../feed-writer';\n\nexport type TestItem = {\n id: string;\n index: number;\n value: string;\n};\n\nexport const defaultCodec: Codec<any> = {\n encode: (obj: any) => Buffer.from(JSON.stringify(obj)),\n decode: (buffer: Uint8Array) => JSON.parse(buffer.toString()),\n};\n\nexport const defaultValueEncoding: AbstractValueEncoding<any> = createCodecEncoding(defaultCodec);\n\nexport type TestBlockGenerator<T> = (i: number) => T;\n\nexport const defaultTestBlockGenerator: TestBlockGenerator<TestItem> = (i) => ({\n id: faker.string.uuid(),\n index: i,\n value: faker.lorem.sentence(),\n});\n\n/**\n * Writes data to feeds.\n */\nexport class TestGenerator<T extends {}> {\n _count = 0;\n\n constructor(private readonly _generate: TestBlockGenerator<T>) {}\n\n async writeBlocks(\n writer: FeedWriter<T>,\n {\n count = 1,\n delay,\n }: {\n count?: number;\n delay?: {\n min: number;\n max: number;\n };\n } = {},\n ) {\n return await Promise.all(\n Array.from(Array(count)).map(async () => {\n const data = this._generate(this._count++);\n const receipt = await writer.write(data);\n if (delay) {\n await sleep(faker.number.int(delay));\n }\n\n return receipt;\n }),\n );\n }\n}\n\nexport const defaultTestGenerator = new TestGenerator<TestItem>(defaultTestBlockGenerator);\n"],
5
- "mappings": ";;;;;;;AAIA,SAASA,OAAOC,oBAAoB;AACpC,SAASC,eAAe;AACxB,SAASC,iBAAiB;;AAOnB,IAAMC,iBAAN,MAAMA;;EACKC,UAAU,IAAIL,MAAAA;EACdM,WAAgB,CAAA;EAEhC,YAAqBC,UAAUJ,UAAUK,OAAM,GAAI;SAA9BD,UAAAA;EAA+B;EAEpD,MAAME,MAAMC,MAAS,EAAEC,WAAU,IAAmB,CAAC,GAA0B;AAC7E,SAAKL,SAASM,KAAKF,IAAAA;AAEnB,UAAMG,UAAwB;MAC5BN,SAAS,KAAKA;MACdO,KAAK,KAAKR,SAASS,SAAS;IAC9B;AAEA,UAAMJ,aAAaE,OAAAA;AAEnBZ,iBAAa,IAAIC,QAAAA,QAAAA;;;QAAW,MAAA;AAC1B,WAAKG,QAAQW,KAAK;QAACN;QAAMG;OAAQ;IACnC,CAAA;AAEA,WAAOA;EACT;AACF;;;AC/BA,SAASI,eAAe;AACxB,SAAuCC,aAAaC,qBAAqB;;;ACDzE,SAASC,aAAa;AAEtB,SAASC,2BAA2B;AACpC,SAASC,aAAa;AAWf,IAAMC,eAA2B;EACtCC,QAAQ,CAACC,QAAaC,OAAOC,KAAKC,KAAKC,UAAUJ,GAAAA,CAAAA;EACjDK,QAAQ,CAACC,WAAuBH,KAAKI,MAAMD,OAAOE,SAAQ,CAAA;AAC5D;AAEO,IAAMC,uBAAmDC,oBAAoBZ,YAAAA;AAI7E,IAAMa,4BAA0D,CAACC,OAAO;EAC7EC,IAAIC,MAAMC,OAAOC,KAAI;EACrBC,OAAOL;EACPM,OAAOJ,MAAMK,MAAMC,SAAQ;AAC7B;AAK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AAS,MAAMW,OAAAA;AAC1C,QAAIK,MAAM;AACR,WAAKX,YAAYW,OAAO,KAAKL,QAAQM,gBAAgBD,IAAAA;IACvD;AAEA,WAAO;EACT;EAEAI,QAAQJ,MAAuB;AAC7B,SAAKX,YAAYW,OAAOhB,SAAS,MAAMgB,IAAAA;AACvC,WAAO;EACT;EAEAK,oBAAoC;AAClC,WAAO,IAAIC,YAAe;MACxBN,MAAM,KAAKA;MACXO,QAAQ,KAAKd;MACbe,WAAW;QACTC,eAAe,KAAKpB,YAAYoB;MAClC;IACF,CAAA;EACF;EAEAC,kBAAgC;AAC9B,WAAO,IAAIC,UAAa;MACtBC,SAAS,KAAKP,kBAAiB;IACjC,CAAA;EACF;AACF;AAKO,IAAMQ,kBAAN,cAA8B1B,YAAAA;EACnC,cAAc;AACZ,UAAM;MACJsB,eAAeK;MACfC,WAAWC;IACb,CAAA;EACF;EAEA,IAAIP,gBAAgB;AAClB,WAAO,KAAKpB,YAAYoB;EAC1B;EAEA,IAAIM,YAAY;AACd,WAAO,KAAK1B,YAAY0B;EAC1B;AACF;",
6
- "names": ["Event", "scheduleTask", "Context", "PublicKey", "MockFeedWriter", "written", "messages", "feedKey", "random", "write", "data", "afterWrite", "push", "receipt", "seq", "length", "emit", "Keyring", "StorageType", "createStorage", "sleep", "createCodecEncoding", "faker", "defaultCodec", "encode", "obj", "Buffer", "from", "JSON", "stringify", "decode", "buffer", "parse", "toString", "defaultValueEncoding", "createCodecEncoding", "defaultTestBlockGenerator", "i", "id", "faker", "string", "uuid", "index", "value", "lorem", "sentence", "TestGenerator", "_count", "_generate", "writeBlocks", "writer", "count", "delay", "Promise", "all", "Array", "map", "data", "receipt", "write", "sleep", "number", "int", "defaultTestGenerator", "evaluate", "builder", "arg", "TestBuilder", "ROOT_DIR", "_properties", "clone", "Object", "assign", "keyring", "Keyring", "storage", "createStorage", "type", "StorageType", "RAM", "root", "createDirectory", "setKeyring", "setStorage", "setRoot", "createFeedFactory", "FeedFactory", "signer", "hypercore", "valueEncoding", "createFeedStore", "FeedStore", "factory", "TestItemBuilder", "defaultValueEncoding", "generator", "defaultTestGenerator"]
4
+ "sourcesContent": ["//\n// Copyright 2022 DXOS.org\n//\n\nimport { Event, scheduleTask } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\n\nimport type { FeedWriter, WriteOptions, WriteReceipt } from '../feed-writer';\n\n/**\n * Mock writer collects and emits messages.\n */\nexport class MockFeedWriter<T extends {}> implements FeedWriter<T> {\n public readonly written = new Event<[T, WriteReceipt]>();\n public readonly messages: T[] = [];\n\n constructor(readonly feedKey = PublicKey.random()) {}\n\n async write(data: T, { afterWrite }: WriteOptions = {}): Promise<WriteReceipt> {\n this.messages.push(data);\n\n const receipt: WriteReceipt = {\n feedKey: this.feedKey,\n seq: this.messages.length - 1,\n };\n\n await afterWrite?.(receipt);\n\n scheduleTask(new Context(), () => {\n this.written.emit([data, receipt]);\n });\n\n return receipt;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Keyring } from '@dxos/keyring';\nimport { type Directory, type Storage, StorageType, createStorage } from '@dxos/random-access-storage';\nimport type { ValueEncoding } from '@dxos/vendor-hypercore/hypercore';\n\nimport { FeedFactory } from '../feed-factory';\nimport { FeedStore } from '../feed-store';\nimport { type TestGenerator, type TestItem, defaultTestGenerator, defaultValueEncoding } from './test-generator';\n\nexport type TestBuilderOptions<T extends {}> = {\n storage?: Storage;\n root?: Directory;\n keyring?: Keyring;\n valueEncoding?: ValueEncoding<T>;\n generator?: TestGenerator<T>;\n};\n\ntype PropertyProvider<T extends {}, P> = (cb: TestBuilder<T>) => P;\n\nconst evaluate = <T extends {}, P>(builder: TestBuilder<T>, arg: P | PropertyProvider<T, P>) =>\n arg === 'function' ? (arg as Function)(builder) : arg;\n\n/**\n * The builder provides building blocks for tests with sensible defaults.\n * - Factory methods trigger the automatic generation of unset required properties.\n * - Avoids explosion of overly specific test functions that require and return large bags of properties.\n */\nexport class TestBuilder<T extends {}> {\n static readonly ROOT_DIR = 'feeds';\n\n constructor(public readonly _properties: TestBuilderOptions<T> = {}) {}\n\n /**\n * Creates a new builder with the current builder's properties.\n */\n clone(): TestBuilder<T> {\n return new TestBuilder<T>(Object.assign({}, this._properties));\n }\n\n get keyring(): Keyring {\n return (this._properties.keyring ??= new Keyring());\n }\n\n get storage(): Storage {\n return (this._properties.storage ??= createStorage({ type: StorageType.RAM }));\n }\n\n get root(): Directory {\n return (this._properties.root ??= this.storage.createDirectory(TestBuilder.ROOT_DIR));\n }\n\n setKeyring(keyring: Keyring | PropertyProvider<T, Keyring>): this {\n this._properties.keyring = evaluate(this, keyring);\n return this;\n }\n\n setStorage(storage: Storage, root?: string): this {\n this._properties.storage = evaluate(this, storage);\n if (root) {\n this._properties.root = this.storage.createDirectory(root);\n }\n\n return this;\n }\n\n setRoot(root: Directory): this {\n this._properties.root = evaluate(this, root);\n return this;\n }\n\n createFeedFactory(): FeedFactory<T> {\n return new FeedFactory<T>({\n root: this.root,\n signer: this.keyring,\n hypercore: {\n valueEncoding: this._properties.valueEncoding,\n },\n });\n }\n\n createFeedStore(): FeedStore<T> {\n return new FeedStore<T>({\n factory: this.createFeedFactory(),\n });\n }\n}\n\n/**\n * Builder with default encoder and generator.\n */\nexport class TestItemBuilder extends TestBuilder<TestItem> {\n constructor() {\n super({\n valueEncoding: defaultValueEncoding,\n generator: defaultTestGenerator,\n });\n }\n\n get valueEncoding() {\n return this._properties.valueEncoding!;\n }\n\n get generator() {\n return this._properties.generator!;\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { sleep } from '@dxos/async';\nimport { type Codec } from '@dxos/codec-protobuf';\nimport { createCodecEncoding } from '@dxos/hypercore';\nimport { random } from '@dxos/random';\nimport type { AbstractValueEncoding } from '@dxos/vendor-hypercore/hypercore';\n\nimport { type FeedWriter } from '../feed-writer';\n\nexport type TestItem = {\n id: string;\n index: number;\n value: string;\n};\n\nexport const defaultCodec: Codec<any> = {\n encode: (obj: any) => Buffer.from(JSON.stringify(obj)),\n decode: (buffer: Uint8Array) => JSON.parse(buffer.toString()),\n};\n\nexport const defaultValueEncoding: AbstractValueEncoding<any> = createCodecEncoding(defaultCodec);\n\nexport type TestBlockGenerator<T> = (i: number) => T;\n\nexport const defaultTestBlockGenerator: TestBlockGenerator<TestItem> = (i) => ({\n id: random.string.uuid(),\n index: i,\n value: random.lorem.sentence(),\n});\n\n/**\n * Writes data to feeds.\n */\nexport class TestGenerator<T extends {}> {\n _count = 0;\n\n constructor(private readonly _generate: TestBlockGenerator<T>) {}\n\n async writeBlocks(\n writer: FeedWriter<T>,\n {\n count = 1,\n delay,\n }: {\n count?: number;\n delay?: {\n min: number;\n max: number;\n };\n } = {},\n ) {\n return await Promise.all(\n Array.from(Array(count)).map(async () => {\n const data = this._generate(this._count++);\n const receipt = await writer.write(data);\n if (delay) {\n await sleep(random.number.int(delay));\n }\n\n return receipt;\n }),\n );\n }\n}\n\nexport const defaultTestGenerator = new TestGenerator<TestItem>(defaultTestBlockGenerator);\n"],
5
+ "mappings": ";;;;;;;AAIA,SAASA,OAAOC,oBAAoB;AACpC,SAASC,eAAe;AACxB,SAASC,iBAAiB;;AAOnB,IAAMC,iBAAN,MAAMA;;EACKC,UAAU,IAAIL,MAAAA;EACdM,WAAgB,CAAA;EAEhC,YAAqBC,UAAUJ,UAAUK,OAAM,GAAI;SAA9BD,UAAAA;EAA+B;EAEpD,MAAME,MAAMC,MAAS,EAAEC,WAAU,IAAmB,CAAC,GAA0B;AAC7E,SAAKL,SAASM,KAAKF,IAAAA;AAEnB,UAAMG,UAAwB;MAC5BN,SAAS,KAAKA;MACdO,KAAK,KAAKR,SAASS,SAAS;IAC9B;AAEA,UAAMJ,aAAaE,OAAAA;AAEnBZ,iBAAa,IAAIC,QAAAA,QAAAA;;;QAAW,MAAA;AAC1B,WAAKG,QAAQW,KAAK;QAACN;QAAMG;OAAQ;IACnC,CAAA;AAEA,WAAOA;EACT;AACF;;;AC/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WAAW,CAAA;EAC9D;EAEA,IAAII,UAAmB;AACrB,WAAQ,KAAKJ,YAAYI,YAAY,IAAIC,QAAAA;EAC3C;EAEA,IAAIC,UAAmB;AACrB,WAAQ,KAAKN,YAAYM,YAAYC,cAAc;MAAEC,MAAMC,YAAYC;IAAI,CAAA;EAC7E;EAEA,IAAIC,OAAkB;AACpB,WAAQ,KAAKX,YAAYW,SAAS,KAAKL,QAAQM,gBAAgBd,aAAYC,QAAQ;EACrF;EAEAc,WAAWT,SAAuD;AAChE,SAAKJ,YAAYI,UAAUT,SAAS,MAAMS,OAAAA;AAC1C,WAAO;EACT;EAEAU,WAAWR,SAAkBK,MAAqB;AAChD,SAAKX,YAAYM,UAAUX,SAAS,MAAMW,OAAAA;AAC1C,QAAIK,MAAM;AACR,WAAKX,YAAYW,OAAO,KAAKL,QAAQM,gBAAgBD,IAAAA;IACvD;AAEA,WAAO;EACT;EAEAI,QAAQJ,MAAuB;AAC7B,SAAKX,YAAYW,OAAOhB,SAAS,MAAMgB,IAAAA;AACvC,WAAO;EACT;EAEAK,oBAAoC;AAClC,WAAO,IAAIC,YAAe;MACxBN,MAAM,KAAKA;MACXO,QAAQ,KAAKd;MACbe,WAAW;QACTC,eAAe,KAAKpB,YAAYoB;MAClC;IACF,CAAA;EACF;EAEAC,kBAAgC;AAC9B,WAAO,IAAIC,UAAa;MACtBC,SAAS,KAAKP,kBAAiB;IACjC,CAAA;EACF;AACF;AAKO,IAAMQ,kBAAN,cAA8B1B,YAAAA;EACnC,cAAc;AACZ,UAAM;MACJsB,eAAeK;MACfC,WAAWC;IACb,CAAA;EACF;EAEA,IAAIP,gBAAgB;AAClB,WAAO,KAAKpB,YAAYoB;EAC1B;EAEA,IAAIM,YAAY;AACd,WAAO,KAAK1B,YAAY0B;EAC1B;AACF;",
6
+ "names": ["Event", "scheduleTask", "Context", "PublicKey", "MockFeedWriter", "written", "messages", "feedKey", "random", "write", "data", "afterWrite", "push", "receipt", "seq", "length", "emit", "Keyring", "StorageType", "createStorage", "sleep", "createCodecEncoding", "random", "defaultCodec", "encode", "obj", "Buffer", "from", "JSON", "stringify", "decode", "buffer", "parse", "toString", "defaultValueEncoding", "createCodecEncoding", "defaultTestBlockGenerator", "i", "id", "random", "string", "uuid", "index", "value", "lorem", "sentence", "TestGenerator", "_count", "_generate", "writeBlocks", "writer", "count", "delay", "Promise", "all", "Array", "map", "data", "receipt", "write", "sleep", "number", "int", "defaultTestGenerator", "evaluate", "builder", "arg", "TestBuilder", "ROOT_DIR", "_properties", "clone", "Object", "assign", "keyring", "Keyring", "storage", "createStorage", "type", "StorageType", "RAM", "root", "createDirectory", "setKeyring", "setStorage", "setRoot", "createFeedFactory", "FeedFactory", "signer", "hypercore", "valueEncoding", "createFeedStore", "FeedStore", "factory", "TestItemBuilder", "defaultValueEncoding", "generator", "defaultTestGenerator"]
7
7
  }
@@ -25,7 +25,7 @@ var FeedWrapper = class {
25
25
  this._hypercore = hypercore2;
26
26
  invariant(this._key, void 0, {
27
27
  F: __dxlog_file,
28
- L: 41,
28
+ L: 40,
29
29
  S: this,
30
30
  A: [
31
31
  "this._key",
@@ -78,13 +78,13 @@ var FeedWrapper = class {
78
78
  seq: this._hypercore.length
79
79
  }, {
80
80
  F: __dxlog_file,
81
- L: 100,
81
+ L: 99,
82
82
  S: this,
83
83
  C: (f, a) => f(...a)
84
84
  });
85
85
  invariant(!this._closed, "Feed closed", {
86
86
  F: __dxlog_file,
87
- L: 101,
87
+ L: 100,
88
88
  S: this,
89
89
  A: [
90
90
  "!this._closed",
@@ -114,7 +114,7 @@ var FeedWrapper = class {
114
114
  const seq = await this.append(data);
115
115
  invariant(seq < this.length, "Invalid seq after write", {
116
116
  F: __dxlog_file,
117
- L: 132,
117
+ L: 131,
118
118
  S: this,
119
119
  A: [
120
120
  "seq < this.length",
@@ -126,7 +126,7 @@ var FeedWrapper = class {
126
126
  seq
127
127
  }, {
128
128
  F: __dxlog_file,
129
- L: 133,
129
+ L: 132,
130
130
  S: this,
131
131
  C: (f, a) => f(...a)
132
132
  });
@@ -178,7 +178,7 @@ var FeedWrapper = class {
178
178
  pendingWrites: Array.from(this._pendingWrites.values()).map((stack) => stack.getStack())
179
179
  }, {
180
180
  F: __dxlog_file,
181
- L: 187,
181
+ L: 186,
182
182
  S: this,
183
183
  C: (f, a) => f(...a)
184
184
  });
@@ -230,7 +230,7 @@ var FeedWrapper = class {
230
230
  async safeClear(from, to) {
231
231
  invariant(from >= 0 && from < to && to <= this.length, "Invalid range", {
232
232
  F: __dxlog_file,
233
- L: 250,
233
+ L: 249,
234
234
  S: this,
235
235
  A: [
236
236
  "from >= 0 && from < to && to <= this.length",
@@ -271,7 +271,7 @@ var BatchedReadStream = class extends Readable {
271
271
  });
272
272
  invariant(opts.live === true, "Only live mode supported", {
273
273
  F: __dxlog_file,
274
- L: 292,
274
+ L: 291,
275
275
  S: this,
276
276
  A: [
277
277
  "opts.live === true",
@@ -280,7 +280,7 @@ var BatchedReadStream = class extends Readable {
280
280
  });
281
281
  invariant(opts.batch !== void 0 && opts.batch > 1, void 0, {
282
282
  F: __dxlog_file,
283
- L: 293,
283
+ L: 292,
284
284
  S: this,
285
285
  A: [
286
286
  "opts.batch !== undefined && opts.batch > 1",
@@ -529,4 +529,4 @@ export {
529
529
  FeedFactory,
530
530
  FeedStore
531
531
  };
532
- //# sourceMappingURL=chunk-HJBZDWE4.mjs.map
532
+ //# sourceMappingURL=chunk-ASTXJ5EK.mjs.map