@wcstack/worker 1.12.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/README.ja.md +184 -0
- package/README.md +184 -0
- package/dist/auto.js +3 -0
- package/dist/auto.min.js +3 -0
- package/dist/index.d.ts +252 -0
- package/dist/index.esm.js +595 -0
- package/dist/index.esm.js.map +1 -0
- package/dist/index.esm.min.js +2 -0
- package/dist/index.esm.min.js.map +1 -0
- package/package.json +72 -0
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
const _config = {
|
|
2
|
+
autoTrigger: true,
|
|
3
|
+
triggerAttribute: "data-worker-target",
|
|
4
|
+
tagNames: {
|
|
5
|
+
worker: "wcs-worker",
|
|
6
|
+
},
|
|
7
|
+
};
|
|
8
|
+
function deepFreeze(obj) {
|
|
9
|
+
if (obj === null || typeof obj !== "object")
|
|
10
|
+
return obj;
|
|
11
|
+
Object.freeze(obj);
|
|
12
|
+
for (const key of Object.keys(obj)) {
|
|
13
|
+
deepFreeze(obj[key]);
|
|
14
|
+
}
|
|
15
|
+
return obj;
|
|
16
|
+
}
|
|
17
|
+
function deepClone(obj) {
|
|
18
|
+
if (obj === null || typeof obj !== "object")
|
|
19
|
+
return obj;
|
|
20
|
+
const clone = {};
|
|
21
|
+
for (const key of Object.keys(obj)) {
|
|
22
|
+
clone[key] = deepClone(obj[key]);
|
|
23
|
+
}
|
|
24
|
+
return clone;
|
|
25
|
+
}
|
|
26
|
+
let frozenConfig = null;
|
|
27
|
+
// Live reference to the mutable internal config: reads always reflect the latest
|
|
28
|
+
// setConfig() call. The readonly IConfig type only blocks callers from writing
|
|
29
|
+
// through it — the underlying object still changes. If you need a stable,
|
|
30
|
+
// frozen snapshot that won't move under you, use getConfig() instead.
|
|
31
|
+
const config = _config;
|
|
32
|
+
function getConfig() {
|
|
33
|
+
if (!frozenConfig) {
|
|
34
|
+
frozenConfig = deepFreeze(deepClone(_config));
|
|
35
|
+
}
|
|
36
|
+
return frozenConfig;
|
|
37
|
+
}
|
|
38
|
+
function setConfig(partialConfig) {
|
|
39
|
+
if (typeof partialConfig.autoTrigger === "boolean") {
|
|
40
|
+
_config.autoTrigger = partialConfig.autoTrigger;
|
|
41
|
+
}
|
|
42
|
+
if (typeof partialConfig.triggerAttribute === "string") {
|
|
43
|
+
_config.triggerAttribute = partialConfig.triggerAttribute;
|
|
44
|
+
}
|
|
45
|
+
if (partialConfig.tagNames) {
|
|
46
|
+
Object.assign(_config.tagNames, partialConfig.tagNames);
|
|
47
|
+
}
|
|
48
|
+
frozenConfig = null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Headless Dedicated Worker primitive. A thin, framework-agnostic wrapper around
|
|
53
|
+
* the `Worker` API exposed through the wc-bindable protocol.
|
|
54
|
+
*
|
|
55
|
+
* A Worker is a "headless async message-passing resource that owns a child
|
|
56
|
+
* thread" — structurally identical to BroadcastCore (structured-clone payloads,
|
|
57
|
+
* no wire encoding, `post` is a `state → element` command-token and an incoming
|
|
58
|
+
* `message` is an `element → state` event-token) with one extra axis: this Core
|
|
59
|
+
* *owns* the underlying resource, so `start()` / `terminate()` spawn and tear
|
|
60
|
+
* down the thread, mirroring how WebSocketCore owns its socket.
|
|
61
|
+
*
|
|
62
|
+
* Message model is bus-style (fire-and-forget `post`, observe `message`), not
|
|
63
|
+
* RPC: there is no request/response correlation. Payloads ride structured clone
|
|
64
|
+
* with NO JSON round-trip (symmetrical with BroadcastCore, deliberately unlike
|
|
65
|
+
* WebSocketCore). The Core never throws — a spawn failure (bad URL, CSP block,
|
|
66
|
+
* absent `Worker`), a non-cloneable `post` (`DataCloneError`), a `post` with no
|
|
67
|
+
* running worker (`InvalidStateError`), an uncaught worker error, and a
|
|
68
|
+
* `messageerror` all flow through the `error` property.
|
|
69
|
+
*/
|
|
70
|
+
class WorkerCore extends EventTarget {
|
|
71
|
+
static wcBindable = {
|
|
72
|
+
protocol: "wc-bindable",
|
|
73
|
+
version: 1,
|
|
74
|
+
properties: [
|
|
75
|
+
{ name: "message", event: "wcs-worker:message" },
|
|
76
|
+
{ name: "error", event: "wcs-worker:error" },
|
|
77
|
+
{ name: "running", event: "wcs-worker:running-changed" },
|
|
78
|
+
],
|
|
79
|
+
commands: [
|
|
80
|
+
{ name: "start" },
|
|
81
|
+
{ name: "post" },
|
|
82
|
+
{ name: "terminate" },
|
|
83
|
+
],
|
|
84
|
+
};
|
|
85
|
+
_target;
|
|
86
|
+
_worker = null;
|
|
87
|
+
_message = null;
|
|
88
|
+
_error = null;
|
|
89
|
+
_running = false;
|
|
90
|
+
// Spawn configuration, retained so an automatic restart can re-spawn the same
|
|
91
|
+
// script with the same options.
|
|
92
|
+
_src = "";
|
|
93
|
+
_type = "module";
|
|
94
|
+
_name = "";
|
|
95
|
+
// Restart-on-error bookkeeping (opt-in; bounded like WebSocketCore reconnect).
|
|
96
|
+
// `_restartCount` is CUMULATIVE over the worker's lifetime: it counts every
|
|
97
|
+
// restart since the last start() and is NOT reset by a period of stable
|
|
98
|
+
// operation, so `_maxRestarts` bounds total restarts, not consecutive crashes.
|
|
99
|
+
// It is reset to 0 only by start() (a fresh spawn / src switch).
|
|
100
|
+
_restartOnError = false;
|
|
101
|
+
_maxRestarts = Infinity;
|
|
102
|
+
_restartInterval = 0;
|
|
103
|
+
_restartCount = 0;
|
|
104
|
+
_restartTimer = null;
|
|
105
|
+
constructor(target) {
|
|
106
|
+
super();
|
|
107
|
+
this._target = target ?? this;
|
|
108
|
+
}
|
|
109
|
+
get message() {
|
|
110
|
+
return this._message;
|
|
111
|
+
}
|
|
112
|
+
get error() {
|
|
113
|
+
return this._error;
|
|
114
|
+
}
|
|
115
|
+
get running() {
|
|
116
|
+
return this._running;
|
|
117
|
+
}
|
|
118
|
+
// --- State setters with event dispatch ---
|
|
119
|
+
// Deliberately NO same-value guard. An incoming message is an event, not
|
|
120
|
+
// idempotent state: the worker posting the same value twice is two distinct
|
|
121
|
+
// occurrences and must re-fire wcs-worker:message each time so a `message:`
|
|
122
|
+
// binding and any `eventToken.message:` subscriber see both.
|
|
123
|
+
_setMessage(message) {
|
|
124
|
+
this._message = message;
|
|
125
|
+
this._target.dispatchEvent(new CustomEvent("wcs-worker:message", {
|
|
126
|
+
detail: message,
|
|
127
|
+
bubbles: true,
|
|
128
|
+
}));
|
|
129
|
+
}
|
|
130
|
+
// Same-value guard. `error` has no derived state, so suppressing redundant
|
|
131
|
+
// null→null dispatches (e.g. a successful spawn clearing an already-null error)
|
|
132
|
+
// avoids spurious events. Reference identity suffices: each failure builds a
|
|
133
|
+
// fresh object and the clear path always passes null.
|
|
134
|
+
_setError(error) {
|
|
135
|
+
if (this._error === error)
|
|
136
|
+
return;
|
|
137
|
+
this._error = error;
|
|
138
|
+
this._target.dispatchEvent(new CustomEvent("wcs-worker:error", {
|
|
139
|
+
detail: error,
|
|
140
|
+
bubbles: true,
|
|
141
|
+
}));
|
|
142
|
+
}
|
|
143
|
+
// No same-value guard needed: every spawn (`start`, restart) goes through
|
|
144
|
+
// `_spawn` (false→true) only after `_terminateWorker` (true→false, guarded by
|
|
145
|
+
// `_worker`), so `running` only ever moves on a real transition.
|
|
146
|
+
_setRunning(running) {
|
|
147
|
+
this._running = running;
|
|
148
|
+
this._target.dispatchEvent(new CustomEvent("wcs-worker:running-changed", {
|
|
149
|
+
detail: running,
|
|
150
|
+
bubbles: true,
|
|
151
|
+
}));
|
|
152
|
+
}
|
|
153
|
+
// --- Public API ---
|
|
154
|
+
/**
|
|
155
|
+
* Spawn the worker from `src`. Any previously-spawned worker is terminated
|
|
156
|
+
* first, so calling `start()` again with a different `src` switches scripts.
|
|
157
|
+
* Idempotent on the same `src` (re-spawning the script we are already running
|
|
158
|
+
* is pure churn) — this also absorbs the custom-element upgrade path where a
|
|
159
|
+
* connected element with a `src` attribute triggers both
|
|
160
|
+
* attributeChangedCallback and connectedCallback, calling start() twice. A
|
|
161
|
+
* consequence of this guard: changing only the options (`type`, `name`,
|
|
162
|
+
* restart-*) while running the same `src` is ignored — call `terminate()`
|
|
163
|
+
* then `start()` to re-spawn with new options. Never throws: a spawn failure
|
|
164
|
+
* surfaces through `error`.
|
|
165
|
+
*/
|
|
166
|
+
start(src, options = {}) {
|
|
167
|
+
if (!src) {
|
|
168
|
+
this._setError({ name: "TypeError", message: "src is required." });
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (this._worker && this._src === src)
|
|
172
|
+
return;
|
|
173
|
+
this._clearRestartTimer();
|
|
174
|
+
this._terminateWorker();
|
|
175
|
+
this._src = src;
|
|
176
|
+
this._type = options.type ?? "module";
|
|
177
|
+
this._name = options.name ?? "";
|
|
178
|
+
this._restartOnError = options.restartOnError ?? false;
|
|
179
|
+
this._maxRestarts = options.maxRestarts ?? Infinity;
|
|
180
|
+
this._restartInterval = options.restartInterval ?? 0;
|
|
181
|
+
this._restartCount = 0;
|
|
182
|
+
this._setError(null);
|
|
183
|
+
this._spawn();
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Post a structured-cloneable value to the worker. The optional `transfer`
|
|
187
|
+
* list moves ownership of `Transferable`s (ArrayBuffer, MessagePort, ...) — the
|
|
188
|
+
* escape hatch the declarative layer cannot express. Never throws: a
|
|
189
|
+
* non-cloneable value surfaces as `DataCloneError` and posting with no running
|
|
190
|
+
* worker surfaces an `InvalidStateError`, both through `error`.
|
|
191
|
+
*/
|
|
192
|
+
post(data, transfer) {
|
|
193
|
+
if (!this._worker) {
|
|
194
|
+
this._setError({
|
|
195
|
+
name: "InvalidStateError",
|
|
196
|
+
message: "Worker is not running. Call start(src) before post().",
|
|
197
|
+
});
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
if (transfer && transfer.length > 0) {
|
|
202
|
+
this._worker.postMessage(data, transfer);
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
this._worker.postMessage(data);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
catch (err) {
|
|
209
|
+
this._setError(this._normalizeError(err));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/** Terminate the worker. Idempotent — a no-op when none is running. */
|
|
213
|
+
terminate() {
|
|
214
|
+
this._clearRestartTimer();
|
|
215
|
+
this._terminateWorker();
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Tear the Core down for a disconnected Shell: terminate the worker and reset
|
|
219
|
+
* the error shadow. Only the `error` clear is silent — it mutates the shadow
|
|
220
|
+
* without dispatching. Terminating a *running* worker still dispatches
|
|
221
|
+
* `wcs-worker:running-changed` (true→false) via `_terminateWorker`, so a
|
|
222
|
+
* dispose on a worker that was live does emit one event on the (now
|
|
223
|
+
* disconnected) element; only a no-op dispose (no worker running) is fully
|
|
224
|
+
* silent.
|
|
225
|
+
*
|
|
226
|
+
* Asymmetry by design: `_message` is deliberately NOT reset. `error` is
|
|
227
|
+
* transient state — a stale error from a previous worker would mislead after a
|
|
228
|
+
* reconnect, so it is cleared. `message` is the last value received (an event
|
|
229
|
+
* payload); it is retained as the Core's last-known datum and is naturally
|
|
230
|
+
* overwritten by the next incoming message.
|
|
231
|
+
*/
|
|
232
|
+
dispose() {
|
|
233
|
+
this._clearRestartTimer();
|
|
234
|
+
this._terminateWorker();
|
|
235
|
+
this._error = null;
|
|
236
|
+
}
|
|
237
|
+
// --- Internal ---
|
|
238
|
+
_spawn() {
|
|
239
|
+
try {
|
|
240
|
+
this._worker = new Worker(this._src, { type: this._type, name: this._name || undefined });
|
|
241
|
+
}
|
|
242
|
+
catch (err) {
|
|
243
|
+
this._setError(this._normalizeError(err));
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
this._worker.addEventListener("message", this._onMessage);
|
|
247
|
+
this._worker.addEventListener("messageerror", this._onMessageError);
|
|
248
|
+
this._worker.addEventListener("error", this._onError);
|
|
249
|
+
this._setRunning(true);
|
|
250
|
+
}
|
|
251
|
+
_onMessage = (event) => {
|
|
252
|
+
this._setMessage(event.data);
|
|
253
|
+
};
|
|
254
|
+
// Fired when the worker posted a value this context cannot deserialize. The
|
|
255
|
+
// event carries no usable payload, so report a synthetic DataError.
|
|
256
|
+
_onMessageError = () => {
|
|
257
|
+
this._setError({
|
|
258
|
+
name: "DataError",
|
|
259
|
+
message: "Failed to deserialize a message received from the worker.",
|
|
260
|
+
});
|
|
261
|
+
};
|
|
262
|
+
// An uncaught error inside the worker script. The worker itself stays alive
|
|
263
|
+
// (the platform does not auto-terminate it), so restart-on-error explicitly
|
|
264
|
+
// re-spawns a fresh worker when enabled and the bound is not exhausted.
|
|
265
|
+
_onError = (event) => {
|
|
266
|
+
this._setError({
|
|
267
|
+
name: "Error",
|
|
268
|
+
message: event.message || "Worker script error.",
|
|
269
|
+
filename: event.filename,
|
|
270
|
+
lineno: event.lineno,
|
|
271
|
+
colno: event.colno,
|
|
272
|
+
});
|
|
273
|
+
if (this._restartOnError && this._restartCount < this._maxRestarts) {
|
|
274
|
+
this._scheduleRestart();
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
_scheduleRestart() {
|
|
278
|
+
this._clearRestartTimer();
|
|
279
|
+
this._restartTimer = setTimeout(() => {
|
|
280
|
+
this._restartTimer = null;
|
|
281
|
+
this._restartCount++;
|
|
282
|
+
this._terminateWorker();
|
|
283
|
+
// Clear the crash error BEFORE re-spawning so a successful restart leaves a
|
|
284
|
+
// consistent running=true / error=null state (an `error` binding must not
|
|
285
|
+
// keep showing the previous script's failure once the fresh worker is live).
|
|
286
|
+
// Order matters: _spawn() re-sets `error` if the new spawn itself fails, so
|
|
287
|
+
// a failed restart still surfaces its own error rather than null.
|
|
288
|
+
this._setError(null);
|
|
289
|
+
this._spawn();
|
|
290
|
+
}, this._restartInterval);
|
|
291
|
+
}
|
|
292
|
+
_clearRestartTimer() {
|
|
293
|
+
if (this._restartTimer !== null) {
|
|
294
|
+
clearTimeout(this._restartTimer);
|
|
295
|
+
this._restartTimer = null;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
_terminateWorker() {
|
|
299
|
+
if (!this._worker)
|
|
300
|
+
return;
|
|
301
|
+
this._worker.removeEventListener("message", this._onMessage);
|
|
302
|
+
this._worker.removeEventListener("messageerror", this._onMessageError);
|
|
303
|
+
this._worker.removeEventListener("error", this._onError);
|
|
304
|
+
this._worker.terminate();
|
|
305
|
+
this._worker = null;
|
|
306
|
+
this._setRunning(false);
|
|
307
|
+
}
|
|
308
|
+
_normalizeError(err) {
|
|
309
|
+
if (err instanceof Error) {
|
|
310
|
+
// DOMException is an Error subclass; its `name` (DataCloneError, etc.) is
|
|
311
|
+
// the meaningful discriminator for consumers switching on failure kind.
|
|
312
|
+
return { name: err.name, message: err.message };
|
|
313
|
+
}
|
|
314
|
+
return { name: "Error", message: String(err) };
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
let registered = false;
|
|
319
|
+
// Attribute names for the optional post-on-click DOM trigger (clipboard.js-style
|
|
320
|
+
// DX). The element carrying `data-worker-target` points at a <wcs-worker> by id;
|
|
321
|
+
// the payload to post comes from either a literal `data-worker-text` or a
|
|
322
|
+
// `data-worker-from` CSS selector resolving to a source element.
|
|
323
|
+
const TEXT_ATTRIBUTE = "data-worker-text";
|
|
324
|
+
const FROM_ATTRIBUTE = "data-worker-from";
|
|
325
|
+
function resolveText(triggerElement) {
|
|
326
|
+
// Literal text wins when present (including an empty string — posting "" is a
|
|
327
|
+
// legitimate request). The `?? ""` right-hand side is defensive and
|
|
328
|
+
// unreachable: hasAttribute() just returned true, so getAttribute() cannot be
|
|
329
|
+
// null here. It exists only to satisfy the `string | null` return type — do
|
|
330
|
+
// not chase coverage on it (the DOM contract makes the null branch impossible).
|
|
331
|
+
if (triggerElement.hasAttribute(TEXT_ATTRIBUTE)) {
|
|
332
|
+
return triggerElement.getAttribute(TEXT_ATTRIBUTE) ?? "";
|
|
333
|
+
}
|
|
334
|
+
const selector = triggerElement.getAttribute(FROM_ATTRIBUTE);
|
|
335
|
+
if (!selector)
|
|
336
|
+
return null;
|
|
337
|
+
// A user-authored selector can be syntactically invalid (e.g. `[data-*` or a
|
|
338
|
+
// bare `:not()`), which makes querySelector throw a SyntaxError. Swallow it and
|
|
339
|
+
// treat the source as unresolvable — the same "nothing to post" path as a
|
|
340
|
+
// selector that matches no element — so one bad attribute never crashes the
|
|
341
|
+
// document-level click handler and kills autoTrigger for the whole tab.
|
|
342
|
+
let source;
|
|
343
|
+
try {
|
|
344
|
+
source = document.querySelector(selector);
|
|
345
|
+
}
|
|
346
|
+
catch {
|
|
347
|
+
return null;
|
|
348
|
+
}
|
|
349
|
+
if (!source)
|
|
350
|
+
return null;
|
|
351
|
+
// Read a form control's `value`; fall back to text content. A bare
|
|
352
|
+
// `"value" in source` check is too broad — it also matches <button>,
|
|
353
|
+
// <li value>, <progress>, etc. (which carry an unrelated `value`), posting the
|
|
354
|
+
// wrong thing. Narrow to the text-bearing controls a user actually points
|
|
355
|
+
// `data-worker-from` at; everything else falls through to textContent.
|
|
356
|
+
if (source instanceof HTMLInputElement ||
|
|
357
|
+
source instanceof HTMLTextAreaElement ||
|
|
358
|
+
source instanceof HTMLSelectElement) {
|
|
359
|
+
return source.value;
|
|
360
|
+
}
|
|
361
|
+
// `?? ""` is defensive: per the DOM spec only Document / DocumentType /
|
|
362
|
+
// Notation nodes have a null `textContent`, and querySelector only ever returns
|
|
363
|
+
// an Element (whose textContent is always a string). The branch is therefore
|
|
364
|
+
// unreachable in practice and kept solely for the `string | null` type — not
|
|
365
|
+
// worth a contrived test.
|
|
366
|
+
return source.textContent ?? "";
|
|
367
|
+
}
|
|
368
|
+
function handleClick(event) {
|
|
369
|
+
const target = event.target;
|
|
370
|
+
if (!(target instanceof Element))
|
|
371
|
+
return;
|
|
372
|
+
const triggerElement = target.closest(`[${config.triggerAttribute}]`);
|
|
373
|
+
if (!triggerElement)
|
|
374
|
+
return;
|
|
375
|
+
const workerId = triggerElement.getAttribute(config.triggerAttribute);
|
|
376
|
+
if (!workerId)
|
|
377
|
+
return;
|
|
378
|
+
// Resolve the registered constructor at call time instead of importing
|
|
379
|
+
// WcsWorker as a value (avoids a components ⇄ autoTrigger import cycle:
|
|
380
|
+
// Worker.connectedCallback() calls registerAutoTrigger()). instanceof against
|
|
381
|
+
// the customElements registry keeps the same identity guarantee.
|
|
382
|
+
const WorkerCtor = customElements.get(config.tagNames.worker);
|
|
383
|
+
const workerElement = document.getElementById(workerId);
|
|
384
|
+
if (!WorkerCtor || !(workerElement instanceof WorkerCtor))
|
|
385
|
+
return;
|
|
386
|
+
const text = resolveText(triggerElement);
|
|
387
|
+
// No resolvable source: leave the click alone (do not preventDefault) so the
|
|
388
|
+
// element's default action is unaffected.
|
|
389
|
+
if (text === null)
|
|
390
|
+
return;
|
|
391
|
+
// Suppress the default action so a post can run without navigating. Intentional:
|
|
392
|
+
// do not attach data-worker-target to an element whose default action you also
|
|
393
|
+
// want (a real <a href> link). See README "Optional DOM Triggering".
|
|
394
|
+
event.preventDefault();
|
|
395
|
+
workerElement.post(text);
|
|
396
|
+
}
|
|
397
|
+
function registerAutoTrigger() {
|
|
398
|
+
if (registered)
|
|
399
|
+
return;
|
|
400
|
+
registered = true;
|
|
401
|
+
document.addEventListener("click", handleClick);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// Named WcsWorker (not `Worker`) to avoid shadowing the global `Worker`
|
|
405
|
+
// constructor and to match the <wcs-broadcast> WcsBroadcast / <wcs-ws>
|
|
406
|
+
// WcsWebSocket convention.
|
|
407
|
+
class WcsWorker extends HTMLElement {
|
|
408
|
+
// The worker spawns synchronously in connectedCallback (no async init), so no
|
|
409
|
+
// connectedCallbackPromise is needed — mirrors <wcs-ws> / <wcs-broadcast>.
|
|
410
|
+
static hasConnectedCallbackPromise = false;
|
|
411
|
+
static wcBindable = {
|
|
412
|
+
...WorkerCore.wcBindable,
|
|
413
|
+
// Shell-level settable surface. `src` selects the script; `manual` suppresses
|
|
414
|
+
// auto-spawn; `keep-alive` keeps the worker past disconnect; the restart-*
|
|
415
|
+
// inputs configure opt-in restart-on-error. There is no momentary `post`
|
|
416
|
+
// property: posting needs an argument (the payload), so element actions run
|
|
417
|
+
// via command-token (`command.post: $command.ping`) or the DOM autoTrigger,
|
|
418
|
+
// keeping `post` a plain command and the `command.post:` wiring readable.
|
|
419
|
+
inputs: [
|
|
420
|
+
{ name: "src", attribute: "src" },
|
|
421
|
+
{ name: "type", attribute: "type" },
|
|
422
|
+
{ name: "name", attribute: "name" },
|
|
423
|
+
{ name: "manual", attribute: "manual" },
|
|
424
|
+
{ name: "keepAlive", attribute: "keep-alive" },
|
|
425
|
+
{ name: "restartOnError", attribute: "restart-on-error" },
|
|
426
|
+
{ name: "maxRestarts", attribute: "max-restarts" },
|
|
427
|
+
{ name: "restartInterval", attribute: "restart-interval" },
|
|
428
|
+
],
|
|
429
|
+
// Commands are identical to the Core's — the attribute accessors (src, type,
|
|
430
|
+
// name, ...) do not collide with start/post/terminate.
|
|
431
|
+
commands: WorkerCore.wcBindable.commands,
|
|
432
|
+
};
|
|
433
|
+
static get observedAttributes() { return ["src"]; }
|
|
434
|
+
_core;
|
|
435
|
+
constructor() {
|
|
436
|
+
super();
|
|
437
|
+
this._core = new WorkerCore(this);
|
|
438
|
+
}
|
|
439
|
+
// --- Attribute accessors ---
|
|
440
|
+
get src() {
|
|
441
|
+
return this.getAttribute("src") || "";
|
|
442
|
+
}
|
|
443
|
+
set src(value) {
|
|
444
|
+
this.setAttribute("src", value);
|
|
445
|
+
}
|
|
446
|
+
get type() {
|
|
447
|
+
return this.getAttribute("type") === "classic" ? "classic" : "module";
|
|
448
|
+
}
|
|
449
|
+
set type(value) {
|
|
450
|
+
this.setAttribute("type", value);
|
|
451
|
+
}
|
|
452
|
+
get name() {
|
|
453
|
+
return this.getAttribute("name") || "";
|
|
454
|
+
}
|
|
455
|
+
set name(value) {
|
|
456
|
+
this.setAttribute("name", value);
|
|
457
|
+
}
|
|
458
|
+
get manual() {
|
|
459
|
+
return this.hasAttribute("manual");
|
|
460
|
+
}
|
|
461
|
+
set manual(value) {
|
|
462
|
+
if (value) {
|
|
463
|
+
this.setAttribute("manual", "");
|
|
464
|
+
}
|
|
465
|
+
else {
|
|
466
|
+
this.removeAttribute("manual");
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
get keepAlive() {
|
|
470
|
+
return this.hasAttribute("keep-alive");
|
|
471
|
+
}
|
|
472
|
+
set keepAlive(value) {
|
|
473
|
+
if (value) {
|
|
474
|
+
this.setAttribute("keep-alive", "");
|
|
475
|
+
}
|
|
476
|
+
else {
|
|
477
|
+
this.removeAttribute("keep-alive");
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
get restartOnError() {
|
|
481
|
+
return this.hasAttribute("restart-on-error");
|
|
482
|
+
}
|
|
483
|
+
set restartOnError(value) {
|
|
484
|
+
if (value) {
|
|
485
|
+
this.setAttribute("restart-on-error", "");
|
|
486
|
+
}
|
|
487
|
+
else {
|
|
488
|
+
this.removeAttribute("restart-on-error");
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
get maxRestarts() {
|
|
492
|
+
const attr = this.getAttribute("max-restarts");
|
|
493
|
+
// `max-restarts="Infinity"` is the documented default-equivalent for an
|
|
494
|
+
// unbounded restart budget. parseInt("Infinity", 10) is NaN, so match it
|
|
495
|
+
// explicitly rather than leaning on the NaN fallback (which would silently
|
|
496
|
+
// break if that fallback ever changed). Any other non-numeric value still
|
|
497
|
+
// falls back to Infinity via the NaN guard.
|
|
498
|
+
if (attr === "Infinity")
|
|
499
|
+
return Infinity;
|
|
500
|
+
const parsed = attr ? parseInt(attr, 10) : Infinity;
|
|
501
|
+
return Number.isNaN(parsed) ? Infinity : parsed;
|
|
502
|
+
}
|
|
503
|
+
set maxRestarts(value) {
|
|
504
|
+
this.setAttribute("max-restarts", String(value));
|
|
505
|
+
}
|
|
506
|
+
get restartInterval() {
|
|
507
|
+
const attr = this.getAttribute("restart-interval");
|
|
508
|
+
const parsed = attr ? parseInt(attr, 10) : 0;
|
|
509
|
+
return Number.isNaN(parsed) ? 0 : parsed;
|
|
510
|
+
}
|
|
511
|
+
set restartInterval(value) {
|
|
512
|
+
this.setAttribute("restart-interval", String(value));
|
|
513
|
+
}
|
|
514
|
+
// --- Core delegated getters ---
|
|
515
|
+
get message() {
|
|
516
|
+
return this._core.message;
|
|
517
|
+
}
|
|
518
|
+
get error() {
|
|
519
|
+
return this._core.error;
|
|
520
|
+
}
|
|
521
|
+
get running() {
|
|
522
|
+
return this._core.running;
|
|
523
|
+
}
|
|
524
|
+
// --- Commands ---
|
|
525
|
+
start() {
|
|
526
|
+
// Delegate unconditionally — including the empty-`src` case — so the Core's
|
|
527
|
+
// never-throw contract holds at the Shell boundary too: start("") raises a
|
|
528
|
+
// TypeError through `error` rather than failing silently. The auto-spawn
|
|
529
|
+
// paths (connectedCallback / attributeChangedCallback) already gate on a
|
|
530
|
+
// non-empty `src`, so this only affects an explicit `el.start()` call.
|
|
531
|
+
this._core.start(this.src, {
|
|
532
|
+
type: this.type,
|
|
533
|
+
name: this.name,
|
|
534
|
+
restartOnError: this.restartOnError,
|
|
535
|
+
maxRestarts: this.maxRestarts,
|
|
536
|
+
restartInterval: this.restartInterval,
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
post(data, transfer) {
|
|
540
|
+
this._core.post(data, transfer);
|
|
541
|
+
}
|
|
542
|
+
terminate() {
|
|
543
|
+
this._core.terminate();
|
|
544
|
+
}
|
|
545
|
+
// --- Lifecycle ---
|
|
546
|
+
attributeChangedCallback(name, _oldValue, newValue) {
|
|
547
|
+
if (name === "src" && this.isConnected && !this.manual && newValue) {
|
|
548
|
+
this.start();
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
connectedCallback() {
|
|
552
|
+
this.style.display = "none";
|
|
553
|
+
if (config.autoTrigger) {
|
|
554
|
+
registerAutoTrigger();
|
|
555
|
+
}
|
|
556
|
+
if (!this.manual && this.src) {
|
|
557
|
+
this.start();
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
disconnectedCallback() {
|
|
561
|
+
// Deliberately does NOT call unregisterAutoTrigger(). The autoTrigger click
|
|
562
|
+
// listener is a single process-wide document listener (registerAutoTrigger
|
|
563
|
+
// is idempotent), shared by every <wcs-worker> on the page — not owned by
|
|
564
|
+
// this element. Tearing it down when the last element disconnects would
|
|
565
|
+
// break a later-inserted trigger, so it is intentionally left installed for
|
|
566
|
+
// the document's lifetime (one passive listener, negligible cost). This
|
|
567
|
+
// mirrors <wcs-broadcast> / <wcs-clipboard>, which register but never
|
|
568
|
+
// unregister either; unregisterAutoTrigger stays exported purely as a
|
|
569
|
+
// symmetric teardown hook for tests / advanced manual control.
|
|
570
|
+
//
|
|
571
|
+
// keep-alive intentionally leaves the worker running past disconnect: the
|
|
572
|
+
// worker outlives the element and ownership transfers to the caller, who must
|
|
573
|
+
// call terminate() to free the thread. Without keep-alive the worker is torn
|
|
574
|
+
// down like <wcs-ws> / <wcs-broadcast> close on disconnect.
|
|
575
|
+
if (!this.keepAlive) {
|
|
576
|
+
this._core.dispose();
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function registerComponents() {
|
|
582
|
+
if (!customElements.get(config.tagNames.worker)) {
|
|
583
|
+
customElements.define(config.tagNames.worker, WcsWorker);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
function bootstrapWorker(userConfig) {
|
|
588
|
+
if (userConfig) {
|
|
589
|
+
setConfig(userConfig);
|
|
590
|
+
}
|
|
591
|
+
registerComponents();
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
export { WcsWorker, WorkerCore, bootstrapWorker, getConfig };
|
|
595
|
+
//# sourceMappingURL=index.esm.js.map
|