@warp-drive-mirror/experiments 0.2.7-beta.0 → 0.2.7-beta.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/CHANGELOG.md +70 -0
  2. package/README.md +2 -1
  3. package/declarations/data-worker.d.ts +35 -2
  4. package/declarations/data-worker.d.ts.map +1 -0
  5. package/declarations/document-storage-CwwTQ49-.d.ts +91 -0
  6. package/declarations/document-storage-CwwTQ49-.d.ts.map +1 -0
  7. package/declarations/document-storage.d.ts +2 -1
  8. package/declarations/image-fetch.d.ts +60 -1
  9. package/declarations/image-fetch.d.ts.map +1 -0
  10. package/declarations/image-worker.d.ts +40 -1
  11. package/declarations/image-worker.d.ts.map +1 -0
  12. package/declarations/storage.d.ts +359 -0
  13. package/declarations/storage.d.ts.map +1 -0
  14. package/declarations/types-CRs-Qww6.d.ts +17 -0
  15. package/declarations/types-CRs-Qww6.d.ts.map +1 -0
  16. package/declarations/worker-fetch.d.ts +23 -1
  17. package/declarations/worker-fetch.d.ts.map +1 -0
  18. package/dist/data-worker.js +235 -339
  19. package/dist/data-worker.js.map +1 -0
  20. package/dist/document-storage-LM925Stz.js +270 -0
  21. package/dist/document-storage-LM925Stz.js.map +1 -0
  22. package/dist/document-storage.js +3 -1
  23. package/dist/image-fetch.js +108 -79
  24. package/dist/image-fetch.js.map +1 -0
  25. package/dist/image-worker.js +95 -95
  26. package/dist/image-worker.js.map +1 -0
  27. package/dist/storage.js +914 -0
  28. package/dist/storage.js.map +1 -0
  29. package/dist/unpkg/dev/data-worker.js +231 -338
  30. package/dist/unpkg/dev/data-worker.js.map +1 -0
  31. package/dist/unpkg/dev/document-storage-DkiEg9rY.js +268 -0
  32. package/dist/unpkg/dev/document-storage-DkiEg9rY.js.map +1 -0
  33. package/dist/unpkg/dev/document-storage.js +2 -348
  34. package/dist/unpkg/dev/image-fetch.js +104 -71
  35. package/dist/unpkg/dev/image-fetch.js.map +1 -0
  36. package/dist/unpkg/dev/image-worker.js +93 -94
  37. package/dist/unpkg/dev/image-worker.js.map +1 -0
  38. package/dist/unpkg/dev/storage.js +913 -0
  39. package/dist/unpkg/dev/storage.js.map +1 -0
  40. package/dist/unpkg/dev/worker-fetch.js +112 -145
  41. package/dist/unpkg/dev/worker-fetch.js.map +1 -0
  42. package/dist/unpkg/dev-deprecated/data-worker.js +231 -338
  43. package/dist/unpkg/dev-deprecated/data-worker.js.map +1 -0
  44. package/dist/unpkg/dev-deprecated/document-storage-DkiEg9rY.js +268 -0
  45. package/dist/unpkg/dev-deprecated/document-storage-DkiEg9rY.js.map +1 -0
  46. package/dist/unpkg/dev-deprecated/document-storage.js +2 -348
  47. package/dist/unpkg/dev-deprecated/image-fetch.js +104 -71
  48. package/dist/unpkg/dev-deprecated/image-fetch.js.map +1 -0
  49. package/dist/unpkg/dev-deprecated/image-worker.js +93 -94
  50. package/dist/unpkg/dev-deprecated/image-worker.js.map +1 -0
  51. package/dist/unpkg/dev-deprecated/storage.js +913 -0
  52. package/dist/unpkg/dev-deprecated/storage.js.map +1 -0
  53. package/dist/unpkg/dev-deprecated/worker-fetch.js +112 -145
  54. package/dist/unpkg/dev-deprecated/worker-fetch.js.map +1 -0
  55. package/dist/unpkg/prod/data-worker.js +224 -324
  56. package/dist/unpkg/prod/data-worker.js.map +1 -0
  57. package/dist/unpkg/prod/document-storage-D0k_6GM9.js +262 -0
  58. package/dist/unpkg/prod/document-storage-D0k_6GM9.js.map +1 -0
  59. package/dist/unpkg/prod/document-storage.js +2 -338
  60. package/dist/unpkg/prod/image-fetch.js +101 -71
  61. package/dist/unpkg/prod/image-fetch.js.map +1 -0
  62. package/dist/unpkg/prod/image-worker.js +93 -94
  63. package/dist/unpkg/prod/image-worker.js.map +1 -0
  64. package/dist/unpkg/prod/storage.js +844 -0
  65. package/dist/unpkg/prod/storage.js.map +1 -0
  66. package/dist/unpkg/prod/worker-fetch.js +109 -145
  67. package/dist/unpkg/prod/worker-fetch.js.map +1 -0
  68. package/dist/unpkg/prod-deprecated/data-worker.js +224 -324
  69. package/dist/unpkg/prod-deprecated/data-worker.js.map +1 -0
  70. package/dist/unpkg/prod-deprecated/document-storage-D0k_6GM9.js +262 -0
  71. package/dist/unpkg/prod-deprecated/document-storage-D0k_6GM9.js.map +1 -0
  72. package/dist/unpkg/prod-deprecated/document-storage.js +2 -338
  73. package/dist/unpkg/prod-deprecated/image-fetch.js +101 -71
  74. package/dist/unpkg/prod-deprecated/image-fetch.js.map +1 -0
  75. package/dist/unpkg/prod-deprecated/image-worker.js +93 -94
  76. package/dist/unpkg/prod-deprecated/image-worker.js.map +1 -0
  77. package/dist/unpkg/prod-deprecated/storage.js +844 -0
  78. package/dist/unpkg/prod-deprecated/storage.js.map +1 -0
  79. package/dist/unpkg/prod-deprecated/worker-fetch.js +109 -145
  80. package/dist/unpkg/prod-deprecated/worker-fetch.js.map +1 -0
  81. package/dist/worker-fetch.js +116 -153
  82. package/dist/worker-fetch.js.map +1 -0
  83. package/package.json +9 -9
  84. package/declarations/data-worker/cache-handler.d.ts +0 -7
  85. package/declarations/data-worker/fetch.d.ts +0 -21
  86. package/declarations/data-worker/types.d.ts +0 -31
  87. package/declarations/data-worker/utils.d.ts +0 -12
  88. package/declarations/data-worker/worker.d.ts +0 -23
  89. package/declarations/document-storage/index.d.ts +0 -90
  90. package/declarations/image-worker/fetch.d.ts +0 -18
  91. package/declarations/image-worker/types.d.ts +0 -21
  92. package/declarations/image-worker/worker.d.ts +0 -14
  93. package/dist/index-CGCX7hY2.js +0 -349
@@ -1,339 +1,3 @@
1
- const WARP_DRIVE_STORAGE_FILE_NAME = 'warp-drive_document-storage';
2
- const WARP_DRIVE_STORAGE_VERSION = 1;
1
+ import { t as DocumentStorage } from "./document-storage-D0k_6GM9.js";
3
2
 
4
- /**
5
- * DocumentStorage is specifically designed around WarpDrive Cache and Request concepts.
6
- *
7
- * CacheFileDocument is a StructuredDocument (request response) whose `content` is
8
- * the ResourceDocument returned by inserting the request into a Store's Cache.
9
- */
10
-
11
- /**
12
- * A CacheDocument is a reconstructed request response that rehydrates ResourceDocument
13
- * with the associated resources based on their identifiers.
14
- */
15
-
16
- class InternalDocumentStorage {
17
- constructor(options) {
18
- this.options = options;
19
- this._lastModified = 0;
20
- this._invalidated = true;
21
- this._fileHandle = this._open(options.scope);
22
- this._channel = Object.assign(new BroadcastChannel(options.scope), {
23
- onmessage: this._onMessage.bind(this)
24
- });
25
- }
26
- _onMessage(_event) {
27
- this._invalidated = true;
28
- }
29
- async _open(scope) {
30
- const directoryHandle = await navigator.storage.getDirectory();
31
- const fileHandle = await directoryHandle.getFileHandle(scope, {
32
- create: true
33
- });
34
- return fileHandle;
35
- }
36
- async _read() {
37
- if (this._filePromise) {
38
- return this._filePromise;
39
- }
40
- if (this._invalidated) {
41
- const updateFile = async () => {
42
- const fileHandle = await this._fileHandle;
43
- const file = await fileHandle.getFile();
44
- const lastModified = file.lastModified;
45
- if (lastModified === this._lastModified && this._cache) {
46
- return this._cache;
47
- }
48
- const contents = await file.text();
49
- const cache = contents ? JSON.parse(contents) : {
50
- documents: [],
51
- resources: []
52
- };
53
- const documents = new Map(cache.documents);
54
- const resources = new Map(cache.resources);
55
- const cacheMap = {
56
- documents,
57
- resources
58
- };
59
- this._cache = cacheMap;
60
- this._invalidated = false;
61
- this._lastModified = lastModified;
62
- return cacheMap;
63
- };
64
- this._filePromise = updateFile();
65
- await this._filePromise;
66
- this._filePromise = null;
67
- }
68
- return this._cache;
69
- }
70
- async _patch(documentKey, document, updatedResources) {
71
- const fileHandle = await this._fileHandle;
72
- // secure a lock before getting latest state
73
- const writable = await fileHandle.createWritable();
74
- const cache = await this._read();
75
- cache.documents.set(documentKey, document);
76
- updatedResources.forEach((resource, key) => {
77
- cache.resources.set(key, resource);
78
- });
79
- const documents = [...cache.documents.entries()];
80
- const resources = [...cache.resources.entries()];
81
- const cacheFile = {
82
- documents,
83
- resources
84
- };
85
- await writable.write(JSON.stringify(cacheFile));
86
- await writable.close();
87
- this._channel.postMessage({
88
- type: 'patch',
89
- key: documentKey,
90
- resources: [...updatedResources.keys()]
91
- });
92
- }
93
- async getDocument(key) {
94
- const cache = await this._read();
95
- // clone the document to avoid leaking the internal cache
96
- const document = safeDocumentHydrate(cache.documents.get(key.lid));
97
- if (!document) {
98
- return null;
99
- }
100
-
101
- // expand the document with the resources
102
- if (document.content) {
103
- if (docHasData(document.content)) {
104
- let data = null;
105
- if (Array.isArray(document.content.data)) {
106
- data = document.content.data.map(resourceIdentifier => {
107
- const resource = cache.resources.get(resourceIdentifier.lid);
108
- if (!resource) {
109
- throw new Error(`Resource not found for ${resourceIdentifier.lid}`);
110
- }
111
-
112
- // clone the resource to avoid leaking the internal cache
113
- return structuredClone(resource);
114
- });
115
- } else if (document.content.data) {
116
- const resource = cache.resources.get(document.content.data.lid);
117
- if (!resource) {
118
- throw new Error(`Resource not found for ${document.content.data.lid}`);
119
- }
120
-
121
- // clone the resource to avoid leaking the internal cache
122
- data = structuredClone(resource);
123
- }
124
- if (document.content.included) {
125
- const included = document.content.included.map(resourceIdentifier => {
126
- const resource = cache.resources.get(resourceIdentifier.lid);
127
- if (!resource) {
128
- throw new Error(`Resource not found for ${resourceIdentifier.lid}`);
129
- }
130
-
131
- // clone the resource to avoid leaking the internal cache
132
- return structuredClone(resource);
133
- });
134
- document.content.included = included;
135
- }
136
- document.content.data = data;
137
- }
138
- }
139
- return document;
140
- }
141
- async putDocument(document, resourceCollector) {
142
- const resources = new Map();
143
- if (!document.content) {
144
- throw new Error(`Document content is missing, only finalized documents can be stored`);
145
- }
146
- if (!document.content.lid) {
147
- throw new Error(`Document content is missing a lid, only documents with a cache-key can be stored`);
148
- }
149
- if (docHasData(document.content)) {
150
- this._getResources(document.content, resourceCollector, resources);
151
- }
152
- await this._patch(document.content.lid, safeDocumentSerialize(document), resources);
153
- }
154
- _getResources(document, resourceCollector, resources = new Map()) {
155
- if (Array.isArray(document.data)) {
156
- document.data.forEach(resourceIdentifier => {
157
- const resource = resourceCollector(resourceIdentifier);
158
- resources.set(resourceIdentifier.lid, structuredClone(resource));
159
- });
160
- } else if (document.data) {
161
- const resource = resourceCollector(document.data);
162
- resources.set(document.data.lid, structuredClone(resource));
163
- }
164
- if (document.included) {
165
- document.included.forEach(resourceIdentifier => {
166
- const resource = resourceCollector(resourceIdentifier);
167
- resources.set(resourceIdentifier.lid, structuredClone(resource));
168
- });
169
- }
170
- return resources;
171
- }
172
- async putResources(document, resourceCollector) {
173
- const fileHandle = await this._fileHandle;
174
- // secure a lock before getting latest state
175
- const writable = await fileHandle.createWritable();
176
- const cache = await this._read();
177
- const updatedResources = this._getResources(document, resourceCollector);
178
- updatedResources.forEach((resource, key) => {
179
- cache.resources.set(key, resource);
180
- });
181
- const documents = [...cache.documents.entries()];
182
- const resources = [...cache.resources.entries()];
183
- const cacheFile = {
184
- documents,
185
- resources
186
- };
187
- await writable.write(JSON.stringify(cacheFile));
188
- await writable.close();
189
- this._channel.postMessage({
190
- type: 'patch',
191
- key: null,
192
- resources: [...updatedResources.keys()]
193
- });
194
- }
195
- async clear(reset) {
196
- const fileHandle = await this._fileHandle;
197
- const writable = await fileHandle.createWritable();
198
- await writable.write('');
199
- await writable.close();
200
- this._invalidated = true;
201
- this._lastModified = 0;
202
- this._cache = null;
203
- this._filePromise = null;
204
- this._channel.postMessage({
205
- type: 'clear'
206
- });
207
- if (!reset) {
208
- this._channel.close();
209
- this._channel = null;
210
- if (!this.options.isolated) {
211
- Storages.delete(this.options.scope);
212
- }
213
- }
214
- }
215
- }
216
- function safeDocumentSerialize(document) {
217
- const doc = document;
218
- const newDoc = {};
219
- if ('request' in doc) {
220
- newDoc.request = prepareRequest(doc.request);
221
- }
222
- if ('response' in doc) {
223
- newDoc.response = prepareResponse(doc.response);
224
- }
225
- if ('content' in doc) {
226
- newDoc.content = structuredClone(doc.content);
227
- }
228
- return newDoc;
229
- }
230
- function prepareRequest(request) {
231
- const {
232
- signal,
233
- headers
234
- } = request;
235
- const requestCopy = Object.assign({}, request);
236
- delete requestCopy.store;
237
- if (signal instanceof AbortSignal) {
238
- delete requestCopy.signal;
239
- }
240
- if (headers instanceof Headers) {
241
- requestCopy.headers = Array.from(headers);
242
- }
243
- return requestCopy;
244
- }
245
- function prepareResponse(response) {
246
- if (!response) return null;
247
- const clone = {};
248
- if (response.headers) {
249
- clone.headers = Array.from(response.headers);
250
- }
251
- clone.ok = response.ok;
252
- clone.redirected = response.redirected;
253
- clone.status = response.status;
254
- clone.statusText = response.statusText;
255
- clone.type = response.type;
256
- clone.url = response.url;
257
- return clone;
258
- }
259
- function safeDocumentHydrate(document) {
260
- const doc = document;
261
- const newDoc = {};
262
- if ('request' in doc) {
263
- const headers = new Headers(doc.request.headers);
264
- const req = Object.assign({}, doc.request, {
265
- headers
266
- });
267
- newDoc.request = new Request(doc.request.url ?? '', req);
268
- }
269
- if ('response' in doc) {
270
- const headers = new Headers(doc.response.headers);
271
- const resp = Object.assign({}, doc.response, {
272
- headers
273
- });
274
- newDoc.response = new Response(null, resp);
275
- }
276
- if ('content' in doc) {
277
- newDoc.content = structuredClone(doc.content);
278
- }
279
- return newDoc;
280
- }
281
- function docHasData(doc) {
282
- return 'data' in doc;
283
- }
284
- const Storages = new Map();
285
-
286
- /**
287
- * DocumentStorage is a wrapper around the StorageManager API that provides
288
- * a simple interface for reading and updating documents and requests.
289
- *
290
- * Some goals for this experiment:
291
- *
292
- * - optimize for storing requests/documents
293
- * - optimize for storing resources
294
- * - optimize for looking up resources associated to a document
295
- * - optimize for notifying cross-tab when data is updated
296
- *
297
- * optional features:
298
- *
299
- * - support for offline mode
300
- * - ?? support for relationship based cache traversal
301
- * - a way to index records by type + another field (e.g updatedAt/createAt/name)
302
- * such that simple queries can be done without having to scan all records
303
- */
304
- class DocumentStorage {
305
- constructor(options = {}) {
306
- options.isolated = options.isolated ?? false;
307
- options.scope = options.scope ?? 'default';
308
- const fileName = `${WARP_DRIVE_STORAGE_FILE_NAME}@version_${WARP_DRIVE_STORAGE_VERSION}:${options.scope}`;
309
- if (!options.isolated && Storages.has(fileName)) {
310
- const storage = Storages.get(fileName);
311
- if (storage) {
312
- this._storage = storage.deref();
313
- return;
314
- }
315
- }
316
- const storage = new InternalDocumentStorage({
317
- scope: fileName,
318
- isolated: options.isolated
319
- });
320
- this._storage = storage;
321
- if (!options.isolated) {
322
- Storages.set(fileName, new WeakRef(storage));
323
- }
324
- }
325
- getDocument(key) {
326
- return this._storage.getDocument(key);
327
- }
328
- putDocument(document, resourceCollector) {
329
- return this._storage.putDocument(document, resourceCollector);
330
- }
331
- putResources(document, resourceCollector) {
332
- return this._storage.putResources(document, resourceCollector);
333
- }
334
- clear(reset) {
335
- return this._storage.clear(reset);
336
- }
337
- }
338
-
339
- export { DocumentStorage };
3
+ export { DocumentStorage };
@@ -1,74 +1,104 @@
1
- import { createDeferred } from '@warp-drive-mirror/core/request';
1
+ import { createDeferred } from "@warp-drive-mirror/core/request";
2
2
 
3
- // @ts-expect-error untyped global
4
- const isServerEnv = typeof FastBoot !== 'undefined';
5
- class ImageFetch {
6
- constructor(worker) {
7
- this.threadId = isServerEnv ? '' : crypto.randomUUID();
8
- this.pending = new Map();
9
- this.cache = new Map();
10
- this.worker = worker;
11
- if (!isServerEnv) {
12
- const fn = event => {
13
- const {
14
- type,
15
- url
16
- } = event.data;
17
- const deferred = this.cleanupRequest(url);
18
- if (!deferred) {
19
- return;
20
- }
21
- if (type === 'success-response') {
22
- deferred.resolve(url);
23
- return;
24
- }
25
- if (type === 'error-response') {
26
- deferred.reject(null);
27
- return;
28
- }
29
- };
30
- if (worker instanceof SharedWorker) {
31
- worker.port.postMessage({
32
- type: 'connect',
33
- thread: this.threadId
34
- });
35
- worker.port.onmessage = fn;
36
- } else if (worker) {
37
- this.channel = new MessageChannel();
38
- worker.postMessage({
39
- type: 'connect',
40
- thread: this.threadId
41
- }, [this.channel.port2]);
42
- this.channel.port1.onmessage = fn;
43
- }
44
- }
45
- }
46
- cleanupRequest(url) {
47
- const deferred = this.pending.get(url);
48
- this.pending.delete(url);
49
- return deferred;
50
- }
51
- _send(event) {
52
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
53
- this.worker instanceof SharedWorker ? this.worker.port.postMessage(event) : this.channel.port1.postMessage(event);
54
- }
55
- load(url) {
56
- if (isServerEnv) {
57
- return Promise.resolve(url);
58
- }
59
- const objectUrl = this.cache.get(url);
60
- if (objectUrl) {
61
- return Promise.resolve(objectUrl);
62
- }
63
- const deferred = createDeferred();
64
- this.pending.set(url, deferred);
65
- this._send({
66
- type: 'load',
67
- thread: this.threadId,
68
- url
69
- });
70
- return deferred.promise;
71
- }
72
- }
3
+ //#region src/image-worker/fetch.ts
4
+ const isServerEnv = typeof FastBoot !== "undefined";
5
+ /**
6
+ * Main-thread client for an {@link ImageWorker}. Sends image `load`
7
+ * requests to a `Worker` or `SharedWorker` running an `ImageWorker`.
8
+ *
9
+ * In FastBoot/SSR, or when constructed with a `null` worker, `ImageFetch`
10
+ * skips worker communication entirely: {@link ImageFetch.load} resolves
11
+ * immediately with the given url.
12
+ *
13
+ * A plain `Worker` is only accepted when running in a `TESTING` build;
14
+ * production usage requires a `SharedWorker`.
15
+ *
16
+ * @public
17
+ */
18
+ var ImageFetch = class {
19
+ /**
20
+ * @param worker - the `Worker` or `SharedWorker` running an
21
+ * {@link ImageWorker}, or `null` to disable worker communication (e.g.
22
+ * in FastBoot/SSR).
23
+ */
24
+ constructor(worker) {
25
+ this.threadId = isServerEnv ? "" : crypto.randomUUID();
26
+ this.pending = /* @__PURE__ */ new Map();
27
+ this.cache = /* @__PURE__ */ new Map();
28
+ this.worker = worker;
29
+ if (!isServerEnv) {
30
+ const fn = (event) => {
31
+ const { type, url } = event.data;
32
+ const deferred = this.cleanupRequest(url);
33
+ if (!deferred) return;
34
+ if (type === "success-response") {
35
+ const { objectUrl } = event.data;
36
+ this.cache.set(url, objectUrl);
37
+ deferred.resolve(objectUrl);
38
+ return;
39
+ }
40
+ if (type === "error-response") {
41
+ deferred.reject(null);
42
+ return;
43
+ }
44
+ };
45
+ if (worker instanceof SharedWorker) {
46
+ worker.port.postMessage({
47
+ type: "connect",
48
+ thread: this.threadId
49
+ });
50
+ worker.port.onmessage = fn;
51
+ } else if (worker) {
52
+ this.channel = new MessageChannel();
53
+ worker.postMessage({
54
+ type: "connect",
55
+ thread: this.threadId
56
+ }, [this.channel.port2]);
57
+ this.channel.port1.onmessage = fn;
58
+ }
59
+ }
60
+ }
61
+ cleanupRequest(url) {
62
+ const deferred = this.pending.get(url);
63
+ this.pending.delete(url);
64
+ return deferred;
65
+ }
66
+ _send(event) {
67
+ this.worker instanceof SharedWorker ? this.worker.port.postMessage(event) : this.channel.port1.postMessage(event);
68
+ }
69
+ /**
70
+ * Requests that the given image url be loaded by the connected
71
+ * {@link ImageWorker}, resolving with an object url for the fetched
72
+ * image's blob once the worker responds (or immediately with the
73
+ * original `url`, in SSR/FastBoot or when this instance was constructed
74
+ * with a `null` worker).
75
+ *
76
+ * The resolved object url is cached in-memory by source url on this
77
+ * instance, so subsequent calls for the same url resolve immediately
78
+ * without another round-trip to the worker.
79
+ *
80
+ * Calling `load` again for a url that is already in-flight (not yet
81
+ * cached) on this instance replaces the pending request rather than
82
+ * joining it — only the most recently issued call for a given url will
83
+ * resolve.
84
+ *
85
+ * @public
86
+ */
87
+ load(url) {
88
+ if (isServerEnv) return Promise.resolve(url);
89
+ const objectUrl = this.cache.get(url);
90
+ if (objectUrl) return Promise.resolve(objectUrl);
91
+ const deferred = createDeferred();
92
+ this.pending.set(url, deferred);
93
+ this._send({
94
+ type: "load",
95
+ thread: this.threadId,
96
+ url
97
+ });
98
+ return deferred.promise;
99
+ }
100
+ };
73
101
 
102
+ //#endregion
74
103
  export { ImageFetch };
104
+ //# sourceMappingURL=image-fetch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-fetch.js","names":["createDeferred","isServerEnv","FastBoot","ImageFetch","constructor","worker","threadId","crypto","randomUUID","pending","Map","cache","isTesting","fn","event","type","url","data","deferred","cleanupRequest","objectUrl","set","resolve","reject","SharedWorker","port","postMessage","thread","onmessage","channel","MessageChannel","port2","port1","get","delete","_send","load","Promise","promise"],"sources":["../../../src/image-worker/fetch.ts"],"sourcesContent":["import { TESTING } from '@warp-drive-mirror/core/build-config/env';\nimport { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { Deferred } from '@warp-drive-mirror/core/request';\nimport { createDeferred } from '@warp-drive-mirror/core/request';\n\nimport type { MainThreadEvent, RequestEventData } from './types';\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { ImageWorker } from './worker';\n\nexport interface FastBoot {\n require(moduleName: string): unknown;\n isFastBoot: boolean;\n request: Request;\n}\n\n// @ts-expect-error untyped global\nconst isServerEnv = typeof FastBoot !== 'undefined';\n\n/**\n * Main-thread client for an {@link ImageWorker}. Sends image `load`\n * requests to a `Worker` or `SharedWorker` running an `ImageWorker`.\n *\n * In FastBoot/SSR, or when constructed with a `null` worker, `ImageFetch`\n * skips worker communication entirely: {@link ImageFetch.load} resolves\n * immediately with the given url.\n *\n * A plain `Worker` is only accepted when running in a `TESTING` build;\n * production usage requires a `SharedWorker`.\n *\n * @public\n */\nexport class ImageFetch {\n declare worker: Worker | SharedWorker;\n declare threadId: string;\n declare pending: Map<string, Deferred<string>>;\n declare channel: MessageChannel;\n declare cache: Map<string, string>;\n\n /**\n * @param worker - the `Worker` or `SharedWorker` running an\n * {@link ImageWorker}, or `null` to disable worker communication (e.g.\n * in FastBoot/SSR).\n */\n constructor(worker: Worker | SharedWorker | null) {\n this.threadId = isServerEnv ? '' : crypto.randomUUID();\n this.pending = new Map();\n this.cache = new Map();\n\n const isTesting = TESTING ? true : false;\n assert(`Expected a SharedWorker instance`, isTesting || isServerEnv || worker instanceof SharedWorker);\n this.worker = worker as SharedWorker;\n\n if (!isServerEnv) {\n const fn = (event: MainThreadEvent) => {\n const { type, url } = event.data;\n const deferred = this.cleanupRequest(url);\n if (!deferred) {\n return;\n }\n\n if (type === 'success-response') {\n const { objectUrl } = event.data;\n this.cache.set(url, objectUrl);\n deferred.resolve(objectUrl);\n return;\n }\n\n if (type === 'error-response') {\n deferred.reject(null);\n return;\n }\n };\n\n if (worker instanceof SharedWorker) {\n worker.port.postMessage({ type: 'connect', thread: this.threadId });\n worker.port.onmessage = fn;\n } else if (worker) {\n this.channel = new MessageChannel();\n worker.postMessage({ type: 'connect', thread: this.threadId }, [this.channel.port2]);\n\n this.channel.port1.onmessage = fn;\n }\n }\n }\n\n cleanupRequest(url: string): Deferred<string> | undefined {\n const deferred = this.pending.get(url);\n this.pending.delete(url);\n\n return deferred;\n }\n\n _send(event: RequestEventData): void {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n this.worker instanceof SharedWorker ? this.worker.port.postMessage(event) : this.channel.port1.postMessage(event);\n }\n\n /**\n * Requests that the given image url be loaded by the connected\n * {@link ImageWorker}, resolving with an object url for the fetched\n * image's blob once the worker responds (or immediately with the\n * original `url`, in SSR/FastBoot or when this instance was constructed\n * with a `null` worker).\n *\n * The resolved object url is cached in-memory by source url on this\n * instance, so subsequent calls for the same url resolve immediately\n * without another round-trip to the worker.\n *\n * Calling `load` again for a url that is already in-flight (not yet\n * cached) on this instance replaces the pending request rather than\n * joining it — only the most recently issued call for a given url will\n * resolve.\n *\n * @public\n */\n load(url: string): Promise<string> {\n if (isServerEnv) {\n return Promise.resolve(url);\n }\n\n const objectUrl = this.cache.get(url);\n if (objectUrl) {\n return Promise.resolve(objectUrl);\n }\n\n const deferred = createDeferred<string>();\n this.pending.set(url, deferred);\n this._send({ type: 'load', thread: this.threadId, url });\n return deferred.promise;\n }\n}\n"],"mappings":";;;AAgBA,MAAMC,cAAc,OAAOC,aAAa;;;;;;;;;;;;;;AAexC,IAAaC,aAAb,MAAwB;;;;;;CAYtBC,YAAYC,QAAsC;EAChD,KAAKC,WAAWL,cAAc,KAAKM,OAAOC,WAAW;EACrD,KAAKC,0BAAU,IAAIC,IAAI;EACvB,KAAKC,wBAAQ,IAAID,IAAI;EAIrB,KAAKL,SAASA;EAEd,IAAI,CAACJ,aAAa;GAChB,MAAMY,MAAMC,UAA2B;IACrC,MAAM,EAAEC,MAAMC,QAAQF,MAAMG;IAC5B,MAAMC,WAAW,KAAKC,eAAeH,GAAG;IACxC,IAAI,CAACE,UACH;IAGF,IAAIH,SAAS,oBAAoB;KAC/B,MAAM,EAAEK,cAAcN,MAAMG;KAC5B,KAAKN,MAAMU,IAAIL,KAAKI,SAAS;KAC7BF,SAASI,QAAQF,SAAS;KAC1B;IACF;IAEA,IAAIL,SAAS,kBAAkB;KAC7BG,SAASK,OAAO,IAAI;KACpB;IACF;GACF;GAEA,IAAIlB,kBAAkBmB,cAAc;IAClCnB,OAAOoB,KAAKC,YAAY;KAAEX,MAAM;KAAWY,QAAQ,KAAKrB;IAAS,CAAC;IAClED,OAAOoB,KAAKG,YAAYf;GAC1B,OAAO,IAAIR,QAAQ;IACjB,KAAKwB,UAAU,IAAIC,eAAe;IAClCzB,OAAOqB,YAAY;KAAEX,MAAM;KAAWY,QAAQ,KAAKrB;IAAS,GAAG,CAAC,KAAKuB,QAAQE,KAAK,CAAC;IAEnF,KAAKF,QAAQG,MAAMJ,YAAYf;GACjC;EACF;CACF;CAEAM,eAAeH,KAA2C;EACxD,MAAME,WAAW,KAAKT,QAAQwB,IAAIjB,GAAG;EACrC,KAAKP,QAAQyB,OAAOlB,GAAG;EAEvB,OAAOE;CACT;CAEAiB,MAAMrB,OAA+B;EAEnC,KAAKT,kBAAkBmB,eAAe,KAAKnB,OAAOoB,KAAKC,YAAYZ,KAAK,IAAI,KAAKe,QAAQG,MAAMN,YAAYZ,KAAK;CAClH;;;;;;;;;;;;;;;;;;;CAoBAsB,KAAKpB,KAA8B;EACjC,IAAIf,aACF,OAAOoC,QAAQf,QAAQN,GAAG;EAG5B,MAAMI,YAAY,KAAKT,MAAMsB,IAAIjB,GAAG;EACpC,IAAII,WACF,OAAOiB,QAAQf,QAAQF,SAAS;EAGlC,MAAMF,WAAWlB,eAAuB;EACxC,KAAKS,QAAQY,IAAIL,KAAKE,QAAQ;EAC9B,KAAKiB,MAAM;GAAEpB,MAAM;GAAQY,QAAQ,KAAKrB;GAAUU;EAAI,CAAC;EACvD,OAAOE,SAASoB;CAClB;AACF"}