@wcstack/worker 1.14.0 → 1.15.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/index.d.ts +29 -21
- package/dist/index.esm.js +42 -3
- package/dist/index.esm.js.map +1 -1
- package/dist/index.esm.min.js +1 -1
- package/dist/index.esm.min.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,19 +1,3 @@
|
|
|
1
|
-
interface ITagNames {
|
|
2
|
-
readonly worker: string;
|
|
3
|
-
}
|
|
4
|
-
interface IWritableTagNames {
|
|
5
|
-
worker?: string;
|
|
6
|
-
}
|
|
7
|
-
interface IConfig {
|
|
8
|
-
readonly autoTrigger: boolean;
|
|
9
|
-
readonly triggerAttribute: string;
|
|
10
|
-
readonly tagNames: ITagNames;
|
|
11
|
-
}
|
|
12
|
-
interface IWritableConfig {
|
|
13
|
-
autoTrigger?: boolean;
|
|
14
|
-
triggerAttribute?: string;
|
|
15
|
-
tagNames?: IWritableTagNames;
|
|
16
|
-
}
|
|
17
1
|
interface IWcBindableProperty {
|
|
18
2
|
readonly name: string;
|
|
19
3
|
readonly event: string;
|
|
@@ -29,11 +13,29 @@ interface IWcBindableCommand {
|
|
|
29
13
|
}
|
|
30
14
|
interface IWcBindable {
|
|
31
15
|
readonly protocol: "wc-bindable";
|
|
32
|
-
readonly version:
|
|
33
|
-
readonly properties: IWcBindableProperty[];
|
|
34
|
-
readonly inputs?: IWcBindableInput[];
|
|
35
|
-
readonly commands?: IWcBindableCommand[];
|
|
16
|
+
readonly version: 1;
|
|
17
|
+
readonly properties: readonly IWcBindableProperty[];
|
|
18
|
+
readonly inputs?: readonly IWcBindableInput[];
|
|
19
|
+
readonly commands?: readonly IWcBindableCommand[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface ITagNames {
|
|
23
|
+
readonly worker: string;
|
|
36
24
|
}
|
|
25
|
+
interface IWritableTagNames {
|
|
26
|
+
worker?: string;
|
|
27
|
+
}
|
|
28
|
+
interface IConfig {
|
|
29
|
+
readonly autoTrigger: boolean;
|
|
30
|
+
readonly triggerAttribute: string;
|
|
31
|
+
readonly tagNames: ITagNames;
|
|
32
|
+
}
|
|
33
|
+
interface IWritableConfig {
|
|
34
|
+
autoTrigger?: boolean;
|
|
35
|
+
triggerAttribute?: string;
|
|
36
|
+
tagNames?: IWritableTagNames;
|
|
37
|
+
}
|
|
38
|
+
|
|
37
39
|
/**
|
|
38
40
|
* Normalized Worker failure. `name` mirrors the underlying `DOMException.name`
|
|
39
41
|
* or `Error.name`: `DataCloneError` when a posted value (or a value the worker
|
|
@@ -66,7 +68,7 @@ interface WcsWorkerStartOptions {
|
|
|
66
68
|
}
|
|
67
69
|
/**
|
|
68
70
|
* Value types for WorkerCore (headless) — the observable state properties.
|
|
69
|
-
* Use with `bind()` from
|
|
71
|
+
* Use with `bind()` from `a wc-bindable binding core` for compile-time type checking.
|
|
70
72
|
*/
|
|
71
73
|
interface WcsWorkerCoreValues {
|
|
72
74
|
/**
|
|
@@ -159,7 +161,11 @@ declare class WorkerCore extends EventTarget {
|
|
|
159
161
|
private _restartInterval;
|
|
160
162
|
private _restartCount;
|
|
161
163
|
private _restartTimer;
|
|
164
|
+
private _gen;
|
|
165
|
+
private _ready;
|
|
162
166
|
constructor(target?: EventTarget);
|
|
167
|
+
get ready(): Promise<void>;
|
|
168
|
+
observe(): Promise<void>;
|
|
163
169
|
get message(): any;
|
|
164
170
|
get error(): WcsWorkerErrorDetail | null;
|
|
165
171
|
get running(): boolean;
|
|
@@ -220,7 +226,9 @@ declare class WcsWorker extends HTMLElement {
|
|
|
220
226
|
static wcBindable: IWcBindable;
|
|
221
227
|
static get observedAttributes(): string[];
|
|
222
228
|
private _core;
|
|
229
|
+
private _connectedCallbackPromise;
|
|
223
230
|
constructor();
|
|
231
|
+
get connectedCallbackPromise(): Promise<void>;
|
|
224
232
|
get src(): string;
|
|
225
233
|
set src(value: string);
|
|
226
234
|
get type(): WorkerType;
|
package/dist/index.esm.js
CHANGED
|
@@ -102,10 +102,30 @@ class WorkerCore extends EventTarget {
|
|
|
102
102
|
_restartInterval = 0;
|
|
103
103
|
_restartCount = 0;
|
|
104
104
|
_restartTimer = null;
|
|
105
|
+
// Generation guard (§3.4): bumped on dispose() and captured at restart-timer
|
|
106
|
+
// schedule time. A restart deferred via setTimeout is the Core's only async
|
|
107
|
+
// work; if dispose() runs while it is pending, the stale timer MUST NOT
|
|
108
|
+
// re-spawn a worker on a torn-down element. _clearRestartTimer() already
|
|
109
|
+
// cancels the pending timer from inside the Core, so this guard is
|
|
110
|
+
// defense-in-depth for any path that fires the callback after invalidation.
|
|
111
|
+
_gen = 0;
|
|
112
|
+
// SSR (§3.8): a worker is command-driven (spawned on start()), so there is no
|
|
113
|
+
// asynchronous probe to await — readiness is immediate.
|
|
114
|
+
_ready = Promise.resolve();
|
|
105
115
|
constructor(target) {
|
|
106
116
|
super();
|
|
107
117
|
this._target = target ?? this;
|
|
108
118
|
}
|
|
119
|
+
get ready() {
|
|
120
|
+
return this._ready;
|
|
121
|
+
}
|
|
122
|
+
// Lifecycle (§3.5). The worker is command-driven (start/post/terminate), so
|
|
123
|
+
// there is no subscription to establish up front: observe() is an idempotent
|
|
124
|
+
// no-op that resolves once ready. dispose() (below) tears down the worker,
|
|
125
|
+
// cancels any pending restart and invalidates in-flight async via _gen.
|
|
126
|
+
observe() {
|
|
127
|
+
return this._ready;
|
|
128
|
+
}
|
|
109
129
|
get message() {
|
|
110
130
|
return this._message;
|
|
111
131
|
}
|
|
@@ -230,6 +250,9 @@ class WorkerCore extends EventTarget {
|
|
|
230
250
|
* overwritten by the next incoming message.
|
|
231
251
|
*/
|
|
232
252
|
dispose() {
|
|
253
|
+
// §3.4: invalidate any in-flight async (a pending restart timer) before
|
|
254
|
+
// tearing down, so a stale timer that somehow fires cannot re-spawn.
|
|
255
|
+
this._gen++;
|
|
233
256
|
this._clearRestartTimer();
|
|
234
257
|
this._terminateWorker();
|
|
235
258
|
this._error = null;
|
|
@@ -276,7 +299,12 @@ class WorkerCore extends EventTarget {
|
|
|
276
299
|
};
|
|
277
300
|
_scheduleRestart() {
|
|
278
301
|
this._clearRestartTimer();
|
|
302
|
+
const gen = this._gen;
|
|
279
303
|
this._restartTimer = setTimeout(() => {
|
|
304
|
+
// §3.4: a dispose() between scheduling and firing bumps _gen; skip the
|
|
305
|
+
// re-spawn so a torn-down Core does not resurrect a worker.
|
|
306
|
+
if (gen !== this._gen)
|
|
307
|
+
return;
|
|
280
308
|
this._restartTimer = null;
|
|
281
309
|
this._restartCount++;
|
|
282
310
|
this._terminateWorker();
|
|
@@ -405,9 +433,12 @@ function registerAutoTrigger() {
|
|
|
405
433
|
// constructor and to match the <wcs-broadcast> WcsBroadcast / <wcs-ws>
|
|
406
434
|
// WcsWebSocket convention.
|
|
407
435
|
class WcsWorker extends HTMLElement {
|
|
408
|
-
//
|
|
409
|
-
//
|
|
410
|
-
|
|
436
|
+
// SSR (§4.1/§4.4): expose connectedCallbackPromise backed by _core.observe()
|
|
437
|
+
// so a shell renderer can await first-connect readiness uniformly across all
|
|
438
|
+
// IO nodes. The worker still spawns synchronously in connectedCallback; the
|
|
439
|
+
// Core's observe() resolves immediately (command-driven, no async probe), so
|
|
440
|
+
// the promise is effectively already-resolved but the contract is honored.
|
|
441
|
+
static hasConnectedCallbackPromise = true;
|
|
411
442
|
static wcBindable = {
|
|
412
443
|
...WorkerCore.wcBindable,
|
|
413
444
|
// Shell-level settable surface. `src` selects the script; `manual` suppresses
|
|
@@ -432,10 +463,14 @@ class WcsWorker extends HTMLElement {
|
|
|
432
463
|
};
|
|
433
464
|
static get observedAttributes() { return ["src"]; }
|
|
434
465
|
_core;
|
|
466
|
+
_connectedCallbackPromise = Promise.resolve();
|
|
435
467
|
constructor() {
|
|
436
468
|
super();
|
|
437
469
|
this._core = new WorkerCore(this);
|
|
438
470
|
}
|
|
471
|
+
get connectedCallbackPromise() {
|
|
472
|
+
return this._connectedCallbackPromise;
|
|
473
|
+
}
|
|
439
474
|
// --- Attribute accessors ---
|
|
440
475
|
get src() {
|
|
441
476
|
return this.getAttribute("src") || "";
|
|
@@ -553,6 +588,10 @@ class WcsWorker extends HTMLElement {
|
|
|
553
588
|
if (config.autoTrigger) {
|
|
554
589
|
registerAutoTrigger();
|
|
555
590
|
}
|
|
591
|
+
// SSR (§4.4): back connectedCallbackPromise with the Core's observe(). It
|
|
592
|
+
// resolves immediately for this command-driven node, but wiring it keeps the
|
|
593
|
+
// readiness contract uniform with the async-init IO nodes.
|
|
594
|
+
this._connectedCallbackPromise = this._core.observe();
|
|
556
595
|
if (!this.manual && this.src) {
|
|
557
596
|
this.start();
|
|
558
597
|
}
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/config.ts","../src/core/WorkerCore.ts","../src/autoTrigger.ts","../src/components/Worker.ts","../src/registerComponents.ts","../src/bootstrapWorker.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n worker: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-worker-target\",\n tagNames: {\n worker: \"wcs-worker\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\n// Live reference to the mutable internal config: reads always reflect the latest\n// setConfig() call. The readonly IConfig type only blocks callers from writing\n// through it — the underlying object still changes. If you need a stable,\n// frozen snapshot that won't move under you, use getConfig() instead.\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (typeof partialConfig.autoTrigger === \"boolean\") {\n _config.autoTrigger = partialConfig.autoTrigger;\n }\n if (typeof partialConfig.triggerAttribute === \"string\") {\n _config.triggerAttribute = partialConfig.triggerAttribute;\n }\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","import { IWcBindable, WcsWorkerErrorDetail, WcsWorkerStartOptions } from \"../types.js\";\n\n/**\n * Headless Dedicated Worker primitive. A thin, framework-agnostic wrapper around\n * the `Worker` API exposed through the wc-bindable protocol.\n *\n * A Worker is a \"headless async message-passing resource that owns a child\n * thread\" — structurally identical to BroadcastCore (structured-clone payloads,\n * no wire encoding, `post` is a `state → element` command-token and an incoming\n * `message` is an `element → state` event-token) with one extra axis: this Core\n * *owns* the underlying resource, so `start()` / `terminate()` spawn and tear\n * down the thread, mirroring how WebSocketCore owns its socket.\n *\n * Message model is bus-style (fire-and-forget `post`, observe `message`), not\n * RPC: there is no request/response correlation. Payloads ride structured clone\n * with NO JSON round-trip (symmetrical with BroadcastCore, deliberately unlike\n * WebSocketCore). The Core never throws — a spawn failure (bad URL, CSP block,\n * absent `Worker`), a non-cloneable `post` (`DataCloneError`), a `post` with no\n * running worker (`InvalidStateError`), an uncaught worker error, and a\n * `messageerror` all flow through the `error` property.\n */\nexport class WorkerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"message\", event: \"wcs-worker:message\" },\n { name: \"error\", event: \"wcs-worker:error\" },\n { name: \"running\", event: \"wcs-worker:running-changed\" },\n ],\n commands: [\n { name: \"start\" },\n { name: \"post\" },\n { name: \"terminate\" },\n ],\n };\n\n private _target: EventTarget;\n private _worker: Worker | null = null;\n private _message: any = null;\n private _error: WcsWorkerErrorDetail | null = null;\n private _running: boolean = false;\n\n // Spawn configuration, retained so an automatic restart can re-spawn the same\n // script with the same options.\n private _src: string = \"\";\n private _type: WorkerType = \"module\";\n private _name: string = \"\";\n\n // Restart-on-error bookkeeping (opt-in; bounded like WebSocketCore reconnect).\n // `_restartCount` is CUMULATIVE over the worker's lifetime: it counts every\n // restart since the last start() and is NOT reset by a period of stable\n // operation, so `_maxRestarts` bounds total restarts, not consecutive crashes.\n // It is reset to 0 only by start() (a fresh spawn / src switch).\n private _restartOnError: boolean = false;\n private _maxRestarts: number = Infinity;\n private _restartInterval: number = 0;\n private _restartCount: number = 0;\n private _restartTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get message(): any {\n return this._message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._error;\n }\n\n get running(): boolean {\n return this._running;\n }\n\n // --- State setters with event dispatch ---\n\n // Deliberately NO same-value guard. An incoming message is an event, not\n // idempotent state: the worker posting the same value twice is two distinct\n // occurrences and must re-fire wcs-worker:message each time so a `message:`\n // binding and any `eventToken.message:` subscriber see both.\n private _setMessage(message: any): void {\n this._message = message;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:message\", {\n detail: message,\n bubbles: true,\n }));\n }\n\n // Same-value guard. `error` has no derived state, so suppressing redundant\n // null→null dispatches (e.g. a successful spawn clearing an already-null error)\n // avoids spurious events. Reference identity suffices: each failure builds a\n // fresh object and the clear path always passes null.\n private _setError(error: WcsWorkerErrorDetail | null): void {\n if (this._error === error) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n // No same-value guard needed: every spawn (`start`, restart) goes through\n // `_spawn` (false→true) only after `_terminateWorker` (true→false, guarded by\n // `_worker`), so `running` only ever moves on a real transition.\n private _setRunning(running: boolean): void {\n this._running = running;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:running-changed\", {\n detail: running,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n /**\n * Spawn the worker from `src`. Any previously-spawned worker is terminated\n * first, so calling `start()` again with a different `src` switches scripts.\n * Idempotent on the same `src` (re-spawning the script we are already running\n * is pure churn) — this also absorbs the custom-element upgrade path where a\n * connected element with a `src` attribute triggers both\n * attributeChangedCallback and connectedCallback, calling start() twice. A\n * consequence of this guard: changing only the options (`type`, `name`,\n * restart-*) while running the same `src` is ignored — call `terminate()`\n * then `start()` to re-spawn with new options. Never throws: a spawn failure\n * surfaces through `error`.\n */\n start(src: string, options: WcsWorkerStartOptions = {}): void {\n if (!src) {\n this._setError({ name: \"TypeError\", message: \"src is required.\" });\n return;\n }\n if (this._worker && this._src === src) return;\n\n this._clearRestartTimer();\n this._terminateWorker();\n\n this._src = src;\n this._type = options.type ?? \"module\";\n this._name = options.name ?? \"\";\n this._restartOnError = options.restartOnError ?? false;\n this._maxRestarts = options.maxRestarts ?? Infinity;\n this._restartInterval = options.restartInterval ?? 0;\n this._restartCount = 0;\n\n this._setError(null);\n this._spawn();\n }\n\n /**\n * Post a structured-cloneable value to the worker. The optional `transfer`\n * list moves ownership of `Transferable`s (ArrayBuffer, MessagePort, ...) — the\n * escape hatch the declarative layer cannot express. Never throws: a\n * non-cloneable value surfaces as `DataCloneError` and posting with no running\n * worker surfaces an `InvalidStateError`, both through `error`.\n */\n post(data: any, transfer?: Transferable[]): void {\n if (!this._worker) {\n this._setError({\n name: \"InvalidStateError\",\n message: \"Worker is not running. Call start(src) before post().\",\n });\n return;\n }\n try {\n if (transfer && transfer.length > 0) {\n this._worker.postMessage(data, transfer);\n } else {\n this._worker.postMessage(data);\n }\n } catch (err) {\n this._setError(this._normalizeError(err));\n }\n }\n\n /** Terminate the worker. Idempotent — a no-op when none is running. */\n terminate(): void {\n this._clearRestartTimer();\n this._terminateWorker();\n }\n\n /**\n * Tear the Core down for a disconnected Shell: terminate the worker and reset\n * the error shadow. Only the `error` clear is silent — it mutates the shadow\n * without dispatching. Terminating a *running* worker still dispatches\n * `wcs-worker:running-changed` (true→false) via `_terminateWorker`, so a\n * dispose on a worker that was live does emit one event on the (now\n * disconnected) element; only a no-op dispose (no worker running) is fully\n * silent.\n *\n * Asymmetry by design: `_message` is deliberately NOT reset. `error` is\n * transient state — a stale error from a previous worker would mislead after a\n * reconnect, so it is cleared. `message` is the last value received (an event\n * payload); it is retained as the Core's last-known datum and is naturally\n * overwritten by the next incoming message.\n */\n dispose(): void {\n this._clearRestartTimer();\n this._terminateWorker();\n this._error = null;\n }\n\n // --- Internal ---\n\n private _spawn(): void {\n try {\n this._worker = new Worker(this._src, { type: this._type, name: this._name || undefined });\n } catch (err) {\n this._setError(this._normalizeError(err));\n return;\n }\n this._worker.addEventListener(\"message\", this._onMessage);\n this._worker.addEventListener(\"messageerror\", this._onMessageError);\n this._worker.addEventListener(\"error\", this._onError);\n this._setRunning(true);\n }\n\n private _onMessage = (event: MessageEvent): void => {\n this._setMessage(event.data);\n };\n\n // Fired when the worker posted a value this context cannot deserialize. The\n // event carries no usable payload, so report a synthetic DataError.\n private _onMessageError = (): void => {\n this._setError({\n name: \"DataError\",\n message: \"Failed to deserialize a message received from the worker.\",\n });\n };\n\n // An uncaught error inside the worker script. The worker itself stays alive\n // (the platform does not auto-terminate it), so restart-on-error explicitly\n // re-spawns a fresh worker when enabled and the bound is not exhausted.\n private _onError = (event: ErrorEvent): void => {\n this._setError({\n name: \"Error\",\n message: event.message || \"Worker script error.\",\n filename: event.filename,\n lineno: event.lineno,\n colno: event.colno,\n });\n if (this._restartOnError && this._restartCount < this._maxRestarts) {\n this._scheduleRestart();\n }\n };\n\n private _scheduleRestart(): void {\n this._clearRestartTimer();\n this._restartTimer = setTimeout(() => {\n this._restartTimer = null;\n this._restartCount++;\n this._terminateWorker();\n // Clear the crash error BEFORE re-spawning so a successful restart leaves a\n // consistent running=true / error=null state (an `error` binding must not\n // keep showing the previous script's failure once the fresh worker is live).\n // Order matters: _spawn() re-sets `error` if the new spawn itself fails, so\n // a failed restart still surfaces its own error rather than null.\n this._setError(null);\n this._spawn();\n }, this._restartInterval);\n }\n\n private _clearRestartTimer(): void {\n if (this._restartTimer !== null) {\n clearTimeout(this._restartTimer);\n this._restartTimer = null;\n }\n }\n\n private _terminateWorker(): void {\n if (!this._worker) return;\n this._worker.removeEventListener(\"message\", this._onMessage);\n this._worker.removeEventListener(\"messageerror\", this._onMessageError);\n this._worker.removeEventListener(\"error\", this._onError);\n this._worker.terminate();\n this._worker = null;\n this._setRunning(false);\n }\n\n private _normalizeError(err: unknown): WcsWorkerErrorDetail {\n if (err instanceof Error) {\n // DOMException is an Error subclass; its `name` (DataCloneError, etc.) is\n // the meaningful discriminator for consumers switching on failure kind.\n return { name: err.name, message: err.message };\n }\n return { name: \"Error\", message: String(err) };\n }\n}\n","import { config } from \"./config.js\";\nimport type { WcsWorker } from \"./components/Worker.js\";\n\nlet registered = false;\n\n// Attribute names for the optional post-on-click DOM trigger (clipboard.js-style\n// DX). The element carrying `data-worker-target` points at a <wcs-worker> by id;\n// the payload to post comes from either a literal `data-worker-text` or a\n// `data-worker-from` CSS selector resolving to a source element.\nconst TEXT_ATTRIBUTE = \"data-worker-text\";\nconst FROM_ATTRIBUTE = \"data-worker-from\";\n\nfunction resolveText(triggerElement: Element): string | null {\n // Literal text wins when present (including an empty string — posting \"\" is a\n // legitimate request). The `?? \"\"` right-hand side is defensive and\n // unreachable: hasAttribute() just returned true, so getAttribute() cannot be\n // null here. It exists only to satisfy the `string | null` return type — do\n // not chase coverage on it (the DOM contract makes the null branch impossible).\n if (triggerElement.hasAttribute(TEXT_ATTRIBUTE)) {\n return triggerElement.getAttribute(TEXT_ATTRIBUTE) ?? \"\";\n }\n const selector = triggerElement.getAttribute(FROM_ATTRIBUTE);\n if (!selector) return null;\n // A user-authored selector can be syntactically invalid (e.g. `[data-*` or a\n // bare `:not()`), which makes querySelector throw a SyntaxError. Swallow it and\n // treat the source as unresolvable — the same \"nothing to post\" path as a\n // selector that matches no element — so one bad attribute never crashes the\n // document-level click handler and kills autoTrigger for the whole tab.\n let source: Element | null;\n try {\n source = document.querySelector(selector);\n } catch {\n return null;\n }\n if (!source) return null;\n // Read a form control's `value`; fall back to text content. A bare\n // `\"value\" in source` check is too broad — it also matches <button>,\n // <li value>, <progress>, etc. (which carry an unrelated `value`), posting the\n // wrong thing. Narrow to the text-bearing controls a user actually points\n // `data-worker-from` at; everything else falls through to textContent.\n if (\n source instanceof HTMLInputElement ||\n source instanceof HTMLTextAreaElement ||\n source instanceof HTMLSelectElement\n ) {\n return source.value;\n }\n // `?? \"\"` is defensive: per the DOM spec only Document / DocumentType /\n // Notation nodes have a null `textContent`, and querySelector only ever returns\n // an Element (whose textContent is always a string). The branch is therefore\n // unreachable in practice and kept solely for the `string | null` type — not\n // worth a contrived test.\n return source.textContent ?? \"\";\n}\n\nfunction handleClick(event: Event): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n\n const triggerElement = target.closest<Element>(`[${config.triggerAttribute}]`);\n if (!triggerElement) return;\n\n const workerId = triggerElement.getAttribute(config.triggerAttribute);\n if (!workerId) return;\n\n // Resolve the registered constructor at call time instead of importing\n // WcsWorker as a value (avoids a components ⇄ autoTrigger import cycle:\n // Worker.connectedCallback() calls registerAutoTrigger()). instanceof against\n // the customElements registry keeps the same identity guarantee.\n const WorkerCtor = customElements.get(config.tagNames.worker);\n const workerElement = document.getElementById(workerId);\n if (!WorkerCtor || !(workerElement instanceof WorkerCtor)) return;\n\n const text = resolveText(triggerElement);\n // No resolvable source: leave the click alone (do not preventDefault) so the\n // element's default action is unaffected.\n if (text === null) return;\n\n // Suppress the default action so a post can run without navigating. Intentional:\n // do not attach data-worker-target to an element whose default action you also\n // want (a real <a href> link). See README \"Optional DOM Triggering\".\n event.preventDefault();\n (workerElement as WcsWorker).post(text);\n}\n\nexport function registerAutoTrigger(): void {\n if (registered) return;\n registered = true;\n document.addEventListener(\"click\", handleClick);\n}\n\nexport function unregisterAutoTrigger(): void {\n if (!registered) return;\n registered = false;\n document.removeEventListener(\"click\", handleClick);\n}\n","import { config } from \"../config.js\";\nimport { IWcBindable, WcsWorkerErrorDetail } from \"../types.js\";\nimport { WorkerCore } from \"../core/WorkerCore.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\n\n// Named WcsWorker (not `Worker`) to avoid shadowing the global `Worker`\n// constructor and to match the <wcs-broadcast> WcsBroadcast / <wcs-ws>\n// WcsWebSocket convention.\nexport class WcsWorker extends HTMLElement {\n // The worker spawns synchronously in connectedCallback (no async init), so no\n // connectedCallbackPromise is needed — mirrors <wcs-ws> / <wcs-broadcast>.\n static hasConnectedCallbackPromise = false;\n static wcBindable: IWcBindable = {\n ...WorkerCore.wcBindable,\n // Shell-level settable surface. `src` selects the script; `manual` suppresses\n // auto-spawn; `keep-alive` keeps the worker past disconnect; the restart-*\n // inputs configure opt-in restart-on-error. There is no momentary `post`\n // property: posting needs an argument (the payload), so element actions run\n // via command-token (`command.post: $command.ping`) or the DOM autoTrigger,\n // keeping `post` a plain command and the `command.post:` wiring readable.\n inputs: [\n { name: \"src\", attribute: \"src\" },\n { name: \"type\", attribute: \"type\" },\n { name: \"name\", attribute: \"name\" },\n { name: \"manual\", attribute: \"manual\" },\n { name: \"keepAlive\", attribute: \"keep-alive\" },\n { name: \"restartOnError\", attribute: \"restart-on-error\" },\n { name: \"maxRestarts\", attribute: \"max-restarts\" },\n { name: \"restartInterval\", attribute: \"restart-interval\" },\n ],\n // Commands are identical to the Core's — the attribute accessors (src, type,\n // name, ...) do not collide with start/post/terminate.\n commands: WorkerCore.wcBindable.commands,\n };\n static get observedAttributes(): string[] { return [\"src\"]; }\n\n private _core: WorkerCore;\n\n constructor() {\n super();\n this._core = new WorkerCore(this);\n }\n\n // --- Attribute accessors ---\n\n get src(): string {\n return this.getAttribute(\"src\") || \"\";\n }\n\n set src(value: string) {\n this.setAttribute(\"src\", value);\n }\n\n get type(): WorkerType {\n return this.getAttribute(\"type\") === \"classic\" ? \"classic\" : \"module\";\n }\n\n set type(value: WorkerType) {\n this.setAttribute(\"type\", value);\n }\n\n get name(): string {\n return this.getAttribute(\"name\") || \"\";\n }\n\n set name(value: string) {\n this.setAttribute(\"name\", value);\n }\n\n get manual(): boolean {\n return this.hasAttribute(\"manual\");\n }\n\n set manual(value: boolean) {\n if (value) {\n this.setAttribute(\"manual\", \"\");\n } else {\n this.removeAttribute(\"manual\");\n }\n }\n\n get keepAlive(): boolean {\n return this.hasAttribute(\"keep-alive\");\n }\n\n set keepAlive(value: boolean) {\n if (value) {\n this.setAttribute(\"keep-alive\", \"\");\n } else {\n this.removeAttribute(\"keep-alive\");\n }\n }\n\n get restartOnError(): boolean {\n return this.hasAttribute(\"restart-on-error\");\n }\n\n set restartOnError(value: boolean) {\n if (value) {\n this.setAttribute(\"restart-on-error\", \"\");\n } else {\n this.removeAttribute(\"restart-on-error\");\n }\n }\n\n get maxRestarts(): number {\n const attr = this.getAttribute(\"max-restarts\");\n // `max-restarts=\"Infinity\"` is the documented default-equivalent for an\n // unbounded restart budget. parseInt(\"Infinity\", 10) is NaN, so match it\n // explicitly rather than leaning on the NaN fallback (which would silently\n // break if that fallback ever changed). Any other non-numeric value still\n // falls back to Infinity via the NaN guard.\n if (attr === \"Infinity\") return Infinity;\n const parsed = attr ? parseInt(attr, 10) : Infinity;\n return Number.isNaN(parsed) ? Infinity : parsed;\n }\n\n set maxRestarts(value: number) {\n this.setAttribute(\"max-restarts\", String(value));\n }\n\n get restartInterval(): number {\n const attr = this.getAttribute(\"restart-interval\");\n const parsed = attr ? parseInt(attr, 10) : 0;\n return Number.isNaN(parsed) ? 0 : parsed;\n }\n\n set restartInterval(value: number) {\n this.setAttribute(\"restart-interval\", String(value));\n }\n\n // --- Core delegated getters ---\n\n get message(): any {\n return this._core.message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._core.error;\n }\n\n get running(): boolean {\n return this._core.running;\n }\n\n // --- Commands ---\n\n start(): void {\n // Delegate unconditionally — including the empty-`src` case — so the Core's\n // never-throw contract holds at the Shell boundary too: start(\"\") raises a\n // TypeError through `error` rather than failing silently. The auto-spawn\n // paths (connectedCallback / attributeChangedCallback) already gate on a\n // non-empty `src`, so this only affects an explicit `el.start()` call.\n this._core.start(this.src, {\n type: this.type,\n name: this.name,\n restartOnError: this.restartOnError,\n maxRestarts: this.maxRestarts,\n restartInterval: this.restartInterval,\n });\n }\n\n post(data: any, transfer?: Transferable[]): void {\n this._core.post(data, transfer);\n }\n\n terminate(): void {\n this._core.terminate();\n }\n\n // --- Lifecycle ---\n\n attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null): void {\n if (name === \"src\" && this.isConnected && !this.manual && newValue) {\n this.start();\n }\n }\n\n connectedCallback(): void {\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n if (!this.manual && this.src) {\n this.start();\n }\n }\n\n disconnectedCallback(): void {\n // Deliberately does NOT call unregisterAutoTrigger(). The autoTrigger click\n // listener is a single process-wide document listener (registerAutoTrigger\n // is idempotent), shared by every <wcs-worker> on the page — not owned by\n // this element. Tearing it down when the last element disconnects would\n // break a later-inserted trigger, so it is intentionally left installed for\n // the document's lifetime (one passive listener, negligible cost). This\n // mirrors <wcs-broadcast> / <wcs-clipboard>, which register but never\n // unregister either; unregisterAutoTrigger stays exported purely as a\n // symmetric teardown hook for tests / advanced manual control.\n //\n // keep-alive intentionally leaves the worker running past disconnect: the\n // worker outlives the element and ownership transfers to the caller, who must\n // call terminate() to free the thread. Without keep-alive the worker is torn\n // down like <wcs-ws> / <wcs-broadcast> close on disconnect.\n if (!this.keepAlive) {\n this._core.dispose();\n }\n }\n}\n","import { WcsWorker } from \"./components/Worker.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.worker)) {\n customElements.define(config.tagNames.worker, WcsWorker);\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapWorker(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n"],"names":[],"mappings":"AAUA,MAAM,OAAO,GAAoB;AAC/B,IAAA,WAAW,EAAE,IAAI;AACjB,IAAA,gBAAgB,EAAE,oBAAoB;AACtC,IAAA,QAAQ,EAAE;AACR,QAAA,MAAM,EAAE,YAAY;AACrB,KAAA;CACF;AAED,SAAS,UAAU,CAAI,GAAM,EAAA;AAC3B,IAAA,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;AAAE,QAAA,OAAO,GAAG;AACvD,IAAA,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;IAClB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;AAClC,QAAA,UAAU,CAAE,GAA+B,CAAC,GAAG,CAAC,CAAC;IACnD;AACA,IAAA,OAAO,GAAG;AACZ;AAEA,SAAS,SAAS,CAAI,GAAM,EAAA;AAC1B,IAAA,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;AAAE,QAAA,OAAO,GAAG;IACvD,MAAM,KAAK,GAA4B,EAAE;IACzC,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QAClC,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAAE,GAA+B,CAAC,GAAG,CAAC,CAAC;IAC/D;AACA,IAAA,OAAO,KAAU;AACnB;AAEA,IAAI,YAAY,GAAmB,IAAI;AAEvC;AACA;AACA;AACA;AACO,MAAM,MAAM,GAAY,OAAkB;SAEjC,SAAS,GAAA;IACvB,IAAI,CAAC,YAAY,EAAE;QACjB,YAAY,GAAG,UAAU,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IAC/C;AACA,IAAA,OAA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ources":["../src/config.ts","../src/core/WorkerCore.ts","../src/autoTrigger.ts","../src/components/Worker.ts","../src/registerComponents.ts","../src/bootstrapWorker.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n worker: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-worker-target\",\n tagNames: {\n worker: \"wcs-worker\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\n// Live reference to the mutable internal config: reads always reflect the latest\n// setConfig() call. The readonly IConfig type only blocks callers from writing\n// through it — the underlying object still changes. If you need a stable,\n// frozen snapshot that won't move under you, use getConfig() instead.\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (typeof partialConfig.autoTrigger === \"boolean\") {\n _config.autoTrigger = partialConfig.autoTrigger;\n }\n if (typeof partialConfig.triggerAttribute === \"string\") {\n _config.triggerAttribute = partialConfig.triggerAttribute;\n }\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","import { IWcBindable, WcsWorkerErrorDetail, WcsWorkerStartOptions } from \"../types.js\";\n\n/**\n * Headless Dedicated Worker primitive. A thin, framework-agnostic wrapper around\n * the `Worker` API exposed through the wc-bindable protocol.\n *\n * A Worker is a \"headless async message-passing resource that owns a child\n * thread\" — structurally identical to BroadcastCore (structured-clone payloads,\n * no wire encoding, `post` is a `state → element` command-token and an incoming\n * `message` is an `element → state` event-token) with one extra axis: this Core\n * *owns* the underlying resource, so `start()` / `terminate()` spawn and tear\n * down the thread, mirroring how WebSocketCore owns its socket.\n *\n * Message model is bus-style (fire-and-forget `post`, observe `message`), not\n * RPC: there is no request/response correlation. Payloads ride structured clone\n * with NO JSON round-trip (symmetrical with BroadcastCore, deliberately unlike\n * WebSocketCore). The Core never throws — a spawn failure (bad URL, CSP block,\n * absent `Worker`), a non-cloneable `post` (`DataCloneError`), a `post` with no\n * running worker (`InvalidStateError`), an uncaught worker error, and a\n * `messageerror` all flow through the `error` property.\n */\nexport class WorkerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"message\", event: \"wcs-worker:message\" },\n { name: \"error\", event: \"wcs-worker:error\" },\n { name: \"running\", event: \"wcs-worker:running-changed\" },\n ],\n commands: [\n { name: \"start\" },\n { name: \"post\" },\n { name: \"terminate\" },\n ],\n };\n\n private _target: EventTarget;\n private _worker: Worker | null = null;\n private _message: any = null;\n private _error: WcsWorkerErrorDetail | null = null;\n private _running: boolean = false;\n\n // Spawn configuration, retained so an automatic restart can re-spawn the same\n // script with the same options.\n private _src: string = \"\";\n private _type: WorkerType = \"module\";\n private _name: string = \"\";\n\n // Restart-on-error bookkeeping (opt-in; bounded like WebSocketCore reconnect).\n // `_restartCount` is CUMULATIVE over the worker's lifetime: it counts every\n // restart since the last start() and is NOT reset by a period of stable\n // operation, so `_maxRestarts` bounds total restarts, not consecutive crashes.\n // It is reset to 0 only by start() (a fresh spawn / src switch).\n private _restartOnError: boolean = false;\n private _maxRestarts: number = Infinity;\n private _restartInterval: number = 0;\n private _restartCount: number = 0;\n private _restartTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Generation guard (§3.4): bumped on dispose() and captured at restart-timer\n // schedule time. A restart deferred via setTimeout is the Core's only async\n // work; if dispose() runs while it is pending, the stale timer MUST NOT\n // re-spawn a worker on a torn-down element. _clearRestartTimer() already\n // cancels the pending timer from inside the Core, so this guard is\n // defense-in-depth for any path that fires the callback after invalidation.\n private _gen = 0;\n // SSR (§3.8): a worker is command-driven (spawned on start()), so there is no\n // asynchronous probe to await — readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get ready(): Promise<void> {\n return this._ready;\n }\n\n // Lifecycle (§3.5). The worker is command-driven (start/post/terminate), so\n // there is no subscription to establish up front: observe() is an idempotent\n // no-op that resolves once ready. dispose() (below) tears down the worker,\n // cancels any pending restart and invalidates in-flight async via _gen.\n observe(): Promise<void> {\n return this._ready;\n }\n\n get message(): any {\n return this._message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._error;\n }\n\n get running(): boolean {\n return this._running;\n }\n\n // --- State setters with event dispatch ---\n\n // Deliberately NO same-value guard. An incoming message is an event, not\n // idempotent state: the worker posting the same value twice is two distinct\n // occurrences and must re-fire wcs-worker:message each time so a `message:`\n // binding and any `eventToken.message:` subscriber see both.\n private _setMessage(message: any): void {\n this._message = message;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:message\", {\n detail: message,\n bubbles: true,\n }));\n }\n\n // Same-value guard. `error` has no derived state, so suppressing redundant\n // null→null dispatches (e.g. a successful spawn clearing an already-null error)\n // avoids spurious events. Reference identity suffices: each failure builds a\n // fresh object and the clear path always passes null.\n private _setError(error: WcsWorkerErrorDetail | null): void {\n if (this._error === error) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n // No same-value guard needed: every spawn (`start`, restart) goes through\n // `_spawn` (false→true) only after `_terminateWorker` (true→false, guarded by\n // `_worker`), so `running` only ever moves on a real transition.\n private _setRunning(running: boolean): void {\n this._running = running;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:running-changed\", {\n detail: running,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n /**\n * Spawn the worker from `src`. Any previously-spawned worker is terminated\n * first, so calling `start()` again with a different `src` switches scripts.\n * Idempotent on the same `src` (re-spawning the script we are already running\n * is pure churn) — this also absorbs the custom-element upgrade path where a\n * connected element with a `src` attribute triggers both\n * attributeChangedCallback and connectedCallback, calling start() twice. A\n * consequence of this guard: changing only the options (`type`, `name`,\n * restart-*) while running the same `src` is ignored — call `terminate()`\n * then `start()` to re-spawn with new options. Never throws: a spawn failure\n * surfaces through `error`.\n */\n start(src: string, options: WcsWorkerStartOptions = {}): void {\n if (!src) {\n this._setError({ name: \"TypeError\", message: \"src is required.\" });\n return;\n }\n if (this._worker && this._src === src) return;\n\n this._clearRestartTimer();\n this._terminateWorker();\n\n this._src = src;\n this._type = options.type ?? \"module\";\n this._name = options.name ?? \"\";\n this._restartOnError = options.restartOnError ?? false;\n this._maxRestarts = options.maxRestarts ?? Infinity;\n this._restartInterval = options.restartInterval ?? 0;\n this._restartCount = 0;\n\n this._setError(null);\n this._spawn();\n }\n\n /**\n * Post a structured-cloneable value to the worker. The optional `transfer`\n * list moves ownership of `Transferable`s (ArrayBuffer, MessagePort, ...) — the\n * escape hatch the declarative layer cannot express. Never throws: a\n * non-cloneable value surfaces as `DataCloneError` and posting with no running\n * worker surfaces an `InvalidStateError`, both through `error`.\n */\n post(data: any, transfer?: Transferable[]): void {\n if (!this._worker) {\n this._setError({\n name: \"InvalidStateError\",\n message: \"Worker is not running. Call start(src) before post().\",\n });\n return;\n }\n try {\n if (transfer && transfer.length > 0) {\n this._worker.postMessage(data, transfer);\n } else {\n this._worker.postMessage(data);\n }\n } catch (err) {\n this._setError(this._normalizeError(err));\n }\n }\n\n /** Terminate the worker. Idempotent — a no-op when none is running. */\n terminate(): void {\n this._clearRestartTimer();\n this._terminateWorker();\n }\n\n /**\n * Tear the Core down for a disconnected Shell: terminate the worker and reset\n * the error shadow. Only the `error` clear is silent — it mutates the shadow\n * without dispatching. Terminating a *running* worker still dispatches\n * `wcs-worker:running-changed` (true→false) via `_terminateWorker`, so a\n * dispose on a worker that was live does emit one event on the (now\n * disconnected) element; only a no-op dispose (no worker running) is fully\n * silent.\n *\n * Asymmetry by design: `_message` is deliberately NOT reset. `error` is\n * transient state — a stale error from a previous worker would mislead after a\n * reconnect, so it is cleared. `message` is the last value received (an event\n * payload); it is retained as the Core's last-known datum and is naturally\n * overwritten by the next incoming message.\n */\n dispose(): void {\n // §3.4: invalidate any in-flight async (a pending restart timer) before\n // tearing down, so a stale timer that somehow fires cannot re-spawn.\n this._gen++;\n this._clearRestartTimer();\n this._terminateWorker();\n this._error = null;\n }\n\n // --- Internal ---\n\n private _spawn(): void {\n try {\n this._worker = new Worker(this._src, { type: this._type, name: this._name || undefined });\n } catch (err) {\n this._setError(this._normalizeError(err));\n return;\n }\n this._worker.addEventListener(\"message\", this._onMessage);\n this._worker.addEventListener(\"messageerror\", this._onMessageError);\n this._worker.addEventListener(\"error\", this._onError);\n this._setRunning(true);\n }\n\n private _onMessage = (event: MessageEvent): void => {\n this._setMessage(event.data);\n };\n\n // Fired when the worker posted a value this context cannot deserialize. The\n // event carries no usable payload, so report a synthetic DataError.\n private _onMessageError = (): void => {\n this._setError({\n name: \"DataError\",\n message: \"Failed to deserialize a message received from the worker.\",\n });\n };\n\n // An uncaught error inside the worker script. The worker itself stays alive\n // (the platform does not auto-terminate it), so restart-on-error explicitly\n // re-spawns a fresh worker when enabled and the bound is not exhausted.\n private _onError = (event: ErrorEvent): void => {\n this._setError({\n name: \"Error\",\n message: event.message || \"Worker script error.\",\n filename: event.filename,\n lineno: event.lineno,\n colno: event.colno,\n });\n if (this._restartOnError && this._restartCount < this._maxRestarts) {\n this._scheduleRestart();\n }\n };\n\n private _scheduleRestart(): void {\n this._clearRestartTimer();\n const gen = this._gen;\n this._restartTimer = setTimeout(() => {\n // §3.4: a dispose() between scheduling and firing bumps _gen; skip the\n // re-spawn so a torn-down Core does not resurrect a worker.\n if (gen !== this._gen) return;\n this._restartTimer = null;\n this._restartCount++;\n this._terminateWorker();\n // Clear the crash error BEFORE re-spawning so a successful restart leaves a\n // consistent running=true / error=null state (an `error` binding must not\n // keep showing the previous script's failure once the fresh worker is live).\n // Order matters: _spawn() re-sets `error` if the new spawn itself fails, so\n // a failed restart still surfaces its own error rather than null.\n this._setError(null);\n this._spawn();\n }, this._restartInterval);\n }\n\n private _clearRestartTimer(): void {\n if (this._restartTimer !== null) {\n clearTimeout(this._restartTimer);\n this._restartTimer = null;\n }\n }\n\n private _terminateWorker(): void {\n if (!this._worker) return;\n this._worker.removeEventListener(\"message\", this._onMessage);\n this._worker.removeEventListener(\"messageerror\", this._onMessageError);\n this._worker.removeEventListener(\"error\", this._onError);\n this._worker.terminate();\n this._worker = null;\n this._setRunning(false);\n }\n\n private _normalizeError(err: unknown): WcsWorkerErrorDetail {\n if (err instanceof Error) {\n // DOMException is an Error subclass; its `name` (DataCloneError, etc.) is\n // the meaningful discriminator for consumers switching on failure kind.\n return { name: err.name, message: err.message };\n }\n return { name: \"Error\", message: String(err) };\n }\n}\n","import { config } from \"./config.js\";\nimport type { WcsWorker } from \"./components/Worker.js\";\n\nlet registered = false;\n\n// Attribute names for the optional post-on-click DOM trigger (clipboard.js-style\n// DX). The element carrying `data-worker-target` points at a <wcs-worker> by id;\n// the payload to post comes from either a literal `data-worker-text` or a\n// `data-worker-from` CSS selector resolving to a source element.\nconst TEXT_ATTRIBUTE = \"data-worker-text\";\nconst FROM_ATTRIBUTE = \"data-worker-from\";\n\nfunction resolveText(triggerElement: Element): string | null {\n // Literal text wins when present (including an empty string — posting \"\" is a\n // legitimate request). The `?? \"\"` right-hand side is defensive and\n // unreachable: hasAttribute() just returned true, so getAttribute() cannot be\n // null here. It exists only to satisfy the `string | null` return type — do\n // not chase coverage on it (the DOM contract makes the null branch impossible).\n if (triggerElement.hasAttribute(TEXT_ATTRIBUTE)) {\n return triggerElement.getAttribute(TEXT_ATTRIBUTE) ?? \"\";\n }\n const selector = triggerElement.getAttribute(FROM_ATTRIBUTE);\n if (!selector) return null;\n // A user-authored selector can be syntactically invalid (e.g. `[data-*` or a\n // bare `:not()`), which makes querySelector throw a SyntaxError. Swallow it and\n // treat the source as unresolvable — the same \"nothing to post\" path as a\n // selector that matches no element — so one bad attribute never crashes the\n // document-level click handler and kills autoTrigger for the whole tab.\n let source: Element | null;\n try {\n source = document.querySelector(selector);\n } catch {\n return null;\n }\n if (!source) return null;\n // Read a form control's `value`; fall back to text content. A bare\n // `\"value\" in source` check is too broad — it also matches <button>,\n // <li value>, <progress>, etc. (which carry an unrelated `value`), posting the\n // wrong thing. Narrow to the text-bearing controls a user actually points\n // `data-worker-from` at; everything else falls through to textContent.\n if (\n source instanceof HTMLInputElement ||\n source instanceof HTMLTextAreaElement ||\n source instanceof HTMLSelectElement\n ) {\n return source.value;\n }\n // `?? \"\"` is defensive: per the DOM spec only Document / DocumentType /\n // Notation nodes have a null `textContent`, and querySelector only ever returns\n // an Element (whose textContent is always a string). The branch is therefore\n // unreachable in practice and kept solely for the `string | null` type — not\n // worth a contrived test.\n return source.textContent ?? \"\";\n}\n\nfunction handleClick(event: Event): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n\n const triggerElement = target.closest<Element>(`[${config.triggerAttribute}]`);\n if (!triggerElement) return;\n\n const workerId = triggerElement.getAttribute(config.triggerAttribute);\n if (!workerId) return;\n\n // Resolve the registered constructor at call time instead of importing\n // WcsWorker as a value (avoids a components ⇄ autoTrigger import cycle:\n // Worker.connectedCallback() calls registerAutoTrigger()). instanceof against\n // the customElements registry keeps the same identity guarantee.\n const WorkerCtor = customElements.get(config.tagNames.worker);\n const workerElement = document.getElementById(workerId);\n if (!WorkerCtor || !(workerElement instanceof WorkerCtor)) return;\n\n const text = resolveText(triggerElement);\n // No resolvable source: leave the click alone (do not preventDefault) so the\n // element's default action is unaffected.\n if (text === null) return;\n\n // Suppress the default action so a post can run without navigating. Intentional:\n // do not attach data-worker-target to an element whose default action you also\n // want (a real <a href> link). See README \"Optional DOM Triggering\".\n event.preventDefault();\n (workerElement as WcsWorker).post(text);\n}\n\nexport function registerAutoTrigger(): void {\n if (registered) return;\n registered = true;\n document.addEventListener(\"click\", handleClick);\n}\n\nexport function unregisterAutoTrigger(): void {\n if (!registered) return;\n registered = false;\n document.removeEventListener(\"click\", handleClick);\n}\n","import { config } from \"../config.js\";\nimport { IWcBindable, WcsWorkerErrorDetail } from \"../types.js\";\nimport { WorkerCore } from \"../core/WorkerCore.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\n\n// Named WcsWorker (not `Worker`) to avoid shadowing the global `Worker`\n// constructor and to match the <wcs-broadcast> WcsBroadcast / <wcs-ws>\n// WcsWebSocket convention.\nexport class WcsWorker extends HTMLElement {\n // SSR (§4.1/§4.4): expose connectedCallbackPromise backed by _core.observe()\n // so a shell renderer can await first-connect readiness uniformly across all\n // IO nodes. The worker still spawns synchronously in connectedCallback; the\n // Core's observe() resolves immediately (command-driven, no async probe), so\n // the promise is effectively already-resolved but the contract is honored.\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...WorkerCore.wcBindable,\n // Shell-level settable surface. `src` selects the script; `manual` suppresses\n // auto-spawn; `keep-alive` keeps the worker past disconnect; the restart-*\n // inputs configure opt-in restart-on-error. There is no momentary `post`\n // property: posting needs an argument (the payload), so element actions run\n // via command-token (`command.post: $command.ping`) or the DOM autoTrigger,\n // keeping `post` a plain command and the `command.post:` wiring readable.\n inputs: [\n { name: \"src\", attribute: \"src\" },\n { name: \"type\", attribute: \"type\" },\n { name: \"name\", attribute: \"name\" },\n { name: \"manual\", attribute: \"manual\" },\n { name: \"keepAlive\", attribute: \"keep-alive\" },\n { name: \"restartOnError\", attribute: \"restart-on-error\" },\n { name: \"maxRestarts\", attribute: \"max-restarts\" },\n { name: \"restartInterval\", attribute: \"restart-interval\" },\n ],\n // Commands are identical to the Core's — the attribute accessors (src, type,\n // name, ...) do not collide with start/post/terminate.\n commands: WorkerCore.wcBindable.commands,\n };\n static get observedAttributes(): string[] { return [\"src\"]; }\n\n private _core: WorkerCore;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n\n constructor() {\n super();\n this._core = new WorkerCore(this);\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n // --- Attribute accessors ---\n\n get src(): string {\n return this.getAttribute(\"src\") || \"\";\n }\n\n set src(value: string) {\n this.setAttribute(\"src\", value);\n }\n\n get type(): WorkerType {\n return this.getAttribute(\"type\") === \"classic\" ? \"classic\" : \"module\";\n }\n\n set type(value: WorkerType) {\n this.setAttribute(\"type\", value);\n }\n\n get name(): string {\n return this.getAttribute(\"name\") || \"\";\n }\n\n set name(value: string) {\n this.setAttribute(\"name\", value);\n }\n\n get manual(): boolean {\n return this.hasAttribute(\"manual\");\n }\n\n set manual(value: boolean) {\n if (value) {\n this.setAttribute(\"manual\", \"\");\n } else {\n this.removeAttribute(\"manual\");\n }\n }\n\n get keepAlive(): boolean {\n return this.hasAttribute(\"keep-alive\");\n }\n\n set keepAlive(value: boolean) {\n if (value) {\n this.setAttribute(\"keep-alive\", \"\");\n } else {\n this.removeAttribute(\"keep-alive\");\n }\n }\n\n get restartOnError(): boolean {\n return this.hasAttribute(\"restart-on-error\");\n }\n\n set restartOnError(value: boolean) {\n if (value) {\n this.setAttribute(\"restart-on-error\", \"\");\n } else {\n this.removeAttribute(\"restart-on-error\");\n }\n }\n\n get maxRestarts(): number {\n const attr = this.getAttribute(\"max-restarts\");\n // `max-restarts=\"Infinity\"` is the documented default-equivalent for an\n // unbounded restart budget. parseInt(\"Infinity\", 10) is NaN, so match it\n // explicitly rather than leaning on the NaN fallback (which would silently\n // break if that fallback ever changed). Any other non-numeric value still\n // falls back to Infinity via the NaN guard.\n if (attr === \"Infinity\") return Infinity;\n const parsed = attr ? parseInt(attr, 10) : Infinity;\n return Number.isNaN(parsed) ? Infinity : parsed;\n }\n\n set maxRestarts(value: number) {\n this.setAttribute(\"max-restarts\", String(value));\n }\n\n get restartInterval(): number {\n const attr = this.getAttribute(\"restart-interval\");\n const parsed = attr ? parseInt(attr, 10) : 0;\n return Number.isNaN(parsed) ? 0 : parsed;\n }\n\n set restartInterval(value: number) {\n this.setAttribute(\"restart-interval\", String(value));\n }\n\n // --- Core delegated getters ---\n\n get message(): any {\n return this._core.message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._core.error;\n }\n\n get running(): boolean {\n return this._core.running;\n }\n\n // --- Commands ---\n\n start(): void {\n // Delegate unconditionally — including the empty-`src` case — so the Core's\n // never-throw contract holds at the Shell boundary too: start(\"\") raises a\n // TypeError through `error` rather than failing silently. The auto-spawn\n // paths (connectedCallback / attributeChangedCallback) already gate on a\n // non-empty `src`, so this only affects an explicit `el.start()` call.\n this._core.start(this.src, {\n type: this.type,\n name: this.name,\n restartOnError: this.restartOnError,\n maxRestarts: this.maxRestarts,\n restartInterval: this.restartInterval,\n });\n }\n\n post(data: any, transfer?: Transferable[]): void {\n this._core.post(data, transfer);\n }\n\n terminate(): void {\n this._core.terminate();\n }\n\n // --- Lifecycle ---\n\n attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null): void {\n if (name === \"src\" && this.isConnected && !this.manual && newValue) {\n this.start();\n }\n }\n\n connectedCallback(): void {\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n // SSR (§4.4): back connectedCallbackPromise with the Core's observe(). It\n // resolves immediately for this command-driven node, but wiring it keeps the\n // readiness contract uniform with the async-init IO nodes.\n this._connectedCallbackPromise = this._core.observe();\n if (!this.manual && this.src) {\n this.start();\n }\n }\n\n disconnectedCallback(): void {\n // Deliberately does NOT call unregisterAutoTrigger(). The autoTrigger click\n // listener is a single process-wide document listener (registerAutoTrigger\n // is idempotent), shared by every <wcs-worker> on the page — not owned by\n // this element. Tearing it down when the last element disconnects would\n // break a later-inserted trigger, so it is intentionally left installed for\n // the document's lifetime (one passive listener, negligible cost). This\n // mirrors <wcs-broadcast> / <wcs-clipboard>, which register but never\n // unregister either; unregisterAutoTrigger stays exported purely as a\n // symmetric teardown hook for tests / advanced manual control.\n //\n // keep-alive intentionally leaves the worker running past disconnect: the\n // worker outlives the element and ownership transfers to the caller, who must\n // call terminate() to free the thread. Without keep-alive the worker is torn\n // down like <wcs-ws> / <wcs-broadcast> close on disconnect.\n if (!this.keepAlive) {\n this._core.dispose();\n }\n }\n}\n","import { WcsWorker } from \"./components/Worker.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.worker)) {\n customElements.define(config.tagNames.worker, WcsWorker);\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapWorker(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n"],"names":[],"mappings":"AAUA,MAAM,OAAO,GAAoB;AAC/B,IAAA,WAAW,EAAE,IAAI;AACjB,IAAA,gBAAgB,EAAE,oBAAoB;AACtC,IAAA,QAAQ,EAAE;AACR,QAAA,MAAM,EAAE,YAAY;AACrB,KAAA;CACF;AAED,SAAS,UAAU,CAAI,GAAM,EAAA;AAC3B,IAAA,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;AAAE,QAAA,OAAO,GAAG;AACvD,IAAA,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;IAClB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;AAClC,QAAA,UAAU,CAAE,GAA+B,CAAC,GAAG,CAAC,CAAC;IACnD;AACA,IAAA,OAAO,GAAG;AACZ;AAEA,SAAS,SAAS,CAAI,GAAM,EAAA;AAC1B,IAAA,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;A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A;AACtF,QAAA,IAAI,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,WAAW,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,QAAQ,EAAE;YAClE,IAAI,CAAC,KAAK,EAAE;QACd;IACF;IAEA,iBAAiB,GAAA;AACf,QAAA,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,MAAM;AAC3B,QAAA,IAAI,MAAM,CAAC,WAAW,EAAE;AACtB,YAAA,mBAAmB,EAAE;QACvB;;;;QAIA,IAAI,CAAC,yBAAyB,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE;QACrD,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,GAAG,EAAE;YAC5B,IAAI,CAAC,KAAK,EAAE;QACd;IACF;IAEA,oBAAoB,GAAA;;;;;;;;;;;;;;;AAelB,QAAA,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;AACnB,YAAA,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE;QACtB;IACF;;;SCvNc,kBAAkB,GAAA;AAChC,IAAA,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;QAC/C,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;IAC1D;AACF;;ACHM,SAAU,eAAe,CAAC,UAA4B,EAAA;IAC1D,IAAI,UAAU,EAAE;QACd,SAAS,CAAC,UAAU,CAAC;IACvB;AACA,IAAA,kBAAkB,EAAE;AACtB;;;;"}
|
package/dist/index.esm.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const t={autoTrigger:!0,triggerAttribute:"data-worker-target",tagNames:{worker:"wcs-worker"}};function e(t){if(null===t||"object"!=typeof t)return t;Object.freeze(t);for(const r of Object.keys(t))e(t[r]);return t}function r(t){if(null===t||"object"!=typeof t)return t;const e={};for(const s of Object.keys(t))e[s]=r(t[s]);return e}let s=null;const n=t;function a(){return s||(s=e(r(t))),s}class i extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"message",event:"wcs-worker:message"},{name:"error",event:"wcs-worker:error"},{name:"running",event:"wcs-worker:running-changed"}],commands:[{name:"start"},{name:"post"},{name:"terminate"}]};_target;_worker=null;_message=null;_error=null;_running=!1;_src="";_type="module";_name="";_restartOnError=!1;_maxRestarts=1/0;_restartInterval=0;_restartCount=0;_restartTimer=null;constructor(t){super(),this._target=t??this}get message(){return this._message}get error(){return this._error}get running(){return this._running}_setMessage(t){this._message=t,this._target.dispatchEvent(new CustomEvent("wcs-worker:message",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-worker:error",{detail:t,bubbles:!0})))}_setRunning(t){this._running=t,this._target.dispatchEvent(new CustomEvent("wcs-worker:running-changed",{detail:t,bubbles:!0}))}start(t,e={}){t?this._worker&&this._src===t||(this._clearRestartTimer(),this._terminateWorker(),this._src=t,this._type=e.type??"module",this._name=e.name??"",this._restartOnError=e.restartOnError??!1,this._maxRestarts=e.maxRestarts??1/0,this._restartInterval=e.restartInterval??0,this._restartCount=0,this._setError(null),this._spawn()):this._setError({name:"TypeError",message:"src is required."})}post(t,e){if(this._worker)try{e&&e.length>0?this._worker.postMessage(t,e):this._worker.postMessage(t)}catch(t){this._setError(this._normalizeError(t))}else this._setError({name:"InvalidStateError",message:"Worker is not running. Call start(src) before post()."})}terminate(){this._clearRestartTimer(),this._terminateWorker()}dispose(){this._clearRestartTimer(),this._terminateWorker(),this._error=null}_spawn(){try{this._worker=new Worker(this._src,{type:this._type,name:this._name||void 0})}catch(t){return void this._setError(this._normalizeError(t))}this._worker.addEventListener("message",this._onMessage),this._worker.addEventListener("messageerror",this._onMessageError),this._worker.addEventListener("error",this._onError),this._setRunning(!0)}_onMessage=t=>{this._setMessage(t.data)};_onMessageError=()=>{this._setError({name:"DataError",message:"Failed to deserialize a message received from the worker."})};_onError=t=>{this._setError({name:"Error",message:t.message||"Worker script error.",filename:t.filename,lineno:t.lineno,colno:t.colno}),this._restartOnError&&this._restartCount<this._maxRestarts&&this._scheduleRestart()};_scheduleRestart(){this._clearRestartTimer()
|
|
1
|
+
const t={autoTrigger:!0,triggerAttribute:"data-worker-target",tagNames:{worker:"wcs-worker"}};function e(t){if(null===t||"object"!=typeof t)return t;Object.freeze(t);for(const r of Object.keys(t))e(t[r]);return t}function r(t){if(null===t||"object"!=typeof t)return t;const e={};for(const s of Object.keys(t))e[s]=r(t[s]);return e}let s=null;const n=t;function a(){return s||(s=e(r(t))),s}class i extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"message",event:"wcs-worker:message"},{name:"error",event:"wcs-worker:error"},{name:"running",event:"wcs-worker:running-changed"}],commands:[{name:"start"},{name:"post"},{name:"terminate"}]};_target;_worker=null;_message=null;_error=null;_running=!1;_src="";_type="module";_name="";_restartOnError=!1;_maxRestarts=1/0;_restartInterval=0;_restartCount=0;_restartTimer=null;_gen=0;_ready=Promise.resolve();constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}get message(){return this._message}get error(){return this._error}get running(){return this._running}_setMessage(t){this._message=t,this._target.dispatchEvent(new CustomEvent("wcs-worker:message",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-worker:error",{detail:t,bubbles:!0})))}_setRunning(t){this._running=t,this._target.dispatchEvent(new CustomEvent("wcs-worker:running-changed",{detail:t,bubbles:!0}))}start(t,e={}){t?this._worker&&this._src===t||(this._clearRestartTimer(),this._terminateWorker(),this._src=t,this._type=e.type??"module",this._name=e.name??"",this._restartOnError=e.restartOnError??!1,this._maxRestarts=e.maxRestarts??1/0,this._restartInterval=e.restartInterval??0,this._restartCount=0,this._setError(null),this._spawn()):this._setError({name:"TypeError",message:"src is required."})}post(t,e){if(this._worker)try{e&&e.length>0?this._worker.postMessage(t,e):this._worker.postMessage(t)}catch(t){this._setError(this._normalizeError(t))}else this._setError({name:"InvalidStateError",message:"Worker is not running. Call start(src) before post()."})}terminate(){this._clearRestartTimer(),this._terminateWorker()}dispose(){this._gen++,this._clearRestartTimer(),this._terminateWorker(),this._error=null}_spawn(){try{this._worker=new Worker(this._src,{type:this._type,name:this._name||void 0})}catch(t){return void this._setError(this._normalizeError(t))}this._worker.addEventListener("message",this._onMessage),this._worker.addEventListener("messageerror",this._onMessageError),this._worker.addEventListener("error",this._onError),this._setRunning(!0)}_onMessage=t=>{this._setMessage(t.data)};_onMessageError=()=>{this._setError({name:"DataError",message:"Failed to deserialize a message received from the worker."})};_onError=t=>{this._setError({name:"Error",message:t.message||"Worker script error.",filename:t.filename,lineno:t.lineno,colno:t.colno}),this._restartOnError&&this._restartCount<this._maxRestarts&&this._scheduleRestart()};_scheduleRestart(){this._clearRestartTimer();const t=this._gen;this._restartTimer=setTimeout(()=>{t===this._gen&&(this._restartTimer=null,this._restartCount++,this._terminateWorker(),this._setError(null),this._spawn())},this._restartInterval)}_clearRestartTimer(){null!==this._restartTimer&&(clearTimeout(this._restartTimer),this._restartTimer=null)}_terminateWorker(){this._worker&&(this._worker.removeEventListener("message",this._onMessage),this._worker.removeEventListener("messageerror",this._onMessageError),this._worker.removeEventListener("error",this._onError),this._worker.terminate(),this._worker=null,this._setRunning(!1))}_normalizeError(t){return t instanceof Error?{name:t.name,message:t.message}:{name:"Error",message:String(t)}}}let o=!1;const u="data-worker-text";function m(t){const e=t.target;if(!(e instanceof Element))return;const r=e.closest(`[${n.triggerAttribute}]`);if(!r)return;const s=r.getAttribute(n.triggerAttribute);if(!s)return;const a=customElements.get(n.tagNames.worker),i=document.getElementById(s);if(!(a&&i instanceof a))return;const o=function(t){if(t.hasAttribute(u))return t.getAttribute(u)??"";const e=t.getAttribute("data-worker-from");if(!e)return null;let r;try{r=document.querySelector(e)}catch{return null}return r?r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement?r.value:r.textContent??"":null}(r);null!==o&&(t.preventDefault(),i.post(o))}class l extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...i.wcBindable,inputs:[{name:"src",attribute:"src"},{name:"type",attribute:"type"},{name:"name",attribute:"name"},{name:"manual",attribute:"manual"},{name:"keepAlive",attribute:"keep-alive"},{name:"restartOnError",attribute:"restart-on-error"},{name:"maxRestarts",attribute:"max-restarts"},{name:"restartInterval",attribute:"restart-interval"}],commands:i.wcBindable.commands};static get observedAttributes(){return["src"]}_core;_connectedCallbackPromise=Promise.resolve();constructor(){super(),this._core=new i(this)}get connectedCallbackPromise(){return this._connectedCallbackPromise}get src(){return this.getAttribute("src")||""}set src(t){this.setAttribute("src",t)}get type(){return"classic"===this.getAttribute("type")?"classic":"module"}set type(t){this.setAttribute("type",t)}get name(){return this.getAttribute("name")||""}set name(t){this.setAttribute("name",t)}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get keepAlive(){return this.hasAttribute("keep-alive")}set keepAlive(t){t?this.setAttribute("keep-alive",""):this.removeAttribute("keep-alive")}get restartOnError(){return this.hasAttribute("restart-on-error")}set restartOnError(t){t?this.setAttribute("restart-on-error",""):this.removeAttribute("restart-on-error")}get maxRestarts(){const t=this.getAttribute("max-restarts");if("Infinity"===t)return 1/0;const e=t?parseInt(t,10):1/0;return Number.isNaN(e)?1/0:e}set maxRestarts(t){this.setAttribute("max-restarts",String(t))}get restartInterval(){const t=this.getAttribute("restart-interval"),e=t?parseInt(t,10):0;return Number.isNaN(e)?0:e}set restartInterval(t){this.setAttribute("restart-interval",String(t))}get message(){return this._core.message}get error(){return this._core.error}get running(){return this._core.running}start(){this._core.start(this.src,{type:this.type,name:this.name,restartOnError:this.restartOnError,maxRestarts:this.maxRestarts,restartInterval:this.restartInterval})}post(t,e){this._core.post(t,e)}terminate(){this._core.terminate()}attributeChangedCallback(t,e,r){"src"===t&&this.isConnected&&!this.manual&&r&&this.start()}connectedCallback(){this.style.display="none",n.autoTrigger&&(o||(o=!0,document.addEventListener("click",m))),this._connectedCallbackPromise=this._core.observe(),!this.manual&&this.src&&this.start()}disconnectedCallback(){this.keepAlive||this._core.dispose()}}function c(e){var r;e&&("boolean"==typeof(r=e).autoTrigger&&(t.autoTrigger=r.autoTrigger),"string"==typeof r.triggerAttribute&&(t.triggerAttribute=r.triggerAttribute),r.tagNames&&Object.assign(t.tagNames,r.tagNames),s=null),customElements.get(n.tagNames.worker)||customElements.define(n.tagNames.worker,l)}export{l as WcsWorker,i as WorkerCore,c as bootstrapWorker,a as getConfig};
|
|
2
2
|
//# sourceMappingURL=index.esm.min.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.min.js","sources":["../src/config.ts","../src/core/WorkerCore.ts","../src/autoTrigger.ts","../src/components/Worker.ts","../src/bootstrapWorker.ts","../src/registerComponents.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n worker: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-worker-target\",\n tagNames: {\n worker: \"wcs-worker\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\n// Live reference to the mutable internal config: reads always reflect the latest\n// setConfig() call. The readonly IConfig type only blocks callers from writing\n// through it — the underlying object still changes. If you need a stable,\n// frozen snapshot that won't move under you, use getConfig() instead.\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (typeof partialConfig.autoTrigger === \"boolean\") {\n _config.autoTrigger = partialConfig.autoTrigger;\n }\n if (typeof partialConfig.triggerAttribute === \"string\") {\n _config.triggerAttribute = partialConfig.triggerAttribute;\n }\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","import { IWcBindable, WcsWorkerErrorDetail, WcsWorkerStartOptions } from \"../types.js\";\n\n/**\n * Headless Dedicated Worker primitive. A thin, framework-agnostic wrapper around\n * the `Worker` API exposed through the wc-bindable protocol.\n *\n * A Worker is a \"headless async message-passing resource that owns a child\n * thread\" — structurally identical to BroadcastCore (structured-clone payloads,\n * no wire encoding, `post` is a `state → element` command-token and an incoming\n * `message` is an `element → state` event-token) with one extra axis: this Core\n * *owns* the underlying resource, so `start()` / `terminate()` spawn and tear\n * down the thread, mirroring how WebSocketCore owns its socket.\n *\n * Message model is bus-style (fire-and-forget `post`, observe `message`), not\n * RPC: there is no request/response correlation. Payloads ride structured clone\n * with NO JSON round-trip (symmetrical with BroadcastCore, deliberately unlike\n * WebSocketCore). The Core never throws — a spawn failure (bad URL, CSP block,\n * absent `Worker`), a non-cloneable `post` (`DataCloneError`), a `post` with no\n * running worker (`InvalidStateError`), an uncaught worker error, and a\n * `messageerror` all flow through the `error` property.\n */\nexport class WorkerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"message\", event: \"wcs-worker:message\" },\n { name: \"error\", event: \"wcs-worker:error\" },\n { name: \"running\", event: \"wcs-worker:running-changed\" },\n ],\n commands: [\n { name: \"start\" },\n { name: \"post\" },\n { name: \"terminate\" },\n ],\n };\n\n private _target: EventTarget;\n private _worker: Worker | null = null;\n private _message: any = null;\n private _error: WcsWorkerErrorDetail | null = null;\n private _running: boolean = false;\n\n // Spawn configuration, retained so an automatic restart can re-spawn the same\n // script with the same options.\n private _src: string = \"\";\n private _type: WorkerType = \"module\";\n private _name: string = \"\";\n\n // Restart-on-error bookkeeping (opt-in; bounded like WebSocketCore reconnect).\n // `_restartCount` is CUMULATIVE over the worker's lifetime: it counts every\n // restart since the last start() and is NOT reset by a period of stable\n // operation, so `_maxRestarts` bounds total restarts, not consecutive crashes.\n // It is reset to 0 only by start() (a fresh spawn / src switch).\n private _restartOnError: boolean = false;\n private _maxRestarts: number = Infinity;\n private _restartInterval: number = 0;\n private _restartCount: number = 0;\n private _restartTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get message(): any {\n return this._message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._error;\n }\n\n get running(): boolean {\n return this._running;\n }\n\n // --- State setters with event dispatch ---\n\n // Deliberately NO same-value guard. An incoming message is an event, not\n // idempotent state: the worker posting the same value twice is two distinct\n // occurrences and must re-fire wcs-worker:message each time so a `message:`\n // binding and any `eventToken.message:` subscriber see both.\n private _setMessage(message: any): void {\n this._message = message;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:message\", {\n detail: message,\n bubbles: true,\n }));\n }\n\n // Same-value guard. `error` has no derived state, so suppressing redundant\n // null→null dispatches (e.g. a successful spawn clearing an already-null error)\n // avoids spurious events. Reference identity suffices: each failure builds a\n // fresh object and the clear path always passes null.\n private _setError(error: WcsWorkerErrorDetail | null): void {\n if (this._error === error) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n // No same-value guard needed: every spawn (`start`, restart) goes through\n // `_spawn` (false→true) only after `_terminateWorker` (true→false, guarded by\n // `_worker`), so `running` only ever moves on a real transition.\n private _setRunning(running: boolean): void {\n this._running = running;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:running-changed\", {\n detail: running,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n /**\n * Spawn the worker from `src`. Any previously-spawned worker is terminated\n * first, so calling `start()` again with a different `src` switches scripts.\n * Idempotent on the same `src` (re-spawning the script we are already running\n * is pure churn) — this also absorbs the custom-element upgrade path where a\n * connected element with a `src` attribute triggers both\n * attributeChangedCallback and connectedCallback, calling start() twice. A\n * consequence of this guard: changing only the options (`type`, `name`,\n * restart-*) while running the same `src` is ignored — call `terminate()`\n * then `start()` to re-spawn with new options. Never throws: a spawn failure\n * surfaces through `error`.\n */\n start(src: string, options: WcsWorkerStartOptions = {}): void {\n if (!src) {\n this._setError({ name: \"TypeError\", message: \"src is required.\" });\n return;\n }\n if (this._worker && this._src === src) return;\n\n this._clearRestartTimer();\n this._terminateWorker();\n\n this._src = src;\n this._type = options.type ?? \"module\";\n this._name = options.name ?? \"\";\n this._restartOnError = options.restartOnError ?? false;\n this._maxRestarts = options.maxRestarts ?? Infinity;\n this._restartInterval = options.restartInterval ?? 0;\n this._restartCount = 0;\n\n this._setError(null);\n this._spawn();\n }\n\n /**\n * Post a structured-cloneable value to the worker. The optional `transfer`\n * list moves ownership of `Transferable`s (ArrayBuffer, MessagePort, ...) — the\n * escape hatch the declarative layer cannot express. Never throws: a\n * non-cloneable value surfaces as `DataCloneError` and posting with no running\n * worker surfaces an `InvalidStateError`, both through `error`.\n */\n post(data: any, transfer?: Transferable[]): void {\n if (!this._worker) {\n this._setError({\n name: \"InvalidStateError\",\n message: \"Worker is not running. Call start(src) before post().\",\n });\n return;\n }\n try {\n if (transfer && transfer.length > 0) {\n this._worker.postMessage(data, transfer);\n } else {\n this._worker.postMessage(data);\n }\n } catch (err) {\n this._setError(this._normalizeError(err));\n }\n }\n\n /** Terminate the worker. Idempotent — a no-op when none is running. */\n terminate(): void {\n this._clearRestartTimer();\n this._terminateWorker();\n }\n\n /**\n * Tear the Core down for a disconnected Shell: terminate the worker and reset\n * the error shadow. Only the `error` clear is silent — it mutates the shadow\n * without dispatching. Terminating a *running* worker still dispatches\n * `wcs-worker:running-changed` (true→false) via `_terminateWorker`, so a\n * dispose on a worker that was live does emit one event on the (now\n * disconnected) element; only a no-op dispose (no worker running) is fully\n * silent.\n *\n * Asymmetry by design: `_message` is deliberately NOT reset. `error` is\n * transient state — a stale error from a previous worker would mislead after a\n * reconnect, so it is cleared. `message` is the last value received (an event\n * payload); it is retained as the Core's last-known datum and is naturally\n * overwritten by the next incoming message.\n */\n dispose(): void {\n this._clearRestartTimer();\n this._terminateWorker();\n this._error = null;\n }\n\n // --- Internal ---\n\n private _spawn(): void {\n try {\n this._worker = new Worker(this._src, { type: this._type, name: this._name || undefined });\n } catch (err) {\n this._setError(this._normalizeError(err));\n return;\n }\n this._worker.addEventListener(\"message\", this._onMessage);\n this._worker.addEventListener(\"messageerror\", this._onMessageError);\n this._worker.addEventListener(\"error\", this._onError);\n this._setRunning(true);\n }\n\n private _onMessage = (event: MessageEvent): void => {\n this._setMessage(event.data);\n };\n\n // Fired when the worker posted a value this context cannot deserialize. The\n // event carries no usable payload, so report a synthetic DataError.\n private _onMessageError = (): void => {\n this._setError({\n name: \"DataError\",\n message: \"Failed to deserialize a message received from the worker.\",\n });\n };\n\n // An uncaught error inside the worker script. The worker itself stays alive\n // (the platform does not auto-terminate it), so restart-on-error explicitly\n // re-spawns a fresh worker when enabled and the bound is not exhausted.\n private _onError = (event: ErrorEvent): void => {\n this._setError({\n name: \"Error\",\n message: event.message || \"Worker script error.\",\n filename: event.filename,\n lineno: event.lineno,\n colno: event.colno,\n });\n if (this._restartOnError && this._restartCount < this._maxRestarts) {\n this._scheduleRestart();\n }\n };\n\n private _scheduleRestart(): void {\n this._clearRestartTimer();\n this._restartTimer = setTimeout(() => {\n this._restartTimer = null;\n this._restartCount++;\n this._terminateWorker();\n // Clear the crash error BEFORE re-spawning so a successful restart leaves a\n // consistent running=true / error=null state (an `error` binding must not\n // keep showing the previous script's failure once the fresh worker is live).\n // Order matters: _spawn() re-sets `error` if the new spawn itself fails, so\n // a failed restart still surfaces its own error rather than null.\n this._setError(null);\n this._spawn();\n }, this._restartInterval);\n }\n\n private _clearRestartTimer(): void {\n if (this._restartTimer !== null) {\n clearTimeout(this._restartTimer);\n this._restartTimer = null;\n }\n }\n\n private _terminateWorker(): void {\n if (!this._worker) return;\n this._worker.removeEventListener(\"message\", this._onMessage);\n this._worker.removeEventListener(\"messageerror\", this._onMessageError);\n this._worker.removeEventListener(\"error\", this._onError);\n this._worker.terminate();\n this._worker = null;\n this._setRunning(false);\n }\n\n private _normalizeError(err: unknown): WcsWorkerErrorDetail {\n if (err instanceof Error) {\n // DOMException is an Error subclass; its `name` (DataCloneError, etc.) is\n // the meaningful discriminator for consumers switching on failure kind.\n return { name: err.name, message: err.message };\n }\n return { name: \"Error\", message: String(err) };\n }\n}\n","import { config } from \"./config.js\";\nimport type { WcsWorker } from \"./components/Worker.js\";\n\nlet registered = false;\n\n// Attribute names for the optional post-on-click DOM trigger (clipboard.js-style\n// DX). The element carrying `data-worker-target` points at a <wcs-worker> by id;\n// the payload to post comes from either a literal `data-worker-text` or a\n// `data-worker-from` CSS selector resolving to a source element.\nconst TEXT_ATTRIBUTE = \"data-worker-text\";\nconst FROM_ATTRIBUTE = \"data-worker-from\";\n\nfunction resolveText(triggerElement: Element): string | null {\n // Literal text wins when present (including an empty string — posting \"\" is a\n // legitimate request). The `?? \"\"` right-hand side is defensive and\n // unreachable: hasAttribute() just returned true, so getAttribute() cannot be\n // null here. It exists only to satisfy the `string | null` return type — do\n // not chase coverage on it (the DOM contract makes the null branch impossible).\n if (triggerElement.hasAttribute(TEXT_ATTRIBUTE)) {\n return triggerElement.getAttribute(TEXT_ATTRIBUTE) ?? \"\";\n }\n const selector = triggerElement.getAttribute(FROM_ATTRIBUTE);\n if (!selector) return null;\n // A user-authored selector can be syntactically invalid (e.g. `[data-*` or a\n // bare `:not()`), which makes querySelector throw a SyntaxError. Swallow it and\n // treat the source as unresolvable — the same \"nothing to post\" path as a\n // selector that matches no element — so one bad attribute never crashes the\n // document-level click handler and kills autoTrigger for the whole tab.\n let source: Element | null;\n try {\n source = document.querySelector(selector);\n } catch {\n return null;\n }\n if (!source) return null;\n // Read a form control's `value`; fall back to text content. A bare\n // `\"value\" in source` check is too broad — it also matches <button>,\n // <li value>, <progress>, etc. (which carry an unrelated `value`), posting the\n // wrong thing. Narrow to the text-bearing controls a user actually points\n // `data-worker-from` at; everything else falls through to textContent.\n if (\n source instanceof HTMLInputElement ||\n source instanceof HTMLTextAreaElement ||\n source instanceof HTMLSelectElement\n ) {\n return source.value;\n }\n // `?? \"\"` is defensive: per the DOM spec only Document / DocumentType /\n // Notation nodes have a null `textContent`, and querySelector only ever returns\n // an Element (whose textContent is always a string). The branch is therefore\n // unreachable in practice and kept solely for the `string | null` type — not\n // worth a contrived test.\n return source.textContent ?? \"\";\n}\n\nfunction handleClick(event: Event): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n\n const triggerElement = target.closest<Element>(`[${config.triggerAttribute}]`);\n if (!triggerElement) return;\n\n const workerId = triggerElement.getAttribute(config.triggerAttribute);\n if (!workerId) return;\n\n // Resolve the registered constructor at call time instead of importing\n // WcsWorker as a value (avoids a components ⇄ autoTrigger import cycle:\n // Worker.connectedCallback() calls registerAutoTrigger()). instanceof against\n // the customElements registry keeps the same identity guarantee.\n const WorkerCtor = customElements.get(config.tagNames.worker);\n const workerElement = document.getElementById(workerId);\n if (!WorkerCtor || !(workerElement instanceof WorkerCtor)) return;\n\n const text = resolveText(triggerElement);\n // No resolvable source: leave the click alone (do not preventDefault) so the\n // element's default action is unaffected.\n if (text === null) return;\n\n // Suppress the default action so a post can run without navigating. Intentional:\n // do not attach data-worker-target to an element whose default action you also\n // want (a real <a href> link). See README \"Optional DOM Triggering\".\n event.preventDefault();\n (workerElement as WcsWorker).post(text);\n}\n\nexport function registerAutoTrigger(): void {\n if (registered) return;\n registered = true;\n document.addEventListener(\"click\", handleClick);\n}\n\nexport function unregisterAutoTrigger(): void {\n if (!registered) return;\n registered = false;\n document.removeEventListener(\"click\", handleClick);\n}\n","import { config } from \"../config.js\";\nimport { IWcBindable, WcsWorkerErrorDetail } from \"../types.js\";\nimport { WorkerCore } from \"../core/WorkerCore.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\n\n// Named WcsWorker (not `Worker`) to avoid shadowing the global `Worker`\n// constructor and to match the <wcs-broadcast> WcsBroadcast / <wcs-ws>\n// WcsWebSocket convention.\nexport class WcsWorker extends HTMLElement {\n // The worker spawns synchronously in connectedCallback (no async init), so no\n // connectedCallbackPromise is needed — mirrors <wcs-ws> / <wcs-broadcast>.\n static hasConnectedCallbackPromise = false;\n static wcBindable: IWcBindable = {\n ...WorkerCore.wcBindable,\n // Shell-level settable surface. `src` selects the script; `manual` suppresses\n // auto-spawn; `keep-alive` keeps the worker past disconnect; the restart-*\n // inputs configure opt-in restart-on-error. There is no momentary `post`\n // property: posting needs an argument (the payload), so element actions run\n // via command-token (`command.post: $command.ping`) or the DOM autoTrigger,\n // keeping `post` a plain command and the `command.post:` wiring readable.\n inputs: [\n { name: \"src\", attribute: \"src\" },\n { name: \"type\", attribute: \"type\" },\n { name: \"name\", attribute: \"name\" },\n { name: \"manual\", attribute: \"manual\" },\n { name: \"keepAlive\", attribute: \"keep-alive\" },\n { name: \"restartOnError\", attribute: \"restart-on-error\" },\n { name: \"maxRestarts\", attribute: \"max-restarts\" },\n { name: \"restartInterval\", attribute: \"restart-interval\" },\n ],\n // Commands are identical to the Core's — the attribute accessors (src, type,\n // name, ...) do not collide with start/post/terminate.\n commands: WorkerCore.wcBindable.commands,\n };\n static get observedAttributes(): string[] { return [\"src\"]; }\n\n private _core: WorkerCore;\n\n constructor() {\n super();\n this._core = new WorkerCore(this);\n }\n\n // --- Attribute accessors ---\n\n get src(): string {\n return this.getAttribute(\"src\") || \"\";\n }\n\n set src(value: string) {\n this.setAttribute(\"src\", value);\n }\n\n get type(): WorkerType {\n return this.getAttribute(\"type\") === \"classic\" ? \"classic\" : \"module\";\n }\n\n set type(value: WorkerType) {\n this.setAttribute(\"type\", value);\n }\n\n get name(): string {\n return this.getAttribute(\"name\") || \"\";\n }\n\n set name(value: string) {\n this.setAttribute(\"name\", value);\n }\n\n get manual(): boolean {\n return this.hasAttribute(\"manual\");\n }\n\n set manual(value: boolean) {\n if (value) {\n this.setAttribute(\"manual\", \"\");\n } else {\n this.removeAttribute(\"manual\");\n }\n }\n\n get keepAlive(): boolean {\n return this.hasAttribute(\"keep-alive\");\n }\n\n set keepAlive(value: boolean) {\n if (value) {\n this.setAttribute(\"keep-alive\", \"\");\n } else {\n this.removeAttribute(\"keep-alive\");\n }\n }\n\n get restartOnError(): boolean {\n return this.hasAttribute(\"restart-on-error\");\n }\n\n set restartOnError(value: boolean) {\n if (value) {\n this.setAttribute(\"restart-on-error\", \"\");\n } else {\n this.removeAttribute(\"restart-on-error\");\n }\n }\n\n get maxRestarts(): number {\n const attr = this.getAttribute(\"max-restarts\");\n // `max-restarts=\"Infinity\"` is the documented default-equivalent for an\n // unbounded restart budget. parseInt(\"Infinity\", 10) is NaN, so match it\n // explicitly rather than leaning on the NaN fallback (which would silently\n // break if that fallback ever changed). Any other non-numeric value still\n // falls back to Infinity via the NaN guard.\n if (attr === \"Infinity\") return Infinity;\n const parsed = attr ? parseInt(attr, 10) : Infinity;\n return Number.isNaN(parsed) ? Infinity : parsed;\n }\n\n set maxRestarts(value: number) {\n this.setAttribute(\"max-restarts\", String(value));\n }\n\n get restartInterval(): number {\n const attr = this.getAttribute(\"restart-interval\");\n const parsed = attr ? parseInt(attr, 10) : 0;\n return Number.isNaN(parsed) ? 0 : parsed;\n }\n\n set restartInterval(value: number) {\n this.setAttribute(\"restart-interval\", String(value));\n }\n\n // --- Core delegated getters ---\n\n get message(): any {\n return this._core.message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._core.error;\n }\n\n get running(): boolean {\n return this._core.running;\n }\n\n // --- Commands ---\n\n start(): void {\n // Delegate unconditionally — including the empty-`src` case — so the Core's\n // never-throw contract holds at the Shell boundary too: start(\"\") raises a\n // TypeError through `error` rather than failing silently. The auto-spawn\n // paths (connectedCallback / attributeChangedCallback) already gate on a\n // non-empty `src`, so this only affects an explicit `el.start()` call.\n this._core.start(this.src, {\n type: this.type,\n name: this.name,\n restartOnError: this.restartOnError,\n maxRestarts: this.maxRestarts,\n restartInterval: this.restartInterval,\n });\n }\n\n post(data: any, transfer?: Transferable[]): void {\n this._core.post(data, transfer);\n }\n\n terminate(): void {\n this._core.terminate();\n }\n\n // --- Lifecycle ---\n\n attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null): void {\n if (name === \"src\" && this.isConnected && !this.manual && newValue) {\n this.start();\n }\n }\n\n connectedCallback(): void {\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n if (!this.manual && this.src) {\n this.start();\n }\n }\n\n disconnectedCallback(): void {\n // Deliberately does NOT call unregisterAutoTrigger(). The autoTrigger click\n // listener is a single process-wide document listener (registerAutoTrigger\n // is idempotent), shared by every <wcs-worker> on the page — not owned by\n // this element. Tearing it down when the last element disconnects would\n // break a later-inserted trigger, so it is intentionally left installed for\n // the document's lifetime (one passive listener, negligible cost). This\n // mirrors <wcs-broadcast> / <wcs-clipboard>, which register but never\n // unregister either; unregisterAutoTrigger stays exported purely as a\n // symmetric teardown hook for tests / advanced manual control.\n //\n // keep-alive intentionally leaves the worker running past disconnect: the\n // worker outlives the element and ownership transfers to the caller, who must\n // call terminate() to free the thread. Without keep-alive the worker is torn\n // down like <wcs-ws> / <wcs-broadcast> close on disconnect.\n if (!this.keepAlive) {\n this._core.dispose();\n }\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapWorker(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n","import { WcsWorker } from \"./components/Worker.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.worker)) {\n customElements.define(config.tagNames.worker, WcsWorker);\n }\n}\n"],"names":["_config","autoTrigger","triggerAttribute","tagNames","worker","deepFreeze","obj","Object","freeze","key","keys","deepClone","clone","frozenConfig","config","getConfig","WorkerCore","EventTarget","static","protocol","version","properties","name","event","commands","_target","_worker","_message","_error","_running","_src","_type","_name","_restartOnError","_maxRestarts","Infinity","_restartInterval","_restartCount","_restartTimer","constructor","target","super","this","message","error","running","_setMessage","dispatchEvent","CustomEvent","detail","bubbles","_setError","_setRunning","start","src","options","_clearRestartTimer","_terminateWorker","type","restartOnError","maxRestarts","restartInterval","_spawn","post","data","transfer","length","postMessage","err","_normalizeError","terminate","dispose","Worker","undefined","addEventListener","_onMessage","_onMessageError","_onError","filename","lineno","colno","_scheduleRestart","setTimeout","clearTimeout","removeEventListener","Error","String","registered","TEXT_ATTRIBUTE","handleClick","Element","triggerElement","closest","workerId","getAttribute","WorkerCtor","customElements","get","workerElement","document","getElementById","text","hasAttribute","selector","source","querySelector","HTMLInputElement","HTMLTextAreaElement","HTMLSelectElement","value","textContent","resolveText","preventDefault","WcsWorker","HTMLElement","wcBindable","inputs","attribute","observedAttributes","_core","setAttribute","manual","removeAttribute","keepAlive","attr","parsed","parseInt","Number","isNaN","attributeChangedCallback","_oldValue","newValue","isConnected","connectedCallback","style","display","disconnectedCallback","bootstrapWorker","userConfig","partialConfig","assign","define"],"mappings":"AAUA,MAAMA,EAA2B,CAC/BC,aAAa,EACbC,iBAAkB,qBAClBC,SAAU,CACRC,OAAQ,eAIZ,SAASC,EAAcC,GACrB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAOA,EACpDC,OAAOC,OAAOF,GACd,IAAK,MAAMG,KAAOF,OAAOG,KAAKJ,GAC5BD,EAAYC,EAAgCG,IAE9C,OAAOH,CACT,CAEA,SAASK,EAAaL,GACpB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAOA,EACpD,MAAMM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6E,MAAM3E,KACpB,CAEA,WAAIC,GACF,OAAOH,KAAK6E,MAAM1E,OACpB,CAIA,KAAAQ,GAMEX,KAAK6E,MAAMlE,MAAMX,KAAKY,IAAK,CACzBI,KAAMhB,KAAKgB,KACXpC,KAAMoB,KAAKpB,KACXqC,eAAgBjB,KAAKiB,eACrBC,YAAalB,KAAKkB,YAClBC,gBAAiBnB,KAAKmB,iBAE1B,CAEA,IAAAE,CAAKC,EAAWC,GACdvB,KAAK6E,MAAMxD,KAAKC,EAAMC,EACxB,CAEA,SAAAK,GACE5B,KAAK6E,MAAMjD,WACb,CAIA,wBAAA2D,CAAyB3G,EAAc4G,EAA0BC,GAClD,QAAT7G,GAAkBoB,KAAK0F,cAAgB1F,KAAK+E,QAAUU,GACxDzF,KAAKW,OAET,CAEA,iBAAAgF,GACE3F,KAAK4F,MAAMC,QAAU,OACjBzH,EAAOb,cD9FTsF,IACJA,GAAa,EACbY,SAASzB,iBAAiB,QAASe,MC+F5B/C,KAAK+E,QAAU/E,KAAKY,KACvBZ,KAAKW,OAET,CAEA,oBAAAmF,GAeO9F,KAAKiF,WACRjF,KAAK6E,MAAMhD,SAEf,EC1MI,SAAUkE,EAAgBC,GJ+C1B,IAAoBC,EI9CpBD,IJ+CqC,kBADjBC,EI7CZD,GJ8CazI,cACvBD,EAAQC,YAAc0I,EAAc1I,aAEQ,iBAAnC0I,EAAczI,mBACvBF,EAAQE,iBAAmByI,EAAczI,kBAEvCyI,EAAcxI,UAChBI,OAAOqI,OAAO5I,EAAQG,SAAUwI,EAAcxI,UAEhDU,EAAe,MKzDVmF,eAAeC,IAAInF,EAAOX,SAASC,SACtC4F,eAAe6C,OAAO/H,EAAOX,SAASC,OAAQ6G,EDIlD"}
|
|
1
|
+
{"version":3,"file":"index.esm.min.js","sources":["../src/config.ts","../src/core/WorkerCore.ts","../src/autoTrigger.ts","../src/components/Worker.ts","../src/bootstrapWorker.ts","../src/registerComponents.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n worker: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-worker-target\",\n tagNames: {\n worker: \"wcs-worker\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\n// Live reference to the mutable internal config: reads always reflect the latest\n// setConfig() call. The readonly IConfig type only blocks callers from writing\n// through it — the underlying object still changes. If you need a stable,\n// frozen snapshot that won't move under you, use getConfig() instead.\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (typeof partialConfig.autoTrigger === \"boolean\") {\n _config.autoTrigger = partialConfig.autoTrigger;\n }\n if (typeof partialConfig.triggerAttribute === \"string\") {\n _config.triggerAttribute = partialConfig.triggerAttribute;\n }\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","import { IWcBindable, WcsWorkerErrorDetail, WcsWorkerStartOptions } from \"../types.js\";\n\n/**\n * Headless Dedicated Worker primitive. A thin, framework-agnostic wrapper around\n * the `Worker` API exposed through the wc-bindable protocol.\n *\n * A Worker is a \"headless async message-passing resource that owns a child\n * thread\" — structurally identical to BroadcastCore (structured-clone payloads,\n * no wire encoding, `post` is a `state → element` command-token and an incoming\n * `message` is an `element → state` event-token) with one extra axis: this Core\n * *owns* the underlying resource, so `start()` / `terminate()` spawn and tear\n * down the thread, mirroring how WebSocketCore owns its socket.\n *\n * Message model is bus-style (fire-and-forget `post`, observe `message`), not\n * RPC: there is no request/response correlation. Payloads ride structured clone\n * with NO JSON round-trip (symmetrical with BroadcastCore, deliberately unlike\n * WebSocketCore). The Core never throws — a spawn failure (bad URL, CSP block,\n * absent `Worker`), a non-cloneable `post` (`DataCloneError`), a `post` with no\n * running worker (`InvalidStateError`), an uncaught worker error, and a\n * `messageerror` all flow through the `error` property.\n */\nexport class WorkerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"message\", event: \"wcs-worker:message\" },\n { name: \"error\", event: \"wcs-worker:error\" },\n { name: \"running\", event: \"wcs-worker:running-changed\" },\n ],\n commands: [\n { name: \"start\" },\n { name: \"post\" },\n { name: \"terminate\" },\n ],\n };\n\n private _target: EventTarget;\n private _worker: Worker | null = null;\n private _message: any = null;\n private _error: WcsWorkerErrorDetail | null = null;\n private _running: boolean = false;\n\n // Spawn configuration, retained so an automatic restart can re-spawn the same\n // script with the same options.\n private _src: string = \"\";\n private _type: WorkerType = \"module\";\n private _name: string = \"\";\n\n // Restart-on-error bookkeeping (opt-in; bounded like WebSocketCore reconnect).\n // `_restartCount` is CUMULATIVE over the worker's lifetime: it counts every\n // restart since the last start() and is NOT reset by a period of stable\n // operation, so `_maxRestarts` bounds total restarts, not consecutive crashes.\n // It is reset to 0 only by start() (a fresh spawn / src switch).\n private _restartOnError: boolean = false;\n private _maxRestarts: number = Infinity;\n private _restartInterval: number = 0;\n private _restartCount: number = 0;\n private _restartTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Generation guard (§3.4): bumped on dispose() and captured at restart-timer\n // schedule time. A restart deferred via setTimeout is the Core's only async\n // work; if dispose() runs while it is pending, the stale timer MUST NOT\n // re-spawn a worker on a torn-down element. _clearRestartTimer() already\n // cancels the pending timer from inside the Core, so this guard is\n // defense-in-depth for any path that fires the callback after invalidation.\n private _gen = 0;\n // SSR (§3.8): a worker is command-driven (spawned on start()), so there is no\n // asynchronous probe to await — readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get ready(): Promise<void> {\n return this._ready;\n }\n\n // Lifecycle (§3.5). The worker is command-driven (start/post/terminate), so\n // there is no subscription to establish up front: observe() is an idempotent\n // no-op that resolves once ready. dispose() (below) tears down the worker,\n // cancels any pending restart and invalidates in-flight async via _gen.\n observe(): Promise<void> {\n return this._ready;\n }\n\n get message(): any {\n return this._message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._error;\n }\n\n get running(): boolean {\n return this._running;\n }\n\n // --- State setters with event dispatch ---\n\n // Deliberately NO same-value guard. An incoming message is an event, not\n // idempotent state: the worker posting the same value twice is two distinct\n // occurrences and must re-fire wcs-worker:message each time so a `message:`\n // binding and any `eventToken.message:` subscriber see both.\n private _setMessage(message: any): void {\n this._message = message;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:message\", {\n detail: message,\n bubbles: true,\n }));\n }\n\n // Same-value guard. `error` has no derived state, so suppressing redundant\n // null→null dispatches (e.g. a successful spawn clearing an already-null error)\n // avoids spurious events. Reference identity suffices: each failure builds a\n // fresh object and the clear path always passes null.\n private _setError(error: WcsWorkerErrorDetail | null): void {\n if (this._error === error) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n // No same-value guard needed: every spawn (`start`, restart) goes through\n // `_spawn` (false→true) only after `_terminateWorker` (true→false, guarded by\n // `_worker`), so `running` only ever moves on a real transition.\n private _setRunning(running: boolean): void {\n this._running = running;\n this._target.dispatchEvent(new CustomEvent(\"wcs-worker:running-changed\", {\n detail: running,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n /**\n * Spawn the worker from `src`. Any previously-spawned worker is terminated\n * first, so calling `start()` again with a different `src` switches scripts.\n * Idempotent on the same `src` (re-spawning the script we are already running\n * is pure churn) — this also absorbs the custom-element upgrade path where a\n * connected element with a `src` attribute triggers both\n * attributeChangedCallback and connectedCallback, calling start() twice. A\n * consequence of this guard: changing only the options (`type`, `name`,\n * restart-*) while running the same `src` is ignored — call `terminate()`\n * then `start()` to re-spawn with new options. Never throws: a spawn failure\n * surfaces through `error`.\n */\n start(src: string, options: WcsWorkerStartOptions = {}): void {\n if (!src) {\n this._setError({ name: \"TypeError\", message: \"src is required.\" });\n return;\n }\n if (this._worker && this._src === src) return;\n\n this._clearRestartTimer();\n this._terminateWorker();\n\n this._src = src;\n this._type = options.type ?? \"module\";\n this._name = options.name ?? \"\";\n this._restartOnError = options.restartOnError ?? false;\n this._maxRestarts = options.maxRestarts ?? Infinity;\n this._restartInterval = options.restartInterval ?? 0;\n this._restartCount = 0;\n\n this._setError(null);\n this._spawn();\n }\n\n /**\n * Post a structured-cloneable value to the worker. The optional `transfer`\n * list moves ownership of `Transferable`s (ArrayBuffer, MessagePort, ...) — the\n * escape hatch the declarative layer cannot express. Never throws: a\n * non-cloneable value surfaces as `DataCloneError` and posting with no running\n * worker surfaces an `InvalidStateError`, both through `error`.\n */\n post(data: any, transfer?: Transferable[]): void {\n if (!this._worker) {\n this._setError({\n name: \"InvalidStateError\",\n message: \"Worker is not running. Call start(src) before post().\",\n });\n return;\n }\n try {\n if (transfer && transfer.length > 0) {\n this._worker.postMessage(data, transfer);\n } else {\n this._worker.postMessage(data);\n }\n } catch (err) {\n this._setError(this._normalizeError(err));\n }\n }\n\n /** Terminate the worker. Idempotent — a no-op when none is running. */\n terminate(): void {\n this._clearRestartTimer();\n this._terminateWorker();\n }\n\n /**\n * Tear the Core down for a disconnected Shell: terminate the worker and reset\n * the error shadow. Only the `error` clear is silent — it mutates the shadow\n * without dispatching. Terminating a *running* worker still dispatches\n * `wcs-worker:running-changed` (true→false) via `_terminateWorker`, so a\n * dispose on a worker that was live does emit one event on the (now\n * disconnected) element; only a no-op dispose (no worker running) is fully\n * silent.\n *\n * Asymmetry by design: `_message` is deliberately NOT reset. `error` is\n * transient state — a stale error from a previous worker would mislead after a\n * reconnect, so it is cleared. `message` is the last value received (an event\n * payload); it is retained as the Core's last-known datum and is naturally\n * overwritten by the next incoming message.\n */\n dispose(): void {\n // §3.4: invalidate any in-flight async (a pending restart timer) before\n // tearing down, so a stale timer that somehow fires cannot re-spawn.\n this._gen++;\n this._clearRestartTimer();\n this._terminateWorker();\n this._error = null;\n }\n\n // --- Internal ---\n\n private _spawn(): void {\n try {\n this._worker = new Worker(this._src, { type: this._type, name: this._name || undefined });\n } catch (err) {\n this._setError(this._normalizeError(err));\n return;\n }\n this._worker.addEventListener(\"message\", this._onMessage);\n this._worker.addEventListener(\"messageerror\", this._onMessageError);\n this._worker.addEventListener(\"error\", this._onError);\n this._setRunning(true);\n }\n\n private _onMessage = (event: MessageEvent): void => {\n this._setMessage(event.data);\n };\n\n // Fired when the worker posted a value this context cannot deserialize. The\n // event carries no usable payload, so report a synthetic DataError.\n private _onMessageError = (): void => {\n this._setError({\n name: \"DataError\",\n message: \"Failed to deserialize a message received from the worker.\",\n });\n };\n\n // An uncaught error inside the worker script. The worker itself stays alive\n // (the platform does not auto-terminate it), so restart-on-error explicitly\n // re-spawns a fresh worker when enabled and the bound is not exhausted.\n private _onError = (event: ErrorEvent): void => {\n this._setError({\n name: \"Error\",\n message: event.message || \"Worker script error.\",\n filename: event.filename,\n lineno: event.lineno,\n colno: event.colno,\n });\n if (this._restartOnError && this._restartCount < this._maxRestarts) {\n this._scheduleRestart();\n }\n };\n\n private _scheduleRestart(): void {\n this._clearRestartTimer();\n const gen = this._gen;\n this._restartTimer = setTimeout(() => {\n // §3.4: a dispose() between scheduling and firing bumps _gen; skip the\n // re-spawn so a torn-down Core does not resurrect a worker.\n if (gen !== this._gen) return;\n this._restartTimer = null;\n this._restartCount++;\n this._terminateWorker();\n // Clear the crash error BEFORE re-spawning so a successful restart leaves a\n // consistent running=true / error=null state (an `error` binding must not\n // keep showing the previous script's failure once the fresh worker is live).\n // Order matters: _spawn() re-sets `error` if the new spawn itself fails, so\n // a failed restart still surfaces its own error rather than null.\n this._setError(null);\n this._spawn();\n }, this._restartInterval);\n }\n\n private _clearRestartTimer(): void {\n if (this._restartTimer !== null) {\n clearTimeout(this._restartTimer);\n this._restartTimer = null;\n }\n }\n\n private _terminateWorker(): void {\n if (!this._worker) return;\n this._worker.removeEventListener(\"message\", this._onMessage);\n this._worker.removeEventListener(\"messageerror\", this._onMessageError);\n this._worker.removeEventListener(\"error\", this._onError);\n this._worker.terminate();\n this._worker = null;\n this._setRunning(false);\n }\n\n private _normalizeError(err: unknown): WcsWorkerErrorDetail {\n if (err instanceof Error) {\n // DOMException is an Error subclass; its `name` (DataCloneError, etc.) is\n // the meaningful discriminator for consumers switching on failure kind.\n return { name: err.name, message: err.message };\n }\n return { name: \"Error\", message: String(err) };\n }\n}\n","import { config } from \"./config.js\";\nimport type { WcsWorker } from \"./components/Worker.js\";\n\nlet registered = false;\n\n// Attribute names for the optional post-on-click DOM trigger (clipboard.js-style\n// DX). The element carrying `data-worker-target` points at a <wcs-worker> by id;\n// the payload to post comes from either a literal `data-worker-text` or a\n// `data-worker-from` CSS selector resolving to a source element.\nconst TEXT_ATTRIBUTE = \"data-worker-text\";\nconst FROM_ATTRIBUTE = \"data-worker-from\";\n\nfunction resolveText(triggerElement: Element): string | null {\n // Literal text wins when present (including an empty string — posting \"\" is a\n // legitimate request). The `?? \"\"` right-hand side is defensive and\n // unreachable: hasAttribute() just returned true, so getAttribute() cannot be\n // null here. It exists only to satisfy the `string | null` return type — do\n // not chase coverage on it (the DOM contract makes the null branch impossible).\n if (triggerElement.hasAttribute(TEXT_ATTRIBUTE)) {\n return triggerElement.getAttribute(TEXT_ATTRIBUTE) ?? \"\";\n }\n const selector = triggerElement.getAttribute(FROM_ATTRIBUTE);\n if (!selector) return null;\n // A user-authored selector can be syntactically invalid (e.g. `[data-*` or a\n // bare `:not()`), which makes querySelector throw a SyntaxError. Swallow it and\n // treat the source as unresolvable — the same \"nothing to post\" path as a\n // selector that matches no element — so one bad attribute never crashes the\n // document-level click handler and kills autoTrigger for the whole tab.\n let source: Element | null;\n try {\n source = document.querySelector(selector);\n } catch {\n return null;\n }\n if (!source) return null;\n // Read a form control's `value`; fall back to text content. A bare\n // `\"value\" in source` check is too broad — it also matches <button>,\n // <li value>, <progress>, etc. (which carry an unrelated `value`), posting the\n // wrong thing. Narrow to the text-bearing controls a user actually points\n // `data-worker-from` at; everything else falls through to textContent.\n if (\n source instanceof HTMLInputElement ||\n source instanceof HTMLTextAreaElement ||\n source instanceof HTMLSelectElement\n ) {\n return source.value;\n }\n // `?? \"\"` is defensive: per the DOM spec only Document / DocumentType /\n // Notation nodes have a null `textContent`, and querySelector only ever returns\n // an Element (whose textContent is always a string). The branch is therefore\n // unreachable in practice and kept solely for the `string | null` type — not\n // worth a contrived test.\n return source.textContent ?? \"\";\n}\n\nfunction handleClick(event: Event): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n\n const triggerElement = target.closest<Element>(`[${config.triggerAttribute}]`);\n if (!triggerElement) return;\n\n const workerId = triggerElement.getAttribute(config.triggerAttribute);\n if (!workerId) return;\n\n // Resolve the registered constructor at call time instead of importing\n // WcsWorker as a value (avoids a components ⇄ autoTrigger import cycle:\n // Worker.connectedCallback() calls registerAutoTrigger()). instanceof against\n // the customElements registry keeps the same identity guarantee.\n const WorkerCtor = customElements.get(config.tagNames.worker);\n const workerElement = document.getElementById(workerId);\n if (!WorkerCtor || !(workerElement instanceof WorkerCtor)) return;\n\n const text = resolveText(triggerElement);\n // No resolvable source: leave the click alone (do not preventDefault) so the\n // element's default action is unaffected.\n if (text === null) return;\n\n // Suppress the default action so a post can run without navigating. Intentional:\n // do not attach data-worker-target to an element whose default action you also\n // want (a real <a href> link). See README \"Optional DOM Triggering\".\n event.preventDefault();\n (workerElement as WcsWorker).post(text);\n}\n\nexport function registerAutoTrigger(): void {\n if (registered) return;\n registered = true;\n document.addEventListener(\"click\", handleClick);\n}\n\nexport function unregisterAutoTrigger(): void {\n if (!registered) return;\n registered = false;\n document.removeEventListener(\"click\", handleClick);\n}\n","import { config } from \"../config.js\";\nimport { IWcBindable, WcsWorkerErrorDetail } from \"../types.js\";\nimport { WorkerCore } from \"../core/WorkerCore.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\n\n// Named WcsWorker (not `Worker`) to avoid shadowing the global `Worker`\n// constructor and to match the <wcs-broadcast> WcsBroadcast / <wcs-ws>\n// WcsWebSocket convention.\nexport class WcsWorker extends HTMLElement {\n // SSR (§4.1/§4.4): expose connectedCallbackPromise backed by _core.observe()\n // so a shell renderer can await first-connect readiness uniformly across all\n // IO nodes. The worker still spawns synchronously in connectedCallback; the\n // Core's observe() resolves immediately (command-driven, no async probe), so\n // the promise is effectively already-resolved but the contract is honored.\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...WorkerCore.wcBindable,\n // Shell-level settable surface. `src` selects the script; `manual` suppresses\n // auto-spawn; `keep-alive` keeps the worker past disconnect; the restart-*\n // inputs configure opt-in restart-on-error. There is no momentary `post`\n // property: posting needs an argument (the payload), so element actions run\n // via command-token (`command.post: $command.ping`) or the DOM autoTrigger,\n // keeping `post` a plain command and the `command.post:` wiring readable.\n inputs: [\n { name: \"src\", attribute: \"src\" },\n { name: \"type\", attribute: \"type\" },\n { name: \"name\", attribute: \"name\" },\n { name: \"manual\", attribute: \"manual\" },\n { name: \"keepAlive\", attribute: \"keep-alive\" },\n { name: \"restartOnError\", attribute: \"restart-on-error\" },\n { name: \"maxRestarts\", attribute: \"max-restarts\" },\n { name: \"restartInterval\", attribute: \"restart-interval\" },\n ],\n // Commands are identical to the Core's — the attribute accessors (src, type,\n // name, ...) do not collide with start/post/terminate.\n commands: WorkerCore.wcBindable.commands,\n };\n static get observedAttributes(): string[] { return [\"src\"]; }\n\n private _core: WorkerCore;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n\n constructor() {\n super();\n this._core = new WorkerCore(this);\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n // --- Attribute accessors ---\n\n get src(): string {\n return this.getAttribute(\"src\") || \"\";\n }\n\n set src(value: string) {\n this.setAttribute(\"src\", value);\n }\n\n get type(): WorkerType {\n return this.getAttribute(\"type\") === \"classic\" ? \"classic\" : \"module\";\n }\n\n set type(value: WorkerType) {\n this.setAttribute(\"type\", value);\n }\n\n get name(): string {\n return this.getAttribute(\"name\") || \"\";\n }\n\n set name(value: string) {\n this.setAttribute(\"name\", value);\n }\n\n get manual(): boolean {\n return this.hasAttribute(\"manual\");\n }\n\n set manual(value: boolean) {\n if (value) {\n this.setAttribute(\"manual\", \"\");\n } else {\n this.removeAttribute(\"manual\");\n }\n }\n\n get keepAlive(): boolean {\n return this.hasAttribute(\"keep-alive\");\n }\n\n set keepAlive(value: boolean) {\n if (value) {\n this.setAttribute(\"keep-alive\", \"\");\n } else {\n this.removeAttribute(\"keep-alive\");\n }\n }\n\n get restartOnError(): boolean {\n return this.hasAttribute(\"restart-on-error\");\n }\n\n set restartOnError(value: boolean) {\n if (value) {\n this.setAttribute(\"restart-on-error\", \"\");\n } else {\n this.removeAttribute(\"restart-on-error\");\n }\n }\n\n get maxRestarts(): number {\n const attr = this.getAttribute(\"max-restarts\");\n // `max-restarts=\"Infinity\"` is the documented default-equivalent for an\n // unbounded restart budget. parseInt(\"Infinity\", 10) is NaN, so match it\n // explicitly rather than leaning on the NaN fallback (which would silently\n // break if that fallback ever changed). Any other non-numeric value still\n // falls back to Infinity via the NaN guard.\n if (attr === \"Infinity\") return Infinity;\n const parsed = attr ? parseInt(attr, 10) : Infinity;\n return Number.isNaN(parsed) ? Infinity : parsed;\n }\n\n set maxRestarts(value: number) {\n this.setAttribute(\"max-restarts\", String(value));\n }\n\n get restartInterval(): number {\n const attr = this.getAttribute(\"restart-interval\");\n const parsed = attr ? parseInt(attr, 10) : 0;\n return Number.isNaN(parsed) ? 0 : parsed;\n }\n\n set restartInterval(value: number) {\n this.setAttribute(\"restart-interval\", String(value));\n }\n\n // --- Core delegated getters ---\n\n get message(): any {\n return this._core.message;\n }\n\n get error(): WcsWorkerErrorDetail | null {\n return this._core.error;\n }\n\n get running(): boolean {\n return this._core.running;\n }\n\n // --- Commands ---\n\n start(): void {\n // Delegate unconditionally — including the empty-`src` case — so the Core's\n // never-throw contract holds at the Shell boundary too: start(\"\") raises a\n // TypeError through `error` rather than failing silently. The auto-spawn\n // paths (connectedCallback / attributeChangedCallback) already gate on a\n // non-empty `src`, so this only affects an explicit `el.start()` call.\n this._core.start(this.src, {\n type: this.type,\n name: this.name,\n restartOnError: this.restartOnError,\n maxRestarts: this.maxRestarts,\n restartInterval: this.restartInterval,\n });\n }\n\n post(data: any, transfer?: Transferable[]): void {\n this._core.post(data, transfer);\n }\n\n terminate(): void {\n this._core.terminate();\n }\n\n // --- Lifecycle ---\n\n attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null): void {\n if (name === \"src\" && this.isConnected && !this.manual && newValue) {\n this.start();\n }\n }\n\n connectedCallback(): void {\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n // SSR (§4.4): back connectedCallbackPromise with the Core's observe(). It\n // resolves immediately for this command-driven node, but wiring it keeps the\n // readiness contract uniform with the async-init IO nodes.\n this._connectedCallbackPromise = this._core.observe();\n if (!this.manual && this.src) {\n this.start();\n }\n }\n\n disconnectedCallback(): void {\n // Deliberately does NOT call unregisterAutoTrigger(). The autoTrigger click\n // listener is a single process-wide document listener (registerAutoTrigger\n // is idempotent), shared by every <wcs-worker> on the page — not owned by\n // this element. Tearing it down when the last element disconnects would\n // break a later-inserted trigger, so it is intentionally left installed for\n // the document's lifetime (one passive listener, negligible cost). This\n // mirrors <wcs-broadcast> / <wcs-clipboard>, which register but never\n // unregister either; unregisterAutoTrigger stays exported purely as a\n // symmetric teardown hook for tests / advanced manual control.\n //\n // keep-alive intentionally leaves the worker running past disconnect: the\n // worker outlives the element and ownership transfers to the caller, who must\n // call terminate() to free the thread. Without keep-alive the worker is torn\n // down like <wcs-ws> / <wcs-broadcast> close on disconnect.\n if (!this.keepAlive) {\n this._core.dispose();\n }\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapWorker(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n","import { WcsWorker } from \"./components/Worker.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.worker)) {\n customElements.define(config.tagNames.worker, WcsWorker);\n }\n}\n"],"names":["_config","autoTrigger","triggerAttribute","tagNames","worker","deepFreeze","obj","Object","freeze","key","keys","deepClone","clone","frozenConfig","config","getConfig","WorkerCore","EventTarget","static","protocol","version","properties","name","event","commands","_target","_worker","_message","_error","_running","_src","_type","_name","_restartOnError","_maxRestarts","Infinity","_restartInterval","_restartCount","_restartTimer","_gen","_ready","Promise","resolve","constructor","target","super","this","ready","observe","message","error","running","_setMessage","dispatchEvent","CustomEvent","detail","bubbles","_setError","_setRunning","start","src","options","_clearRestartTimer","_terminateWorker","type","restartOnError","maxRestarts","restartInterval","_spawn","post","data","transfer","length","postMessage","err","_normalizeError","terminate","dispose","Worker","undefined","addEventListener","_onMessage","_onMessageError","_onError","filename","lineno","colno","_scheduleRestart","gen","setTimeout","clearTimeout","removeEventListener","Error","String","registered","TEXT_ATTRIBUTE","handleClick","Element","triggerElement","closest","workerId","getAttribute","WorkerCtor","customElements","get","workerElement","document","getElementById","text","hasAttribute","selector","source","querySelector","HTMLInputElement","HTMLTextAreaElement","HTMLSelectElement","value","textContent","resolveText","preventDefault","WcsWorker","HTMLElement","wcBindable","inputs","attribute","observedAttributes","_core","_connectedCallbackPromise","connectedCallbackPromise","setAttribute","manual","removeAttribute","keepAlive","attr","parsed","parseInt","Number","isNaN","attributeChangedCallback","_oldValue","newValue","isConnected","connectedCallback","style","display","disconnectedCallback","bootstrapWorker","userConfig","partialConfig","assign","define"],"mappings":"AAUA,MAAMA,EAA2B,CAC/BC,aAAa,EACbC,iBAAkB,qBAClBC,SAAU,CACRC,OAAQ,eAIZ,SAASC,EAAcC,GACrB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAOA,EACpDC,OAAOC,OAAOF,GACd,IAAK,MAAMG,KAAOF,OAAOG,KAAKJ,GAC5BD,EAAYC,EAAgCG,IAE9C,OAAOH,CACT,CAEA,SAASK,EAAaL,GACpB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAOA,EACpD,MAAMM,EAAiC,CAAA,EACvC,IAAK,MAAMH,KAAOF,OAAOG,KAAKJ,GAC5BM,EAAMH,GAAOE,EAAWL,EAAgCG,IAE1D,OAAOG,CACT,CAEA,IAAIC,EAA+B,KAM5B,MAAMC,EAAkBd,WAEfe,IAId,OAHKF,IACHA,EAAeR,EAAWM,EAAUX,KAE/Ba,CACT,CC5BM,MAAOG,UAAmBC,YAC9BC,kBAAiC,CAC/BC,SAAU,cACVC,QAAS,EACTC,WAAY,CACV,CAAEC,KAAM,UAAWC,MAAO,sBAC1B,CAAED,KAAM,QAASC,MAAO,oBACxB,CAAED,KAAM,UAAWC,MAAO,+BAE5BC,SAAU,CACR,CAAEF,KAAM,SACR,CAAEA,KAAM,QACR,CAAEA,KAAM,eAIJG,QACAC,QAAyB,KACzBC,SAAgB,KAChBC,OAAsC,KACtCC,UAAoB,EAIpBC,KAAe,GACfC,MAAoB,SACpBC,MAAgB,GAOhBC,iBAA2B,EAC3BC,aAAuBC,IACvBC,iBAA2B,EAC3BC,cAAwB,EACxBC,cAAsD,KAQtDC,KAAO,EAGPC,OAAwBC,QAAQC,UAExC,WAAAC,CAAYC,GACVC,QACAC,KAAKrB,QAAUmB,GAAUE,IAC3B,CAEA,SAAIC,GACF,OAAOD,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A,iBAAAmF,GACEhG,KAAKiG,MAAMC,QAAU,OACjBlI,EAAOb,cDtGT6F,IACJA,GAAa,EACbY,SAAS1B,iBAAiB,QAASgB,KC0GjClD,KAAKiF,0BAA4BjF,KAAKgF,MAAM9E,WACvCF,KAAKoF,QAAUpF,KAAKc,KACvBd,KAAKa,OAET,CAEA,oBAAAsF,GAeOnG,KAAKsF,WACRtF,KAAKgF,MAAMjD,SAEf,ECtNI,SAAUqE,EAAgBC,GJ+C1B,IAAoBC,EI9CpBD,IJ+CqC,kBADjBC,EI7CZD,GJ8CalJ,cACvBD,EAAQC,YAAcmJ,EAAcnJ,aAEQ,iBAAnCmJ,EAAclJ,mBACvBF,EAAQE,iBAAmBkJ,EAAclJ,kBAEvCkJ,EAAcjJ,UAChBI,OAAO8I,OAAOrJ,EAAQG,SAAUiJ,EAAcjJ,UAEhDU,EAAe,MKzDV0F,eAAeC,IAAI1F,EAAOX,SAASC,SACtCmG,eAAe+C,OAAOxI,EAAOX,SAASC,OAAQoH,EDIlD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wcstack/worker",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.15.0",
|
|
4
4
|
"description": "Declarative Web Worker component for Web Components. Framework-agnostic Dedicated Worker primitive via wc-bindable-protocol.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.esm.js",
|