@inkandswitch/patchwork-bootloader 0.4.3 → 0.5.0

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.
package/dist/site.js DELETED
@@ -1,602 +0,0 @@
1
- /**
2
- * High-level browser-app boot sequence for a Patchwork site.
3
- *
4
- * Layers on top of {@link setupServiceWorker} (the package default export) to
5
- * construct the Repo, wire up the automerge-worker port, load plugins via the
6
- * ModuleWatcher, resolve the user's account document, and hand control to the
7
- * configured root tool.
8
- *
9
- * This entry point pulls in DOM- and plugin-layer dependencies (patchwork
10
- * elements, plugins, filesystem) and is intended for use only from a browser
11
- * site's `main.ts`. Non-UI consumers should import the package default (which
12
- * only does SW registration and the automerge-worker handoff).
13
- */
14
- import { initializeWasm, isValidAutomergeUrl, isValidDocumentId, MessageChannelNetworkAdapter, Repo, stringifyAutomergeUrl, } from "@automerge/vanillajs/slim";
15
- import { IndexedDBWorkerStorageAdapter } from "@automerge/automerge-repo-storage-indexeddb/IndexedDBWorkerStorageAdapter";
16
- import * as Automerge from "@automerge/automerge/slim";
17
- import * as AutomergeRepo from "@automerge/automerge-repo/slim";
18
- import { initKeyhiveWasm, initializeAutomergeRepoKeyhiveWithRepo, } from "@automerge/automerge-repo-keyhive";
19
- // eslint-disable-next-line
20
- // @ts-ignore — initSync is a wasm-bindgen runtime helper not in the .d.ts
21
- import { initSync as initSubductionSync } from "@automerge/automerge-subduction/slim";
22
- import { MemorySigner } from "@automerge/automerge-subduction/slim";
23
- const siteName = typeof __SITE_NAME__ !== "undefined" ? __SITE_NAME__ : "patchwork.inkandswitch.com";
24
- const useKeyhiveSyncServer = typeof __KEYHIVE_SYNC_SERVER__ !== "undefined" && __KEYHIVE_SYNC_SERVER__;
25
- import { ModuleWatcher } from "@inkandswitch/patchwork-filesystem";
26
- import { importAutomergePackageViaWorker } from "./module-loader.js";
27
- import { openDocument, registerPatchworkViewElement, } from "@inkandswitch/patchwork-elements";
28
- import { registerRepoProviderElement } from "@inkandswitch/patchwork-providers";
29
- import { getRegistry, registerPlugins, resolveAccountHandle, unregisterPlugins, } from "@inkandswitch/patchwork-plugins";
30
- import * as plugins from "@inkandswitch/patchwork-plugins";
31
- import setupServiceWorker, { lifecycleLoggingEnabled } from "./setup.js";
32
- import debug from "debug";
33
- const log = debug("patchwork:bootloader:site");
34
- // Legacy big-patchwork hash shape: `<slug>--<documentId>[?…]`. The slug can
35
- // contain characters we don't otherwise permit (e.g. `drawing-(branch-1)`), so
36
- // we anchor on the `--` before the base58 document id and allow any non-query
37
- // characters ahead of it rather than a strict slug charset.
38
- const BIG_PATCHWORK_HASH_REGEX = /^(?<title>[^=&?/#]*)--(?<docId>[1-9A-HJ-NP-Za-km-z]+)/;
39
- const [automergeWasm, subductionWasm] = await Promise.all([
40
- fetch("/automerge.wasm").then((r) => r.bytes()),
41
- fetch("/subduction.wasm").then((r) => r.bytes()),
42
- ]);
43
- /**
44
- * Boot a Patchwork browser site.
45
- *
46
- * Performs the full application-shell setup: service worker + port, Repo,
47
- * plugin/module loading, account resolution, URL-hash routing, and dev-console
48
- * globals (`window.repo`, `window.patchwork`, `window.uncache`). Returns the
49
- * constructed Repo, ModuleWatcher and account handle for sites that want to
50
- * do additional wiring after boot.
51
- */
52
- export async function bootPatchworkSite(config) {
53
- const defaultModuleSources = resolveDefaultModules(config);
54
- showLoadingAnimation();
55
- log(`booting`, config);
56
- installLifecycleLogging();
57
- await initializeWasm(automergeWasm);
58
- initSubductionSync(subductionWasm);
59
- log("enabling workers");
60
- const sw = await setupServiceWorker();
61
- if (!sw)
62
- throw new Error("Failed to set up service worker");
63
- log("workers ready");
64
- let hive;
65
- let repo;
66
- let tabSignerIdentity;
67
- // Called with a fresh port when the automerge worker dies and is recreated
68
- // (see recoverAutomergeWorker in setup.ts); assigned once the repo exists.
69
- let onWorkerPortRenewed;
70
- // If a Repo is already on `window` — an embedding context provided one before
71
- // this entry ran — reuse it and its keyhive instead of standing up a fresh
72
- // realm-local Repo, so we share the same documents and sync/keyhive context.
73
- // Otherwise create our own below.
74
- if (window.repo) {
75
- log("using existing Repo from window");
76
- repo = window.repo;
77
- hive = window.hive;
78
- }
79
- else {
80
- // Get the initial automerge-worker port via subscribeToRepoChannel,
81
- // then pass it to keyhive init which wraps it in its own network adapter.
82
- // The listener is called again with a fresh port if the worker is ever
83
- // recreated after dying.
84
- let resolveFirstPort;
85
- const firstPortPromise = new Promise((r) => {
86
- resolveFirstPort = r;
87
- });
88
- let seenFirstPort = false;
89
- log("subscribing to repo channel");
90
- // Deliberately not awaited: subscribeToRepoChannel resolves only after
91
- // the boot channel's port-ready handshake, which can take its full 30s
92
- // timeout against a stranded worker connection. Boot should block on the
93
- // first *delivered* port instead — if the boot channel stalls, worker
94
- // recovery hands the listener a good port long before that timeout.
95
- void sw.subscribeToRepoChannel((port) => {
96
- if (!seenFirstPort) {
97
- seenFirstPort = true;
98
- resolveFirstPort(port);
99
- }
100
- else if (onWorkerPortRenewed) {
101
- onWorkerPortRenewed(port);
102
- }
103
- else {
104
- console.warn("automerge worker port renewed before the repo existed; dropping it");
105
- }
106
- });
107
- const workerPort = await firstPortPromise;
108
- log("repo channel subscribed");
109
- let workerAdapter = new MessageChannelNetworkAdapter(workerPort);
110
- if (config.keyhive) {
111
- log("setting up keyhive");
112
- initKeyhiveWasm();
113
- ({ hive, repo } = await initializeAutomergeRepoKeyhiveWithRepo({
114
- createRepo: (config) => new Repo(config),
115
- storage: new IndexedDBWorkerStorageAdapter(`${siteName}-keyhive`),
116
- peerIdSuffix: siteName + Math.random().toString(36).slice(2),
117
- networkAdapter: workerAdapter,
118
- automaticArchiveIngestion: true,
119
- cachingMode: "periodic",
120
- onlyShareWithHardcodedServerPeerId: false,
121
- // ARK selects the relay via `syncServer` ("keyhive" | "subduction").
122
- // Defaults to "subduction".
123
- ...(useKeyhiveSyncServer ? { syncServer: "keyhive" } : {}),
124
- repo: {
125
- storage: new IndexedDBWorkerStorageAdapter(),
126
- enableRemoteHeadsGossiping: true,
127
- },
128
- }));
129
- log("keyhive setup complete");
130
- }
131
- else {
132
- log("creating repo");
133
- // Pass an explicit signer (instead of the Repo's internal default) so we
134
- // can expose tab signer identity on window.patchwork for dev inspection.
135
- // The tab never connects via Subduction (no endpoints/adapters), so this
136
- // id never goes on the wire.
137
- const tabSigner = new MemorySigner();
138
- repo = new Repo({
139
- network: [workerAdapter],
140
- storage: new IndexedDBWorkerStorageAdapter(),
141
- signer: tabSigner,
142
- async sharePolicy(peerId) {
143
- return peerId.includes("automerge-worker");
144
- },
145
- enableRemoteHeadsGossiping: true,
146
- peerId: `${config.titleSuffix}-tab-${crypto.randomUUID()}`,
147
- });
148
- tabSignerIdentity = {
149
- peerId: tabSigner.peerId().toString(),
150
- verifyingKey: tabSigner.verifyingKey().toHex(),
151
- };
152
- console.log("[patchwork] tab subduction identity:", tabSignerIdentity);
153
- log("repo created");
154
- }
155
- // The worker was recreated with cold state: wire the repo onto the fresh
156
- // port and drop the adapter stranded on the dead one. `repo`/`hive` are
157
- // settled by the time this can fire (recovery needs a missed heartbeat).
158
- const bootHive = hive;
159
- onWorkerPortRenewed = (port) => {
160
- const fresh = new MessageChannelNetworkAdapter(port);
161
- // Mirror the boot wiring: a keyhive repo talks to the worker through a
162
- // keyhive adapter wrapped around the message channel (same parameters
163
- // the worker uses for its side of the pair).
164
- const registered = bootHive
165
- ? bootHive.createKeyhiveNetworkAdapter(fresh, false, false, 2000)
166
- : fresh;
167
- repo.networkSubsystem.addNetworkAdapter(registered);
168
- for (const adapter of [...repo.networkSubsystem.adapters]) {
169
- if (adapter === registered)
170
- continue;
171
- // The keyhive wrapper keeps the wrapped adapter on `.networkAdapter`.
172
- const base = adapter.networkAdapter ?? adapter;
173
- if (base !== workerAdapter)
174
- continue;
175
- try {
176
- repo.networkSubsystem.removeNetworkAdapter(adapter);
177
- }
178
- catch (err) {
179
- console.error("failed to remove stale worker network adapter", err);
180
- }
181
- }
182
- workerAdapter = fresh;
183
- console.warn(`[lifecycle] ${new Date().toISOString()} repo re-wired to the ` +
184
- `recreated automerge worker`);
185
- };
186
- }
187
- log("popping repo on window");
188
- window.repo = repo;
189
- log("await repo.networkSubsystem.whenReady()");
190
- await repo.networkSubsystem.whenReady();
191
- log("networkSubsystem ready");
192
- if (hive) {
193
- hive.networkAdapter.syncKeyhive?.();
194
- }
195
- installDevConsoleGlobals(repo, hive, sw.getRepoChannel);
196
- registerRepoProviderElement(repo);
197
- const rootElement = document.getElementById(config.rootElementId ?? "root");
198
- if (!rootElement) {
199
- throw new Error(`bootPatchworkSite: no element with id="${config.rootElementId ?? "root"}"`);
200
- }
201
- // `<repo-provider>` sits above the root and answers `repo:handle-descriptor`
202
- // for any view outside a remapper (resolving to the requested url unchanged).
203
- const repoProvider = document.createElement("repo-provider");
204
- rootElement.parentElement.insertBefore(repoProvider, rootElement);
205
- repoProvider.appendChild(rootElement);
206
- registerPatchworkViewElement({ hive, repo });
207
- // The watcher is started with the site's default-tools bundle alone so that
208
- // `resolveAccountHandle` below has something to await on (the `account`
209
- // datatype lives in that bundle today). The user's own module-settings URL
210
- // is added lazily once it appears on the account doc — see below.
211
- const moduleWatcher = new ModuleWatcher(repo, buildSystemSources(defaultModuleSources), onModuleLoaded, unregisterPlugins,
212
- // Discover an Automerge package's plugin descriptors off the main thread;
213
- // each plugin's load() re-imports the package (at heads) on this thread.
214
- importAutomergePackageViaWorker);
215
- const accountDocHandle = (await resolveAccountHandle(repo, {
216
- storageKey: config.accountStorageKey,
217
- hive,
218
- }));
219
- // TODO: something we (Orion & pvh) changed in the types made this necessary
220
- // fix this before merging to main!
221
- window.accountDocHandle = accountDocHandle;
222
- wireModuleSettingsWhenReady(accountDocHandle, moduleWatcher);
223
- primeRootElement(rootElement, accountDocHandle);
224
- logToolRegistryWhenLoaded(moduleWatcher);
225
- window.patchwork = {
226
- repo,
227
- packages: moduleWatcher,
228
- plugins,
229
- accountDocHandle,
230
- ...(tabSignerIdentity ? { signer: tabSignerIdentity } : {}),
231
- sw: {
232
- connectClassicSync: sw.connectClassicSync,
233
- subscribeToRepoChannel: sw.subscribeToRepoChannel,
234
- subscribeSyncState: sw.subscribeSyncState,
235
- },
236
- };
237
- window.uncache = uncache;
238
- installHashRouting({
239
- rootElement,
240
- repo,
241
- accountDocHandle,
242
- titleSuffix: config.titleSuffix,
243
- });
244
- return { repo, moduleWatcher, accountDocHandle };
245
- }
246
- // ─── Internals ──────────────────────────────────────────────────────────
247
- /**
248
- * A module-list source is valid if it is an Automerge URL or looks like an
249
- * HTTP(S)/site-relative manifest URL.
250
- */
251
- function isValidModuleSource(source) {
252
- if (isValidAutomergeUrl(source))
253
- return true;
254
- return (source.startsWith("/") ||
255
- source.startsWith("http://") ||
256
- source.startsWith("https://") ||
257
- source.startsWith("./"));
258
- }
259
- /**
260
- * Resolve the site's default module-list sources, honouring the
261
- * `localStorage.systemPackageListURL` dev override (which replaces the entire
262
- * built-in default bundle).
263
- */
264
- function resolveDefaultModules(config) {
265
- const builtin = config.defaultModules ?? config.defaultModulesUrl ?? [];
266
- const builtinList = (Array.isArray(builtin) ? builtin : [builtin]).filter(Boolean);
267
- const storage = globalThis.localStorage;
268
- // `defaultToolsUrl` is the pre-rename key, still honoured for existing browsers.
269
- const override = storage?.getItem("systemPackageListURL") ??
270
- storage?.getItem("defaultToolsUrl");
271
- if (override) {
272
- if (isValidModuleSource(override)) {
273
- if (!builtinList.includes(override)) {
274
- console.info(`using systemPackageListURL override from localStorage: ${override}`);
275
- }
276
- return [override];
277
- }
278
- console.warn(`ignoring invalid systemPackageListURL in localStorage: ${override}; using built-in default`);
279
- }
280
- if (builtinList.length === 0) {
281
- throw new Error("bootPatchworkSite: no default module sources configured (set `defaultModules`)");
282
- }
283
- return builtinList;
284
- }
285
- /**
286
- * Turn an ordered list of module-list sources into the name-keyed map the
287
- * ModuleWatcher expects. The first source keeps the canonical `system` name;
288
- * additional sources get suffixed names. None may be `user` (reserved for the
289
- * per-account settings doc, which has branch-override precedence).
290
- */
291
- function buildSystemSources(sources) {
292
- const map = {};
293
- sources.forEach((source, index) => {
294
- const name = index === 0 ? "system" : `system-${index}`;
295
- map[name] = source;
296
- });
297
- return map;
298
- }
299
- function installDevConsoleGlobals(repo, hive, getRepoChannel) {
300
- window.repo = repo;
301
- window.Automerge = Automerge;
302
- window.AutomergeRepo = AutomergeRepo;
303
- if (hive) {
304
- window.hive = hive;
305
- }
306
- window.getRepoChannel = getRepoChannel;
307
- }
308
- /**
309
- * Log this tab's Page Lifecycle + connectivity transitions (visibility,
310
- * freeze, bfcache, online/offline) so they line up against the SharedWorker's
311
- * sync-socket reaps. [lifecycle]-tagged, on by default.
312
- */
313
- function installLifecycleLogging() {
314
- if (typeof document === "undefined")
315
- return;
316
- const opts = { capture: true };
317
- const note = (label, extra) => {
318
- if (!lifecycleLoggingEnabled())
319
- return;
320
- const msg = `[lifecycle] ${new Date().toISOString()} ${label}`;
321
- if (extra === undefined)
322
- console.info(msg);
323
- else
324
- console.info(msg, extra);
325
- };
326
- document.addEventListener("visibilitychange", () => note(`visibilitychange → ${document.visibilityState}`), opts);
327
- document.addEventListener("freeze", () => note("freeze (tab suspended)"), opts);
328
- document.addEventListener("resume", () => note("resume (tab unsuspended)"), opts);
329
- window.addEventListener("pageshow", (e) => note("pageshow", { persisted: e.persisted }), opts);
330
- window.addEventListener("pagehide", (e) => note("pagehide", { persisted: e.persisted }), opts);
331
- window.addEventListener("online", () => note("online"), opts);
332
- window.addEventListener("offline", () => note("offline"), opts);
333
- note(`lifecycle logging installed (visibilityState=${document.visibilityState}, hasFocus=${document.hasFocus()})`);
334
- }
335
- function onModuleLoaded(name, mod) {
336
- if (Array.isArray(mod.plugins)) {
337
- log(`registering ${mod.plugins.length} plugin(s) from ${name.slice(0, 30)}...`, mod.plugins.map((p) => `${p.type}:${p.id}`));
338
- registerPlugins(mod.plugins, name);
339
- }
340
- else {
341
- console.warn(`module ${name.slice(0, 30)}... has no plugins array`, Object.keys(mod));
342
- }
343
- }
344
- /**
345
- * The frame lazy-creates `moduleSettingsUrl` on first mount. Watch for it to
346
- * appear on the account doc and feed it into the ModuleWatcher so the user's
347
- * own tool bundle loads alongside the site default. Idempotent.
348
- */
349
- function wireModuleSettingsWhenReady(accountDocHandle, moduleWatcher) {
350
- const wire = () => {
351
- const url = accountDocHandle.doc()?.moduleSettingsUrl;
352
- if (!url)
353
- return;
354
- void moduleWatcher.addUrl("user", url);
355
- accountDocHandle.off("change", wire);
356
- };
357
- wire();
358
- if (!accountDocHandle.doc()?.moduleSettingsUrl) {
359
- accountDocHandle.on("change", wire);
360
- }
361
- }
362
- /**
363
- * Set initial `tool-id` / `doc-url` attributes on the root
364
- * `<patchwork-view>` based on the URL hash (if it specifies a frame
365
- * override) or the account doc's configured frame tool + the account doc
366
- * itself.
367
- */
368
- function primeRootElement(rootElement, accountDocHandle) {
369
- rootElement.style.visibility = "hidden";
370
- const initialParams = new URLSearchParams(location.hash.slice(1));
371
- if (initialParams.has("frame")) {
372
- rootElement.setAttribute("tool-id", initialParams.get("frame"));
373
- const docUrl = docParamToUrl(initialParams.get("doc")) ?? accountDocHandle.url;
374
- rootElement.setAttribute("doc-url", docUrl);
375
- }
376
- else {
377
- rootElement.setAttribute("tool-id", accountDocHandle.doc().frameToolId);
378
- rootElement.setAttribute("doc-url", accountDocHandle.url);
379
- }
380
- }
381
- function logToolRegistryWhenLoaded(moduleWatcher) {
382
- moduleWatcher.doneLoading
383
- .then(() => {
384
- const toolReg = getRegistry("patchwork:tool");
385
- const tools = toolReg.all();
386
- log(`doneLoading: ${tools.length} tools registered:`, tools.map((t) => t.id));
387
- })
388
- .catch((err) => {
389
- console.error("doneLoading rejected:", err);
390
- });
391
- }
392
- const LOADING_STYLE_ID = "pw-bootloader-loading-styles";
393
- const LOADING_ELEMENT_ID = "pw-bootloader-loading";
394
- function showLoadingAnimation() {
395
- if (!document.getElementById(LOADING_STYLE_ID)) {
396
- const style = document.createElement("style");
397
- style.id = LOADING_STYLE_ID;
398
- style.textContent = `
399
- @keyframes pw-bootloader-pulse {
400
- 0%, 100% { opacity: 0.25; }
401
- 50% { opacity: 0.95; }
402
- }
403
- #${LOADING_ELEMENT_ID} {
404
- position: fixed;
405
- inset: 0;
406
- z-index: 0;
407
- pointer-events: none;
408
- background-color: #fff;
409
- background-image:
410
- radial-gradient(ellipse 55% 45% at 28% 35%, #fde4ec, transparent 70%),
411
- radial-gradient(ellipse 50% 55% at 72% 65%, #e0f0fb, transparent 70%),
412
- radial-gradient(ellipse 65% 55% at 50% 50%, #f1e6f6, transparent 80%);
413
- animation: pw-bootloader-pulse 3.5s ease-in-out infinite;
414
- transition: opacity 0.6s ease-out;
415
- top: 0;
416
- left: 0;
417
- right: 0;
418
- bottom: 0;
419
- }
420
- @media (prefers-color-scheme: dark) {
421
- #${LOADING_ELEMENT_ID} {
422
- background-color: #000;
423
- background-image:
424
- radial-gradient(ellipse 55% 45% at 28% 35%, #2a1d33, transparent 70%),
425
- radial-gradient(ellipse 50% 55% at 72% 65%, #1a2738, transparent 70%),
426
- radial-gradient(ellipse 65% 55% at 50% 50%, #221a2e, transparent 80%);
427
- }
428
- }
429
- #${LOADING_ELEMENT_ID}.pw-bootloader-fading {
430
- opacity: 0;
431
- animation: none;
432
- }
433
- `;
434
- document.head.appendChild(style);
435
- }
436
- if (document.getElementById(LOADING_ELEMENT_ID))
437
- return;
438
- const el = document.createElement("div");
439
- el.id = LOADING_ELEMENT_ID;
440
- document.body.appendChild(el);
441
- }
442
- function hideLoadingAnimation() {
443
- const el = document.getElementById(LOADING_ELEMENT_ID);
444
- if (!el)
445
- return;
446
- el.classList.add("pw-bootloader-fading");
447
- setTimeout(() => el.remove(), 700);
448
- }
449
- async function uncache(match) {
450
- for (const name of await caches.keys()) {
451
- const cache = await caches.open(name);
452
- for (const request of await cache.keys()) {
453
- if (request.url.includes(match)) {
454
- cache.delete(request);
455
- }
456
- }
457
- }
458
- }
459
- // The `doc=` value is an automerge URL — we keep its `:` (and any `#`/`|`
460
- // heads) literal rather than percent-encoding it so links stay readable.
461
- const RAW_HASH_KEYS = new Set(["doc"]);
462
- // Emit hash params in a stable order so re-serializing the same logical params
463
- // yields a byte-identical string (avoids spurious `hashchange` round-trips).
464
- const HASH_KEY_ORDER = ["doc", "tool", "type", "title", "frame"];
465
- function serializeHashParams(params) {
466
- const emitted = new Set();
467
- const parts = [];
468
- const emit = (key) => {
469
- if (emitted.has(key))
470
- return;
471
- const value = params.get(key);
472
- if (!value)
473
- return;
474
- emitted.add(key);
475
- parts.push(`${key}=${RAW_HASH_KEYS.has(key) ? value : encodeURIComponent(value)}`);
476
- };
477
- for (const key of HASH_KEY_ORDER)
478
- emit(key);
479
- for (const key of params.keys())
480
- emit(key);
481
- return parts.join("&");
482
- }
483
- /**
484
- * Coerce a `doc=` hash param to a full automerge URL. Accepts a full URL
485
- * (`automerge:<id>[#heads]`) or a bare document id for backwards compatibility
486
- * with older links.
487
- */
488
- function docParamToUrl(docParam) {
489
- if (!docParam)
490
- return undefined;
491
- if (isValidAutomergeUrl(docParam)) {
492
- return docParam;
493
- }
494
- const documentId = docParam.replace(/^automerge:/, "");
495
- if (isValidDocumentId(documentId)) {
496
- return stringifyAutomergeUrl({ documentId: documentId });
497
- }
498
- return undefined;
499
- }
500
- function installHashRouting(params) {
501
- const { rootElement, repo, accountDocHandle, titleSuffix } = params;
502
- rootElement.addEventListener("patchwork:open-document", async (event) => {
503
- const params = new URLSearchParams(window.location.hash.slice(1));
504
- const { url, toolId, type, title } = event.detail;
505
- // `doc` is now the full automerge URL — heads, if any, live inside it, so
506
- // the separate `heads=` param is gone.
507
- params.delete("heads");
508
- params.set("doc", url);
509
- if (toolId)
510
- params.set("tool", toolId);
511
- else
512
- params.delete("tool");
513
- if (title)
514
- params.set("title", title);
515
- else
516
- params.delete("title");
517
- if (type)
518
- params.set("type", type);
519
- else
520
- params.delete("type");
521
- window.location.hash = serializeHashParams(params);
522
- try {
523
- const docHandle = await repo.find(url);
524
- const doc = docHandle.doc();
525
- const docType = type || doc?.["@patchwork"]?.type;
526
- if (!docType)
527
- return;
528
- const registry = getRegistry("patchwork:datatype");
529
- const datatype = await registry.load(docType);
530
- if (!datatype)
531
- return;
532
- const docTitle = datatype.module.getTitle(doc);
533
- if (docTitle) {
534
- document.title = `${docTitle} | ${titleSuffix}`;
535
- }
536
- }
537
- catch (e) {
538
- console.error("Failed to update document title", e);
539
- }
540
- });
541
- let firstMount = true;
542
- const reveal = () => {
543
- if (!firstMount)
544
- return;
545
- firstMount = false;
546
- rootElement.style.visibility = "visible";
547
- hideLoadingAnimation();
548
- };
549
- rootElement.addEventListener("patchwork:mounted", (event) => {
550
- handleHashChange();
551
- if (event.target !== rootElement)
552
- return;
553
- console.info("root element mounted");
554
- reveal();
555
- // Re-resolve routing after a beat so deep-links from freshly-loaded tools
556
- // get a second chance to render.
557
- setTimeout(handleHashChange, 1000);
558
- });
559
- // Failsafe: if nothing ever mounts, reveal the element anyway after 12s so
560
- // the user sees *something* rather than a blank page.
561
- setTimeout(reveal, 12_000);
562
- const handleHashChange = async () => {
563
- const hash = window.location.hash.slice(1);
564
- // Legacy big-patchwork link (`<slug>--<docId>?…`): if the hash carries a
565
- // `--` followed by a valid document id, normalize it to the canonical
566
- // `#doc=automerge:<docId>` form and let routing re-run on the hashchange.
567
- const legacyDocId = BIG_PATCHWORK_HASH_REGEX.exec(hash)?.groups?.docId;
568
- if (legacyDocId && isValidDocumentId(legacyDocId)) {
569
- window.location.hash = serializeHashParams(new URLSearchParams({
570
- doc: stringifyAutomergeUrl({ documentId: legacyDocId }),
571
- }));
572
- return;
573
- }
574
- // Bare automerge URL in hash: /#automerge:<documentId>
575
- if (isValidAutomergeUrl(hash)) {
576
- const url = hash;
577
- window.location.hash = "";
578
- openDocument(rootElement, url);
579
- return;
580
- }
581
- const params = new URLSearchParams(hash);
582
- const docUrl = docParamToUrl(params.get("doc"));
583
- const toolId = params.get("tool");
584
- const title = params.get("title");
585
- const type = params.get("type");
586
- const frame = params.get("frame");
587
- if (frame) {
588
- const frameDocUrl = docUrl ?? accountDocHandle.url;
589
- if (rootElement.getAttribute("tool-id") !== frame ||
590
- rootElement.getAttribute("doc-url") !== frameDocUrl) {
591
- rootElement.setAttribute("tool-id", frame);
592
- rootElement.setAttribute("doc-url", frameDocUrl);
593
- }
594
- }
595
- if (docUrl) {
596
- rootElement.dispatchEvent(new CustomEvent("patchwork:open-document", {
597
- detail: { url: docUrl, toolId, title, type },
598
- }));
599
- }
600
- };
601
- window.addEventListener("hashchange", handleHashChange);
602
- }
@@ -1,4 +0,0 @@
1
- import type { Plugin } from "vite";
2
- import type { PatchworkVitePluginOptions } from "./patchwork-plugin.js";
3
- export declare const builtins: Record<string, string>;
4
- export declare function importmap(options?: PatchworkVitePluginOptions): Plugin;