@deviltea/widget-core 0.0.6 → 0.1.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.
@@ -1,192 +0,0 @@
1
- import { effect, endBatch, setActiveSub, startBatch } from "alien-signals";
2
- //#region src/runtime/adapter.ts
3
- /**
4
- * Invokes `listener(value)` with no active alien subscriber (restoring the previous one afterward) and
5
- * isolates a synchronous throw so it cannot escape into the current alien-signals flush. Baseline
6
- * reporting for an isolated exception is a queued microtask rethrow.
7
- */
8
- function invokeListenerIsolated(listener, value) {
9
- const previous = setActiveSub(void 0);
10
- try {
11
- listener(value);
12
- } catch (error) {
13
- queueMicrotask(() => {
14
- throw error;
15
- });
16
- } finally {
17
- setActiveSub(previous);
18
- }
19
- }
20
- /**
21
- * Calls a synchronous semantic event listener without leaking its reads into an enclosing
22
- * Property/effect. Unlike reactive value listeners, event listener exceptions propagate immediately.
23
- */
24
- function invokeListenerUntracked(listener, args) {
25
- const previous = setActiveSub(void 0);
26
- try {
27
- listener(...args);
28
- } finally {
29
- setActiveSub(previous);
30
- }
31
- }
32
- /**
33
- * Nesting depth of the calls that can drive an `alien-signals` evaluation/flush and therefore have to be
34
- * back out of the reactive graph before a deferred propagation is safe to release: `RuntimeState`'s
35
- * `attemptSet`, `RuntimeMethod`'s `invoke` and the tracked read of a Property's result computed. Purely
36
- * local bookkeeping for {@link writeDeferringFlush}, not a semantic boundary of its own.
37
- */
38
- let operationDepth = 0;
39
- /** Number of `startBatch()` calls {@link writeDeferringFlush} has opened and not yet closed. */
40
- let deferredFlushDepth = 0;
41
- /**
42
- * Closes every batch level {@link writeDeferringFlush} left open, letting alien-signals flush the
43
- * notifications it already queued.
44
- *
45
- * The loop condition is re-tested after every `endBatch()`: that flush can run an effect whose Property
46
- * recompute commits its own diagnostic snapshot, which opens a fresh level this same drain must then close.
47
- * A recompute that throws inside one of those flushes must not leave alien-signals permanently batched
48
- * (every later flush in the Runtime's life would be silently suspended), so the remaining levels are
49
- * closed before the throw is rethrown.
50
- */
51
- function releaseDeferredFlushes() {
52
- while (deferredFlushDepth > 0) {
53
- --deferredFlushDepth;
54
- try {
55
- endBatch();
56
- } catch (error) {
57
- releaseDeferredFlushes();
58
- throw error;
59
- }
60
- }
61
- }
62
- /**
63
- * Tracks one nesting level of the calls that can drive an evaluation, and releases every flush
64
- * {@link writeDeferringFlush} deferred inside it once the outermost level is leaving.
65
- *
66
- * The release runs while the depth is still `1`, so a listener that the release's own flush invokes and
67
- * that re-enters the Runtime cannot re-enter the drain loop. The decrement is unconditional: a Property
68
- * recompute that throws inside the release's flush (`createTrackedSubscription` isolates the external
69
- * listener, never the tracked read) must not leave the depth pinned above `0`, or every later call would
70
- * look nested and no release would ever run again.
71
- */
72
- function runRuntimeOperation(fn) {
73
- ++operationDepth;
74
- try {
75
- return fn();
76
- } finally {
77
- try {
78
- if (operationDepth === 1) releaseDeferredFlushes();
79
- } finally {
80
- --operationDepth;
81
- }
82
- }
83
- }
84
- /**
85
- * Performs a signal write whose propagation must not be flushed while a computed may still be
86
- * mid-evaluation, by holding an alien batch open until the outermost {@link runRuntimeOperation} frame on
87
- * the stack is leaving — i.e. until nothing that could still be evaluating remains.
88
- *
89
- * Why this is required in pinned alien-signals@3.2.1 (`esm/index.mjs` / `esm/system.mjs`):
90
- *
91
- * - `signalOper` ends a changed write with `propagate(subs, ...)` followed by `if (!batchDepth) flush()`.
92
- * A write performed from inside a computed's own evaluator therefore starts a *nested* flush that runs
93
- * the effects the outer propagation had already queued — while the computed that queued them is still
94
- * mid-`updateComputed`.
95
- * - `updateComputed` sets `c.flags = 1 | 4` (`Mutable | RecursedCheck`) and only assigns
96
- * `c.value = c.getter(...)` after the getter returns, so during that window the computed carries
97
- * neither `Dirty` (16) nor `Pending` (32) and still holds its previous value.
98
- * - `checkDirty` has no `RecursedCheck` branch: a queued effect whose dependency chain passes through
99
- * that computed hits none of its `(1 | 16)` / `(1 | 32)` cases, concludes `dirty === false`, and then
100
- * clears its own intermediate's `Pending` flag (`sub.flags &= ~32`). The intermediate is now marked
101
- * clean while still holding a stale cached value, so the later `shallowPropagate` — which only
102
- * upgrades subscribers that are still `Pending` — skips it for good: the effect never runs again and
103
- * even an untracked `.get()` returns the stale cache.
104
- *
105
- * Keeping `batchDepth > 0` for the write removes the nested flush entirely: `propagate` still marks and
106
- * queues every watcher through alien-signals' own bookkeeping, and the queue is drained later — by the
107
- * flush that is already running (it re-reads the shared queue length) or by
108
- * {@link runRuntimeOperation}'s release. Nothing here re-implements propagation, ordering or dedupe.
109
- *
110
- * The write itself is unconditional and immediate, so a snapshot is committed exactly where it was
111
- * before: `pendingValue` is written synchronously and every later read commits it (`signalOper`'s read
112
- * path runs `updateSignal` when the signal is `Dirty`), which keeps "the snapshot is committed by the
113
- * time the operation's `ExecutionResult` is observable" true. Only the *notification* moves — never past
114
- * the end of the operation that produced it.
115
- *
116
- * One consequence of using an alien batch as the deferral mechanism, rather than a normative rule about
117
- * Runtime operations: while a level is open, alien-signals coalesces as it does inside any batch, so two
118
- * writes to the *same* signal before the release notify its subscribers once, with the final value. This
119
- * is not a new Runtime semantic — it is the ordinary behavior of the batching alien-signals already owns,
120
- * already observable inside `RuntimeMethod.invoke`'s batch. Every actual completed recompute still
121
- * notifies each of its own subscribers exactly once; alien-signals, not this module, decides which
122
- * recomputes happen.
123
- */
124
- function writeDeferringFlush(write) {
125
- if (operationDepth === 0) {
126
- write();
127
- return;
128
- }
129
- startBatch();
130
- ++deferredFlushDepth;
131
- write();
132
- }
133
- /**
134
- * Creates a Runtime-owned public subscription: an alien `effect()` that tracks `read()`, skips the
135
- * bootstrap run, and invokes `listener` through {@link invokeListenerIsolated} on every actual
136
- * subsequent run. Returns an idempotent unsubscribe function registered with the Runtime's disposal
137
- * bookkeeping.
138
- */
139
- function createTrackedSubscription(context, read, listener) {
140
- let isBootstrap = true;
141
- const rawDispose = effect(() => {
142
- const value = read();
143
- if (isBootstrap) {
144
- isBootstrap = false;
145
- return;
146
- }
147
- invokeListenerIsolated(listener, value);
148
- });
149
- return context.registerSubscription(rawDispose);
150
- }
151
- //#endregion
152
- //#region src/runtime/event.ts
153
- function createEventPrimitive(context) {
154
- const listeners = /* @__PURE__ */ new Set();
155
- let inspectionListeners = null;
156
- function publishInspectionOccurrence(args) {
157
- if (inspectionListeners === null) return;
158
- const snapshot = inspectionListeners.slice();
159
- for (const { listener } of snapshot) invokeListenerIsolated(listener, args);
160
- }
161
- return {
162
- public: Object.freeze({ subscribe(listener) {
163
- context.assertActive();
164
- const entry = { listener };
165
- listeners.add(entry);
166
- return context.registerSubscription(() => listeners.delete(entry));
167
- } }),
168
- emit(...args) {
169
- context.assertActive();
170
- const listenersSnapshot = [...listeners];
171
- publishInspectionOccurrence(Object.freeze([...args]));
172
- for (const { listener } of listenersSnapshot) invokeListenerUntracked(listener, args);
173
- },
174
- inspection: { subscribe(listener) {
175
- const entry = { listener };
176
- if (inspectionListeners === null) inspectionListeners = [];
177
- inspectionListeners.push(entry);
178
- return () => {
179
- if (inspectionListeners === null) return;
180
- const index = inspectionListeners.indexOf(entry);
181
- if (index !== -1) inspectionListeners.splice(index, 1);
182
- };
183
- } }
184
- };
185
- }
186
- function buildEventEmitter(events) {
187
- const emitter = Object.create(null);
188
- for (const [name, primitive] of events) emitter[name] = (...args) => primitive.emit(...args);
189
- return Object.freeze(emitter);
190
- }
191
- //#endregion
192
- export { runRuntimeOperation as a, invokeListenerIsolated as i, createEventPrimitive as n, writeDeferringFlush as o, createTrackedSubscription as r, buildEventEmitter as t };
@@ -1,199 +0,0 @@
1
- //#region src/readonly-map.ts
2
- /** Creates a map-shaped, runtime immutable projection without exposing mutating Map methods. */
3
- function createReadonlyMap(entries) {
4
- const map = new Map(entries);
5
- const result = {
6
- get size() {
7
- return map.size;
8
- },
9
- get(key) {
10
- return map.get(key);
11
- },
12
- has(key) {
13
- return map.has(key);
14
- },
15
- keys() {
16
- return map.keys();
17
- },
18
- values() {
19
- return map.values();
20
- },
21
- entries() {
22
- return map.entries();
23
- },
24
- forEach(callbackfn, thisArg) {
25
- map.forEach((value, key) => callbackfn.call(thisArg, value, key, result));
26
- },
27
- [Symbol.iterator]() {
28
- return map[Symbol.iterator]();
29
- }
30
- };
31
- return Object.freeze(result);
32
- }
33
- //#endregion
34
- //#region src/plugin.ts
35
- /**
36
- * Framework-private brand carrying the plugin's phantom interfaces and its erased definition record.
37
- */
38
- const widgetPluginBrand = Symbol("@deviltea/widget-core:widget-plugin");
39
- /**
40
- * Declares a stable semantic value-contract id while retaining the associated TypeScript value type for
41
- * Plugin-author checking. Core does not interpret, register, validate, or schema-check contract ids.
42
- */
43
- function createWidgetValueContract(id) {
44
- return Object.freeze({ id });
45
- }
46
- const WIDGET_CONFIG_JSON_SCHEMA_DIALECT = "https://json-schema.org/draft/2020-12/schema";
47
- /**
48
- * Provenance probe: true only for plugins completed by this loaded module instance. A plugin from
49
- * another module instance (its brand is a different Symbol) or a structural look-alike is foreign.
50
- * Capability separation, not a security sandbox.
51
- */
52
- function isCoreWidgetPlugin(value) {
53
- if (typeof value !== "object" || value === null) return false;
54
- const brand = value[widgetPluginBrand];
55
- return typeof brand === "object" && brand !== null && typeof brand.definition === "object" && brand.definition !== null;
56
- }
57
- /**
58
- * Reads the erased definition record of a plugin.
59
- */
60
- function readWidgetPluginDefinition(plugin) {
61
- return plugin[widgetPluginBrand].definition;
62
- }
63
- /**
64
- * Builds the section keyed-chain object.
65
- *
66
- * Declared member keys exist only at the type level, so every string member access resolves to a
67
- * consuming function; the returned chain object is the same object by identity.
68
- */
69
- function createSection(sink) {
70
- const section = new Proxy({}, { get(_target, key) {
71
- if (typeof key !== "string") return void 0;
72
- return (definition) => {
73
- sink.set(key, definition);
74
- return section;
75
- };
76
- } });
77
- return section;
78
- }
79
- /**
80
- * Starts the plugin builder for one plugin `type`.
81
- *
82
- * Phase order is `description -> interfaces -> config? -> slots? -> state? -> properties? -> methods? -> events? -> done()`;
83
- * a phase exists only when its capability is declared. Calling a declared phase out of order (or
84
- * repeating it) fails type-checking with an order-specific diagnostic; the runtime builder itself is
85
- * order-agnostic.
86
- */
87
- function createWidgetPlugin(type) {
88
- const draft = {
89
- description: "",
90
- config: null,
91
- slots: null,
92
- validateStructure: null,
93
- state: null,
94
- properties: null,
95
- methods: null,
96
- events: null
97
- };
98
- const builder = {
99
- description(description) {
100
- draft.description = description;
101
- return builder;
102
- },
103
- interfaces: () => builder,
104
- config(definition) {
105
- draft.config = Object.freeze({
106
- ...definition,
107
- schema: definition.schema ?? null
108
- });
109
- return builder;
110
- },
111
- slots(definitions, validateStructure) {
112
- draft.slots = new Map(Object.entries(definitions));
113
- draft.validateStructure = validateStructure ?? null;
114
- return builder;
115
- },
116
- state(build) {
117
- const members = /* @__PURE__ */ new Map();
118
- draft.state = members;
119
- build(createSection(members));
120
- return builder;
121
- },
122
- properties(build) {
123
- const members = /* @__PURE__ */ new Map();
124
- draft.properties = members;
125
- build(createSection(members));
126
- return builder;
127
- },
128
- methods(build) {
129
- const members = /* @__PURE__ */ new Map();
130
- draft.methods = members;
131
- build(createSection(members));
132
- return builder;
133
- },
134
- events(build) {
135
- const members = /* @__PURE__ */ new Map();
136
- draft.events = members;
137
- build(createSection(members));
138
- return builder;
139
- },
140
- done() {
141
- const definition = Object.freeze({
142
- type,
143
- description: draft.description,
144
- config: draft.config,
145
- slots: draft.slots,
146
- validateStructure: draft.validateStructure,
147
- state: draft.state,
148
- properties: draft.properties,
149
- methods: draft.methods,
150
- events: draft.events
151
- });
152
- const capabilities = Object.freeze({
153
- config: definition.config !== null,
154
- slots: definition.slots !== null,
155
- state: definition.state !== null,
156
- properties: definition.properties !== null,
157
- methods: definition.methods !== null,
158
- events: definition.events !== null
159
- });
160
- const config = definition.config === null ? null : Object.freeze({
161
- description: definition.config.description,
162
- schema: definition.config.schema
163
- });
164
- const descriptions = Object.freeze({
165
- config: config?.description ?? null,
166
- slots: definition.slots === null ? null : createReadonlyMap([...definition.slots].map(([key, slot]) => [key, slot.description]))
167
- });
168
- return Object.freeze({
169
- type,
170
- description: draft.description,
171
- capabilities,
172
- config,
173
- descriptions,
174
- [widgetPluginBrand]: Object.freeze({ definition })
175
- });
176
- }
177
- };
178
- return builder;
179
- }
180
- //#endregion
181
- //#region src/runtime/internals.ts
182
- const runtimeInternals = Symbol("@deviltea/widget-core:runtime-internals");
183
- /**
184
- * Provenance probe: true only for Runtimes produced by this loaded module instance.
185
- */
186
- function isCoreRuntime(value) {
187
- if (typeof value !== "object" || value === null) return false;
188
- return value[runtimeInternals] !== void 0;
189
- }
190
- /**
191
- * Reads the internals carried by a Runtime produced by `createWidgetSystemRuntime`.
192
- */
193
- function readRuntimeInternals(runtime) {
194
- const internals = runtime[runtimeInternals];
195
- if (internals === void 0) throw new Error("The runtime was not produced by this widget core build.");
196
- return internals;
197
- }
198
- //#endregion
199
- export { createWidgetPlugin as a, readWidgetPluginDefinition as c, WIDGET_CONFIG_JSON_SCHEMA_DIALECT as i, createReadonlyMap as l, readRuntimeInternals as n, createWidgetValueContract as o, runtimeInternals as r, isCoreWidgetPlugin as s, isCoreRuntime as t };