@inkandswitch/patchwork-bootloader 0.3.0 → 0.3.2
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/CHANGELOG.md +20 -0
- package/dist/automerge-worker.js +468 -9
- package/dist/externals.js +1 -2
- package/dist/module-loader-worker.d.ts +1 -0
- package/dist/module-loader-worker.js +55 -0
- package/dist/module-loader.d.ts +13 -0
- package/dist/module-loader.js +72 -0
- package/dist/service-worker.js +58 -6
- package/dist/setup.d.ts +6 -1
- package/dist/setup.js +177 -2
- package/dist/site.d.ts +7 -7
- package/dist/site.js +194 -71
- package/dist/types.d.ts +72 -0
- package/dist/types.js +6 -0
- package/dist/vite/service-worker-plugin.js +4 -0
- package/package.json +18 -14
- package/src/automerge-worker.ts +512 -9
- package/src/externals.ts +1 -2
- package/src/module-loader-worker.ts +68 -0
- package/src/module-loader.ts +85 -0
- package/src/service-worker.ts +78 -6
- package/src/setup.ts +194 -7
- package/src/site.ts +230 -92
- package/src/types.ts +97 -0
- package/src/vite/service-worker-plugin.ts +4 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
type Descriptor = Record<string, unknown> & {
|
|
2
|
+
id?: string;
|
|
3
|
+
type?: string;
|
|
4
|
+
};
|
|
5
|
+
/**
|
|
6
|
+
* ModuleWatcher `importAutomergeModule` hook: discover descriptors in the
|
|
7
|
+
* worker, then return the `{ plugins }` shape with a main-thread `load()` per
|
|
8
|
+
* plugin that imports the package at heads and calls its real loader.
|
|
9
|
+
*/
|
|
10
|
+
export declare function importAutomergeModuleViaWorker(urlAtHeads: string): Promise<{
|
|
11
|
+
plugins: Descriptor[];
|
|
12
|
+
}>;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Main-thread client for the module-loader worker (see module-loader-worker.ts).
|
|
2
|
+
//
|
|
3
|
+
// `importAutomergeModuleViaWorker` is wired into the ModuleWatcher in place of
|
|
4
|
+
// its default (direct, main-thread) package import. It asks the worker to
|
|
5
|
+
// import the package entry point and report which plugins it exports, then
|
|
6
|
+
// returns the same `{ plugins }` shape the watcher already feeds to
|
|
7
|
+
// `registerPlugins` — except each plugin's `load()` re-imports the package
|
|
8
|
+
// (pinned to the same heads) on this thread and runs the real plugin loader.
|
|
9
|
+
import { importPluginFromFolderDocUrl } from "@inkandswitch/patchwork-filesystem";
|
|
10
|
+
const WORKER_PATH = "/module-loader-worker.js";
|
|
11
|
+
let worker;
|
|
12
|
+
let nextRequestId = 1;
|
|
13
|
+
const pending = new Map();
|
|
14
|
+
function getWorker() {
|
|
15
|
+
if (worker)
|
|
16
|
+
return worker;
|
|
17
|
+
worker = new Worker(WORKER_PATH, {
|
|
18
|
+
type: "module",
|
|
19
|
+
name: "patchwork-module-loader",
|
|
20
|
+
});
|
|
21
|
+
worker.addEventListener("message", (event) => {
|
|
22
|
+
const data = event.data;
|
|
23
|
+
if (!data || (data.type !== "descriptors" && data.type !== "error"))
|
|
24
|
+
return;
|
|
25
|
+
const entry = pending.get(data.id);
|
|
26
|
+
if (!entry)
|
|
27
|
+
return;
|
|
28
|
+
pending.delete(data.id);
|
|
29
|
+
if (data.type === "descriptors")
|
|
30
|
+
entry.resolve(data.descriptors);
|
|
31
|
+
else
|
|
32
|
+
entry.reject(new Error(data.error));
|
|
33
|
+
});
|
|
34
|
+
worker.addEventListener("error", (event) => {
|
|
35
|
+
// An uncaught worker error can't be tied to a single request — fail every
|
|
36
|
+
// outstanding one so callers don't hang.
|
|
37
|
+
const error = new Error(`module-loader worker error: ${event.message ?? "unknown"}`);
|
|
38
|
+
for (const [, entry] of pending)
|
|
39
|
+
entry.reject(error);
|
|
40
|
+
pending.clear();
|
|
41
|
+
});
|
|
42
|
+
return worker;
|
|
43
|
+
}
|
|
44
|
+
/** Ask the worker which plugins the package at `urlAtHeads` exports. */
|
|
45
|
+
function discoverDescriptors(urlAtHeads) {
|
|
46
|
+
const id = nextRequestId++;
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
pending.set(id, { resolve, reject });
|
|
49
|
+
getWorker().postMessage({ type: "discover", id, url: urlAtHeads });
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* ModuleWatcher `importAutomergeModule` hook: discover descriptors in the
|
|
54
|
+
* worker, then return the `{ plugins }` shape with a main-thread `load()` per
|
|
55
|
+
* plugin that imports the package at heads and calls its real loader.
|
|
56
|
+
*/
|
|
57
|
+
export async function importAutomergeModuleViaWorker(urlAtHeads) {
|
|
58
|
+
const url = urlAtHeads;
|
|
59
|
+
const descriptors = await discoverDescriptors(url);
|
|
60
|
+
const plugins = descriptors.map((descriptor) => {
|
|
61
|
+
const { id, type } = descriptor;
|
|
62
|
+
// A plugin id is only unique within a plugin type, so both are needed to
|
|
63
|
+
// re-select the right plugin when its load() re-imports the package.
|
|
64
|
+
if (typeof id !== "string" || typeof type !== "string")
|
|
65
|
+
return descriptor;
|
|
66
|
+
return {
|
|
67
|
+
...descriptor,
|
|
68
|
+
load: () => importPluginFromFolderDocUrl(url, type, id),
|
|
69
|
+
};
|
|
70
|
+
});
|
|
71
|
+
return { plugins };
|
|
72
|
+
}
|
package/dist/service-worker.js
CHANGED
|
@@ -17,7 +17,36 @@ function log(...args) {
|
|
|
17
17
|
return;
|
|
18
18
|
console.log.call(console, `%cpatchwork:serviceworker%c\n`, `color: #00ffcc; font-weight: bold`, "color: inherit", ...args);
|
|
19
19
|
}
|
|
20
|
+
// ── Lifecycle diagnostics ──────────────────────────────────────────────
|
|
21
|
+
// [lifecycle] markers for SW (re)boots, install/activate, crashes, and stranded
|
|
22
|
+
// handoffs. The SW can't read localStorage, so it always emits and forwards to
|
|
23
|
+
// the tab, which gates rendering on the live toggle. The SW holds no sync
|
|
24
|
+
// socket — observability only.
|
|
25
|
+
async function postToClients(message) {
|
|
26
|
+
const clients = await self.clients.matchAll({
|
|
27
|
+
type: "window",
|
|
28
|
+
includeUncontrolled: true,
|
|
29
|
+
});
|
|
30
|
+
for (const client of clients)
|
|
31
|
+
client.postMessage(message);
|
|
32
|
+
}
|
|
33
|
+
function lifecycle(level, text) {
|
|
34
|
+
const msg = `[lifecycle] ${new Date().toISOString()} ${text}`;
|
|
35
|
+
console[level](msg);
|
|
36
|
+
void postToClients({ type: "sw-lifecycle", level, msg });
|
|
37
|
+
}
|
|
38
|
+
lifecycle("info", `booted (scope ${self.registration?.scope ?? "?"})`);
|
|
39
|
+
self.addEventListener("error", (event) => {
|
|
40
|
+
const e = event;
|
|
41
|
+
lifecycle("warn", `uncaught error: ${e.message}` +
|
|
42
|
+
(e.filename ? ` @ ${e.filename}:${e.lineno}:${e.colno}` : ""));
|
|
43
|
+
});
|
|
44
|
+
self.addEventListener("unhandledrejection", (event) => {
|
|
45
|
+
const reason = event.reason;
|
|
46
|
+
lifecycle("warn", `unhandled rejection: ${reason instanceof Error ? reason.stack || reason.message : String(reason)}`);
|
|
47
|
+
});
|
|
20
48
|
self.addEventListener("install", (event) => {
|
|
49
|
+
lifecycle("info", "install (skipWaiting)");
|
|
21
50
|
// waitUntil keeps the worker alive until skipWaiting resolves, so a freshly
|
|
22
51
|
// installed SW reliably jumps the "waiting" queue instead of stalling until
|
|
23
52
|
// every old tab closes.
|
|
@@ -34,12 +63,28 @@ async function clearOldCaches() {
|
|
|
34
63
|
await Promise.all(deletePromises);
|
|
35
64
|
}
|
|
36
65
|
self.addEventListener("activate", (event) => {
|
|
37
|
-
|
|
38
|
-
// runs detached — the new worker can be killed before it takes control, so
|
|
39
|
-
// existing tabs keep talking to the old SW. Extend the event instead.
|
|
66
|
+
lifecycle("info", "activate (claiming clients)");
|
|
40
67
|
event.waitUntil((async () => {
|
|
41
68
|
await clearOldCaches();
|
|
42
69
|
await self.clients.claim();
|
|
70
|
+
// Pre-cache pages of already-open clients so they survive going offline
|
|
71
|
+
// before the next navigation.
|
|
72
|
+
const allClients = await self.clients.matchAll({ type: "window" });
|
|
73
|
+
const cache = await caches.open(cachename);
|
|
74
|
+
await Promise.all(allClients.map(async (client) => {
|
|
75
|
+
try {
|
|
76
|
+
const existing = await cache.match(client.url);
|
|
77
|
+
if (!existing) {
|
|
78
|
+
const response = await fetch(client.url);
|
|
79
|
+
if (cacheableStatuses.includes(response.status)) {
|
|
80
|
+
await cache.put(client.url, response);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
// Network may be unavailable during activation
|
|
86
|
+
}
|
|
87
|
+
}));
|
|
43
88
|
})());
|
|
44
89
|
});
|
|
45
90
|
self.addEventListener("message", async (event) => {
|
|
@@ -72,7 +117,12 @@ handoffChannel.addEventListener("message", (event) => {
|
|
|
72
117
|
else if (data?.type === "online") {
|
|
73
118
|
// The automerge worker (re)started — re-broadcast anything still in
|
|
74
119
|
// flight so requests that raced its boot aren't stranded.
|
|
75
|
-
|
|
120
|
+
const stranded = [...pendingHandoffs.values()];
|
|
121
|
+
if (stranded.length > 0) {
|
|
122
|
+
lifecycle("info", `automerge worker (re)started; re-broadcasting ${stranded.length} ` +
|
|
123
|
+
`in-flight asset handoff(s)`);
|
|
124
|
+
}
|
|
125
|
+
for (const { message } of stranded) {
|
|
76
126
|
log(`re-broadcasting handoff ${message.id} to the fresh worker`);
|
|
77
127
|
handoffChannel.postMessage(message);
|
|
78
128
|
}
|
|
@@ -98,6 +148,8 @@ function handoff(request, handoffURL) {
|
|
|
98
148
|
log(`broadcasting handoff request for cache ${cachename}`, message);
|
|
99
149
|
handoffChannel.postMessage(message);
|
|
100
150
|
const timeout = setTimeout(() => {
|
|
151
|
+
lifecycle("warn", `asset handoff ${id} stranded: no reply from the automerge worker after ` +
|
|
152
|
+
`${HANDOFF_TIMEOUT_MS}ms (${handoffURL.href})`);
|
|
101
153
|
resolvers.reject(new Error(`no reply from the automerge worker after ${HANDOFF_TIMEOUT_MS}ms`));
|
|
102
154
|
}, HANDOFF_TIMEOUT_MS);
|
|
103
155
|
return resolvers.promise.finally(() => {
|
|
@@ -153,7 +205,7 @@ self.addEventListener("fetch", (fetchEvent) => {
|
|
|
153
205
|
// response in our cache
|
|
154
206
|
const cached = await cache.match(request);
|
|
155
207
|
if (!cached) {
|
|
156
|
-
return new Response(`the automerge worker reported ${handoffURL} cached, but it has no match in ${cachename}`, { status:
|
|
208
|
+
return new Response(`the automerge worker reported ${handoffURL} cached, but it has no match in ${cachename}`, { status: 555 });
|
|
157
209
|
}
|
|
158
210
|
log(`serving ${handoffURL} from cache ${cachename} after handoff`);
|
|
159
211
|
return withSpecialHeaders(cached);
|
|
@@ -185,7 +237,7 @@ self.addEventListener("fetch", (fetchEvent) => {
|
|
|
185
237
|
if (match)
|
|
186
238
|
return match;
|
|
187
239
|
return new Response(message, {
|
|
188
|
-
status:
|
|
240
|
+
status: 556,
|
|
189
241
|
headers: { "content-type": "text/plain" },
|
|
190
242
|
});
|
|
191
243
|
}
|
package/dist/setup.d.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import type { SetupServiceWorkerOptions, SetupServiceWorkerResult } from "./types.js";
|
|
1
|
+
import type { SetupServiceWorkerOptions, SetupServiceWorkerResult, SyncStateDocMessage } from "./types.js";
|
|
2
|
+
export declare function lifecycleLoggingEnabled(): boolean;
|
|
2
3
|
export declare function bumpServiceWorkerCache(sw?: ServiceWorker | null): void;
|
|
4
|
+
export declare function getAutomergeWorker(): SharedWorker;
|
|
5
|
+
type SyncStateListener = (update: SyncStateDocMessage) => void;
|
|
6
|
+
export declare function subscribeSyncState(documentId: string, listener: SyncStateListener): () => void;
|
|
3
7
|
export declare function connectClassicSync(server?: string): Promise<void>;
|
|
4
8
|
export default function setupServiceWorker(options?: SetupServiceWorkerOptions): Promise<SetupServiceWorkerResult>;
|
|
9
|
+
export {};
|
package/dist/setup.js
CHANGED
|
@@ -2,6 +2,37 @@ import { readClassicSyncServer, DEFAULT_CLASSIC_SYNC_SERVER, } from "./sync-conf
|
|
|
2
2
|
import debug from "debug";
|
|
3
3
|
const serviceWorkerDebugging = debug.enabled("patchwork:serviceworker");
|
|
4
4
|
const workerDebugging = debug.enabled("patchwork:automergeworker");
|
|
5
|
+
// Diagnostic [lifecycle] logging, on by default. Disable via
|
|
6
|
+
// localStorage["patchwork:lifecycle-logs"] = "off". Read live at log time.
|
|
7
|
+
const LIFECYCLE_LOG_KEY = "patchwork:lifecycle-logs";
|
|
8
|
+
export function lifecycleLoggingEnabled() {
|
|
9
|
+
try {
|
|
10
|
+
const v = globalThis.localStorage?.getItem(LIFECYCLE_LOG_KEY);
|
|
11
|
+
return v !== "off" && v !== "false" && v !== "0" && v !== "no";
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
// The SW can't read localStorage, so it always emits [lifecycle] markers and
|
|
18
|
+
// forwards them as `sw-lifecycle`; gate rendering here on the live toggle.
|
|
19
|
+
let swLifecycleListenerInstalled = false;
|
|
20
|
+
function installServiceWorkerLogForwarding() {
|
|
21
|
+
if (swLifecycleListenerInstalled)
|
|
22
|
+
return;
|
|
23
|
+
if (typeof navigator === "undefined" || !navigator.serviceWorker)
|
|
24
|
+
return;
|
|
25
|
+
swLifecycleListenerInstalled = true;
|
|
26
|
+
navigator.serviceWorker.addEventListener("message", (event) => {
|
|
27
|
+
const data = event.data;
|
|
28
|
+
if (data?.type !== "sw-lifecycle")
|
|
29
|
+
return;
|
|
30
|
+
if (!lifecycleLoggingEnabled())
|
|
31
|
+
return;
|
|
32
|
+
const fn = console[data.level] ?? console.log;
|
|
33
|
+
fn(`[service-worker] ${data.msg}`);
|
|
34
|
+
});
|
|
35
|
+
}
|
|
5
36
|
const key = "patchworkServiceWorkerCacheVersion";
|
|
6
37
|
let nextRepoChannelId = 0;
|
|
7
38
|
function bumpServiceWorkerCacheVersion() {
|
|
@@ -48,7 +79,7 @@ function configureServiceWorker(sw) {
|
|
|
48
79
|
// port; it talks to the service worker over a BroadcastChannel.
|
|
49
80
|
let automergeWorkerPath = "/automerge-worker.js";
|
|
50
81
|
let automergeWorker;
|
|
51
|
-
function getAutomergeWorker() {
|
|
82
|
+
export function getAutomergeWorker() {
|
|
52
83
|
if (!automergeWorker) {
|
|
53
84
|
automergeWorker = new SharedWorker(automergeWorkerPath, {
|
|
54
85
|
name: "patchwork-automerge",
|
|
@@ -57,10 +88,141 @@ function getAutomergeWorker() {
|
|
|
57
88
|
// Control replies (port-ready &c) come back on this port, so it needs
|
|
58
89
|
// start() — we listen with addEventListener, not onmessage.
|
|
59
90
|
automergeWorker.port.start();
|
|
91
|
+
// Surface the SharedWorker's console output and uncaught errors in this
|
|
92
|
+
// tab's console (it has its own console that's awkward to find otherwise).
|
|
93
|
+
automergeWorker.port.addEventListener("message", (event) => {
|
|
94
|
+
if (event.data?.type === "sync-state") {
|
|
95
|
+
dispatchSyncState(event.data);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (event.data?.type !== "console")
|
|
99
|
+
return;
|
|
100
|
+
const { level, args } = event.data;
|
|
101
|
+
// Gate forwarded [lifecycle] logs on the toggle too.
|
|
102
|
+
if (!lifecycleLoggingEnabled() &&
|
|
103
|
+
typeof args?.[0] === "string" &&
|
|
104
|
+
args[0].includes("[lifecycle]")) {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const fn = console[level] ?? console.log;
|
|
108
|
+
// The worker's logs (debug library, the worker's own log()) carry %c
|
|
109
|
+
// format directives in args[0] with CSS in the following args. Prefix
|
|
110
|
+
// the tag into the format string rather than as a separate positional,
|
|
111
|
+
// or the %c would no longer be in arg 0 and the CSS would print raw.
|
|
112
|
+
if (typeof args[0] === "string") {
|
|
113
|
+
fn(`[automerge-worker] ${args[0]}`, ...args.slice(1));
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
fn("[automerge-worker]", ...args);
|
|
117
|
+
}
|
|
118
|
+
});
|
|
60
119
|
automergeWorker.port.postMessage({ type: "debug", debug: workerDebugging });
|
|
120
|
+
installWorkerDeathDetection(automergeWorker);
|
|
61
121
|
}
|
|
62
122
|
return automergeWorker;
|
|
63
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* Detect when the automerge SharedWorker dies or restarts: control-port close,
|
|
126
|
+
* worker error, changed instance id, or an unanswered heartbeat while the tab
|
|
127
|
+
* is visible (a miss while hidden is more likely suspension). [lifecycle]-tagged.
|
|
128
|
+
*/
|
|
129
|
+
function installWorkerDeathDetection(worker) {
|
|
130
|
+
const stamp = () => new Date().toISOString();
|
|
131
|
+
const warn = (msg) => {
|
|
132
|
+
if (lifecycleLoggingEnabled())
|
|
133
|
+
console.warn(`[lifecycle] ${stamp()} ${msg}`);
|
|
134
|
+
};
|
|
135
|
+
const info = (msg) => {
|
|
136
|
+
if (lifecycleLoggingEnabled())
|
|
137
|
+
console.info(`[lifecycle] ${stamp()} ${msg}`);
|
|
138
|
+
};
|
|
139
|
+
let instanceId;
|
|
140
|
+
let lastPongAt = Date.now();
|
|
141
|
+
let warnedUnresponsive = false;
|
|
142
|
+
worker.port.addEventListener("message", (event) => {
|
|
143
|
+
const data = event.data;
|
|
144
|
+
if (data?.type !== "hello" && data?.type !== "pong")
|
|
145
|
+
return;
|
|
146
|
+
if (data.type === "pong") {
|
|
147
|
+
lastPongAt = Date.now();
|
|
148
|
+
warnedUnresponsive = false;
|
|
149
|
+
}
|
|
150
|
+
if (instanceId === undefined) {
|
|
151
|
+
instanceId = data.instanceId;
|
|
152
|
+
info(`automerge SharedWorker instance ${data.instanceId} (via ${data.type})`);
|
|
153
|
+
}
|
|
154
|
+
else if (data.instanceId && data.instanceId !== instanceId) {
|
|
155
|
+
warn(`automerge SharedWorker RESTARTED (instance ${data.instanceId}, ` +
|
|
156
|
+
`was ${instanceId}) — fresh peerId + cold state; docs need re-subscribe`);
|
|
157
|
+
instanceId = data.instanceId;
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
// Fires when the SharedWorker is destroyed (where supported).
|
|
161
|
+
worker.port.addEventListener("close", () => {
|
|
162
|
+
warn("automerge SharedWorker control port CLOSED — worker terminated");
|
|
163
|
+
});
|
|
164
|
+
worker.addEventListener("error", event => {
|
|
165
|
+
warn(`automerge SharedWorker error: ${event.message || event}`);
|
|
166
|
+
});
|
|
167
|
+
// A missed pong while the tab is visible means the worker likely died (an
|
|
168
|
+
// active tab keeps it alive); a miss while hidden is more likely suspension.
|
|
169
|
+
const HEARTBEAT_MS = 10_000;
|
|
170
|
+
const HEARTBEAT_TIMEOUT_MS = 25_000;
|
|
171
|
+
let seq = 0;
|
|
172
|
+
setInterval(() => {
|
|
173
|
+
try {
|
|
174
|
+
worker.port.postMessage({ type: "ping", id: ++seq });
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
// Port already torn down — the "close" handler covers that case.
|
|
178
|
+
}
|
|
179
|
+
const silentMs = Date.now() - lastPongAt;
|
|
180
|
+
const visible = typeof document === "undefined" || document.visibilityState === "visible";
|
|
181
|
+
if (silentMs > HEARTBEAT_TIMEOUT_MS && visible && !warnedUnresponsive) {
|
|
182
|
+
warnedUnresponsive = true;
|
|
183
|
+
warn(`automerge SharedWorker UNRESPONSIVE ~${Math.round(silentMs / 1000)}s ` +
|
|
184
|
+
`while tab visible — likely died/crashed`);
|
|
185
|
+
}
|
|
186
|
+
}, HEARTBEAT_MS);
|
|
187
|
+
}
|
|
188
|
+
const syncStateListeners = new Map();
|
|
189
|
+
function dispatchSyncState(update) {
|
|
190
|
+
const listeners = syncStateListeners.get(update.documentId);
|
|
191
|
+
if (!listeners)
|
|
192
|
+
return;
|
|
193
|
+
for (const listener of listeners) {
|
|
194
|
+
try {
|
|
195
|
+
listener(update);
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
console.error("sync-state listener threw", err);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
export function subscribeSyncState(documentId, listener) {
|
|
203
|
+
const worker = getAutomergeWorker();
|
|
204
|
+
let listeners = syncStateListeners.get(documentId);
|
|
205
|
+
if (!listeners) {
|
|
206
|
+
syncStateListeners.set(documentId, (listeners = new Set()));
|
|
207
|
+
// First local watcher for this doc — ask the worker to start pushing it.
|
|
208
|
+
worker.port.postMessage({ type: "sync-sub", documentId });
|
|
209
|
+
}
|
|
210
|
+
listeners.add(listener);
|
|
211
|
+
let active = true;
|
|
212
|
+
return () => {
|
|
213
|
+
if (!active)
|
|
214
|
+
return; // idempotent
|
|
215
|
+
active = false;
|
|
216
|
+
const set = syncStateListeners.get(documentId);
|
|
217
|
+
if (!set)
|
|
218
|
+
return;
|
|
219
|
+
set.delete(listener);
|
|
220
|
+
if (set.size === 0) {
|
|
221
|
+
syncStateListeners.delete(documentId);
|
|
222
|
+
worker.port.postMessage({ type: "sync-unsub", documentId });
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
}
|
|
64
226
|
export function connectClassicSync(server = readClassicSyncServer()) {
|
|
65
227
|
const url = server.trim() || DEFAULT_CLASSIC_SYNC_SERVER;
|
|
66
228
|
if (!/^wss?:\/\//.test(url)) {
|
|
@@ -155,11 +317,15 @@ function getRepoChannel() {
|
|
|
155
317
|
return port1;
|
|
156
318
|
}
|
|
157
319
|
export default async function setupServiceWorker(options) {
|
|
320
|
+
// Attach the SW→tab [lifecycle] log bridge as early as possible so boot /
|
|
321
|
+
// install / activate markers from the controlling worker are rendered here.
|
|
322
|
+
installServiceWorkerLogForwarding();
|
|
158
323
|
if (options?.workerPath)
|
|
159
324
|
automergeWorkerPath = options.workerPath;
|
|
160
325
|
// Start the automerge worker right away so it boots (wasm, repo) while the
|
|
161
326
|
// service worker installs.
|
|
162
|
-
getAutomergeWorker();
|
|
327
|
+
const shared = getAutomergeWorker();
|
|
328
|
+
// todo delete
|
|
163
329
|
const path = options?.path ?? "/service-worker.js";
|
|
164
330
|
// No controller at this point means the page loaded without a service
|
|
165
331
|
// worker — i.e. this is a first-time install (or a hard reload). Wait for
|
|
@@ -183,9 +349,18 @@ export default async function setupServiceWorker(options) {
|
|
|
183
349
|
configureServiceWorker(navigator.serviceWorker.controller);
|
|
184
350
|
});
|
|
185
351
|
console.log("service worker alive, loading %c patchwork system ", "background: #fcf2f0; color: #333; border: 2px solid; border-radius: 4px");
|
|
352
|
+
// todon't
|
|
353
|
+
window.killsw = () => {
|
|
354
|
+
if (automergeWorker) {
|
|
355
|
+
automergeWorker.port.close();
|
|
356
|
+
automergeWorker = undefined;
|
|
357
|
+
}
|
|
358
|
+
};
|
|
186
359
|
return {
|
|
360
|
+
shared,
|
|
187
361
|
connectClassicSync,
|
|
188
362
|
getRepoChannel,
|
|
363
|
+
subscribeSyncState,
|
|
189
364
|
async subscribeToRepoChannel(listener) {
|
|
190
365
|
// The automerge worker outlives the page, so unlike the old in-service-
|
|
191
366
|
// worker repo there's nothing to reconnect: one port, handed over once.
|
package/dist/site.d.ts
CHANGED
|
@@ -11,12 +11,12 @@
|
|
|
11
11
|
* site's `main.ts`. Non-UI consumers should import the package default (which
|
|
12
12
|
* only does SW registration and the automerge-worker handoff).
|
|
13
13
|
*/
|
|
14
|
-
import { type DocHandle, Repo, type AutomergeUrl
|
|
14
|
+
import { type DocHandle, Repo, type AutomergeUrl } from "@automerge/vanillajs/slim";
|
|
15
15
|
import { type AutomergeRepoKeyhive } from "@automerge/automerge-repo-keyhive";
|
|
16
16
|
import { ModuleWatcher } from "@inkandswitch/patchwork-filesystem";
|
|
17
17
|
import { type AccountDoc } from "@inkandswitch/patchwork-plugins";
|
|
18
18
|
import * as plugins from "@inkandswitch/patchwork-plugins";
|
|
19
|
-
import type { ServiceWorkerRepoChannelListener } from "./types.js";
|
|
19
|
+
import type { ServiceWorkerRepoChannelListener, SyncStateDocMessage } from "./types.js";
|
|
20
20
|
declare global {
|
|
21
21
|
interface Window {
|
|
22
22
|
accountDocHandle: DocHandle<AccountDoc>;
|
|
@@ -30,9 +30,14 @@ declare global {
|
|
|
30
30
|
packages: ModuleWatcher;
|
|
31
31
|
plugins: typeof plugins;
|
|
32
32
|
accountDocHandle: DocHandle<AccountDoc>;
|
|
33
|
+
signer?: {
|
|
34
|
+
peerId: string;
|
|
35
|
+
verifyingKey: string;
|
|
36
|
+
};
|
|
33
37
|
sw: {
|
|
34
38
|
connectClassicSync: (server?: string) => Promise<void>;
|
|
35
39
|
subscribeToRepoChannel: (listener: ServiceWorkerRepoChannelListener) => Promise<() => void>;
|
|
40
|
+
subscribeSyncState: (documentId: string, listener: (update: SyncStateDocMessage) => void) => () => void;
|
|
36
41
|
};
|
|
37
42
|
};
|
|
38
43
|
uncache: (match: string) => Promise<void>;
|
|
@@ -82,11 +87,6 @@ export interface SiteConfig {
|
|
|
82
87
|
* Defaults to `"root"`.
|
|
83
88
|
*/
|
|
84
89
|
rootElementId?: string;
|
|
85
|
-
/**
|
|
86
|
-
* Storage IDs to subscribe to for remote-heads gossiping. Defaults to
|
|
87
|
-
* Ink & Switch's production Subduction storage.
|
|
88
|
-
*/
|
|
89
|
-
remoteStorageIds?: StorageId[];
|
|
90
90
|
/**
|
|
91
91
|
* When true, initialize keyhive for access control.
|
|
92
92
|
* The Repo will use keyhive's network adapter, peerId, and idFactory
|