deno.land / x / esm@v135_2 / hot.ts

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*! 🔥 esm.sh/hot * Docs: https://til.esm.sh/hot */
/// <reference lib="webworker" />
import type { ArchiveEntry, FireOptions, HotCore, Plugin } from "./server/embed/types/hot.d.ts";
const VERSION = 135;const doc: Document | undefined = globalThis.document;const kHot = "esm.sh/hot";const kMessage = "message";const kVfs = "vfs";const kTypeEsmArchive = "application/esm-archive";const kHotArchive = "#hot-archive";
/** class `VFS` implements the virtual file system by using indexed database. */class VFS { #db: IDBDatabase | Promise<IDBDatabase>;
constructor(scope: string, version: number) { const req = indexedDB.open(scope, version); req.onupgradeneeded = () => { const db = req.result; if (!db.objectStoreNames.contains(kVfs)) { db.createObjectStore(kVfs, { keyPath: "name" }); } }; this.#db = waitIDBRequest<IDBDatabase>(req); }
async #begin(readonly = false) { let db = this.#db; if (db instanceof Promise) { db = this.#db = await db; } return db.transaction(kVfs, readonly ? "readonly" : "readwrite") .objectStore(kVfs); }
async has(name: string) { const tx = await this.#begin(true); return await waitIDBRequest<string>(tx.getKey(name)) === name; }
async get(name: string) { const tx = await this.#begin(true); const ret = await waitIDBRequest<File & { content: ArrayBuffer } | undefined>(tx.get(name)); if (ret) { return new File([ret.content], ret.name, ret); } }
async put(file: File) { const { name, type, lastModified } = file; if (await this.has(name)) { return name; } const content = await file.arrayBuffer(); const tx = await this.#begin(); return waitIDBRequest<string>(tx.put({ name, type, lastModified, content })); }
async delete(name: string) { const tx = await this.#begin(); return waitIDBRequest<void>(tx.delete(name)); }}
/** * class `Archive` implements the reader for esm-archive format. * more details see https://www.npmjs.com/package/esm-archive */class Archive { #buffer: ArrayBuffer; #entries: Record<string, ArchiveEntry> = {};
static invalidFormat = new Error("Invalid esm-archive format");
constructor(buffer: ArrayBuffer) { this.#buffer = buffer; this.#parse(); }
public checksum: number;
#parse() { const dv = new DataView(this.#buffer); const decoder = new TextDecoder(); const readUint32 = (offset: number) => dv.getUint32(offset); const readString = (offset: number, length: number) => decoder.decode(new Uint8Array(this.#buffer, offset, length)); if (this.#buffer.byteLength < 18 || readString(0, 10) !== "ESMARCHIVE") { throw Archive.invalidFormat; } const length = readUint32(10); if (length !== this.#buffer.byteLength) { throw Archive.invalidFormat; } this.checksum = readUint32(14); let offset = 18; while (offset < dv.byteLength) { const nameLen = dv.getUint16(offset); offset += 2; const name = readString(offset, nameLen); offset += nameLen; const typeLen = dv.getUint8(offset); offset += 1; const type = readString(offset, typeLen); offset += typeLen; const lastModified = readUint32(offset) * 1000; // convert to ms offset += 4; const size = readUint32(offset); offset += 4; this.#entries[name] = { name, type, lastModified, offset, size }; offset += size; } }
exists(name: string) { return name in this.#entries; }
openFile(name: string) { const info = this.#entries[name]; return info ? new File([this.#buffer.slice(info.offset, info.offset + info.size)], info.name, info) : null; }}
/** class `Hot` implements the `HotCore` interface. */class Hot implements HotCore { #vfs = new VFS(kHot, VERSION); #swScript: string | null = null; #swActive: ServiceWorker | null = null; #archive: Archive | null = null; #fireListeners: ((sw: ServiceWorker) => void)[] = []; #promises: Promise<any>[] = []; #bc = new BroadcastChannel(kHot);
get vfs() { return this.#vfs; }
onUpdateFound = () => location.reload();
onFire(handler: (reg: ServiceWorker) => void) { if (this.#swActive) { handler(this.#swActive); } else { this.#fireListeners.push(handler); } return this; }
waitUntil(...promises: readonly Promise<void>[]) { this.#promises.push(...promises); return this; }
use(...plugins: readonly Plugin[]) { plugins.forEach((plugin) => plugin.setup(this)); return this; }
async fire(options: FireOptions = {}) { const sw = navigator.serviceWorker; if (!sw) { throw new Error("Service Worker not supported"); }
const { main, swScript = "/sw.js", swUpdateViaCache } = options;
// add preload link for the main module if it's provided if (main) { appendElement("link", { rel: "modulepreload", href: main }); }
if (this.#swScript === swScript) { return; } this.#swScript = swScript;
// register Service Worker const reg = await sw.register(this.#swScript, { type: "module", updateViaCache: swUpdateViaCache, }); const tryFireApp = async () => { if (reg.active?.state === "activated") { await this.#fireApp(reg.active); main && appendElement("script", { type: "module", src: main }); } };
// detect Service Worker update available and wait for it to become installed reg.onupdatefound = () => { const { installing } = reg; if (installing) { installing.onstatechange = () => { const { waiting } = reg; // it's first install if (waiting && !sw.controller) { waiting.onstatechange = tryFireApp; } }; } };
// detect controller change sw.oncontrollerchange = this.onUpdateFound;
// fire app immediately if there's an activated Service Worker tryFireApp(); }
async #fireApp(swActive: ServiceWorker) { // download and send esm archive to Service Worker queryElements<HTMLLinkElement>(`link[rel=preload][as=fetch][type^="${kTypeEsmArchive}"][href]`, (el) => { this.#promises.push( fetch(el.href).then((res) => { if (res.ok) { if (el.type.endsWith("+gzip")) { res = new Response(res.body?.pipeThrough(new DecompressionStream("gzip"))); } return res.arrayBuffer(); } return Promise.reject(new Error(res.statusText ?? `<${res.status}>`)); }).then((arrayBuffer) => { swActive.postMessage({ [kHotArchive]: arrayBuffer }); this.#bc.onmessage = (evt) => { if (evt.data === kHotArchive) { this.onUpdateFound(); } }; }).catch((err) => { console.error("Failed to fetch", el.href, err[kMessage]); }), ); });
// wait until all promises resolved await Promise.all(this.#promises); this.#promises = [];
// fire all `fire` listeners for (const handler of this.#fireListeners) { handler(swActive); } this.#fireListeners = []; this.#swActive = swActive;
// apply "[type=hot/module]" script tags queryElements<HTMLScriptElement>("script[type='hot/module']", (el) => { const copy = el.cloneNode(true) as HTMLScriptElement; copy.type = "module"; el.replaceWith(copy); }); }
listen() { // @ts-expect-error missing types if (typeof clients === "undefined") { throw new Error("Service Worker scope not found."); }
const vfs = this.#vfs; const on: typeof addEventListener = addEventListener; const serveVFS = async (name: string) => { const file = await vfs.get(name); if (!file) { return createResponse("Not Found", {}, 404); } return createResponse(file, { "content-type": file.type }); };
this.#promises.push( vfs.get(kHotArchive).then(async (file) => { if (file) { this.#archive = new Archive(await file.arrayBuffer()); } }).catch((err) => console.error(err[kMessage])), );
on("install", (evt) => { // @ts-expect-error missing types skipWaiting(); evt.waitUntil(Promise.all(this.#promises)); });
on("activate", (evt) => { // @ts-expect-error missing types evt.waitUntil(clients.claim()); });
on("fetch", (evt) => { const { request } = evt as FetchEvent; const respondWith = (res: Response | Promise<Response>) => evt.respondWith(res); const url = new URL(request.url); const { pathname } = url; const archive = this.#archive; if (url.origin === location.origin && pathname.startsWith("/@hot/")) { respondWith(serveVFS(pathname.slice(6))); } if (archive?.exists(request.url)) { const file = archive.openFile(request.url)!; respondWith(createResponse(file, { "content-type": file.type })); } });
on(kMessage, (evt) => { const { data } = evt; if (typeof data === "object" && data !== null) { const buffer = data[kHotArchive]; if (buffer instanceof ArrayBuffer) { try { const archive = new Archive(buffer); if (archive.checksum !== this.#archive?.checksum) { this.#archive = archive; this.#bc.postMessage(kHotArchive); vfs.put(new File([buffer], kHotArchive, { type: kTypeEsmArchive })); } } catch (err) { console.error(err[kMessage]); } } } }); }}
/** query all elements by the given selectors. */function queryElements<T extends Element>( selectors: string, callback: (value: T) => void,) { // @ts-expect-error throw error if document is not available doc.querySelectorAll(selectors).forEach(callback);}
/** create a response object. */function createResponse( body: BodyInit | null, headers: HeadersInit = {}, status = 200,): Response { return new Response(body, { headers, status });}
/** append an element to the document. */function appendElement(tag: string, attrs: Record<string, string>, pos: "head" | "body" = "head") { const el = doc!.createElement(tag); for (const [k, v] of Object.entries(attrs)) { el[k] = v; } doc![pos].appendChild(el);}
/** wait for the given IDBRequest. */function waitIDBRequest<T>(req: IDBRequest): Promise<T> { return new Promise((resolve, reject) => { req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); });}
export const hot = new Hot();export default hot;
esm

Version Info

Tagged at
2 months ago