@vrtmrz/livesync-commonlib 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +4 -0
  2. package/dist/common/models/diff.definition.d.ts +4 -0
  3. package/dist/common/utils.d.ts +1 -1
  4. package/dist/common/utils.doc.d.ts +5 -0
  5. package/dist/common/utils.doc.js +8 -0
  6. package/dist/common/utils.js +1 -3
  7. package/dist/conflicts/filenameCaseConflict.d.ts +8 -0
  8. package/dist/conflicts/filenameCaseConflict.js +26 -0
  9. package/dist/conflicts.d.ts +1 -0
  10. package/dist/conflicts.js +9 -1
  11. package/dist/interfaces/DatabaseFileAccess.d.ts +12 -1
  12. package/dist/interfaces/FileReflectionProvenance.js +1 -0
  13. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  14. package/dist/managers/ConflictManager.d.ts +6 -2
  15. package/dist/managers/ConflictManager.js +73 -22
  16. package/dist/managers/EntryManager/EntryManager.d.ts +5 -0
  17. package/dist/managers/EntryManager/EntryManager.js +5 -0
  18. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +5 -1
  19. package/dist/managers/EntryManager/EntryManagerImpls.js +92 -6
  20. package/dist/managers/LiveSyncManagers.js +2 -1
  21. package/dist/managers/StorageEventManager/admission.d.ts +15 -3
  22. package/dist/managers/StorageEventManager/admission.js +13 -3
  23. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  24. package/dist/managers/StorageEventManager/processing.js +3 -3
  25. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  26. package/dist/managers/StorageEventManager/queue.js +70 -30
  27. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  28. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  29. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  30. package/dist/managers/StorageEventManager/state.js +9 -7
  31. package/dist/managers/StorageEventManager.d.ts +6 -0
  32. package/dist/managers/StorageEventManager.js +135 -18
  33. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  34. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  35. package/dist/managers/adapters/index.d.ts +1 -1
  36. package/dist/pouchdb/LiveSyncLocalDB.js +3 -4
  37. package/dist/replication/index.d.ts +2 -0
  38. package/dist/replication/index.js +2 -0
  39. package/dist/replication/replicationResultQueueStore.d.ts +101 -0
  40. package/dist/replication/replicationResultQueueStore.js +140 -0
  41. package/dist/serviceFeatures/offlineScanner/files.js +15 -3
  42. package/dist/serviceFeatures/offlineScanner/scan.js +1 -4
  43. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +5 -4
  44. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +28 -7
  45. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +8 -2
  46. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +52 -9
  47. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +30 -0
  48. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +82 -10
  49. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +118 -12
  50. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +32 -8
  51. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +2 -8
  52. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +4 -5
  53. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  54. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  55. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  56. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  57. package/dist/worker/WorkerPushStreamReader.js +179 -0
  58. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  59. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  60. package/dist/worker/bg.worker.js +2 -16
  61. package/dist/worker/bg.worker.splitting.d.ts +3 -7
  62. package/dist/worker/bg.worker.splitting.js +46 -47
  63. package/dist/worker/bgWorker.d.ts +8 -14
  64. package/dist/worker/bgWorker.direct.d.ts +5 -28
  65. package/dist/worker/bgWorker.direct.js +32 -2
  66. package/dist/worker/bgWorker.errors.d.ts +1 -0
  67. package/dist/worker/bgWorker.errors.js +12 -0
  68. package/dist/worker/bgWorker.js +716 -296
  69. package/dist/worker/bgWorker.splitting.d.ts +12 -26
  70. package/dist/worker/bgWorker.splitting.js +115 -107
  71. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  72. package/dist/worker/outOfBandCancelIterator.js +8 -0
  73. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  74. package/dist/worker/serveBackgroundWorker.js +35 -0
  75. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  76. package/dist/worker/splitConnectionTracker.js +73 -0
  77. package/dist/worker/splitGate.d.ts +19 -0
  78. package/dist/worker/splitGate.js +71 -0
  79. package/dist/worker/universalTypes.d.ts +0 -30
  80. package/dist/worker/universalTypes.js +0 -4
  81. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  82. package/dist/worker/workerPushStreamProtocol.js +143 -0
  83. package/docs/conflict-resolution.md +22 -8
  84. package/docs/development.md +6 -0
  85. package/docs/offline-scanner.md +2 -0
  86. package/docs/storage-events-and-reflection.md +171 -2
  87. package/package.json +1 -1
  88. package/dist/worker/bg.common.d.ts +0 -2
  89. package/dist/worker/bg.common.js +0 -6
  90. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  91. package/dist/worker/bg.worker.encryption.js +0 -30
  92. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  93. package/dist/worker/bgWorker.encryption.js +0 -40
@@ -0,0 +1,299 @@
1
+ import { RpcError, withTransfer } from "@vrtmrz/rpc";
2
+ import {
3
+ VERSION,
4
+ DEFAULT_BATCH_TARGET_BYTES,
5
+ DEFAULT_CLAIM_TIMEOUT_MS,
6
+ DEFAULT_MAX_BATCH_ITEMS,
7
+ canSend,
8
+ checkLimits,
9
+ deserialiseError,
10
+ disconnected,
11
+ isPositiveSafeInteger,
12
+ isRecord,
13
+ isWireError,
14
+ measureItem,
15
+ protocolError,
16
+ serialiseError
17
+ } from "./workerPushStreamProtocol.js";
18
+ class WorkerPushStreamProducer {
19
+ constructor(options) {
20
+ this.options = options;
21
+ const {
22
+ batchTargetBytes = DEFAULT_BATCH_TARGET_BYTES,
23
+ maxBatchItems = DEFAULT_MAX_BATCH_ITEMS,
24
+ claimTimeoutMs = DEFAULT_CLAIM_TIMEOUT_MS,
25
+ signal
26
+ } = options;
27
+ this.batchTargetBytes = batchTargetBytes;
28
+ this.maxBatchItems = maxBatchItems;
29
+ this.signal = signal;
30
+ checkLimits(options.maxItemBytes, this.batchTargetBytes, this.maxBatchItems, claimTimeoutMs);
31
+ const { port1, port2 } = new MessageChannel();
32
+ this.producerPort = port1;
33
+ this.readerPort = port2;
34
+ this.claimTimer = setTimeout(
35
+ () => this.finish({ error: new RpcError("timeout", "Worker stream port was not claimed.") }),
36
+ claimTimeoutMs
37
+ );
38
+ this.producerPort.addEventListener("message", this.onMessage);
39
+ this.producerPort.addEventListener("messageerror", this.onMessageError);
40
+ this.producerPort.addEventListener("close", this.onClose);
41
+ signal?.addEventListener("abort", this.onAbort, { once: true });
42
+ this.producerPort.start();
43
+ if (signal?.aborted) {
44
+ this.onAbort();
45
+ }
46
+ }
47
+ options;
48
+ readerPort;
49
+ producerPort;
50
+ controller = new AbortController();
51
+ batchTargetBytes;
52
+ maxBatchItems;
53
+ signal;
54
+ source;
55
+ finished = false;
56
+ pumping = false;
57
+ initialGrant = 0;
58
+ inFlightBytes = 0;
59
+ oversizedInFlight = false;
60
+ batch = [];
61
+ batchCharge = 0;
62
+ stagedItem;
63
+ flushTimer;
64
+ yieldChannel;
65
+ yieldAfterBatch;
66
+ resolveYield;
67
+ claimTimer;
68
+ post(message) {
69
+ this.producerPort.postMessage(message);
70
+ }
71
+ /** Unblock the pump and close both ends of its scheduling channel. */
72
+ clearYield() {
73
+ const resolve = this.resolveYield;
74
+ this.resolveYield = void 0;
75
+ this.yieldAfterBatch = void 0;
76
+ resolve?.();
77
+ if (this.yieldChannel !== void 0) {
78
+ this.yieldChannel.port1.onmessage = null;
79
+ this.yieldChannel.port1.close();
80
+ this.yieldChannel.port2.close();
81
+ this.yieldChannel = void 0;
82
+ }
83
+ }
84
+ /** Let pending port events run between batches without relying on a timer. */
85
+ scheduleYield() {
86
+ if (this.yieldAfterBatch !== void 0) {
87
+ return;
88
+ }
89
+ if (this.yieldChannel === void 0) {
90
+ this.yieldChannel = new MessageChannel();
91
+ }
92
+ const channel = this.yieldChannel;
93
+ this.yieldAfterBatch = new Promise((resolve) => {
94
+ this.resolveYield = resolve;
95
+ channel.port1.onmessage = () => {
96
+ if (this.resolveYield === resolve) {
97
+ this.resolveYield = void 0;
98
+ this.yieldAfterBatch = void 0;
99
+ resolve();
100
+ }
101
+ };
102
+ channel.port2.postMessage(void 0);
103
+ });
104
+ }
105
+ finish(failure, notifyPeer = true) {
106
+ if (this.finished) {
107
+ return;
108
+ }
109
+ this.finished = true;
110
+ clearTimeout(this.claimTimer);
111
+ clearTimeout(this.flushTimer);
112
+ this.clearYield();
113
+ this.batch = [];
114
+ this.stagedItem = void 0;
115
+ this.producerPort.removeEventListener("message", this.onMessage);
116
+ this.producerPort.removeEventListener("messageerror", this.onMessageError);
117
+ this.producerPort.removeEventListener("close", this.onClose);
118
+ this.signal?.removeEventListener("abort", this.onAbort);
119
+ try {
120
+ if (failure && notifyPeer) {
121
+ this.post({ version: VERSION, type: "error", error: serialiseError(failure.error) });
122
+ }
123
+ } catch {
124
+ } finally {
125
+ this.producerPort.close();
126
+ if (failure || this.source) {
127
+ this.controller.abort(failure?.error);
128
+ }
129
+ if (this.source) {
130
+ try {
131
+ void Promise.resolve(this.source.return?.()).catch(() => void 0);
132
+ } catch {
133
+ }
134
+ this.source = void 0;
135
+ }
136
+ }
137
+ }
138
+ postBatch(shouldYield) {
139
+ this.post({ version: VERSION, type: "batch", items: this.batch, chargeBytes: this.batchCharge });
140
+ this.inFlightBytes += this.batchCharge;
141
+ this.oversizedInFlight = this.batchCharge > this.initialGrant;
142
+ this.batch = [];
143
+ this.batchCharge = 0;
144
+ if (shouldYield) {
145
+ this.scheduleYield();
146
+ }
147
+ }
148
+ flushWhileReading = () => {
149
+ if (!this.finished && this.batch.length > 0) {
150
+ try {
151
+ this.postBatch(true);
152
+ } catch (error) {
153
+ this.finish({ error });
154
+ }
155
+ }
156
+ };
157
+ /** Flush a full batch before admitting the staged item against the remaining credit. */
158
+ admitStagedItem(limit) {
159
+ const next = this.stagedItem;
160
+ if (this.batch.length > 0 && next.charge > limit - this.batchCharge) {
161
+ this.postBatch(true);
162
+ return "continue";
163
+ }
164
+ if (!canSend(next.charge, this.inFlightBytes, this.initialGrant)) {
165
+ return "wait";
166
+ }
167
+ this.batch.push(next.item);
168
+ this.batchCharge += next.charge;
169
+ this.stagedItem = void 0;
170
+ if (this.batchCharge >= limit || this.batch.length === this.maxBatchItems) {
171
+ this.postBatch(true);
172
+ }
173
+ return "continue";
174
+ }
175
+ /** Flush an accumulated batch if the source takes another task to produce an item. */
176
+ async readNextItem(iterator) {
177
+ if (this.batch.length > 0) {
178
+ this.flushTimer = setTimeout(this.flushWhileReading, 0);
179
+ }
180
+ try {
181
+ return await iterator.next();
182
+ } finally {
183
+ clearTimeout(this.flushTimer);
184
+ }
185
+ }
186
+ async pump(iterator) {
187
+ if (this.pumping) {
188
+ return;
189
+ }
190
+ this.pumping = true;
191
+ try {
192
+ while (!this.finished) {
193
+ if (this.yieldAfterBatch !== void 0) {
194
+ await this.yieldAfterBatch;
195
+ if (this.finished) {
196
+ return;
197
+ }
198
+ }
199
+ if (this.oversizedInFlight) {
200
+ return;
201
+ }
202
+ const available = this.initialGrant - this.inFlightBytes;
203
+ const limit = Math.min(this.batchTargetBytes, available);
204
+ if (this.stagedItem !== void 0) {
205
+ if (this.admitStagedItem(limit) === "wait") {
206
+ return;
207
+ }
208
+ continue;
209
+ }
210
+ if (available <= 0) {
211
+ return;
212
+ }
213
+ const result = await this.readNextItem(iterator);
214
+ if (this.finished) {
215
+ return;
216
+ }
217
+ if (result.done) {
218
+ if (this.batch.length > 0) {
219
+ this.postBatch(false);
220
+ }
221
+ this.post({ version: VERSION, type: "end" });
222
+ this.source = void 0;
223
+ this.finish();
224
+ return;
225
+ }
226
+ this.stagedItem = { item: result.value, charge: measureItem(this.options, result.value) };
227
+ }
228
+ } catch (error) {
229
+ this.finish({ error });
230
+ } finally {
231
+ this.pumping = false;
232
+ }
233
+ }
234
+ applyCancel(rawError) {
235
+ if (rawError === void 0) {
236
+ this.finish({ error: new RpcError("aborted", "Worker stream reader cancelled.") }, false);
237
+ } else if (isWireError(rawError)) {
238
+ this.finish({ error: deserialiseError(rawError) }, false);
239
+ } else {
240
+ this.finish({ error: protocolError("Invalid Worker stream cancellation error.") });
241
+ }
242
+ }
243
+ applyCredit(bytes) {
244
+ if (this.initialGrant === 0) {
245
+ this.initialGrant = bytes;
246
+ clearTimeout(this.claimTimer);
247
+ try {
248
+ this.source = this.options.createSource(this.controller.signal)[Symbol.asyncIterator]();
249
+ } catch (error) {
250
+ this.finish({ error });
251
+ return;
252
+ }
253
+ } else {
254
+ if (bytes > this.inFlightBytes) {
255
+ this.finish({ error: protocolError("Worker stream refunded more than the outstanding charge.") });
256
+ return;
257
+ }
258
+ this.inFlightBytes -= bytes;
259
+ if (this.inFlightBytes === 0) {
260
+ this.oversizedInFlight = false;
261
+ }
262
+ }
263
+ if (this.source) {
264
+ void this.pump(this.source);
265
+ }
266
+ }
267
+ onMessage = ({ data }) => {
268
+ if (!isRecord(data) || data.version !== VERSION) {
269
+ this.finish({ error: protocolError("Invalid Worker stream reader message.") });
270
+ return;
271
+ }
272
+ if (data.type === "cancel") {
273
+ this.applyCancel(data.error);
274
+ return;
275
+ }
276
+ if (data.type !== "credit" || !isPositiveSafeInteger(data.bytes)) {
277
+ this.finish({ error: protocolError("Invalid Worker stream credit.") });
278
+ return;
279
+ }
280
+ this.applyCredit(data.bytes);
281
+ };
282
+ onMessageError = () => {
283
+ this.finish({ error: protocolError("Could not decode Worker stream reader message.") });
284
+ };
285
+ onClose = () => {
286
+ this.finish({ error: new RpcError("disconnected", "Worker stream port closed unexpectedly.") }, false);
287
+ };
288
+ onAbort = () => {
289
+ this.finish({ error: disconnected(this.signal) });
290
+ };
291
+ }
292
+ function serveWorkerPushStream(options) {
293
+ const { readerPort } = new WorkerPushStreamProducer(options);
294
+ return withTransfer(readerPort, [readerPort]);
295
+ }
296
+ export {
297
+ WorkerPushStreamProducer,
298
+ serveWorkerPushStream
299
+ };
@@ -0,0 +1,28 @@
1
+ import { type ReadOptions } from "./workerPushStreamProtocol.js";
2
+ export declare class WorkerPushStreamReader<T> {
3
+ private readonly options;
4
+ private readonly port;
5
+ private readonly initialCreditBytes;
6
+ private readonly maxBatchItems;
7
+ private readonly signal;
8
+ private readonly onRemoteEnd;
9
+ private readonly onError;
10
+ private readonly queue;
11
+ private inFlightBytes;
12
+ private remoteEnded;
13
+ private outcome;
14
+ private waiting;
15
+ constructor(options: ReadOptions<T>);
16
+ start(): void;
17
+ cancel(): void;
18
+ private detach;
19
+ private finish;
20
+ private acceptBatch;
21
+ private onMessage;
22
+ private onMessageError;
23
+ private onClose;
24
+ private onAbort;
25
+ private sendCredit;
26
+ read(): AsyncGenerator<readonly T[], void, unknown>;
27
+ }
28
+ export declare function readWorkerPushStream<T>(options: ReadOptions<T>): AsyncGenerator<readonly T[], void, unknown>;
@@ -0,0 +1,179 @@
1
+ import { RpcError } from "@vrtmrz/rpc";
2
+ import { promiseWithResolvers } from "octagonal-wheels/promises";
3
+ import {
4
+ VERSION,
5
+ DEFAULT_INITIAL_CREDIT_BYTES,
6
+ DEFAULT_MAX_BATCH_ITEMS,
7
+ cancelWorkerPushStream,
8
+ checkLimits,
9
+ deserialiseError,
10
+ disconnected,
11
+ isRecord,
12
+ isWireError,
13
+ protocolError,
14
+ stopGeneratorOnReturn,
15
+ validateBatch
16
+ } from "./workerPushStreamProtocol.js";
17
+ class WorkerPushStreamReader {
18
+ constructor(options) {
19
+ this.options = options;
20
+ const {
21
+ port,
22
+ signal,
23
+ onRemoteEnd,
24
+ onError,
25
+ initialCreditBytes = DEFAULT_INITIAL_CREDIT_BYTES,
26
+ maxBatchItems = DEFAULT_MAX_BATCH_ITEMS
27
+ } = options;
28
+ this.port = port;
29
+ this.initialCreditBytes = initialCreditBytes;
30
+ this.maxBatchItems = maxBatchItems;
31
+ this.signal = signal;
32
+ this.onRemoteEnd = onRemoteEnd;
33
+ this.onError = onError;
34
+ checkLimits(options.maxItemBytes, this.initialCreditBytes, this.maxBatchItems);
35
+ }
36
+ options;
37
+ port;
38
+ initialCreditBytes;
39
+ maxBatchItems;
40
+ signal;
41
+ onRemoteEnd;
42
+ onError;
43
+ queue = [];
44
+ inFlightBytes = 0;
45
+ remoteEnded = false;
46
+ outcome;
47
+ waiting;
48
+ start() {
49
+ this.port.addEventListener("message", this.onMessage);
50
+ this.port.addEventListener("messageerror", this.onMessageError);
51
+ this.port.addEventListener("close", this.onClose);
52
+ this.signal?.addEventListener("abort", this.onAbort, { once: true });
53
+ this.port.start();
54
+ if (this.signal?.aborted) {
55
+ this.onAbort();
56
+ } else {
57
+ this.sendCredit(this.initialCreditBytes);
58
+ }
59
+ }
60
+ cancel() {
61
+ this.finish("return");
62
+ }
63
+ detach() {
64
+ this.port.removeEventListener("message", this.onMessage);
65
+ this.port.removeEventListener("messageerror", this.onMessageError);
66
+ this.port.removeEventListener("close", this.onClose);
67
+ this.signal?.removeEventListener("abort", this.onAbort);
68
+ }
69
+ finish(result, notifyPeer = true) {
70
+ if (this.outcome !== void 0) {
71
+ return;
72
+ }
73
+ this.outcome = result;
74
+ this.queue.length = 0;
75
+ this.waiting?.resolve();
76
+ if (!this.remoteEnded) {
77
+ this.detach();
78
+ if (notifyPeer) {
79
+ cancelWorkerPushStream(this.port, result === "return" ? void 0 : result);
80
+ } else {
81
+ this.port.close();
82
+ }
83
+ }
84
+ if (result !== "return") {
85
+ const { onError } = this;
86
+ onError?.(result.error);
87
+ }
88
+ }
89
+ acceptBatch(data) {
90
+ const batch = validateBatch(
91
+ this.options,
92
+ data,
93
+ this.maxBatchItems,
94
+ this.inFlightBytes,
95
+ this.initialCreditBytes
96
+ );
97
+ this.inFlightBytes += batch.chargeBytes;
98
+ this.queue.push(batch);
99
+ this.waiting?.resolve();
100
+ }
101
+ onMessage = ({ data }) => {
102
+ try {
103
+ if (!isRecord(data) || data.version !== VERSION) {
104
+ throw protocolError("Invalid Worker stream producer message.");
105
+ }
106
+ switch (data.type) {
107
+ case "batch":
108
+ this.acceptBatch(data);
109
+ return;
110
+ case "end": {
111
+ this.remoteEnded = true;
112
+ this.detach();
113
+ this.port.close();
114
+ this.waiting?.resolve();
115
+ const { onRemoteEnd } = this;
116
+ onRemoteEnd?.();
117
+ return;
118
+ }
119
+ case "error":
120
+ if (isWireError(data.error)) {
121
+ this.finish({ error: deserialiseError(data.error) }, false);
122
+ return;
123
+ }
124
+ }
125
+ throw protocolError("Invalid Worker stream producer message type or error.");
126
+ } catch (error) {
127
+ this.finish({ error });
128
+ }
129
+ };
130
+ onMessageError = () => {
131
+ this.finish({ error: protocolError("Could not decode Worker stream producer message.") });
132
+ };
133
+ onClose = () => {
134
+ if (!this.remoteEnded) {
135
+ this.finish({ error: new RpcError("disconnected", "Worker stream port closed unexpectedly.") }, false);
136
+ }
137
+ };
138
+ onAbort = () => {
139
+ this.finish({ error: disconnected(this.signal) });
140
+ };
141
+ sendCredit(bytes) {
142
+ try {
143
+ const message = { version: VERSION, type: "credit", bytes };
144
+ this.port.postMessage(message);
145
+ } catch (error) {
146
+ this.finish({ error });
147
+ }
148
+ }
149
+ async *read() {
150
+ while (this.outcome === void 0) {
151
+ const batch = this.queue.shift();
152
+ if (batch !== void 0) {
153
+ yield batch.items;
154
+ if (this.outcome === void 0 && !this.remoteEnded) {
155
+ this.inFlightBytes -= batch.chargeBytes;
156
+ this.sendCredit(batch.chargeBytes);
157
+ }
158
+ } else if (this.remoteEnded) {
159
+ return;
160
+ } else {
161
+ this.waiting = promiseWithResolvers();
162
+ await this.waiting.promise;
163
+ this.waiting = void 0;
164
+ }
165
+ }
166
+ if (this.outcome !== "return") {
167
+ throw this.outcome.error;
168
+ }
169
+ }
170
+ }
171
+ function readWorkerPushStream(options) {
172
+ const reader = new WorkerPushStreamReader(options);
173
+ reader.start();
174
+ return stopGeneratorOnReturn(reader.read(), () => reader.cancel());
175
+ }
176
+ export {
177
+ WorkerPushStreamReader,
178
+ readWorkerPushStream
179
+ };
@@ -0,0 +1,18 @@
1
+ import type { SplitArguments } from "./universalTypes.js";
2
+ export type WorkerSplitRequest = Omit<SplitArguments, "type" | "key">;
3
+ type EncryptionArguments = [input: string, passphrase: string, autoCalculateIterations: boolean];
4
+ type HkdfEncryptionArguments = [input: string, passphrase: string, salt: Uint8Array<ArrayBuffer>];
5
+ export declare const backgroundWorkerContract: {
6
+ readonly split: import("@vrtmrz/rpc").CallMethodDescriptor<[request: WorkerSplitRequest], MessagePort, import("@vrtmrz/rpc").TransferRequirement, "required">;
7
+ readonly encrypt: import("@vrtmrz/rpc").CallMethodDescriptor<EncryptionArguments, string, "none", "none">;
8
+ readonly decrypt: import("@vrtmrz/rpc").CallMethodDescriptor<EncryptionArguments, string, "none", "none">;
9
+ readonly encryptHKDF: import("@vrtmrz/rpc").CallMethodDescriptor<HkdfEncryptionArguments, string, "none", "none">;
10
+ readonly decryptHKDF: import("@vrtmrz/rpc").CallMethodDescriptor<HkdfEncryptionArguments, string, "none", "none">;
11
+ };
12
+ export declare function splitChunkCapacity(dataSrc: Blob): number;
13
+ export declare function splitStreamItems(dataSrc: Blob): {
14
+ isItem: (item: unknown) => item is string;
15
+ chargeItem: (item: string) => number;
16
+ maxItemBytes: number;
17
+ };
18
+ export {};
@@ -0,0 +1,24 @@
1
+ import { call, defineContract } from "@vrtmrz/rpc";
2
+ import { isStringItem, ITEM_OVERHEAD_BYTES, measureStringItem } from "./workerPushStreamProtocol.js";
3
+ const backgroundWorkerContract = defineContract({
4
+ split: call().transfer({ result: "required" }),
5
+ encrypt: call(),
6
+ decrypt: call(),
7
+ encryptHKDF: call(),
8
+ decryptHKDF: call()
9
+ });
10
+ function splitChunkCapacity(dataSrc) {
11
+ return Math.max(2, 8 * Math.ceil(dataSrc.size / 3));
12
+ }
13
+ function splitStreamItems(dataSrc) {
14
+ return {
15
+ isItem: isStringItem,
16
+ chargeItem: measureStringItem,
17
+ maxItemBytes: ITEM_OVERHEAD_BYTES + splitChunkCapacity(dataSrc)
18
+ };
19
+ }
20
+ export {
21
+ backgroundWorkerContract,
22
+ splitChunkCapacity,
23
+ splitStreamItems
24
+ };
@@ -1,16 +1,2 @@
1
- import { cancelSplit, processSplit } from "./bg.worker.splitting.js";
2
- import { processEncryption } from "./bg.worker.encryption.js";
3
- self.onmessage = (e) => {
4
- const data = e.data.data;
5
- if (data.type === "split") {
6
- return processSplit(data);
7
- } else if (data.type === "cancelSplit") {
8
- cancelSplit(data.key);
9
- } else if (data.type === "encrypt" || data.type === "decrypt") {
10
- return processEncryption(data);
11
- } else if (data.type === "encryptHKDF" || data.type === "decryptHKDF") {
12
- return processEncryption(data);
13
- } else {
14
- self.postMessage({ key: data.key, error: new Error("Invalid type") });
15
- }
16
- };
1
+ import { serveBackgroundWorker } from "./serveBackgroundWorker.js";
2
+ serveBackgroundWorker(self);
@@ -1,7 +1,3 @@
1
- import type { SplitArguments } from "./universalTypes.js";
2
- export declare function cancelSplit(key: number): void;
3
- /**
4
- * Processes the splitting of data into chunks.
5
- * @param data The data to be split.
6
- */
7
- export declare function processSplit(data: SplitArguments): Promise<void>;
1
+ import { type CancelSignal } from "@vrtmrz/rpc";
2
+ import type { WorkerSplitRequest } from "./backgroundWorkerRpcContract.js";
3
+ export declare function splitBackgroundRequest(request: WorkerSplitRequest, signal: CancelSignal): AsyncGenerator<string, void, unknown>;
@@ -1,24 +1,10 @@
1
- import { splitPiecesRabinKarp, splitPieces2V2, splitPieces2 } from "../string_and_binary/chunks.js";
2
- import { postBack } from "./bg.common.js";
3
- import { END_OF_DATA } from "./universalTypes.js";
4
- function getMainThreadPostBack(key) {
5
- const _key = key;
6
- let seq = 0;
7
- return function(data) {
8
- if (data === END_OF_DATA) {
9
- if (seq === 0) {
10
- postBack(_key, seq++, "");
11
- }
12
- postBack(_key, seq++, END_OF_DATA);
13
- } else {
14
- postBack(_key, seq++, data);
15
- }
16
- };
17
- }
18
- const activeSplits = /* @__PURE__ */ new Map();
19
- function cancelSplit(key) {
20
- activeSplits.get(key)?.abort();
21
- }
1
+ import { RpcError } from "@vrtmrz/rpc";
2
+ import { splitPieces2, splitPieces2V2, splitPiecesRabinKarp } from "../string_and_binary/chunks.js";
3
+ const splitters = {
4
+ 1: splitPieces2,
5
+ 2: splitPieces2V2,
6
+ 3: splitPiecesRabinKarp
7
+ };
22
8
  function readErrorField(error, field) {
23
9
  try {
24
10
  const value = error?.[field];
@@ -27,46 +13,59 @@ function readErrorField(error, field) {
27
13
  return void 0;
28
14
  }
29
15
  }
30
- async function processSplit(data) {
31
- const key = data.key;
32
- const dataSrc = data.dataSrc;
33
- const pieceSize = data.pieceSize;
34
- const plainSplit = data.plainSplit;
35
- const minimumChunkSize = data.minimumChunkSize;
36
- const filename = data.filename;
37
- const useSegmenter = data.useSegmenter;
16
+ function asRemoteSplitError(error) {
17
+ const remoteName = readErrorField(error, "name") ?? "Error";
18
+ const message = typeof error === "string" ? error : readErrorField(error, "message") ?? "Background splitting failed";
19
+ return new RpcError("remote-error", message, { remoteName });
20
+ }
21
+ function bridgeCancellation(signal, controller) {
22
+ const abort = () => controller.abort(signal.reason);
23
+ if (signal.aborted) {
24
+ abort();
25
+ } else {
26
+ signal.addEventListener("abort", abort, { once: true });
27
+ }
28
+ return () => signal.removeEventListener("abort", abort);
29
+ }
30
+ async function* splitBackgroundRequest(request, signal) {
31
+ if (signal.aborted) {
32
+ return;
33
+ }
38
34
  const controller = new AbortController();
39
- const signal = controller.signal;
40
- activeSplits.set(key, controller);
35
+ const removeAbortListener = request.splitVersion === 3 ? bridgeCancellation(signal, controller) : () => {
36
+ };
41
37
  try {
42
- const splitLegacy = data.splitVersion === 2 ? splitPieces2V2 : splitPieces2;
43
- const gen = data.splitVersion === 3 ? await splitPiecesRabinKarp(
38
+ const { dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter, splitVersion } = request;
39
+ const splitter = splitters[splitVersion];
40
+ const split = splitVersion === 3 ? await splitter(
44
41
  dataSrc,
45
42
  pieceSize,
46
43
  plainSplit,
47
44
  minimumChunkSize,
48
45
  filename,
49
46
  useSegmenter,
50
- signal
51
- ) : await splitLegacy(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter);
52
- const emit = getMainThreadPostBack(key);
53
- for await (const v of gen()) {
47
+ controller.signal
48
+ ) : await splitter(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter);
49
+ if (signal.aborted) {
50
+ return;
51
+ }
52
+ let produced = false;
53
+ for await (const chunk of split()) {
54
54
  if (signal.aborted) {
55
- break;
55
+ return;
56
56
  }
57
- emit(v);
57
+ produced = true;
58
+ yield chunk;
59
+ }
60
+ if (!produced && !signal.aborted) {
61
+ yield "";
58
62
  }
59
- emit(END_OF_DATA);
60
63
  } catch (error) {
61
- const name = readErrorField(error, "name") ?? "Error";
62
- const message = typeof error === "string" ? error : readErrorField(error, "message") ?? "Background splitting failed";
63
- const stack = readErrorField(error, "stack");
64
- self.postMessage({ key, error: { name, message, stack } });
64
+ throw asRemoteSplitError(error);
65
65
  } finally {
66
- activeSplits.delete(key);
66
+ removeAbortListener();
67
67
  }
68
68
  }
69
69
  export {
70
- cancelSplit,
71
- processSplit
70
+ splitBackgroundRequest
72
71
  };