snapse 0.0.0-stage → 0.9.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.
Files changed (86) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1169 -2
  3. package/dist/DOM/domFunctions.d.ts +12 -0
  4. package/dist/DOM/elements/DOMElements.d.ts +141 -0
  5. package/dist/DOM/elements/SVGElements.d.ts +65 -0
  6. package/dist/DOM/elements/elementAttributeTypes.d.ts +100 -0
  7. package/dist/DOM/nodeControllers/ComponentController.d.ts +10 -0
  8. package/dist/DOM/nodeControllers/ElementController.d.ts +14 -0
  9. package/dist/DOM/nodeControllers/NodeController.d.ts +81 -0
  10. package/dist/DOM/nodeControllers/RootController.d.ts +12 -0
  11. package/dist/DOM/nodeControllers/SVGElementController.d.ts +4 -0
  12. package/dist/DOM/nodeControllers/StateController.d.ts +43 -0
  13. package/dist/DOM/server/serialize.d.ts +2 -0
  14. package/dist/DOM/server/serverNodes.d.ts +41 -0
  15. package/dist/DOM/types.d.ts +84 -0
  16. package/dist/DOM/util/RenderError.d.ts +10 -0
  17. package/dist/DOM/util/childShape.d.ts +7 -0
  18. package/dist/DOM/util/deferredNodes.d.ts +7 -0
  19. package/dist/DOM/util/domNode.d.ts +2 -0
  20. package/dist/DOM/util/moveBeforeSupport.d.ts +1 -0
  21. package/dist/DOM/util/nodeCount.d.ts +2 -0
  22. package/dist/DOM/util/util.d.ts +2 -0
  23. package/dist/DOM.d.ts +4 -0
  24. package/dist/SVG.d.ts +3 -0
  25. package/dist/common/computeMutation.d.ts +16 -0
  26. package/dist/common/dev.d.ts +1 -0
  27. package/dist/common/shorthands.d.ts +1 -0
  28. package/dist/common/undoUtils.d.ts +1 -0
  29. package/dist/common/util.d.ts +4 -0
  30. package/dist/index.d.ts +7 -0
  31. package/dist/lint/index.d.ts +7 -0
  32. package/dist/lint/index.js +8 -0
  33. package/dist/lint/noBooleanStateArgument.d.ts +2 -0
  34. package/dist/lint/noBooleanStateArgument.js +43 -0
  35. package/dist/lint/noStateTruthiness.d.ts +2 -0
  36. package/dist/lint/noStateTruthiness.js +92 -0
  37. package/dist/lint/stateTypes.d.ts +4 -0
  38. package/dist/lint/stateTypes.js +14 -0
  39. package/dist/server.d.ts +2 -0
  40. package/dist/snapse.DOM.cjs +1 -0
  41. package/dist/snapse.DOM.development.cjs +115 -0
  42. package/dist/snapse.DOM.development.js +1 -0
  43. package/dist/snapse.SVG.cjs +1 -0
  44. package/dist/snapse.SVG.development.cjs +66 -0
  45. package/dist/snapse.SVG.development.js +1 -0
  46. package/dist/snapse.SVG.js +1 -0
  47. package/dist/snapse.cjs +1 -0
  48. package/dist/snapse.development.cjs +13 -0
  49. package/dist/snapse.development.js +1 -0
  50. package/dist/snapse.js +75 -0
  51. package/dist/snapse.server.cjs +1 -0
  52. package/dist/snapse.server.development.cjs +3 -0
  53. package/dist/snapse.server.development.js +1 -0
  54. package/dist/snapseCore-Bc8ZDYHa.cjs +1 -0
  55. package/dist/snapseCore-DpadpXgD.js +3002 -0
  56. package/dist/snapseCore-Xfnvf03Z.cjs +4135 -0
  57. package/dist/state/common/refCountAndType.d.ts +8 -0
  58. package/dist/state/common/stateProperty.d.ts +1 -0
  59. package/dist/state/compute.d.ts +2 -0
  60. package/dist/state/state.d.ts +39 -0
  61. package/dist/state/stateInternals/LightState.d.ts +20 -0
  62. package/dist/state/stateInternals/internalFunctions.d.ts +13 -0
  63. package/dist/state/stateInternals/notify.d.ts +7 -0
  64. package/dist/state/stateInternals/poison.d.ts +4 -0
  65. package/dist/state/stateInternals/stateUpdate.d.ts +9 -0
  66. package/dist/state/subscribeChanges.d.ts +2 -0
  67. package/dist/state/transforms/CallbackTransform.d.ts +13 -0
  68. package/dist/state/transforms/ChainFunctionTransform.d.ts +8 -0
  69. package/dist/state/transforms/ChangeAggregateTransform.d.ts +20 -0
  70. package/dist/state/transforms/ChangeCallbackTransform.d.ts +5 -0
  71. package/dist/state/transforms/ComputeTransform.d.ts +4 -0
  72. package/dist/state/transforms/DOMRootTransform.d.ts +8 -0
  73. package/dist/state/transforms/FunctionTransform.d.ts +5 -0
  74. package/dist/state/transforms/IsTransform.d.ts +25 -0
  75. package/dist/state/transforms/LightStateFunctionTransform.d.ts +3 -0
  76. package/dist/state/transforms/MapArrayTransform.d.ts +10 -0
  77. package/dist/state/transforms/MapValueTransform.d.ts +3 -0
  78. package/dist/state/transforms/OptTransform.d.ts +10 -0
  79. package/dist/state/transforms/PromiseTransform.d.ts +6 -0
  80. package/dist/state/transforms/SubscribeTransform.d.ts +13 -0
  81. package/dist/state/transforms/Transform.d.ts +35 -0
  82. package/dist/state/transforms/transforms.d.ts +30 -0
  83. package/dist/state/types/stateTypes.d.ts +175 -0
  84. package/dist/state/types/types.d.ts +35 -0
  85. package/dist/undo/undo.d.ts +39 -0
  86. package/package.json +141 -4
@@ -0,0 +1,3002 @@
1
+ //#region src/state/transforms/transforms.ts
2
+ var transforms = {};
3
+ //#endregion
4
+ //#region src/state/common/refCountAndType.ts
5
+ var STATE_TYPE_BITS = 3;
6
+ var STATE_TYPE_MASK = 2 ** STATE_TYPE_BITS - 1;
7
+ var PROMOTED_ELEMENT_FLAG = 2 ** STATE_TYPE_BITS;
8
+ var REFCOUNT_SHIFT = 4;
9
+ var NON_REFCOUNT_MASK = 15;
10
+ var getStateType = (s) => s.rct & STATE_TYPE_MASK;
11
+ var setStateType = (s, stateType) => s.rct = s.rct & -8 | stateType;
12
+ var getRefCount = (s) => s.rct >>> REFCOUNT_SHIFT;
13
+ var setRefCount = (s, refCount) => s.rct = s.rct & NON_REFCOUNT_MASK | refCount << REFCOUNT_SHIFT;
14
+ var isPromotedElement = (s) => !!(s.rct & PROMOTED_ELEMENT_FLAG);
15
+ var markPromotedElement = (s) => s.rct |= PROMOTED_ELEMENT_FLAG;
16
+ //#endregion
17
+ //#region src/common/shorthands.ts
18
+ var isArray = Array.isArray;
19
+ //#endregion
20
+ //#region src/state/stateInternals/notify.ts
21
+ var flushTimeout;
22
+ var flushPendingWork;
23
+ var registerFlushPendingWork = (fn) => {
24
+ flushPendingWork = fn;
25
+ };
26
+ var queueFlush = () => flushTimeout ??= setTimeout(flush, 0);
27
+ var fastFlush = (f, e) => {
28
+ flushTimeout = true;
29
+ try {
30
+ f(e);
31
+ transforms.Transform.flush();
32
+ } finally {
33
+ flushTimeout = void 0;
34
+ }
35
+ transforms.CallbackTransform.flush();
36
+ flushPendingWork();
37
+ };
38
+ var flush = (s) => {
39
+ clearTimeout(flushTimeout);
40
+ flushTimeout = void 0;
41
+ const ls = getLightState(s);
42
+ if (ls) refresh(ls);
43
+ else {
44
+ transforms.Transform.flush();
45
+ transforms.CallbackTransform.flush();
46
+ flushPendingWork();
47
+ }
48
+ };
49
+ var notify = (target) => {
50
+ const store = target.subs;
51
+ if (!store) return;
52
+ if (store instanceof Transform) store.queue(target);
53
+ else if (isArray(store)) for (let i = 0; i < store.length; i++) store[i].queue(target);
54
+ else for (const s of store) s.queue(target);
55
+ };
56
+ //#endregion
57
+ //#region src/state/stateInternals/internalFunctions.ts
58
+ var setFn = (target) => (value) => {
59
+ assertWritable(target);
60
+ return updateValue(target, value);
61
+ };
62
+ var commonInternalFunctions_symbol = /* @__PURE__ */ new Map([[Symbol.toPrimitive, (target) => {
63
+ connectTouchedState(target);
64
+ return target.v[Symbol.toPrimitive];
65
+ }], [Symbol.iterator, (target) => target.v[Symbol.iterator]]]);
66
+ var orFunction = (source, value) => {
67
+ const v = source.v;
68
+ return !v || v instanceof Array && v.length === 0 ? value : delightstate(source);
69
+ };
70
+ var notFunction = (source) => !source.v;
71
+ var valueMethod = (name) => (target) => {
72
+ connectTouchedState(target);
73
+ return target.v?.[name]?.bind(target.v);
74
+ };
75
+ var commonInternalFunctions_string = /* @__PURE__ */ new Map([
76
+ ["toString", valueMethod("toString")],
77
+ ["valueOf", valueMethod("valueOf")],
78
+ ["set", setFn],
79
+ ["then", (target) => (onFulfilled) => {
80
+ const resolve = (v) => {
81
+ s.uns(target);
82
+ onFulfilled(v);
83
+ };
84
+ const s = new transforms.CallbackTransform(target, resolve);
85
+ const verBeforeSub = target.ver;
86
+ s.subTo(target);
87
+ if (target.ver !== verBeforeSub) resolve(target.v);
88
+ }],
89
+ ["is", (target) => (cmp) => {
90
+ return transforms.IsTransform.for(target).new(cmp);
91
+ }],
92
+ ["opt", (target) => (options, def) => new transforms.OptTransform(target, options, def).execute()],
93
+ ["or", (target) => (value) => new transforms.FunctionTransform(target, orFunction, [target, value]).execute()],
94
+ ["not", (target) => () => new transforms.FunctionTransform(target, notFunction, [target]).execute()],
95
+ ["toJSON", (target) => {
96
+ const is = target.v;
97
+ return is?.toJSON instanceof Function ? is.toJSON.bind(is) : () => is;
98
+ }]
99
+ ]);
100
+ var commonInternalFunctions = new Map([...commonInternalFunctions_symbol, ...commonInternalFunctions_string]);
101
+ var pojoInternalFunctions = new Map([
102
+ ...commonInternalFunctions_symbol,
103
+ ["toJSON", commonInternalFunctions_string.get("toJSON")],
104
+ ["toString", commonInternalFunctions_string.get("toString")],
105
+ ["valueOf", commonInternalFunctions_string.get("valueOf")]
106
+ ]);
107
+ var updateArray = (target, fn) => {
108
+ return (...args) => {
109
+ assertWritable(target);
110
+ target.ver = createVersion();
111
+ const r = target.v[fn](...args);
112
+ notify(target);
113
+ return r;
114
+ };
115
+ };
116
+ var arrayOnlyInternalFunctions = new Map([
117
+ "copyWithin",
118
+ "fill",
119
+ "pop",
120
+ "push",
121
+ "reverse",
122
+ "shift",
123
+ "sort",
124
+ "splice",
125
+ "unshift"
126
+ ].map((fn) => [fn, (t) => updateArray(t, fn)]));
127
+ arrayOnlyInternalFunctions.set("map", (target) => (f) => new transforms.MapArrayTransform(target, f).execute());
128
+ arrayOnlyInternalFunctions.set("length", (target) => {
129
+ connectTouchedState(target);
130
+ return target.v?.length;
131
+ });
132
+ var booleanPredicateArrayFunction = (fn) => (target) => (...args) => {
133
+ const predicate = args[0];
134
+ args[0] = (...predicateArgs) => peek(predicate(...predicateArgs));
135
+ return new transforms.ChainFunctionTransform(target, args, fn).execute();
136
+ };
137
+ for (const fn of [
138
+ "filter",
139
+ "some",
140
+ "every",
141
+ "find",
142
+ "findIndex",
143
+ "findLast",
144
+ "findLastIndex"
145
+ ]) arrayOnlyInternalFunctions.set(fn, booleanPredicateArrayFunction(fn));
146
+ var arraySearchFunction = (fn) => {
147
+ const hook = (t, ...hookArgs) => {
148
+ return Array.from(t.prx, peek)[fn](...peek(hookArgs).map(peek));
149
+ };
150
+ return (target) => (...args) => new transforms.FunctionTransform(target, hook, [target, ...args]).execute();
151
+ };
152
+ for (const fn of [
153
+ "includes",
154
+ "indexOf",
155
+ "lastIndexOf"
156
+ ]) arrayOnlyInternalFunctions.set(fn, arraySearchFunction(fn));
157
+ var primitiveOnlyInternalFunctions = /* @__PURE__ */ new Map([]);
158
+ primitiveOnlyInternalFunctions.set(Symbol.toPrimitive, (target) => () => {
159
+ connectTouchedState(target);
160
+ return target.v;
161
+ });
162
+ var arrayInternalFunctions = new Map([...commonInternalFunctions, ...arrayOnlyInternalFunctions]);
163
+ var internalFunctions = [
164
+ new Map([...commonInternalFunctions, ...primitiveOnlyInternalFunctions]),
165
+ arrayInternalFunctions,
166
+ pojoInternalFunctions,
167
+ new Map([
168
+ ...commonInternalFunctions_symbol,
169
+ ["set", setFn],
170
+ ["opt", commonInternalFunctions_string.get("opt")],
171
+ ["or", commonInternalFunctions_string.get("or")]
172
+ ]),
173
+ commonInternalFunctions_symbol,
174
+ new Map([
175
+ ...commonInternalFunctions_symbol,
176
+ ["set", setFn],
177
+ ["opt", commonInternalFunctions_string.get("opt")],
178
+ ["or", (target) => {
179
+ return typeof target.v?.or === "function" ? (...args) => new transforms.ChainFunctionTransform(target, args, "or").execute() : (value) => new transforms.FunctionTransform(target, orFunction, [target, value]).execute();
180
+ }]
181
+ ])
182
+ ];
183
+ //#endregion
184
+ //#region src/DOM/util/util.ts
185
+ var isNode = (v) => destate(v) != null;
186
+ //#endregion
187
+ //#region src/DOM/util/domNode.ts
188
+ var isDOMNode = (v) => typeof v?.nodeType === "number";
189
+ var isElementNode = (v) => v?.nodeType === 1;
190
+ //#endregion
191
+ //#region src/DOM/util/RenderError.ts
192
+ var RenderError = class extends Error {
193
+ resetFn;
194
+ cause;
195
+ fallbackRendered = false;
196
+ halted = false;
197
+ constructor(cause, resetFn) {
198
+ super("Component render failed");
199
+ this.resetFn = resetFn;
200
+ this.cause = cause;
201
+ }
202
+ reset() {
203
+ this.resetFn();
204
+ }
205
+ stopPropagation() {
206
+ this.halted = true;
207
+ }
208
+ get propagationStopped() {
209
+ return this.halted;
210
+ }
211
+ };
212
+ var HYDRATE_MARKER_TEXT = "𝒮";
213
+ var nonemptyShape = (shapes, index) => {
214
+ while (index < shapes.length && shapes[index] === 3) index++;
215
+ return shapes[index];
216
+ };
217
+ var computeUnsafeJunctions = (shapes) => {
218
+ const unsafe = [];
219
+ let left = shapes[0] === 3 ? void 0 : shapes[0];
220
+ for (let i = 1; i < shapes.length; i++) {
221
+ const current = shapes[i];
222
+ const right = nonemptyShape(shapes, i);
223
+ unsafe[i] = !(left === void 0 || right === void 0 || left === 0 || right === 0 || left === 1 && right === 1);
224
+ left = current === 3 ? left : current;
225
+ }
226
+ return unsafe;
227
+ };
228
+ //#endregion
229
+ //#region src/DOM/util/nodeCount.ts
230
+ var getNodeCount = (node) => node instanceof NodeController ? node.nc : 1;
231
+ //#endregion
232
+ //#region src/DOM/util/deferredNodes.ts
233
+ var deferred = /* @__PURE__ */ new Set();
234
+ var draining = /* @__PURE__ */ new Set();
235
+ var deferNode = (n) => void deferred.add(n);
236
+ var adoptDeferredNode = (n) => {
237
+ deferred.delete(n);
238
+ draining.delete(n);
239
+ };
240
+ var hasDeferredNodes = () => deferred.size > 0 || draining.size > 0;
241
+ var isDeferred = (n) => deferred.has(n) || draining.has(n);
242
+ var swapDeferredNodes = () => {
243
+ const t = deferred;
244
+ deferred = draining;
245
+ draining = t;
246
+ };
247
+ var clearDrainedDeferredNodes = () => draining.clear();
248
+ var liveChildNodeAt = (parent, atIndex, startNode, startNodeIndex = 0) => {
249
+ if (!hasDeferredNodes()) return parent.childNodes[atIndex] ?? null;
250
+ let n = startNode === void 0 ? parent.firstChild : startNode;
251
+ let liveNodeIndex = startNode === void 0 ? 0 : startNodeIndex;
252
+ while (n) {
253
+ if (!isDeferred(n)) {
254
+ if (liveNodeIndex === atIndex) return n;
255
+ liveNodeIndex++;
256
+ }
257
+ n = n.nextSibling;
258
+ }
259
+ return null;
260
+ };
261
+ var liveChildNodeCount = (parent) => {
262
+ if (!hasDeferredNodes()) return parent.childNodes.length;
263
+ let count = 0;
264
+ for (let n = parent.firstChild; n; n = n.nextSibling) if (!isDeferred(n)) count++;
265
+ return count;
266
+ };
267
+ var holdsPOJO = (ls) => {
268
+ refresh(ls);
269
+ return isPOJO(ls.v);
270
+ };
271
+ var isNodeController = (c) => c instanceof NodeController;
272
+ var isBlankText = (n) => n?.nodeType === Node.TEXT_NODE && !n.data.trim();
273
+ var resolveCallableFallback = (fallback) => {
274
+ if (fallback instanceof Function) return fallback;
275
+ const ls = getLightState(fallback);
276
+ if (ls) {
277
+ refresh(ls);
278
+ if (typeof ls.v === "function") return ls.v;
279
+ }
280
+ };
281
+ var notifyAncestors = (start, renderError) => {
282
+ for (let c = start; c && !renderError.propagationStopped; c = c.par) if (c.catchParams) c.triggerCatch(renderError);
283
+ };
284
+ var NodeController = class NodeController {
285
+ ctx;
286
+ el;
287
+ par;
288
+ nc = 0;
289
+ cid;
290
+ args;
291
+ c;
292
+ subs;
293
+ def;
294
+ catchParams;
295
+ static StateController;
296
+ static setStateController(stateController) {
297
+ NodeController.StateController = stateController;
298
+ }
299
+ static ComponentController;
300
+ static setComponentController(componentController) {
301
+ NodeController.ComponentController = componentController;
302
+ }
303
+ static mightBeReplayedFromArgs(node) {
304
+ const p = node.par;
305
+ if (p instanceof NodeController.StateController) return NodeController.mightBeReplayedFromArgs(p);
306
+ return !!(p.flg & 20) && p.args !== void 0;
307
+ }
308
+ static stateMightReuseArgs(sc, child) {
309
+ if (isPromotedElement(sc.def)) return NodeController.stateMightReuseArgs(sc.par, child);
310
+ const tfm = sc.tfm;
311
+ return !((tfm?.flg ?? 0) & 2) || child.cid !== tfm.runId || NodeController.mightBeReplayedFromArgs(sc);
312
+ }
313
+ static invokeDetached(fallback, namedStates, level, ctx) {
314
+ /* v8 ignore next */
315
+ const noop = () => null;
316
+ const dummyParent = new NodeController.ComponentController(noop);
317
+ const isRender = ctx?.md === 2;
318
+ dummyParent.ctx = isRender ? ctx : {};
319
+ const detachedDOMContext = {
320
+ p: (isRender ? ctx.doc : document).createElement("div"),
321
+ n: null,
322
+ i: 0,
323
+ s: 0
324
+ };
325
+ fallback.build(dummyParent, detachedDOMContext, dummyParent, namedStates, void 0, level);
326
+ fallback.remove();
327
+ dummyParent.remove();
328
+ }
329
+ constructor(definition, args) {
330
+ this.def = definition;
331
+ if (args) this.args = args;
332
+ this.cid = currentRunId();
333
+ }
334
+ parseArgsRecursive(args, children, previousStateControllers) {
335
+ let properties;
336
+ for (let i = 0; i < args.length; i++) {
337
+ const arg = args[i];
338
+ if (typeof arg === "string" || typeof arg === "number") {
339
+ children.push(this.createTextChild(arg));
340
+ continue;
341
+ }
342
+ if (typeof arg === "object" && arg instanceof NodeController) {
343
+ children.push(arg);
344
+ continue;
345
+ }
346
+ const ls = getLightState(arg);
347
+ if (i === 0 && (ls ? holdsPOJO(ls) : isPOJO(arg))) properties = arg;
348
+ else if (ls) children.push(previousStateControllers?.lookup(ls) ?? new NodeController.StateController(ls));
349
+ else if (isDOMNode(arg)) children.push(arg);
350
+ else if (isArray(arg)) this.parseArgsRecursive(arg, children, previousStateControllers);
351
+ else if (arg instanceof Promise) children.push(new NodeController.StateController(new transforms.PromiseTransform(arg).execute()));
352
+ else if (arg instanceof Function) children.push(new NodeController.ComponentController(arg));
353
+ else if (isNode(arg)) children.push(this.createTextChild(arg));
354
+ }
355
+ return properties;
356
+ }
357
+ createTextChild(value) {
358
+ return this.ctx?.md === 1 ? 42 : this.ctx?.md === 2 ? this.ctx.doc.createTextNode(String(value)) : document.createTextNode(String(value));
359
+ }
360
+ parseArgs(args, previousStateControllers) {
361
+ this.c = [];
362
+ return args ? this.parseArgsRecursive(args, this.c, previousStateControllers) : void 0;
363
+ }
364
+ catch(v) {
365
+ this.catchParams = {
366
+ fbValue: v,
367
+ lvl: 1
368
+ };
369
+ return this;
370
+ }
371
+ build(parentController, DOMContext, stateContext, namedStates, hydrationContext, level = 1) {
372
+ const originalArgs = this.args;
373
+ const catchParams = this.catchParams;
374
+ if (catchParams) {
375
+ catchParams.lvl = level;
376
+ const fallback = catchParams.fbValue;
377
+ if (fallback instanceof NodeController.ComponentController || isState(fallback)) {
378
+ catchParams.stateContext = stateContext;
379
+ catchParams.namedStates = namedStates;
380
+ }
381
+ }
382
+ try {
383
+ this.par = parentController;
384
+ if (parentController) this.ctx = this.inheritContext(parentController.ctx);
385
+ const properties = this.parseArgs(this.args);
386
+ if (!(parentController instanceof NodeController.StateController ? NodeController.stateMightReuseArgs(parentController, this) : !!((parentController?.flg ?? 0) & 20) && parentController.args !== void 0)) this.args = void 0;
387
+ namedStates = this.buildNode(properties, namedStates, stateContext, hydrationContext, level) ?? namedStates;
388
+ this.createChildren(parentController, DOMContext, stateContext, namedStates, hydrationContext, level);
389
+ } catch (e) {
390
+ if (!catchParams) throw e;
391
+ const renderError = this.renderFallback(e, originalArgs, parentController, DOMContext, stateContext, namedStates, hydrationContext, level);
392
+ if (!renderError.propagationStopped) notifyAncestors(this.par, renderError);
393
+ }
394
+ }
395
+ triggerCatch(cause) {
396
+ const { stateContext, namedStates, lvl: level } = this.catchParams;
397
+ return this.renderFallback(cause, this.args, this.par, void 0, stateContext, namedStates, void 0, level);
398
+ }
399
+ renderFallback(cause, originalArgs, parentController, DOMContext, stateContext, namedStates, hydrationContext, level) {
400
+ const renderError = cause instanceof RenderError ? cause : new RenderError(cause, () => {
401
+ this.remove();
402
+ this.args = originalArgs;
403
+ const newDOMContext = this.getMountElement() ? void 0 : this.par.findNode(this);
404
+ const prevCount = this.nc;
405
+ this.build(parentController, newDOMContext, stateContext, namedStates, hydrationContext, level);
406
+ const newCount = this.nc;
407
+ this.nc = prevCount;
408
+ this.updateNodeCount(newCount);
409
+ });
410
+ const fallback = this.catchParams.fbValue;
411
+ const callable = resolveCallableFallback(fallback);
412
+ if (renderError.fallbackRendered) {
413
+ if (callable) callable(renderError);
414
+ else if (fallback instanceof NodeController.ComponentController) {
415
+ fallback.renderError = renderError;
416
+ NodeController.invokeDetached(fallback, this.catchParams.namedStates, level, this.ctx);
417
+ }
418
+ return renderError;
419
+ }
420
+ this.remove();
421
+ if (DOMContext === void 0 && !this.getMountElement()) DOMContext = this.par.findNode(this);
422
+ if (callable) this.parseArgs([callable(renderError)]);
423
+ else {
424
+ if (fallback instanceof NodeController.ComponentController) fallback.renderError = renderError;
425
+ this.parseArgs([fallback]);
426
+ }
427
+ this.createChildren(parentController, DOMContext, stateContext, namedStates, hydrationContext, level);
428
+ renderError.fallbackRendered = !!this.c?.length;
429
+ return renderError;
430
+ }
431
+ createChildren(parentController, DOMContext, stateContext, namedStates, hydrationContext, level = 1) {
432
+ const mountElement = this.getMountElement();
433
+ if (mountElement) {
434
+ DOMContext = {
435
+ p: mountElement,
436
+ n: null,
437
+ i: 0,
438
+ s: 0
439
+ };
440
+ if (this.ctx?.md === 1) hydrationContext = { nxt: mountElement.firstChild };
441
+ }
442
+ const childStateContext = this.flg & 1 ? stateContext ?? this : this;
443
+ this.nc = this.addChildren(DOMContext, hydrationContext, childStateContext, namedStates, level);
444
+ if (this.ctx?.md === 1 && mountElement) this.removeExcessNodes(hydrationContext);
445
+ if (!parentController && this.ctx?.md === 1) this.ctx.md = 0;
446
+ }
447
+ getMountElement() {
448
+ return this.el;
449
+ }
450
+ inheritContext(ctx) {
451
+ return ctx;
452
+ }
453
+ getNodes(p) {
454
+ if (isDOMNode(p)) return [p];
455
+ return p.el ? [p.el] : p.c.flatMap((c) => this.getNodes(c));
456
+ }
457
+ isSoleChild(child) {
458
+ return this.c?.length === 1 && this.c[0] === child;
459
+ }
460
+ isSpent() {
461
+ return this.par !== void 0 && this.args === void 0;
462
+ }
463
+ isMounted() {
464
+ return this.el !== void 0 || this.c !== void 0;
465
+ }
466
+ heldForm() {
467
+ if (this.flg & 8 || this.catchParams !== void 0) return this;
468
+ if (this.el) return this.c ? this : this.el;
469
+ const only = !this.subs && this.c?.length === 1 ? this.c[0] : void 0;
470
+ if (!only) return this;
471
+ return only instanceof NodeController ? only.heldForm() : only;
472
+ }
473
+ getFirstNode(node) {
474
+ if (isDOMNode(node)) return node;
475
+ if (node.el) return node.el;
476
+ for (const c of node.c) {
477
+ const nc = this.getFirstNode(c);
478
+ if (nc) return nc;
479
+ }
480
+ }
481
+ classifyChild(child) {
482
+ if (child === 42) return 1;
483
+ if (isDOMNode(child)) return isElementNode(child) ? 0 : 1;
484
+ if (child.flg & 2) {
485
+ const ls = child.def;
486
+ if (ls.v == null) return 3;
487
+ return ls.v instanceof NodeController && ls.v.flg & 4 ? 0 : 2;
488
+ }
489
+ return child.flg & 4 ? 0 : 2;
490
+ }
491
+ dropNode(hydrationContext) {
492
+ const skip = hydrationContext.nxt;
493
+ hydrationContext.nxt = skip.nextSibling;
494
+ skip.parentNode?.removeChild(skip);
495
+ }
496
+ removeExcessNodes(hydrationContext) {
497
+ while (hydrationContext.nxt?.nodeType === Node.COMMENT_NODE || isBlankText(hydrationContext.nxt)) this.dropNode(hydrationContext);
498
+ }
499
+ crossJunction(hydrationContext) {
500
+ while (isBlankText(hydrationContext.nxt)) this.dropNode(hydrationContext);
501
+ const marker = hydrationContext.nxt;
502
+ if (marker?.nodeType === Node.COMMENT_NODE && marker.textContent === "𝒮") this.dropNode(hydrationContext);
503
+ }
504
+ resolveChild(child, isStateController) {
505
+ if (child.flg & 8 || child.catchParams !== void 0) return child;
506
+ if (child.el) {
507
+ if (!child.subs) {
508
+ if (!child.c?.some(isNodeController)) {
509
+ child.c = void 0;
510
+ return child.el;
511
+ }
512
+ const only = child.c;
513
+ if (this.el && only.length === 1 && only[0] instanceof NodeController && only[0].el) {
514
+ only[0].par = this;
515
+ child.c = void 0;
516
+ return only[0];
517
+ }
518
+ }
519
+ return child;
520
+ }
521
+ if (isStateController) {
522
+ if (!child.subs && child.c?.length === 1) {
523
+ const only = child.c[0];
524
+ if (only instanceof NodeController) {
525
+ only.par = this;
526
+ return this.resolveChild(only, isStateController);
527
+ }
528
+ return only;
529
+ }
530
+ return child;
531
+ }
532
+ const spliced = child.c;
533
+ for (const c of spliced) if (c instanceof NodeController) c.par = this;
534
+ return spliced;
535
+ }
536
+ addChildren(DOMContext, hydrationContext, stateContext, namedStates, level = 1) {
537
+ const children = this.c;
538
+ if (!children.length) return this.getParallelNodeCount(0);
539
+ const isStateController = !!(this.flg & 2);
540
+ const unsafeJunctions = children.length > 1 && this.ctx?.md !== 0 ? computeUnsafeJunctions(children.map(this.classifyChild, this)) : void 0;
541
+ let nodeCount = 0;
542
+ let junctionIndex = 0;
543
+ for (let i = 0; i < children.length; i++) {
544
+ let child = children[i];
545
+ const controllerChild = child instanceof NodeController ? child : void 0;
546
+ if (unsafeJunctions?.[junctionIndex++]) {
547
+ if (this.ctx.md === 2) DOMContext.p.insertBefore(this.ctx.doc.createComment(HYDRATE_MARKER_TEXT), DOMContext.n);
548
+ else if (hydrationContext) this.crossJunction(hydrationContext);
549
+ }
550
+ if (controllerChild) {
551
+ const childStateContext = isStateController ? controllerChild : stateContext;
552
+ controllerChild.build(this, DOMContext, childStateContext, namedStates, hydrationContext, level + 1);
553
+ }
554
+ if (!controllerChild || controllerChild.el) {
555
+ if (this.ctx?.md === 1) {
556
+ if (child === 42) {
557
+ if (hydrationContext.nxt?.nodeType === Node.TEXT_NODE) {
558
+ child = hydrationContext.nxt;
559
+ hydrationContext.nxt = hydrationContext.nxt.nextSibling;
560
+ } else {
561
+ const emptyText = document.createTextNode("");
562
+ DOMContext.p.insertBefore(emptyText, hydrationContext.nxt ?? null);
563
+ child = emptyText;
564
+ }
565
+ }
566
+ } else DOMContext.p.insertBefore(controllerChild?.el ?? child, DOMContext.n);
567
+ }
568
+ if (controllerChild) {
569
+ const resolved = this.resolveChild(controllerChild, isStateController);
570
+ if (isArray(resolved)) {
571
+ children.splice(i, 1, ...resolved);
572
+ i += resolved.length - 1;
573
+ for (const r of resolved) nodeCount += getNodeCount(r);
574
+ } else {
575
+ nodeCount += getNodeCount(resolved);
576
+ children[i] = resolved;
577
+ }
578
+ } else {
579
+ nodeCount++;
580
+ children[i] = child;
581
+ }
582
+ }
583
+ return this.getParallelNodeCount(nodeCount);
584
+ }
585
+ getParallelNodeCount(childrenNodeCount) {
586
+ return this.el ? 1 : childrenNodeCount;
587
+ }
588
+ updateNodeCount(newCount) {
589
+ const diff = newCount - this.nc;
590
+ this.nc = newCount;
591
+ if (!diff) return;
592
+ for (let c = this.par; c && !c.getMountElement(); c = c.par) c.nc += diff;
593
+ }
594
+ enclosingMountElement() {
595
+ let c = this.par;
596
+ while (c && !c.getMountElement()) c = c.par;
597
+ return c?.getMountElement();
598
+ }
599
+ handleReactiveError(e) {
600
+ let current = e;
601
+ if (this.catchParams) {
602
+ current = this.triggerCatch(current);
603
+ if (current.propagationStopped) return;
604
+ }
605
+ for (let c = this.par; c; c = c.par) if (c.catchParams) {
606
+ current = c.triggerCatch(current);
607
+ if (current.propagationStopped) return;
608
+ }
609
+ if (!(current instanceof RenderError)) throw current;
610
+ }
611
+ addCleanup(fn) {
612
+ if (this.subs) this.subs.push(fn);
613
+ else this.subs = [fn];
614
+ }
615
+ addSub(transform, target = this) {
616
+ if (this.ctx?.md === 2) return;
617
+ transform.subTo(transform.srcLs);
618
+ if (target.subs) target.subs.push(transform);
619
+ else target.subs = [transform];
620
+ }
621
+ unsubscribeAll() {
622
+ if (!this.subs) return;
623
+ for (const sub of this.subs) typeof sub === "function" ? sub() : sub.uns(sub.srcLs);
624
+ this.subs = void 0;
625
+ }
626
+ remove(removeNode = true) {
627
+ this.unsubscribeAll();
628
+ this.removeChildren(removeNode && !this.el);
629
+ if (removeNode) {
630
+ if (this.el?.parentNode) this.el.remove();
631
+ this.el = void 0;
632
+ }
633
+ }
634
+ removeChildren(removeNodes = true) {
635
+ for (const child of this.c ?? []) if (child instanceof NodeController) child.remove(removeNodes);
636
+ else if (removeNodes && isDOMNode(child)) child.parentNode?.removeChild(child);
637
+ if (removeNodes) this.c = void 0;
638
+ }
639
+ findNode(referenceNode, nodeIndex = 0, startChildIndex = 0, startNode, startNodeIndex = 0) {
640
+ for (let childIndex = startChildIndex; childIndex < this.c.length; childIndex++) {
641
+ const child = this.c[childIndex];
642
+ if (child === referenceNode) {
643
+ const mountElement = this.getMountElement();
644
+ if (mountElement) {
645
+ nodeIndex += this.pnc;
646
+ return {
647
+ p: mountElement,
648
+ n: liveChildNodeAt(mountElement, nodeIndex, startNode, startNodeIndex),
649
+ i: nodeIndex,
650
+ s: childIndex
651
+ };
652
+ }
653
+ const result = this.par.findNode(this, nodeIndex, 0, startNode, startNodeIndex);
654
+ result.s = childIndex;
655
+ return result;
656
+ }
657
+ nodeIndex += getNodeCount(child);
658
+ }
659
+ /* v8 ignore next */
660
+ throw Error("Internal unexpected error.");
661
+ }
662
+ };
663
+ NodeController.prototype.flg = 0;
664
+ NodeController.prototype.pnc = 0;
665
+ //#endregion
666
+ //#region src/common/util.ts
667
+ var isPOJO = (v) => {
668
+ return typeof v === "object" && v !== null && Object.getPrototypeOf(v) === Object.prototype;
669
+ };
670
+ var classifyStateType = (v) => {
671
+ if (isArray(v)) return 1;
672
+ if (v) {
673
+ if (typeof v === "object") {
674
+ if (v instanceof NodeController) return 5;
675
+ return isPOJO(v) ? 2 : 4;
676
+ }
677
+ if (typeof v === "function") return 3;
678
+ }
679
+ return 0;
680
+ };
681
+ var camelToKebab = (s) => {
682
+ return s.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
683
+ };
684
+ //#endregion
685
+ //#region src/state/stateInternals/poison.ts
686
+ var poisonCauses = /* @__PURE__ */ new WeakMap();
687
+ var createPoisonedValue = (cause) => {
688
+ const marker = new Proxy(Object.create(null), {
689
+ getPrototypeOf: () => null,
690
+ get(_target, prop) {
691
+ if (prop === Symbol.toPrimitive) return () => {
692
+ throw cause;
693
+ };
694
+ throw cause;
695
+ },
696
+ has: () => {
697
+ throw cause;
698
+ }
699
+ });
700
+ poisonCauses.set(marker, cause);
701
+ return marker;
702
+ };
703
+ var isPoisoned = (v) => poisonCauses.has(v);
704
+ var throwIfPoisoned = (v) => {
705
+ const cause = poisonCauses.get(v);
706
+ if (cause) throw cause;
707
+ };
708
+ //#endregion
709
+ //#region src/state/stateInternals/stateUpdate.ts
710
+ var latestVersion = 0;
711
+ var createVersion = () => ++latestVersion;
712
+ var peekVersion = () => latestVersion;
713
+ var assertWritable = (ls) => {
714
+ if (!ls.tf) return;
715
+ throw TypeError("Chained state is read-only");
716
+ };
717
+ var promoteMemberToStateLightState = (owner, container, prop) => {
718
+ const ls = createStateLightState(container[prop]);
719
+ if (owner.tf) ls.tf ??= DERIVED_MEMBER;
720
+ container[prop] = ls.prx;
721
+ return ls;
722
+ };
723
+ var upsertProperty = (container, key, subValue, version, byOwner = false) => {
724
+ if (!(key in container)) {
725
+ container[key] = subValue;
726
+ return;
727
+ }
728
+ const old = container[key];
729
+ const lss = getLightState(old);
730
+ if (byOwner && (isState(subValue) || lss && lss.tf !== DERIVED_MEMBER)) {
731
+ if (getLightState(subValue) !== lss) container[key] = subValue;
732
+ return;
733
+ }
734
+ if (lss) {
735
+ if (!byOwner) assertWritable(lss);
736
+ return updateValue(lss, subValue, version, byOwner);
737
+ }
738
+ const dSubValue = destate(subValue);
739
+ if (isPOJO(old) && isPOJO(dSubValue)) upsertPojo(old, dSubValue, version, byOwner);
740
+ else container[key] = dSubValue;
741
+ };
742
+ var upsertPojo = (oldPojo, newValue, version, byOwner) => {
743
+ for (const [key, sv] of Object.entries(newValue)) upsertProperty(oldPojo, key, byOwner ? sv : destate(sv), version, byOwner);
744
+ };
745
+ var updateValue = (ls, v, version, byOwner = !!ls.tf) => {
746
+ version = version ?? ++latestVersion;
747
+ ls.tf?.dequeue();
748
+ const newValue = destate(v);
749
+ const oldValue = ls.v;
750
+ ls.ver = version;
751
+ ls.drt = version;
752
+ if (newValue === oldValue) return true;
753
+ if (isPOJO(oldValue) && isPOJO(newValue) && !isPoisoned(newValue)) upsertPojo(oldValue, newValue, version, byOwner);
754
+ else ls.v = newValue;
755
+ setStateType(ls, classifyStateType(newValue));
756
+ notify(ls);
757
+ return true;
758
+ };
759
+ var refresh = (ls) => ls.tf?.rfr();
760
+ //#endregion
761
+ //#region src/state/transforms/Transform.ts
762
+ var touchedStatesStack = [];
763
+ var touchedStatesCaptureActive;
764
+ var transformQueue = /* @__PURE__ */ new Set();
765
+ var rootQueue = [];
766
+ var queueRoot = (transform) => {
767
+ rootQueue.push(transform);
768
+ queueFlush();
769
+ };
770
+ var setPool = [];
771
+ var acquireSet = () => setPool.pop() ?? /* @__PURE__ */ new Set();
772
+ var releaseSet = (s) => {
773
+ s.clear();
774
+ setPool.push(s);
775
+ };
776
+ var capturePool = [];
777
+ var acquireCapture = (transform, sources) => {
778
+ const c = capturePool.pop();
779
+ if (!c) return {
780
+ tfm: transform,
781
+ touchedStates: sources
782
+ };
783
+ c.tfm = transform;
784
+ c.touchedStates = sources;
785
+ return c;
786
+ };
787
+ var releaseCapture = (c) => capturePool.push(c);
788
+ var PENDING_VERSION = -1;
789
+ var runSeq = 0;
790
+ var nextRunId = () => ++runSeq;
791
+ var currentRunId = () => touchedStatesCaptureActive?.tfm.runId ?? 0;
792
+ var Transform = class Transform {
793
+ tgt;
794
+ srcLs;
795
+ hookFunction;
796
+ hookArgs;
797
+ constructor(source, hook) {
798
+ this.srcLs = source;
799
+ this.hookFunction = hook;
800
+ }
801
+ static isDirty(target) {
802
+ const epoch = peekVersion();
803
+ if (target.drt === epoch) return false;
804
+ if (target.drt === -epoch) return true;
805
+ const store = target.srcs;
806
+ let dirty = false;
807
+ if (store) {
808
+ if (store instanceof LightState) dirty = Transform.sourceIsDirty(store, target);
809
+ else for (const s of store) if (Transform.sourceIsDirty(s, target)) {
810
+ dirty = true;
811
+ break;
812
+ }
813
+ }
814
+ target.drt = dirty ? -epoch : epoch;
815
+ return dirty;
816
+ }
817
+ static sourceIsDirty(s, target) {
818
+ return s !== target && (s.ver > target.ver || Transform.isDirty(s));
819
+ }
820
+ static throwDelayed(e) {
821
+ queueMicrotask(() => {
822
+ throw e;
823
+ });
824
+ }
825
+ static flush() {
826
+ do {
827
+ for (const transform of transformQueue) try {
828
+ transform.execute();
829
+ } catch (e) {
830
+ Transform.throwDelayed(e);
831
+ }
832
+ transformQueue.clear();
833
+ while (rootQueue.length) rootQueue.pop().execute();
834
+ } while (transformQueue.size);
835
+ }
836
+ queue(_target) {
837
+ transformQueue.add(this);
838
+ queueFlush();
839
+ }
840
+ dequeue() {
841
+ transformQueue.delete(this);
842
+ }
843
+ subTo(state) {
844
+ const store = state.subs;
845
+ const rc = getRefCount(state);
846
+ setRefCount(state, rc + 1);
847
+ if (rc === 0) state.tf?.subscribeSources(state);
848
+ if (store) {
849
+ if (store instanceof Transform) state.subs = [store, this];
850
+ else if (isArray(store)) {
851
+ if (store.length < 8) store.push(this);
852
+ else {
853
+ const set = new Set(store);
854
+ set.add(this);
855
+ state.subs = set;
856
+ }
857
+ } else store.add(this);
858
+ } else state.subs = this;
859
+ }
860
+ subscribeSources(state) {
861
+ const store = state.srcs;
862
+ if (store) {
863
+ if (store instanceof LightState) this.subTo(store);
864
+ else for (const source of store) this.subTo(source);
865
+ }
866
+ refresh(state);
867
+ }
868
+ uns(state) {
869
+ this.dequeue();
870
+ const subscriptions = state.subs;
871
+ if (subscriptions === this) state.subs = void 0;
872
+ else if (isArray(subscriptions)) subscriptions.splice(subscriptions.indexOf(this), 1);
873
+ else subscriptions.delete(this);
874
+ const rc = getRefCount(state) - 1;
875
+ setRefCount(state, rc);
876
+ if (rc === 0) state.tf?.unsubscribeSources(state);
877
+ }
878
+ unsubscribeSources(state) {
879
+ const store = state.srcs;
880
+ if (!store) return;
881
+ if (store instanceof LightState) this.uns(store);
882
+ else for (const source of store) this.uns(source);
883
+ }
884
+ rfr() {
885
+ if (this.tgt && this.tgt.ver !== PENDING_VERSION && Transform.isDirty(this.tgt)) this.execute();
886
+ }
887
+ execute() {
888
+ if (this.tgt || !this.runId) this.runId = nextRunId();
889
+ touchedStatesCaptureActive && touchedStatesStack.push(touchedStatesCaptureActive);
890
+ const sources = acquireSet();
891
+ if (this.srcLs) sources.add(this.srcLs);
892
+ const capture = acquireCapture(this, sources);
893
+ touchedStatesCaptureActive = capture;
894
+ if (this.tgt) this.tgt.ver = PENDING_VERSION;
895
+ let value;
896
+ const hf = destate(this.hookFunction);
897
+ try {
898
+ value = this.hookArgs ? hf(...this.hookArgs) : hf();
899
+ } catch (e) {
900
+ value = createPoisonedValue(e);
901
+ } finally {
902
+ touchedStatesCaptureActive = touchedStatesStack.pop();
903
+ releaseCapture(capture);
904
+ }
905
+ if (!sources.size && !this.tgt && !isPoisoned(value)) {
906
+ releaseSet(sources);
907
+ return value;
908
+ }
909
+ const ls = getLightState(value);
910
+ if (ls && !sources.has(ls)) {
911
+ if (ls.ver === PENDING_VERSION) value = createPoisonedValue(new CircularDependencyError());
912
+ else if (!this.tgt && this instanceof transforms.MapValueTransform && this.hasOnlyPassthroughSource(sources)) {
913
+ refresh(ls);
914
+ releaseSet(sources);
915
+ return value;
916
+ } else {
917
+ refresh(ls);
918
+ sources.add(ls);
919
+ }
920
+ }
921
+ const result = this.updateTarget(value, sources);
922
+ releaseSet(sources);
923
+ return result;
924
+ }
925
+ hasOnlyPassthroughSource(sources) {
926
+ return !!(sources.size === 1 && this.hookArgs && sources.has(getLightState(this.hookArgs[0])));
927
+ }
928
+ updateTarget(newValue, newSources) {
929
+ if (this.tgt) updateValue(this.tgt, newValue, peekVersion());
930
+ else {
931
+ this.tgt = new LightState(destate(newValue));
932
+ this.tgt.tf = this;
933
+ }
934
+ const store = this.tgt.srcs;
935
+ if (!(newSources.size === 1 && store instanceof LightState && newSources.has(store))) {
936
+ if (getRefCount(this.tgt)) {
937
+ for (const source of newSources) if (!(isArray(store) ? store.includes(source) : store instanceof Set ? store.has(source) : store === source)) this.subTo(source);
938
+ if (store instanceof LightState) {
939
+ if (!newSources.has(store)) this.uns(store);
940
+ } else for (const source of store) if (!newSources.has(source)) this.uns(source);
941
+ }
942
+ const target = this.tgt;
943
+ if (newSources.size === 0) target.srcs = void 0;
944
+ else if (newSources.size === 1) [target.srcs] = newSources;
945
+ else if (newSources.size <= 8) target.srcs = [...newSources];
946
+ else target.srcs = new Set(newSources);
947
+ }
948
+ return this.flg & 1 ? this.tgt : state(this.tgt);
949
+ }
950
+ static connect(target) {
951
+ if (touchedStatesCaptureActive) {
952
+ if (target.ver === PENDING_VERSION) throw new CircularDependencyError();
953
+ touchedStatesCaptureActive.touchedStates.add(target);
954
+ if (touchedStatesCaptureActive.tfm.tgt) {
955
+ const c = touchedStatesCaptureActive;
956
+ touchedStatesCaptureActive = void 0;
957
+ refresh(target);
958
+ touchedStatesCaptureActive = c;
959
+ }
960
+ }
961
+ }
962
+ };
963
+ var connectTouchedState = (target) => Transform.connect(target);
964
+ Transform.prototype.flg = 0;
965
+ Transform.prototype.runId = 0;
966
+ var DERIVED_MEMBER = new Transform();
967
+ transforms.Transform = Transform;
968
+ //#endregion
969
+ //#region src/state/state.ts
970
+ var CircularDependencyError = class extends Error {
971
+ constructor() {
972
+ super("circular dependency");
973
+ }
974
+ };
975
+ var stateRegistry = /* @__PURE__ */ new WeakMap();
976
+ var isState = (value) => {
977
+ return typeof value === "function" && stateRegistry.has(value);
978
+ };
979
+ var isLightState = (value) => {
980
+ return typeof value !== "function" && value instanceof LightState;
981
+ };
982
+ var isAnyState = (value) => {
983
+ return typeof value === "function" ? stateRegistry.has(value) : value instanceof LightState;
984
+ };
985
+ var subscribeWith = (state, createSubscription) => {
986
+ if (activeSubscriptions === null) throw Error("Cannot call subscribe after await in async function");
987
+ const [target, transform] = createSubscription(stateRegistry.get(state));
988
+ transform.subTo(target);
989
+ let subscribed = target;
990
+ const unsubscribe = () => {
991
+ subscribed && transform.uns(subscribed);
992
+ subscribed = void 0;
993
+ };
994
+ activeSubscriptions?.add(unsubscribe);
995
+ return unsubscribe;
996
+ };
997
+ var subscribe = (state, callback = () => 0, options) => subscribeWith(state, (ls) => [options?.["deep"] ? transforms.SubscribeTransform.for(ls) : ls, new transforms.CallbackTransform(ls, callback)]);
998
+ function findState(name, def) {
999
+ if (!activeExistingNamedStates || !(name in activeExistingNamedStates)) {
1000
+ if (arguments.length > 1) return def;
1001
+ throw Error("State not found");
1002
+ }
1003
+ return activeExistingNamedStates[name];
1004
+ }
1005
+ var lightState = (value) => new LightState(value);
1006
+ /* v8 ignore next */
1007
+ var staticTarget = () => {};
1008
+ var state = (value, name) => {
1009
+ if (name && !activeNewNamedStates) throw Error("Cannot define named state after await in async function");
1010
+ const newState = createStateLightState(value).prx;
1011
+ if (name) activeNewNamedStates.set(name, newState);
1012
+ return newState;
1013
+ };
1014
+ var createStateLightState = (value) => {
1015
+ const ls = isLightState(value) ? value : value instanceof Promise ? new transforms.PromiseTransform(value).execute() : new LightState(getLightState(value)?.v ?? value);
1016
+ if (ls.prx) return ls;
1017
+ const newState = new Proxy(staticTarget, ls);
1018
+ ls.prx = newState;
1019
+ stateRegistry.set(newState, ls);
1020
+ return ls;
1021
+ };
1022
+ var peek = (value) => {
1023
+ const ls = getLightState(value);
1024
+ if (!ls) return value;
1025
+ connectTouchedState(ls);
1026
+ return ls.v;
1027
+ };
1028
+ var getLightState = (value) => {
1029
+ return typeof value === "function" ? stateRegistry.get(value) : value instanceof LightState ? value : void 0;
1030
+ };
1031
+ var delightstate = (value) => value.v;
1032
+ var destate = (value) => {
1033
+ const ls = getLightState(value);
1034
+ return ls ? ls.v : value;
1035
+ };
1036
+ var subscriptionsCache = /* @__PURE__ */ new Set();
1037
+ var namedStatesCache = /* @__PURE__ */ new Map();
1038
+ var activeSubscriptions;
1039
+ var activeExistingNamedStates;
1040
+ var activeNewNamedStates;
1041
+ var isInComponent = () => activeSubscriptions != null;
1042
+ var startCapturingStateCalls = (namedStates) => {
1043
+ activeExistingNamedStates = namedStates;
1044
+ activeSubscriptions = subscriptionsCache;
1045
+ activeNewNamedStates = namedStatesCache;
1046
+ };
1047
+ var stopCapturingStateCalls = () => {
1048
+ let namedStates;
1049
+ if (activeExistingNamedStates) {
1050
+ namedStates = activeNewNamedStates.size ? Object.assign({}, activeExistingNamedStates, Object.fromEntries(activeNewNamedStates)) : activeExistingNamedStates;
1051
+ namedStatesCache.clear();
1052
+ } else if (activeNewNamedStates.size) namedStates = Object.fromEntries(activeNewNamedStates);
1053
+ namedStatesCache.clear();
1054
+ const subscriptions = activeSubscriptions.size ? [...activeSubscriptions.values()] : void 0;
1055
+ subscriptionsCache.clear();
1056
+ activeSubscriptions = null;
1057
+ activeExistingNamedStates = void 0;
1058
+ activeNewNamedStates = void 0;
1059
+ return {
1060
+ namedStates,
1061
+ subscriptions
1062
+ };
1063
+ };
1064
+ //#endregion
1065
+ //#region src/state/stateInternals/LightState.ts
1066
+ var LightState = class {
1067
+ v;
1068
+ rct;
1069
+ ver;
1070
+ subs;
1071
+ srcs;
1072
+ tf;
1073
+ prx;
1074
+ drt;
1075
+ constructor(value) {
1076
+ this.v = value;
1077
+ this.rct = classifyStateType(value);
1078
+ this.subs = void 0;
1079
+ this.srcs = void 0;
1080
+ this.tf = void 0;
1081
+ this.prx = void 0;
1082
+ this.ver = createVersion();
1083
+ this.drt = 0;
1084
+ }
1085
+ get(_target, prop, receiver) {
1086
+ const stateType = getStateType(this);
1087
+ const fn = internalFunctions[stateType].get(prop);
1088
+ if (fn) return fn(this, receiver);
1089
+ const s = this.v;
1090
+ if (s == null) return void 0;
1091
+ if (typeof prop === "symbol") return s[prop];
1092
+ const sp = s[prop];
1093
+ const spLs = getLightState(sp);
1094
+ if (stateType !== 2 && typeof (spLs ? spLs.v : sp) === "function") return (...args) => new transforms.ChainFunctionTransform(this, args, prop).execute();
1095
+ connectTouchedState(this);
1096
+ if (spLs?.prx || stateType !== 1 && stateType !== 2) return sp;
1097
+ if (!(prop in s)) return;
1098
+ return promoteMemberToStateLightState(this, s, prop).prx;
1099
+ }
1100
+ set(_target, prop, value) {
1101
+ assertWritable(this);
1102
+ const is = this.v;
1103
+ const ls = getLightState(is[prop]);
1104
+ if (ls) {
1105
+ assertWritable(ls);
1106
+ return updateValue(ls, value);
1107
+ }
1108
+ const version = createVersion();
1109
+ upsertProperty(is, prop, value, version);
1110
+ this.ver = version;
1111
+ notify(this);
1112
+ return true;
1113
+ }
1114
+ getPrototypeOf() {
1115
+ const is = this.v;
1116
+ return is == null ? null : Object.getPrototypeOf(is);
1117
+ }
1118
+ apply(_target, thisArg, argumentsList) {
1119
+ return new transforms.FunctionTransform(this, this.prx, argumentsList).execute();
1120
+ }
1121
+ getOwnPropertyDescriptor(_target, key) {
1122
+ const is = this.v;
1123
+ return is && typeof is === "object" || typeof is === "function" ? Reflect.getOwnPropertyDescriptor(is, key) : void 0;
1124
+ }
1125
+ deleteProperty(_target, prop) {
1126
+ assertWritable(this);
1127
+ if (getStateType(this) !== 2) throw TypeError("Cannot delete state properties");
1128
+ const is = this.v;
1129
+ if (!(prop in is)) return true;
1130
+ delete is[prop];
1131
+ this.ver = createVersion();
1132
+ notify(this);
1133
+ return true;
1134
+ }
1135
+ ownKeys() {
1136
+ if (this.v == null) return [];
1137
+ return Reflect.ownKeys(this.v);
1138
+ }
1139
+ };
1140
+ var reflect = Reflect;
1141
+ var proto = LightState.prototype;
1142
+ for (const key of Object.getOwnPropertyNames(Reflect)) proto[key] ??= function(_target, ...args) {
1143
+ return reflect[key](this.v, ...args);
1144
+ };
1145
+ //#endregion
1146
+ //#region src/state/transforms/ChainFunctionTransform.ts
1147
+ var ChainFunctionTransform = class extends Transform {
1148
+ hookName;
1149
+ constructor(source, args, name) {
1150
+ super(source);
1151
+ this.hookArgs = args;
1152
+ this.hookName = name;
1153
+ }
1154
+ execute() {
1155
+ const is = this.srcLs.v;
1156
+ const boundThis = isArray(is) ? this.srcLs.prx : is;
1157
+ this.hookFunction = is[this.hookName].bind(boundThis);
1158
+ return super.execute();
1159
+ }
1160
+ };
1161
+ ChainFunctionTransform.prototype.flg = 2;
1162
+ transforms.ChainFunctionTransform = ChainFunctionTransform;
1163
+ //#endregion
1164
+ //#region src/state/transforms/MapArrayTransform.ts
1165
+ var MAX_LINEAR_LOOKUPS = 2;
1166
+ var MapArrayTransform = class extends Transform {
1167
+ previousElements;
1168
+ previousIndexStates;
1169
+ execute() {
1170
+ this.runId = nextRunId();
1171
+ refresh(this.srcLs);
1172
+ const is = this.srcLs.v;
1173
+ if (!isArray(is)) throw TypeError("Cannot apply map function to non-array value");
1174
+ const sourceProxy = this.srcLs.prx;
1175
+ const previousResults = this.tgt ? this.tgt.v : [];
1176
+ const previousElements = this.previousElements ?? [];
1177
+ const previousIndexStates = this.previousIndexStates;
1178
+ const srcFunction = getLightState(this.hookFunction);
1179
+ const passesIndex = this.hookFunction.length > 1;
1180
+ const indexStates = passesIndex ? [] : void 0;
1181
+ const sameLength = previousElements.length === is.length;
1182
+ const r = sameLength ? previousResults.slice() : [];
1183
+ let previousPositionsByElement;
1184
+ let lookupCount = 0;
1185
+ let expectedPreviousPosition = 0;
1186
+ for (let i = 0; i < is.length; i++) {
1187
+ const element = is[i];
1188
+ let previousPosition;
1189
+ if (typeof element !== "function") previousPosition = -1;
1190
+ else if (element === previousElements[expectedPreviousPosition]) previousPosition = expectedPreviousPosition++;
1191
+ else if (element === previousElements[expectedPreviousPosition + 1]) {
1192
+ previousPosition = expectedPreviousPosition + 1;
1193
+ expectedPreviousPosition += 2;
1194
+ } else {
1195
+ previousPosition = lookupCount++ < MAX_LINEAR_LOOKUPS ? previousElements.indexOf(element) : (previousPositionsByElement ??= new Map(previousElements.map((e, position) => [e, position]))).get(element) ?? -1;
1196
+ if (previousPosition >= expectedPreviousPosition && is[i + 1] === previousElements[previousPosition + 1]) expectedPreviousPosition = previousPosition + 1;
1197
+ }
1198
+ if (previousPosition < 0) {
1199
+ r[i] = this.mapElement(i, element, srcFunction, passesIndex ? sourceProxy : void 0, indexStates);
1200
+ continue;
1201
+ }
1202
+ if (!sameLength || previousPosition !== i) r[i] = previousResults[previousPosition];
1203
+ if (indexStates) {
1204
+ const indexState = previousIndexStates[previousPosition];
1205
+ if (previousPosition !== i) indexState.set(i);
1206
+ indexStates[i] = indexState;
1207
+ }
1208
+ }
1209
+ this.previousElements = is.slice();
1210
+ this.previousIndexStates = indexStates;
1211
+ if (this.tgt) updateValue(this.tgt, r);
1212
+ else this.tgt = getLightState(state(r));
1213
+ this.tgt.srcs = this.srcLs;
1214
+ this.tgt.tf = this;
1215
+ return this.tgt.prx;
1216
+ }
1217
+ mapElement(i, element, srcFunction, sourceProxy, indexStates) {
1218
+ const is = this.srcLs.v;
1219
+ const v = typeof element === "function" ? element : promoteMemberToStateLightState(this.srcLs, is, i).prx;
1220
+ let args;
1221
+ if (indexStates) {
1222
+ const indexState = state(i);
1223
+ indexStates[i] = indexState;
1224
+ args = [
1225
+ v,
1226
+ indexState,
1227
+ sourceProxy
1228
+ ];
1229
+ } else args = [v];
1230
+ const row = new transforms.MapValueTransform(srcFunction, this.hookFunction, args);
1231
+ row.runId = this.runId;
1232
+ return row.execute();
1233
+ }
1234
+ };
1235
+ MapArrayTransform.prototype.flg = 2;
1236
+ transforms.MapArrayTransform = MapArrayTransform;
1237
+ //#endregion
1238
+ //#region src/state/transforms/FunctionTransform.ts
1239
+ var FunctionTransform = class extends Transform {
1240
+ constructor(source, hookFunction, args) {
1241
+ super(source, hookFunction);
1242
+ this.hookArgs = args;
1243
+ }
1244
+ };
1245
+ transforms.FunctionTransform = FunctionTransform;
1246
+ //#endregion
1247
+ //#region src/state/transforms/LightStateFunctionTransform.ts
1248
+ var LightStateFunctionTransform = class extends FunctionTransform {};
1249
+ LightStateFunctionTransform.prototype.flg = 3;
1250
+ transforms.LightStateFunctionTransform = LightStateFunctionTransform;
1251
+ //#endregion
1252
+ //#region src/state/transforms/MapValueTransform.ts
1253
+ var MapValueTransform = class extends LightStateFunctionTransform {};
1254
+ transforms.MapValueTransform = MapValueTransform;
1255
+ //#endregion
1256
+ //#region src/state/transforms/CallbackTransform.ts
1257
+ var callbackQueue = /* @__PURE__ */ new Set();
1258
+ var queuedInPriorityOrder = true;
1259
+ var lastQueuedPriority = -Infinity;
1260
+ var CallbackTransform = class extends Transform {
1261
+ prio;
1262
+ payload;
1263
+ constructor(source, callback, data, priority) {
1264
+ super(source, callback);
1265
+ this.payload = data;
1266
+ this.prio = priority ?? 2 ** 29;
1267
+ }
1268
+ static flush() {
1269
+ const queue = callbackQueue.size > 1 ? Array.from(callbackQueue) : callbackQueue;
1270
+ if (!queuedInPriorityOrder && queue !== callbackQueue) queue.sort((a, b) => a.prio - b.prio);
1271
+ queuedInPriorityOrder = true;
1272
+ lastQueuedPriority = -Infinity;
1273
+ for (const transform of queue) if (callbackQueue.delete(transform)) try {
1274
+ transform.execute();
1275
+ } catch (e) {
1276
+ Transform.throwDelayed(e);
1277
+ }
1278
+ }
1279
+ queue() {
1280
+ const sizeBefore = callbackQueue.size;
1281
+ callbackQueue.add(this);
1282
+ if (callbackQueue.size !== sizeBefore) {
1283
+ if (this.prio < lastQueuedPriority) queuedInPriorityOrder = false;
1284
+ else lastQueuedPriority = this.prio;
1285
+ }
1286
+ queueFlush();
1287
+ }
1288
+ dequeue() {
1289
+ callbackQueue.delete(this);
1290
+ }
1291
+ execute() {
1292
+ return this.hookFunction(destate(this.srcLs), this.payload);
1293
+ }
1294
+ };
1295
+ transforms.CallbackTransform = CallbackTransform;
1296
+ //#endregion
1297
+ //#region src/state/transforms/OptTransform.ts
1298
+ var OptTransform = class extends Transform {
1299
+ opt;
1300
+ def;
1301
+ constructor(selector, options, def) {
1302
+ super(selector);
1303
+ this.opt = options;
1304
+ this.def = def;
1305
+ }
1306
+ execute() {
1307
+ refresh(this.srcLs);
1308
+ const dselector = this.srcLs.v;
1309
+ let value;
1310
+ if (typeof dselector === "number" && isArray(destate(this.opt)) || isPOJO(destate(this.opt))) value = dselector in this.opt ? this.opt[dselector] : this.def;
1311
+ else if (isArray(dselector) ? dselector.length > 0 : dselector) value = this.opt;
1312
+ else value = this.def;
1313
+ const sources = acquireSet();
1314
+ sources.add(this.srcLs);
1315
+ const ls = getLightState(value);
1316
+ if (ls) {
1317
+ sources.add(ls);
1318
+ refresh(ls);
1319
+ }
1320
+ const result = this.updateTarget(value, sources);
1321
+ releaseSet(sources);
1322
+ return result;
1323
+ }
1324
+ };
1325
+ transforms.OptTransform = OptTransform;
1326
+ //#endregion
1327
+ //#region src/state/transforms/IsTransform.ts
1328
+ var IsTargetTransform = class extends Transform {
1329
+ owner;
1330
+ targetLs;
1331
+ keyVal;
1332
+ cmpLs;
1333
+ constructor(owner, targetLs, keyVal, cmpLs) {
1334
+ super();
1335
+ this.owner = owner;
1336
+ this.targetLs = targetLs;
1337
+ this.keyVal = keyVal;
1338
+ this.cmpLs = cmpLs;
1339
+ }
1340
+ subTo(ls) {
1341
+ this.owner.subTo(ls);
1342
+ }
1343
+ uns(ls) {
1344
+ this.owner.uns(ls);
1345
+ }
1346
+ rfr() {
1347
+ this.owner.refreshTarget(this.targetLs);
1348
+ }
1349
+ };
1350
+ var targetTransform = (target) => target.tf;
1351
+ var includes = (targets, target) => targets === target || isArray(targets) && targets.includes(target);
1352
+ transforms.IsTransform = class IsTransform extends Transform {
1353
+ compared = /* @__PURE__ */ new Map();
1354
+ sourceToKey = /* @__PURE__ */ new Map();
1355
+ oldReference;
1356
+ sourceRefCount = 0;
1357
+ queued = [];
1358
+ static instances = /* @__PURE__ */ new WeakMap();
1359
+ static for(reference) {
1360
+ return IsTransform.instances.get(reference) ?? new IsTransform(reference);
1361
+ }
1362
+ constructor(reference) {
1363
+ super(reference);
1364
+ this.oldReference = reference.v;
1365
+ IsTransform.instances.set(reference, this);
1366
+ }
1367
+ refreshTarget(target) {
1368
+ refresh(this.srcLs);
1369
+ const tf = targetTransform(target);
1370
+ if (tf.cmpLs) refresh(tf.cmpLs);
1371
+ if (target.ver >= this.srcLs.ver && (!tf.cmpLs || target.ver >= tf.cmpLs.ver)) return;
1372
+ if (tf.cmpLs && !Object.is(tf.keyVal, tf.cmpLs.v)) this.rekeyCompared(target, tf.cmpLs.v);
1373
+ updateValue(target, Object.is(tf.keyVal, this.srcLs.v));
1374
+ }
1375
+ rekeyCompared(target, key) {
1376
+ const tf = targetTransform(target);
1377
+ const targets = this.compared.get(tf.keyVal);
1378
+ const registered = includes(targets, target);
1379
+ if (isArray(targets) && registered) this.removeCompared(tf.keyVal, targets, targets.indexOf(target));
1380
+ else if (registered) this.compared.delete(tf.keyVal);
1381
+ if (registered) this.addCompared(key, target, tf.cmpLs);
1382
+ else {
1383
+ tf.keyVal = key;
1384
+ this.sourceToKey.set(tf.cmpLs, key);
1385
+ }
1386
+ }
1387
+ execute() {
1388
+ const reference = this.srcLs.v;
1389
+ while (this.queued.length) this.updateComparedState(this.queued.pop(), reference);
1390
+ if (reference === this.oldReference) return;
1391
+ for (const ref of [this.oldReference, reference]) {
1392
+ const targets = this.compared.get(ref);
1393
+ if (!targets) continue;
1394
+ const value = Object.is(ref, reference);
1395
+ if (isArray(targets)) for (const result of targets) updateValue(result, value, this.srcLs.ver);
1396
+ else updateValue(targets, value, this.srcLs.ver);
1397
+ }
1398
+ this.oldReference = reference;
1399
+ }
1400
+ updateComparedState(ls, reference) {
1401
+ const target = this.popComparedState(ls);
1402
+ this.addCompared(ls.v, target, ls);
1403
+ updateValue(target, Object.is(ls.v, reference), ls.ver);
1404
+ }
1405
+ popComparedState(ls) {
1406
+ const old = this.sourceToKey.get(ls);
1407
+ const targets = this.compared.get(old);
1408
+ if (!isArray(targets)) {
1409
+ this.compared.delete(old);
1410
+ return targets;
1411
+ }
1412
+ const i = targets.findIndex((rls) => targetTransform(rls).cmpLs === ls);
1413
+ const target = targets[i];
1414
+ this.removeCompared(old, targets, i);
1415
+ return target;
1416
+ }
1417
+ removeCompared(key, targets, i) {
1418
+ targets.splice(i, 1);
1419
+ if (targets.length === 1) this.compared.set(key, targets[0]);
1420
+ }
1421
+ queue(target) {
1422
+ if (target && target !== this.srcLs) this.queued.push(target);
1423
+ super.queue();
1424
+ }
1425
+ isOwnTarget(ls) {
1426
+ return ls.tf instanceof IsTargetTransform && ls.tf.owner === this;
1427
+ }
1428
+ subTo(ls) {
1429
+ if (this.sourceToKey.has(ls)) return super.subTo(ls);
1430
+ const key = targetTransform(ls).keyVal;
1431
+ if (!includes(this.compared.get(key), ls)) {
1432
+ this.addCompared(key, ls);
1433
+ updateValue(ls, Object.is(key, this.srcLs.v));
1434
+ }
1435
+ if (++this.sourceRefCount === 1) super.subTo(this.srcLs);
1436
+ }
1437
+ uns(state) {
1438
+ if (!this.isOwnTarget(state)) return super.uns(state);
1439
+ const key = targetTransform(state).keyVal;
1440
+ const targets = this.compared.get(key);
1441
+ if (isArray(targets)) this.removeCompared(key, targets, targets.indexOf(state));
1442
+ else this.compared.delete(key);
1443
+ if (--this.sourceRefCount === 0) super.uns(this.srcLs);
1444
+ }
1445
+ addCompared(comparedValue, target, comparedState) {
1446
+ if (comparedState) this.sourceToKey.set(comparedState, comparedValue);
1447
+ targetTransform(target).keyVal = comparedValue;
1448
+ const targets = this.compared.get(comparedValue);
1449
+ if (!targets) this.compared.set(comparedValue, target);
1450
+ else if (isArray(targets)) targets.push(target);
1451
+ else this.compared.set(comparedValue, [targets, target]);
1452
+ }
1453
+ new(compared) {
1454
+ const reference = this.srcLs.v;
1455
+ const ls = getLightState(compared);
1456
+ const comparedValue = ls?.v ?? compared;
1457
+ const target = lightState(Object.is(comparedValue, reference));
1458
+ target.tf = new IsTargetTransform(this, target, comparedValue, ls);
1459
+ target.srcs = ls ? [target, ls] : target;
1460
+ this.addCompared(comparedValue, target, ls);
1461
+ return state(target);
1462
+ }
1463
+ };
1464
+ //#endregion
1465
+ //#region src/state/transforms/ComputeTransform.ts
1466
+ var ComputeTransform = class extends Transform {
1467
+ constructor(computeFunction) {
1468
+ super();
1469
+ this.hookFunction = computeFunction;
1470
+ }
1471
+ };
1472
+ ComputeTransform.prototype.flg = 2;
1473
+ transforms.ComputeTransform = ComputeTransform;
1474
+ //#endregion
1475
+ //#region src/state/transforms/PromiseTransform.ts
1476
+ var PromiseTransform = class extends Transform {
1477
+ constructor(promise) {
1478
+ super();
1479
+ this.tgt = new LightState(void 0);
1480
+ promise.then((v) => {
1481
+ updateValue(this.tgt, v);
1482
+ }, (cause) => {
1483
+ updateValue(this.tgt, createPoisonedValue(cause));
1484
+ });
1485
+ }
1486
+ execute() {
1487
+ return this.tgt;
1488
+ }
1489
+ };
1490
+ transforms.PromiseTransform = PromiseTransform;
1491
+ //#endregion
1492
+ //#region src/state/transforms/SubscribeTransform.ts
1493
+ var getSubState = (owner, prop) => {
1494
+ const container = owner.v;
1495
+ const ls = getLightState(container[prop]);
1496
+ if (ls) return ls;
1497
+ if (!(prop in container)) return void 0;
1498
+ return promoteMemberToStateLightState(owner, container, prop);
1499
+ };
1500
+ var SubscribeTransform = class SubscribeTransform extends Transform {
1501
+ static instances = /* @__PURE__ */ new WeakMap();
1502
+ pendingSelf = false;
1503
+ seq = 0;
1504
+ static for(ls) {
1505
+ return (SubscribeTransform.instances.get(ls) ?? new SubscribeTransform(ls)).tgt;
1506
+ }
1507
+ constructor(source) {
1508
+ super(source);
1509
+ SubscribeTransform.instances.set(source, this);
1510
+ this.execute();
1511
+ }
1512
+ queue(target) {
1513
+ if (target === this.srcLs) this.pendingSelf = true;
1514
+ super.queue(target);
1515
+ }
1516
+ execute() {
1517
+ const sources = acquireSet();
1518
+ if (this.pendingSelf || !this.tgt) {
1519
+ this.pendingSelf = false;
1520
+ sources.add(this.srcLs);
1521
+ const stateType = getStateType(this.srcLs);
1522
+ if (stateType === 1 || stateType === 2) {
1523
+ const parent = this.srcLs.v;
1524
+ for (const key of Object.keys(parent)) {
1525
+ const childLs = getSubState(this.srcLs, key);
1526
+ if (!childLs) continue;
1527
+ const childType = getStateType(childLs);
1528
+ const nestedLs = (childType === 1 || childType === 2) && SubscribeTransform.for(childLs);
1529
+ sources.add(nestedLs || childLs);
1530
+ }
1531
+ }
1532
+ } else {
1533
+ const store = this.tgt.srcs;
1534
+ for (const s of store) sources.add(s);
1535
+ }
1536
+ this.updateTarget(this.seq++, sources);
1537
+ releaseSet(sources);
1538
+ }
1539
+ };
1540
+ SubscribeTransform.prototype.flg = 1;
1541
+ transforms.SubscribeTransform = SubscribeTransform;
1542
+ //#endregion
1543
+ //#region src/state/transforms/DOMRootTransform.ts
1544
+ var DOMRootTransform = class extends Transform {
1545
+ rootCtl;
1546
+ constructor(root) {
1547
+ super();
1548
+ this.rootCtl = root;
1549
+ }
1550
+ queue() {
1551
+ queueRoot(this);
1552
+ }
1553
+ execute() {
1554
+ this.rootCtl.createRoot();
1555
+ }
1556
+ };
1557
+ transforms.DOMRootTransform = DOMRootTransform;
1558
+ //#endregion
1559
+ //#region src/common/computeMutation.ts
1560
+ var afterIndex = /* @__PURE__ */ new Map();
1561
+ var beforeSet = /* @__PURE__ */ new Set();
1562
+ var flushRun$1 = (out, lo, hi) => {
1563
+ if (lo < 0) return;
1564
+ out.push(lo);
1565
+ if (hi > lo) out.push(-1 - hi);
1566
+ };
1567
+ var computeMutation = (before, after, known) => {
1568
+ let prefixL = 0;
1569
+ if (known) prefixL = known.pre;
1570
+ else while (prefixL < after.length && before[prefixL] === after[prefixL]) prefixL++;
1571
+ if (prefixL === after.length && prefixL === before.length) return {};
1572
+ let suffixL = 0;
1573
+ if (known?.suf !== void 0) suffixL = known.suf;
1574
+ else while (before[before.length - 1 - suffixL] === after[after.length - 1 - suffixL]) suffixL++;
1575
+ const commonLength = prefixL + suffixL;
1576
+ if (commonLength === after.length) return before.length - commonLength === 1 ? {
1577
+ removed: [prefixL],
1578
+ pre: prefixL,
1579
+ suf: suffixL
1580
+ } : {
1581
+ removed: [prefixL, -1 - (before.length - suffixL - 1)],
1582
+ pre: prefixL,
1583
+ suf: suffixL
1584
+ };
1585
+ if (commonLength === before.length) return after.length - commonLength === 1 ? {
1586
+ added: [prefixL],
1587
+ pre: prefixL,
1588
+ suf: suffixL
1589
+ } : {
1590
+ added: [prefixL, -1 - (after.length - suffixL - 1)],
1591
+ pre: prefixL,
1592
+ suf: suffixL
1593
+ };
1594
+ return before.length === after.length && mutateSingleMoveOrSwap(before, after, prefixL, suffixL, known?.changedCount) || diffChangedMiddle(before, after, prefixL, suffixL);
1595
+ };
1596
+ var mutateSingleMoveOrSwap = (before, after, prefixL, suffixL, changedCount) => {
1597
+ const first = prefixL;
1598
+ const last = after.length - suffixL - 1;
1599
+ const movedForward = after[last] === before[first];
1600
+ const movedBack = after[first] === before[last];
1601
+ if (!movedForward && !movedBack) return void 0;
1602
+ const swapped = movedForward && movedBack && last > first + 1;
1603
+ if (changedCount === 2) {
1604
+ if (!movedForward || !movedBack) return void 0;
1605
+ } else {
1606
+ const offset = Number(movedBack) - Number(movedForward);
1607
+ for (let i = first + Number(movedForward); i <= last - Number(movedBack); i++) if (before[i] !== after[i + offset]) return void 0;
1608
+ }
1609
+ let common;
1610
+ let move;
1611
+ if (swapped) {
1612
+ common = [last];
1613
+ flushRun$1(common, first + 1, last - 1);
1614
+ common.push(first);
1615
+ move = [first, last];
1616
+ } else if (movedForward) {
1617
+ common = [last];
1618
+ flushRun$1(common, first, last - 1);
1619
+ move = [last];
1620
+ } else {
1621
+ common = [
1622
+ first + 1,
1623
+ -1 - last,
1624
+ first
1625
+ ];
1626
+ move = [first];
1627
+ }
1628
+ return {
1629
+ removed: [],
1630
+ moved: move,
1631
+ added: [],
1632
+ kept: common,
1633
+ pre: prefixL,
1634
+ suf: suffixL
1635
+ };
1636
+ };
1637
+ var diffChangedMiddle = (before, after, prefixL, suffixL) => {
1638
+ const remove = [];
1639
+ const add = [];
1640
+ const move = [];
1641
+ const common = [];
1642
+ afterIndex.clear();
1643
+ beforeSet.clear();
1644
+ for (let i = prefixL; i < after.length - suffixL; i++) afterIndex.set(after[i], i);
1645
+ let runLo = -1;
1646
+ let runHi = -1;
1647
+ for (let beforeI = prefixL; beforeI <= before.length - 1 - suffixL; beforeI++) {
1648
+ const v = before[beforeI];
1649
+ const afterI = afterIndex.get(v);
1650
+ if (afterI !== void 0) {
1651
+ common.push(afterI);
1652
+ beforeSet.add(v);
1653
+ } else if (runLo >= 0 && beforeI === runHi + 1) runHi = beforeI;
1654
+ else {
1655
+ flushRun$1(remove, runLo, runHi);
1656
+ runLo = runHi = beforeI;
1657
+ }
1658
+ }
1659
+ flushRun$1(remove, runLo, runHi);
1660
+ const stableRuns = extractLongestIncreasingSubsequence(common);
1661
+ let sr = stableRuns.length - 1;
1662
+ let stable = Infinity;
1663
+ let stableHi = Infinity;
1664
+ if (stableRuns.length) {
1665
+ stable = stableRuns[sr--];
1666
+ stableHi = stableRuns[sr] < 0 ? -1 - stableRuns[sr--] : stable;
1667
+ }
1668
+ let keptRank = prefixL;
1669
+ let moveLo = -1;
1670
+ let moveHi = -1;
1671
+ let addLo = -1;
1672
+ let addHi = -1;
1673
+ for (let i = prefixL; i < after.length - suffixL; i++) if (beforeSet.has(after[i])) {
1674
+ if (i === stable) {
1675
+ if (stable < stableHi) stable++;
1676
+ else if (sr >= 0) {
1677
+ stable = stableRuns[sr--];
1678
+ stableHi = stableRuns[sr] < 0 ? -1 - stableRuns[sr--] : stable;
1679
+ } else stable = Infinity;
1680
+ } else if (moveLo >= 0 && keptRank === moveHi + 1) moveHi = keptRank;
1681
+ else {
1682
+ flushRun$1(move, moveLo, moveHi);
1683
+ moveLo = moveHi = keptRank;
1684
+ }
1685
+ keptRank++;
1686
+ } else if (addLo >= 0 && i === addHi + 1) addHi = i;
1687
+ else {
1688
+ flushRun$1(add, addLo, addHi);
1689
+ addLo = addHi = i;
1690
+ }
1691
+ flushRun$1(move, moveLo, moveHi);
1692
+ flushRun$1(add, addLo, addHi);
1693
+ return {
1694
+ removed: remove,
1695
+ moved: move,
1696
+ added: add,
1697
+ kept: common,
1698
+ pre: prefixL,
1699
+ suf: suffixL
1700
+ };
1701
+ };
1702
+ var extractLongestIncreasingSubsequence = (X) => {
1703
+ const N = X.length;
1704
+ if (N < 2) return [...X];
1705
+ const predecessor = new Int32Array(N);
1706
+ const lowestEnd = new Int32Array(N + 1);
1707
+ let longestLIS = 1;
1708
+ let lo, hi, mid;
1709
+ for (let i = 1; i < N; i++) {
1710
+ lo = 1;
1711
+ hi = longestLIS + 1;
1712
+ while (lo < hi) {
1713
+ mid = lo + hi >> 1;
1714
+ if (X[lowestEnd[mid]] >= X[i]) hi = mid;
1715
+ else lo = mid + 1;
1716
+ }
1717
+ predecessor[i] = lowestEnd[lo - 1];
1718
+ lowestEnd[lo] = i;
1719
+ if (lo > longestLIS) longestLIS = lo;
1720
+ }
1721
+ const runs = [];
1722
+ let k = lowestEnd[longestLIS];
1723
+ let runHi = X[k];
1724
+ let runLo = runHi;
1725
+ for (let n = longestLIS - 1; n > 0; n--) {
1726
+ k = predecessor[k];
1727
+ const v = X[k];
1728
+ if (v === runLo - 1) runLo = v;
1729
+ else {
1730
+ if (runHi > runLo) runs.push(-1 - runHi);
1731
+ runs.push(runLo);
1732
+ runHi = runLo = v;
1733
+ }
1734
+ }
1735
+ if (runHi > runLo) runs.push(-1 - runHi);
1736
+ runs.push(runLo);
1737
+ return runs;
1738
+ };
1739
+ //#endregion
1740
+ //#region src/DOM/util/moveBeforeSupport.ts
1741
+ var supportsMoveBefore = typeof Element !== "undefined" && typeof Element.prototype.moveBefore === "function";
1742
+ //#endregion
1743
+ //#region src/DOM/nodeControllers/StateController.ts
1744
+ var stateControllerMap = /* @__PURE__ */ new Map();
1745
+ var promoteArrayElements = (arr) => {
1746
+ for (let i = 0; i < arr.length; i++) {
1747
+ const el = arr[i];
1748
+ if (isAnyState(el) || isArray(el)) continue;
1749
+ const ls = lightState(el);
1750
+ markPromotedElement(ls);
1751
+ arr[i] = ls;
1752
+ }
1753
+ return arr;
1754
+ };
1755
+ var getKeptChildren = (newChildren, mutation) => {
1756
+ let keptChildren = newChildren;
1757
+ if (mutation.added.length) {
1758
+ const add = mutation.added;
1759
+ keptChildren = [];
1760
+ let k = 0;
1761
+ let lo = add[k++];
1762
+ let hi = k < add.length && add[k] < 0 ? -1 - add[k++] : lo;
1763
+ for (let i = 0; i < newChildren.length; i++) {
1764
+ if (i > hi && k < add.length) {
1765
+ lo = add[k++];
1766
+ hi = k < add.length && add[k] < 0 ? -1 - add[k++] : lo;
1767
+ }
1768
+ if (i < lo || i > hi) keptChildren.push(newChildren[i]);
1769
+ }
1770
+ }
1771
+ return keptChildren;
1772
+ };
1773
+ var StateController = class StateController extends NodeController {
1774
+ nst;
1775
+ nxt;
1776
+ insertionParent;
1777
+ nestLevel = 1;
1778
+ namedStates;
1779
+ static pendingDestroy = /* @__PURE__ */ new Set();
1780
+ static idleDestroy = /* @__PURE__ */ new Set();
1781
+ static pendingClears = /* @__PURE__ */ new Map();
1782
+ static idleClears = /* @__PURE__ */ new Map();
1783
+ static pendingCalls = /* @__PURE__ */ new Set();
1784
+ static idleCalls = /* @__PURE__ */ new Set();
1785
+ static previousStateControllers = {
1786
+ prev: [],
1787
+ indexed: false,
1788
+ lookup(ls) {
1789
+ if (!this.indexed) {
1790
+ for (const child of this.prev) if (child instanceof StateController) stateControllerMap.set(child.def, child);
1791
+ this.indexed = true;
1792
+ }
1793
+ return stateControllerMap.get(ls);
1794
+ }
1795
+ };
1796
+ static movableControllersByDef = /* @__PURE__ */ new Map();
1797
+ get tfm() {
1798
+ return this.def.tf;
1799
+ }
1800
+ build(parentController, DOMContext, stateContext, namedStates, hydrationContext, level = 1) {
1801
+ super.build(parentController, DOMContext, stateContext, namedStates, hydrationContext, level);
1802
+ StateController.registerMovableChildren(this);
1803
+ }
1804
+ remove(removeNode = true) {
1805
+ const def = this.def;
1806
+ if (StateController.movableControllersByDef.get(def) === this) StateController.movableControllersByDef.delete(def);
1807
+ super.remove(removeNode);
1808
+ }
1809
+ static registerMovableChildren(sc) {
1810
+ if (sc.nst !== 1 || sc.ctx?.md === 2 || !sc.hasMovableChildren()) return;
1811
+ for (const child of sc.c) if (child instanceof StateController) StateController.movableControllersByDef.set(child.def, child);
1812
+ }
1813
+ static detachFromDonor(donor, gainer) {
1814
+ const donorPar = donor.par;
1815
+ if (!(donorPar instanceof StateController) || donorPar === gainer || !donorPar.c) return;
1816
+ const dc = donorPar.c;
1817
+ const di = dc.indexOf(donor);
1818
+ dc.splice(di, 1);
1819
+ donorPar.updateNodeCount(donorPar.nc - getNodeCount(donor));
1820
+ }
1821
+ hasMovableChildren() {
1822
+ return !!(this.par && this.par.flg & 4);
1823
+ }
1824
+ static registerPendingCall(fn) {
1825
+ StateController.pendingCalls.add(fn);
1826
+ }
1827
+ static flushPendingWork() {
1828
+ const clears = StateController.pendingClears;
1829
+ if (clears.size) {
1830
+ StateController.pendingClears = StateController.idleClears;
1831
+ StateController.idleClears = clears;
1832
+ for (const [sc, el] of clears) sc.detachCleared(el);
1833
+ clears.clear();
1834
+ }
1835
+ const pending = StateController.pendingDestroy;
1836
+ if (pending.size) {
1837
+ StateController.pendingDestroy = StateController.idleDestroy;
1838
+ StateController.idleDestroy = pending;
1839
+ swapDeferredNodes();
1840
+ for (const child of pending) if (child instanceof Node) child.parentNode?.removeChild(child);
1841
+ else child.remove();
1842
+ pending.clear();
1843
+ clearDrainedDeferredNodes();
1844
+ }
1845
+ const calls = StateController.pendingCalls;
1846
+ if (calls.size) {
1847
+ StateController.pendingCalls = StateController.idleCalls;
1848
+ StateController.idleCalls = calls;
1849
+ for (const fn of calls) fn();
1850
+ calls.clear();
1851
+ }
1852
+ }
1853
+ buildNode(_properties, namedStates, _stateContext, _hydrationContext, level = 1) {
1854
+ this.nestLevel = level;
1855
+ this.namedStates = namedStates;
1856
+ const is = this.def;
1857
+ refresh(is);
1858
+ const tf = is.tf;
1859
+ if (tf && tf.flg & 2 && is.v instanceof NodeController && is.v.isSpent()) tf.execute();
1860
+ const value = is.v;
1861
+ if (typeof value === "string" || typeof value === "number") this.c = [this.createTextChild(value)];
1862
+ else this.parseArgs(this.childArgs(value));
1863
+ this.addSub(new CallbackTransform(is, StateController.stateChanged, this, this.nestLevel));
1864
+ this.nst = this.checkNodeStateType();
1865
+ }
1866
+ childArgs(value) {
1867
+ if (!isArray(value)) return [value];
1868
+ return this.def.tf ? value : promoteArrayElements(value);
1869
+ }
1870
+ checkNodeStateType() {
1871
+ const state = this.def;
1872
+ const stateType = getStateType(state);
1873
+ return stateType !== 0 ? stateType : state.v == null ? 6 : 0;
1874
+ }
1875
+ static stateChanged(_value, sc) {
1876
+ sc.onStateChange();
1877
+ }
1878
+ onStateChange() {
1879
+ try {
1880
+ this.updateBody();
1881
+ } catch (e) {
1882
+ this.handleReactiveError(e);
1883
+ }
1884
+ }
1885
+ updateBody() {
1886
+ const definition = this.def.v;
1887
+ const oldNodeStateType = this.nst;
1888
+ this.nst = this.checkNodeStateType();
1889
+ const node = this.c[0];
1890
+ if (node && oldNodeStateType === 0 && this.nst === 0) {
1891
+ node.textContent = String(definition);
1892
+ return;
1893
+ }
1894
+ const pendingClear = StateController.pendingClears.get(this);
1895
+ if (pendingClear) {
1896
+ StateController.pendingClears.delete(this);
1897
+ this.detachCleared(pendingClear);
1898
+ }
1899
+ if (oldNodeStateType === 1 && this.nst === 1 && !definition.length && this.clearAll()) return;
1900
+ if ((oldNodeStateType === 1 || this.nst === 1) && (oldNodeStateType === this.nst || this.hasMovableChildren())) {
1901
+ const oldChildren = this.c;
1902
+ const pos = this.par.findNode(this);
1903
+ this.nxt = liveChildNodeAt(pos.p, pos.i + this.nc, pos.n, pos.i);
1904
+ const previousStateControllers = StateController.previousStateControllers;
1905
+ previousStateControllers.prev = oldChildren;
1906
+ previousStateControllers.indexed = false;
1907
+ this.parseArgs(this.childArgs(definition), previousStateControllers);
1908
+ previousStateControllers.prev = [];
1909
+ stateControllerMap.clear();
1910
+ let fnr = {
1911
+ i: 0,
1912
+ s: 0
1913
+ };
1914
+ let cursorNode;
1915
+ let cursorNodeIndex = 0;
1916
+ const children = this.c;
1917
+ let newNodeCount = 0;
1918
+ let firstChange;
1919
+ let lastChange = 0;
1920
+ let changedCount = 0;
1921
+ const movable = this.hasMovableChildren();
1922
+ const registersMovableChildren = movable && this.nst === 1 && this.ctx?.md !== 2;
1923
+ for (let idx = 0; idx < children.length; idx++) {
1924
+ let child = children[idx];
1925
+ if (child instanceof NodeController) {
1926
+ if (child.par !== this) {
1927
+ const donor = movable && child instanceof StateController && !child.par ? StateController.movableControllersByDef.get(child.def) : void 0;
1928
+ if (donor) {
1929
+ StateController.pendingDestroy.delete(donor);
1930
+ for (const n of this.getNodes(donor)) adoptDeferredNode(n);
1931
+ StateController.detachFromDonor(donor, this);
1932
+ donor.par = this;
1933
+ child = children[idx] = donor;
1934
+ } else if (movable && !(child instanceof StateController) && child.isMounted() && this.adoptBareChild(child)) {} else if (child.flg & 4) {
1935
+ child.build(this, void 0, child, this.namedStates, void 0, this.nestLevel + 1);
1936
+ if (cursorNode !== void 0) cursorNodeIndex += getNodeCount(child);
1937
+ } else {
1938
+ fnr = this.findNode(child, fnr.i, fnr.s, cursorNode, cursorNodeIndex);
1939
+ child.build(this, fnr, child, this.namedStates, void 0, this.nestLevel + 1);
1940
+ cursorNode = fnr.n;
1941
+ cursorNodeIndex = fnr.i + getNodeCount(child);
1942
+ }
1943
+ }
1944
+ children[idx] = this.resolveChild(child, true);
1945
+ }
1946
+ const resolvedChild = children[idx];
1947
+ if (registersMovableChildren && resolvedChild instanceof StateController) StateController.movableControllersByDef.set(resolvedChild.def, resolvedChild);
1948
+ newNodeCount += getNodeCount(resolvedChild);
1949
+ if (resolvedChild !== oldChildren[idx]) {
1950
+ firstChange ??= idx;
1951
+ lastChange = idx;
1952
+ changedCount++;
1953
+ }
1954
+ }
1955
+ const newChildren = children;
1956
+ const sameLength = newChildren.length === oldChildren.length;
1957
+ const mutation = computeMutation(oldChildren, newChildren, {
1958
+ pre: firstChange ?? newChildren.length,
1959
+ suf: sameLength ? newChildren.length - 1 - lastChange : void 0,
1960
+ changedCount: sameLength ? changedCount : void 0
1961
+ });
1962
+ this.applyMutation(mutation, oldChildren, newChildren);
1963
+ this.updateNodeCount(newNodeCount);
1964
+ return;
1965
+ }
1966
+ this.removeChildren();
1967
+ this.parseArgs(this.childArgs(definition));
1968
+ this.updateNodeCount(this.addChildren(this.par.findNode(this), void 0, void 0, this.namedStates, this.nestLevel));
1969
+ StateController.registerMovableChildren(this);
1970
+ }
1971
+ clearAll() {
1972
+ if (!this.nc || this.ctx?.md === 2) return false;
1973
+ if (this.hasMovableChildren()) {
1974
+ const el = this.par.el;
1975
+ if (!this.par.isSoleChild(this) || el.childNodes.length !== this.nc) return false;
1976
+ for (const child of this.c) {
1977
+ StateController.pendingDestroy.add(child);
1978
+ if (child instanceof NodeController) child.par = void 0;
1979
+ }
1980
+ StateController.pendingClears.set(this, el);
1981
+ } else {
1982
+ const el = this.enclosingMountElement();
1983
+ if (el?.childNodes.length !== this.nc) return false;
1984
+ el.textContent = "";
1985
+ this.removeChildren(false);
1986
+ }
1987
+ this.c = [];
1988
+ this.updateNodeCount(0);
1989
+ return true;
1990
+ }
1991
+ detachCleared(el) {
1992
+ el.textContent = "";
1993
+ }
1994
+ adoptBareChild(child) {
1995
+ const held = child.heldForm();
1996
+ if (!StateController.pendingDestroy.delete(held)) {
1997
+ const owner = child.par;
1998
+ if (!(owner instanceof StateController) || owner === this || !owner.hasMovableChildren()) return false;
1999
+ const oc = owner.c;
2000
+ oc.splice(oc.indexOf(held), 1);
2001
+ owner.updateNodeCount(owner.nc - getNodeCount(held));
2002
+ }
2003
+ for (const n of this.getNodes(held)) adoptDeferredNode(n);
2004
+ child.par = this;
2005
+ return true;
2006
+ }
2007
+ detachChild(children, i) {
2008
+ const child = children[i];
2009
+ if (!this.hasMovableChildren()) {
2010
+ if (child instanceof Node) child.parentNode?.removeChild(child);
2011
+ else child.remove();
2012
+ return;
2013
+ }
2014
+ StateController.pendingDestroy.add(child);
2015
+ if (child instanceof Node) deferNode(child);
2016
+ else for (const n of this.getNodes(child)) deferNode(n);
2017
+ if (child instanceof NodeController) child.par = void 0;
2018
+ }
2019
+ insertChild(children, i) {
2020
+ const child = children[i];
2021
+ this.insertionParent ??= this.par.findNode(this);
2022
+ const parent = this.insertionParent.p;
2023
+ const ref = this.nextDomNode(children, i);
2024
+ const node = child instanceof NodeController ? child.el : child;
2025
+ if (node) StateController.insertNode(parent, node, ref);
2026
+ else for (const childNode of this.getNodes(child)) StateController.insertNode(parent, childNode, ref);
2027
+ }
2028
+ static insertNode(parent, node, ref) {
2029
+ if (node.parentNode !== parent || node.nextSibling !== ref) {
2030
+ if (supportsMoveBefore && node.parentNode) parent.moveBefore(node, ref);
2031
+ else parent.insertBefore(node, ref);
2032
+ }
2033
+ }
2034
+ moveChild(children, i) {
2035
+ const child = children[i];
2036
+ this.insertionParent ??= this.par.findNode(this);
2037
+ const parent = this.insertionParent.p;
2038
+ const ref = this.nextDomNode(children, i);
2039
+ for (const childNode of this.getNodes(child)) if (supportsMoveBefore) parent.moveBefore(childNode, ref);
2040
+ else parent.insertBefore(childNode, ref);
2041
+ }
2042
+ nextDomNode(children, i) {
2043
+ for (let j = i + 1; j < children.length; j++) if (getNodeCount(children[j])) return this.getFirstNode(children[j]);
2044
+ return this.nxt ?? null;
2045
+ }
2046
+ mutateRange(children, range, operator) {
2047
+ if (!range) return;
2048
+ let hi = -1;
2049
+ for (let k = range.length - 1; k >= 0; k--) {
2050
+ const e = range[k];
2051
+ if (e < 0) hi = -1 - e;
2052
+ else {
2053
+ for (let j = hi < 0 ? e : hi; j >= e; j--) operator.call(this, children, j);
2054
+ hi = -1;
2055
+ }
2056
+ }
2057
+ }
2058
+ applyMutation(mutation, oldChildren, newChildren) {
2059
+ this.mutateRange(oldChildren, mutation.removed, this.detachChild);
2060
+ if (mutation.moved) this.mutateRange(getKeptChildren(newChildren, mutation), mutation.moved, this.moveChild);
2061
+ this.mutateRange(newChildren, mutation.added, this.insertChild);
2062
+ this.insertionParent = void 0;
2063
+ this.nxt = void 0;
2064
+ }
2065
+ };
2066
+ StateController.prototype.flg = 10;
2067
+ registerFlushPendingWork(StateController.flushPendingWork);
2068
+ //#endregion
2069
+ //#region src/DOM/nodeControllers/ElementController.ts
2070
+ var collectClassNames = (v, classNames) => {
2071
+ const dv = peek(v);
2072
+ throwIfPoisoned(dv);
2073
+ if (typeof dv === "string") classNames.push(dv);
2074
+ else if (isArray(dv)) for (const subValue of dv) collectClassNames(subValue, classNames);
2075
+ else if (isPOJO(dv)) {
2076
+ const classObject = v;
2077
+ for (const className in classObject) {
2078
+ const rawEnabled = peek(classObject[className]);
2079
+ throwIfPoisoned(rawEnabled);
2080
+ if (rawEnabled) classNames.push(className);
2081
+ }
2082
+ }
2083
+ return classNames;
2084
+ };
2085
+ var calculateClassString = (v) => collectClassNames(v, []).join(" ");
2086
+ var refreshClassStates = (v) => {
2087
+ const ls = getLightState(v);
2088
+ if (ls) refresh(ls);
2089
+ const value = ls ? ls.v : v;
2090
+ if (isArray(value)) for (const subValue of value) refreshClassStates(subValue);
2091
+ else if (isPOJO(value)) {
2092
+ const classObject = value;
2093
+ for (const className in classObject) refreshClassStates(classObject[className]);
2094
+ }
2095
+ };
2096
+ var nonAttributeKeys = /* @__PURE__ */ new Set([
2097
+ "innerHTML",
2098
+ "value",
2099
+ "checked",
2100
+ "selected",
2101
+ "autofocus"
2102
+ ]);
2103
+ var isLifecycleKey = (key) => key === "nodeCreated" || key === "nodeRemoved" || key === "nodeInserted";
2104
+ var isAutoBindableEventKey = (key) => key === "input" || key === "change";
2105
+ var isEventListener = (v) => typeof v === "function" ? !isState(v) : typeof v?.handleEvent === "function";
2106
+ var isEventListenerTuple = (v) => isArray(v) && isEventListener(v[0]);
2107
+ var isPlainArray = (v) => {
2108
+ return v != null && Object.getPrototypeOf(v) === Array.prototype;
2109
+ };
2110
+ var isReactiveClassObject = (classObject) => {
2111
+ for (const className in classObject) if (isAnyState(classObject[className])) return true;
2112
+ return false;
2113
+ };
2114
+ var isReactiveClassValue = (v) => isAnyState(v) || isPlainArray(v) && v.some(isReactiveClassValue) || isPOJO(v) && isReactiveClassObject(v);
2115
+ var ElementController = class ElementController extends NodeController {
2116
+ makeElement(tagName) {
2117
+ return (this.ctx?.md === 2 ? this.ctx.doc : document).createElement(tagName);
2118
+ }
2119
+ remove(removeNode = true) {
2120
+ super.remove(removeNode);
2121
+ if (removeNode && this.eventListeners) this.eventListeners = void 0;
2122
+ }
2123
+ buildNode(properties, _namedStates, stateContext, hydrationContext) {
2124
+ const target = stateContext;
2125
+ if (this.ctx?.md === 1) {
2126
+ this.removeExcessNodes(hydrationContext);
2127
+ if (!(hydrationContext.nxt instanceof HTMLElement || hydrationContext.nxt instanceof SVGElement)) throw Error("Hydration failed due to DOM mismatch");
2128
+ this.el = hydrationContext.nxt;
2129
+ hydrationContext.nxt = hydrationContext.nxt.nextSibling;
2130
+ } else this.el = this.makeElement(this.def);
2131
+ if (properties) for (const key in properties) {
2132
+ const value = properties[key];
2133
+ if (key === "class") {
2134
+ const isReactive = typeof value !== "string" && isReactiveClassValue(value);
2135
+ if (isReactive) refreshClassStates(value);
2136
+ this.handleProp(key, typeof value === "string" ? value : isReactive ? new transforms.LightStateFunctionTransform(void 0, calculateClassString, [value]).execute() : calculateClassString(value), target);
2137
+ } else if (key === "style") {
2138
+ const styleObject = value;
2139
+ for (const styleKey in styleObject) this.handleProp(key, styleObject[styleKey], target, camelToKebab(styleKey));
2140
+ } else this.handleProp(key, value, target);
2141
+ }
2142
+ }
2143
+ joinPropArray(a) {
2144
+ return a.filter((v) => peek(v) != null).join("");
2145
+ }
2146
+ handleProp(key, value, stateContext, subkey) {
2147
+ if ((typeof value === "string" || typeof value === "number") && !subkey && !nonAttributeKeys.has(key) && (value !== "" || key !== "class")) {
2148
+ this.el.setAttribute(key, String(value));
2149
+ return;
2150
+ }
2151
+ const joinedValue = isPlainArray(value) && !isEventListenerTuple(destate(value)) ? value.some(isAnyState) ? new transforms.LightStateFunctionTransform(void 0, this.joinPropArray, [value]).execute() : this.joinPropArray(value) : value;
2152
+ const joinedValueLightState = this.updateProperty(key, joinedValue, subkey, stateContext);
2153
+ if (joinedValueLightState) this.addSub(new CallbackTransform(joinedValueLightState, ElementController.propertyChanged, {
2154
+ ctl: this,
2155
+ prop: key,
2156
+ subkey
2157
+ }), stateContext);
2158
+ }
2159
+ static propertyChanged(newValue, binding) {
2160
+ binding.ctl.applyUpdate(newValue, binding.prop, binding.subkey);
2161
+ }
2162
+ applyUpdate(newValue, key, subkey) {
2163
+ try {
2164
+ this.updateProperty(key, newValue, subkey);
2165
+ } catch (e) {
2166
+ this.handleReactiveError(e);
2167
+ }
2168
+ }
2169
+ updateProperty(key, value, subkey, target) {
2170
+ let ls = getLightState(value);
2171
+ if (ls) refresh(ls);
2172
+ let dv = ls ? ls.v : value;
2173
+ throwIfPoisoned(dv);
2174
+ if (key === "innerHTML") this.el.innerHTML = String(dv);
2175
+ else if (key === "style") this.el.style.setProperty(subkey, dv);
2176
+ else if (this.ctx?.md !== 2 && (key === "value" || key === "checked" || key === "selected")) this.el[key] = dv;
2177
+ else if (this.eventListeners && key in this.eventListeners || (typeof dv === "function" || isEventListenerTuple(dv)) && !isLifecycleKey(key) || ls && isAutoBindableEventKey(key)) {
2178
+ if (this.ctx?.md !== 2) {
2179
+ if (this.eventListeners && key in this.eventListeners) {
2180
+ this.el.removeEventListener(key, ...this.eventListeners[key]);
2181
+ delete this.eventListeners[key];
2182
+ } else if (dv !== null && typeof dv !== "function" && !isArray(dv) && (dv !== void 0 || !ls.tf)) {
2183
+ const stateToUpdate = ls;
2184
+ assertWritable(stateToUpdate);
2185
+ dv = (ev) => {
2186
+ const checked = ev.target.type === "checkbox" || ev.target.type === "radio";
2187
+ const numeric = ev.target.type === "number" || ev.target.type === "range";
2188
+ updateValue(stateToUpdate, checked ? ev.target.checked : numeric ? ev.target.valueAsNumber : ev.target.value);
2189
+ };
2190
+ ls = void 0;
2191
+ }
2192
+ if (dv != null) {
2193
+ const tuple = isArray(dv) ? dv : void 0;
2194
+ const rawHandler = tuple ? tuple[0] : dv;
2195
+ const listenerOptions = tuple?.[1];
2196
+ const wrapped = typeof rawHandler === "function" ? (e) => fastFlush(rawHandler, e) : { handleEvent: (e) => fastFlush((ev) => rawHandler.handleEvent(ev), e) };
2197
+ this.el.addEventListener(key, wrapped, listenerOptions);
2198
+ if (ls || !target) (this.eventListeners ??= {})[key] = [wrapped, listenerOptions];
2199
+ }
2200
+ }
2201
+ } else if (key === "autofocus" && this.ctx?.md === 0) {} else if (typeof dv === "string" || typeof dv === "number" || typeof dv === "bigint") {
2202
+ if (dv === "" && key === "class") this.el.removeAttribute(key);
2203
+ else this.el.setAttribute(key, String(dv));
2204
+ } else if (dv === null || dv === false) this.el.removeAttribute(key);
2205
+ else if (dv === true) this.el.setAttribute(key, "");
2206
+ else if (this.ctx?.md === 2 && isLifecycleKey(key)) {} else if (key === "nodeCreated") dv?.({ target: this.el });
2207
+ else if (key === "nodeRemoved") {
2208
+ if (ls) throw TypeError("nodeRemoved cannot be a reactive State");
2209
+ target.addCleanup(dv);
2210
+ } else if (key === "nodeInserted") {
2211
+ const callback = dv;
2212
+ if (this.ctx?.md === 1) callback?.({ target: this.el });
2213
+ else if (callback) this.deferUntilConnected(() => callback({ target: this.el }));
2214
+ }
2215
+ if (key === "autofocus" && dv && this.ctx?.md === 0) this.deferUntilConnected(() => this.el.focus());
2216
+ return ls;
2217
+ }
2218
+ deferUntilConnected(fn) {
2219
+ const el = this.el;
2220
+ StateController.registerPendingCall(() => {
2221
+ if (el.isConnected) fn();
2222
+ });
2223
+ }
2224
+ };
2225
+ ElementController.prototype.flg = 4;
2226
+ //#endregion
2227
+ //#region src/DOM/nodeControllers/SVGElementController.ts
2228
+ var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
2229
+ var SVGElementController = class extends ElementController {
2230
+ makeElement(tagName) {
2231
+ return this.ctx?.md === 2 ? this.ctx.doc.createElement(tagName) : document.createElementNS(SVG_NAMESPACE, tagName);
2232
+ }
2233
+ };
2234
+ //#endregion
2235
+ //#region src/DOM/nodeControllers/ComponentController.ts
2236
+ var ComponentController = class extends NodeController {
2237
+ orValue;
2238
+ renderError;
2239
+ buildNode(properties, namedStates, stateContext) {
2240
+ const target = stateContext;
2241
+ startCapturingStateCalls(namedStates);
2242
+ let args;
2243
+ let captured;
2244
+ try {
2245
+ const componentArgs = {
2246
+ ...properties ?? {},
2247
+ children: this.c,
2248
+ renderError: this.renderError
2249
+ };
2250
+ if (this.orValue && this.def.constructor.name === "AsyncFunction") {
2251
+ const componentPromise = this.def(componentArgs);
2252
+ const delayedComponent = new transforms.PromiseTransform(componentPromise).execute();
2253
+ args = new transforms.FunctionTransform(delayedComponent, orFunction, [delayedComponent, this.orValue]).execute();
2254
+ } else args = this.def(componentArgs);
2255
+ } finally {
2256
+ captured = stopCapturingStateCalls();
2257
+ }
2258
+ const { namedStates: newNamedStates, subscriptions } = captured;
2259
+ subscriptions?.forEach((unsub) => target.addCleanup(unsub));
2260
+ this.parseArgs([args]);
2261
+ return newNamedStates;
2262
+ }
2263
+ or(v) {
2264
+ this.orValue = v;
2265
+ return this;
2266
+ }
2267
+ };
2268
+ ComponentController.prototype.flg = 1;
2269
+ //#endregion
2270
+ //#region src/DOM/nodeControllers/RootController.ts
2271
+ var RootController = class extends NodeController {
2272
+ rootEl;
2273
+ constructor(definition, args) {
2274
+ super(definition, args);
2275
+ if (!isInComponent()) new transforms.DOMRootTransform(this).queue();
2276
+ }
2277
+ buildNode(properties) {
2278
+ const inherited = this.ctx?.md;
2279
+ const mode = properties?.mode;
2280
+ this.ctx = {
2281
+ md: mode === void 0 ? inherited ?? 0 : mode === "render" ? 2 : mode === "hydrate" ? 1 : 0,
2282
+ doc: properties?.doc ?? this.ctx?.doc
2283
+ };
2284
+ const given = properties?.root;
2285
+ if (this.par) {
2286
+ if (inherited === 2) {
2287
+ this.c = [];
2288
+ this.rootEl = this.ctx.doc.createElement("");
2289
+ return;
2290
+ }
2291
+ if (inherited === 1 && mode === void 0) this.ctx.md = 0;
2292
+ }
2293
+ if (this.ctx.md === 2) {
2294
+ if (given) throw Error("render mode does not install into a root - use renderToString()");
2295
+ this.rootEl = this.ctx.doc.createElement("");
2296
+ return;
2297
+ }
2298
+ this.rootEl = given ?? document.body;
2299
+ if (this.ctx.md === 0) this.pnc = liveChildNodeCount(this.rootEl);
2300
+ }
2301
+ getMountElement() {
2302
+ return this.rootEl;
2303
+ }
2304
+ getParallelNodeCount() {
2305
+ return 0;
2306
+ }
2307
+ createRoot() {
2308
+ if (!this.rootEl) this.build();
2309
+ }
2310
+ renderedRoot() {
2311
+ return this.rootEl;
2312
+ }
2313
+ remove() {
2314
+ this.unsubscribeAll();
2315
+ this.removeChildren(true);
2316
+ }
2317
+ };
2318
+ RootController.prototype.flg = 25;
2319
+ //#endregion
2320
+ //#region src/DOM/domFunctions.ts
2321
+ NodeController.setStateController(StateController);
2322
+ NodeController.setComponentController(ComponentController);
2323
+ var component = (definition) => (...args) => new ComponentController(definition, args);
2324
+ var domElement = (elementName) => (...args) => new ElementController(elementName, args);
2325
+ var svgElement = (elementName) => (...args) => new SVGElementController(elementName, args);
2326
+ var SnapseRoot = (...args) => new RootController("", args);
2327
+ //#endregion
2328
+ //#region src/state/compute.ts
2329
+ var compute = (computeFunction) => new transforms.ComputeTransform(computeFunction).execute();
2330
+ //#endregion
2331
+ //#region src/common/undoUtils.ts
2332
+ var decodeAscendingRLE = function* (range) {
2333
+ if (!range) return;
2334
+ let runStart;
2335
+ for (let k = 0; k < range.length; k++) {
2336
+ const v = range[k];
2337
+ if (v < 0) for (let j = runStart + 1; j < -v; j++) yield j;
2338
+ else {
2339
+ runStart = v;
2340
+ yield v;
2341
+ }
2342
+ }
2343
+ };
2344
+ //#endregion
2345
+ //#region src/state/transforms/ChangeAggregateTransform.ts
2346
+ var deepDestate = (value) => {
2347
+ const raw = destate(value);
2348
+ if (isArray(raw)) return raw.map(deepDestate);
2349
+ if (isPOJO(raw)) return Object.fromEntries(Object.entries(raw).map(([k, v]) => [k, deepDestate(v)]));
2350
+ return raw;
2351
+ };
2352
+ var ChangeAggregateTransform = class ChangeAggregateTransform extends Transform {
2353
+ parent;
2354
+ pathKey;
2355
+ changes;
2356
+ containerChildren;
2357
+ leafValues;
2358
+ previousArrayChildren;
2359
+ seq = 0;
2360
+ flg = 1;
2361
+ static forState(ls) {
2362
+ return new ChangeAggregateTransform(ls, void 0, "", [], /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map(), false).tgt;
2363
+ }
2364
+ constructor(source, parent, key, changes, containerChildren, leafValues, addChanges = true) {
2365
+ super(source);
2366
+ this.parent = parent;
2367
+ this.pathKey = key;
2368
+ this.changes = changes;
2369
+ this.containerChildren = containerChildren;
2370
+ this.leafValues = leafValues;
2371
+ this.execute(addChanges);
2372
+ }
2373
+ buildPath(extra) {
2374
+ const segments = extra !== void 0 ? [extra] : [];
2375
+ if (this.parent) segments.unshift(this.pathKey);
2376
+ let node = this.parent;
2377
+ while (node?.parent) {
2378
+ segments.unshift(node.pathKey);
2379
+ node = node.parent;
2380
+ }
2381
+ return segments;
2382
+ }
2383
+ drain() {
2384
+ const records = this.changes.slice();
2385
+ this.changes.length = 0;
2386
+ return records;
2387
+ }
2388
+ execute(addChanges = true) {
2389
+ const sources = acquireSet();
2390
+ sources.add(this.srcLs);
2391
+ const isArray = getStateType(this.srcLs) === 1;
2392
+ const parent = this.srcLs.v;
2393
+ const keys = Object.keys(parent);
2394
+ const currentChildren = [];
2395
+ let childReplaced = false;
2396
+ for (let i = 0; i < keys.length; i++) {
2397
+ const key = keys[i];
2398
+ const childLs = getSubState(this.srcLs, key);
2399
+ if (isArray) {
2400
+ currentChildren.push(childLs);
2401
+ childReplaced ||= this.previousArrayChildren?.[i] !== childLs;
2402
+ }
2403
+ const childType = getStateType(childLs);
2404
+ if (childType === 1 || childType === 2) {
2405
+ let childContainer = this.containerChildren.get(childLs);
2406
+ if (childContainer) {
2407
+ if (isArray) childContainer.pathKey = key;
2408
+ } else {
2409
+ childContainer = new ChangeAggregateTransform(childLs, this, key, this.changes, this.containerChildren, this.leafValues, addChanges && !isArray);
2410
+ this.containerChildren.set(childLs, childContainer);
2411
+ }
2412
+ sources.add(childContainer.tgt);
2413
+ } else {
2414
+ const cur = destate(childLs);
2415
+ const had = this.leafValues.has(childLs);
2416
+ const prev = this.leafValues.get(childLs);
2417
+ if (addChanges && (had && !Object.is(prev, cur) || !had && !isArray)) this.changes.push({
2418
+ "path": this.buildPath(key),
2419
+ "value": cur,
2420
+ "oldValue": prev
2421
+ });
2422
+ this.leafValues.set(childLs, cur);
2423
+ sources.add(childLs);
2424
+ }
2425
+ }
2426
+ if (isArray && (childReplaced || keys.length != this.previousArrayChildren?.length)) this.handleArrayMutation(currentChildren, addChanges);
2427
+ this.updateTarget(this.seq++, sources);
2428
+ releaseSet(sources);
2429
+ }
2430
+ handleArrayMutation(currentChildren, addChanges) {
2431
+ const previousChildren = this.previousArrayChildren ?? [];
2432
+ const mutation = computeMutation(previousChildren, currentChildren);
2433
+ if (addChanges) {
2434
+ const addedValues = [];
2435
+ for (const i of decodeAscendingRLE(mutation.added)) {
2436
+ const ls = currentChildren[i];
2437
+ const containerChild = this.containerChildren.get(ls);
2438
+ addedValues.push(containerChild ? deepDestate(containerChild.srcLs.v) : this.leafValues.get(ls));
2439
+ }
2440
+ const removedValues = [];
2441
+ for (const i of decodeAscendingRLE(mutation.removed)) {
2442
+ const ls = previousChildren[i];
2443
+ const child = this.containerChildren.get(ls);
2444
+ removedValues.push(child ? deepDestate(child.srcLs.v) : this.leafValues.get(ls));
2445
+ }
2446
+ const record = {
2447
+ "path": this.buildPath(),
2448
+ "reorder": true,
2449
+ "prefixL": mutation.pre,
2450
+ "suffixL": mutation.suf,
2451
+ "addedValues": addedValues,
2452
+ "removedValues": removedValues
2453
+ };
2454
+ if (mutation.removed !== void 0) record["remove"] = mutation.removed;
2455
+ if (mutation.added !== void 0) record["add"] = mutation.added;
2456
+ if (mutation.kept !== void 0) record["common"] = mutation.kept;
2457
+ this.changes.push(record);
2458
+ }
2459
+ for (const i of decodeAscendingRLE(mutation.removed)) {
2460
+ const ls = previousChildren[i];
2461
+ this.containerChildren.delete(ls);
2462
+ this.leafValues.delete(ls);
2463
+ }
2464
+ this.previousArrayChildren = currentChildren;
2465
+ }
2466
+ };
2467
+ //#endregion
2468
+ //#region src/state/transforms/ChangeCallbackTransform.ts
2469
+ var ChangeCallbackTransform = class extends CallbackTransform {
2470
+ execute() {
2471
+ const records = this.srcLs.tf.drain();
2472
+ if (!records.length) return;
2473
+ const v = destate(this.srcLs);
2474
+ for (let i = 0; i < records.length; i++) {
2475
+ if (i === records.length - 1) records[i]["done"] = true;
2476
+ try {
2477
+ this.hookFunction(v, records[i]);
2478
+ } catch (e) {
2479
+ Transform.throwDelayed(e);
2480
+ }
2481
+ }
2482
+ }
2483
+ };
2484
+ //#endregion
2485
+ //#region src/state/subscribeChanges.ts
2486
+ var subscribeChanges = (state, callback) => subscribeWith(state, (ls) => {
2487
+ const target = ChangeAggregateTransform.forState(ls);
2488
+ return [target, new ChangeCallbackTransform(target, callback)];
2489
+ });
2490
+ //#endregion
2491
+ //#region src/undo/undo.ts
2492
+ var flushRun = (out, lo, hi) => {
2493
+ out.push(lo);
2494
+ if (hi > lo) out.push(-1 - hi);
2495
+ };
2496
+ var encodeAscendingRLE = (values) => {
2497
+ const out = [];
2498
+ let lo = -1;
2499
+ let hi = -2;
2500
+ for (const v of values) {
2501
+ if (v < 0) return values;
2502
+ if (v !== hi + 1) {
2503
+ if (lo >= 0) flushRun(out, lo, hi);
2504
+ lo = v;
2505
+ }
2506
+ hi = v;
2507
+ }
2508
+ flushRun(out, lo, hi);
2509
+ return out;
2510
+ };
2511
+ var stripDefaults = (change) => {
2512
+ for (const k in change) {
2513
+ if (k === "value" || k === "oldValue") continue;
2514
+ const v = change[k];
2515
+ if (!v || isArray(v) && v.length === 0) delete change[k];
2516
+ }
2517
+ };
2518
+ var TrackHistory = class {
2519
+ tracked;
2520
+ opts;
2521
+ undoStack = [];
2522
+ redoStack = [];
2523
+ batch = [];
2524
+ applying = false;
2525
+ batching = false;
2526
+ unsub;
2527
+ undoEmpty;
2528
+ redoEmpty;
2529
+ historyVersions;
2530
+ onChange = (_v, change) => {
2531
+ if (this.applying || !change) return;
2532
+ stripDefaults(change);
2533
+ if (change.common) change.common = encodeAscendingRLE(change.common);
2534
+ if (this.batch.length === 0 && this.redoStack.length) {
2535
+ this.redoStack.length = 0;
2536
+ this.updateDerivedState();
2537
+ }
2538
+ this.batch.push(change);
2539
+ if (this.batching || !change.done) return;
2540
+ this.finalizeBatch();
2541
+ };
2542
+ finalizeBatch() {
2543
+ if (!this.batch.length) return;
2544
+ this.undoStack.push({
2545
+ batch: this.batch,
2546
+ t: this.opts?.addHistoryVersion?.() ?? Date.now()
2547
+ });
2548
+ if (this.opts?.limit && this.undoStack.length > this.opts.limit) this.undoStack.shift();
2549
+ this.batch = [];
2550
+ this.updateDerivedState();
2551
+ }
2552
+ updateDerivedState() {
2553
+ this.undoEmpty.set(this.undoStack.length === 0);
2554
+ this.redoEmpty.set(this.redoStack.length === 0);
2555
+ this.historyVersions.set(this.undoStack.map((entry) => entry.t));
2556
+ }
2557
+ constructor(root, opts) {
2558
+ this.tracked = root;
2559
+ this.opts = opts;
2560
+ this.undoEmpty = state(true);
2561
+ this.redoEmpty = state(true);
2562
+ this.historyVersions = state([]);
2563
+ this.unsub = subscribeChanges(root, this.onChange);
2564
+ }
2565
+ walkToNode(path = []) {
2566
+ let node = this.tracked;
2567
+ for (const key of path) node = node[key];
2568
+ return node;
2569
+ }
2570
+ applyReorder(parent, change, forward) {
2571
+ const src = peek(parent);
2572
+ const uncompactedSrc = forward ? void 0 : src.slice();
2573
+ const addValues = forward ? change.addedValues : change.removedValues;
2574
+ const remove = forward ? change.remove : change.add;
2575
+ const removedCount = (forward ? change.removedValues : change.addedValues)?.length ?? 0;
2576
+ const afterLength = src.length - removedCount + (addValues?.length ?? 0);
2577
+ const prefixL = change.prefixL ?? 0;
2578
+ const suffixL = change.suffixL ?? 0;
2579
+ const rle = decodeAscendingRLE(remove);
2580
+ let skip = rle.next().value;
2581
+ let j = 0;
2582
+ for (let i = 0; i < src.length; i++) {
2583
+ while (i < (skip ?? src.length)) src[j++] = src[i++];
2584
+ skip = rle.next().value;
2585
+ }
2586
+ const keptLength = j;
2587
+ let out = [];
2588
+ if (change.common) {
2589
+ for (let p = 0; p < prefixL; p++) out[p] = src[p];
2590
+ let mid = prefixL;
2591
+ if (forward) for (const i of decodeAscendingRLE(change.common)) out[i] = src[mid++];
2592
+ else for (const i of decodeAscendingRLE(change.common)) out[mid++] = uncompactedSrc[i];
2593
+ const suffixStart = forward ? afterLength - suffixL : mid;
2594
+ for (let s = 0; s < suffixL; s++) out[suffixStart + s] = src[keptLength - suffixL + s];
2595
+ } else out = src.slice();
2596
+ j = 0;
2597
+ if (forward && change.common) for (const i of decodeAscendingRLE(change.add)) out[i] = addValues[j++];
2598
+ else {
2599
+ const spliceAt = decodeAscendingRLE(forward ? change.add : change.remove);
2600
+ for (const i of spliceAt) out.splice(i, 0, addValues[j++]);
2601
+ }
2602
+ out.length = afterLength;
2603
+ parent.set(out);
2604
+ }
2605
+ applyChange(change, forward) {
2606
+ if (change.reorder) return this.applyReorder(this.walkToNode(change.path), change, forward);
2607
+ const path = change.path;
2608
+ const parent = this.walkToNode(path.slice(0, -1));
2609
+ const key = path[path.length - 1];
2610
+ parent[key] = forward ? change.value : change.oldValue;
2611
+ }
2612
+ replay(entry, forward) {
2613
+ this.applying = true;
2614
+ if (forward) for (const change of entry.batch) this.applyChange(change, true);
2615
+ else for (let i = entry.batch.length - 1; i >= 0; i--) this.applyChange(entry.batch[i], false);
2616
+ flush();
2617
+ this.applying = false;
2618
+ }
2619
+ undo = () => {
2620
+ const entry = this.undoStack.pop();
2621
+ if (!entry) return false;
2622
+ this.replay(entry, false);
2623
+ this.redoStack.push(entry);
2624
+ this.updateDerivedState();
2625
+ return true;
2626
+ };
2627
+ redo = () => {
2628
+ const entry = this.redoStack.pop();
2629
+ if (!entry) return false;
2630
+ this.replay(entry, true);
2631
+ this.undoStack.push(entry);
2632
+ this.updateDerivedState();
2633
+ return true;
2634
+ };
2635
+ restoreAt(timestamp) {
2636
+ while (this.undoStack.length && this.undoStack[this.undoStack.length - 1].t > timestamp) {
2637
+ const entry = this.undoStack.pop();
2638
+ this.replay(entry, false);
2639
+ this.redoStack.push(entry);
2640
+ }
2641
+ while (this.redoStack.length && this.redoStack[this.redoStack.length - 1].t <= timestamp) {
2642
+ const entry = this.redoStack.pop();
2643
+ this.replay(entry, true);
2644
+ this.undoStack.push(entry);
2645
+ }
2646
+ this.updateDerivedState();
2647
+ }
2648
+ startBatch() {
2649
+ this.batching = true;
2650
+ }
2651
+ commitBatch() {
2652
+ this.batching = false;
2653
+ this.finalizeBatch();
2654
+ }
2655
+ getHistory() {
2656
+ return [...this.undoStack];
2657
+ }
2658
+ setHistory(history) {
2659
+ this.undoStack.length = 0;
2660
+ this.undoStack.push(...history);
2661
+ this.redoStack.length = 0;
2662
+ this.updateDerivedState();
2663
+ }
2664
+ unsubscribe() {
2665
+ this.unsub();
2666
+ }
2667
+ };
2668
+ //#endregion
2669
+ //#region src/DOM/elements/DOMElements.ts
2670
+ function inputFactory(...args) {
2671
+ return new ElementController("input", args);
2672
+ }
2673
+ var a$1 = domElement("a");
2674
+ var abbr = domElement("abbr");
2675
+ var address = domElement("address");
2676
+ var area = domElement("area");
2677
+ var article = domElement("article");
2678
+ var aside = domElement("aside");
2679
+ var audio = domElement("audio");
2680
+ var b = domElement("b");
2681
+ var base = domElement("base");
2682
+ var bdi = domElement("bdi");
2683
+ var bdo = domElement("bdo");
2684
+ var blockquote = domElement("blockquote");
2685
+ var body = domElement("body");
2686
+ var br = domElement("br");
2687
+ var button = domElement("button");
2688
+ var canvas = domElement("canvas");
2689
+ var caption = domElement("caption");
2690
+ var cite = domElement("cite");
2691
+ var code = domElement("code");
2692
+ var col = domElement("col");
2693
+ var colgroup = domElement("colgroup");
2694
+ var data = domElement("data");
2695
+ var datalist = domElement("datalist");
2696
+ var dd = domElement("dd");
2697
+ var del = domElement("del");
2698
+ var details = domElement("details");
2699
+ var dfn = domElement("dfn");
2700
+ var dialog = domElement("dialog");
2701
+ var div = domElement("div");
2702
+ var dl = domElement("dl");
2703
+ var dt = domElement("dt");
2704
+ var em = domElement("em");
2705
+ var embed = domElement("embed");
2706
+ var fieldset = domElement("fieldset");
2707
+ var figcaption = domElement("figcaption");
2708
+ var figure = domElement("figure");
2709
+ var footer = domElement("footer");
2710
+ var form = domElement("form");
2711
+ var h1 = domElement("h1");
2712
+ var h2 = domElement("h2");
2713
+ var h3 = domElement("h3");
2714
+ var h4 = domElement("h4");
2715
+ var h5 = domElement("h5");
2716
+ var h6 = domElement("h6");
2717
+ var head = domElement("head");
2718
+ var header = domElement("header");
2719
+ var hgroup = domElement("hgroup");
2720
+ var hr = domElement("hr");
2721
+ var html = domElement("html");
2722
+ var i = domElement("i");
2723
+ var iframe = domElement("iframe");
2724
+ var img = domElement("img");
2725
+ var input = inputFactory;
2726
+ var ins = domElement("ins");
2727
+ var kbd = domElement("kbd");
2728
+ var label = domElement("label");
2729
+ var legend = domElement("legend");
2730
+ var li = domElement("li");
2731
+ var link = domElement("link");
2732
+ var main = domElement("main");
2733
+ var map = domElement("map");
2734
+ var mark = domElement("mark");
2735
+ var menu = domElement("menu");
2736
+ var meta = domElement("meta");
2737
+ var meter = domElement("meter");
2738
+ var nav = domElement("nav");
2739
+ var noscript = domElement("noscript");
2740
+ var object = domElement("object");
2741
+ var ol = domElement("ol");
2742
+ var optgroup = domElement("optgroup");
2743
+ var option = domElement("option");
2744
+ var output = domElement("output");
2745
+ var p = domElement("p");
2746
+ var picture = domElement("picture");
2747
+ var pre = domElement("pre");
2748
+ var progress = domElement("progress");
2749
+ var q = domElement("q");
2750
+ var rp = domElement("rp");
2751
+ var rt = domElement("rt");
2752
+ var ruby = domElement("ruby");
2753
+ var s = domElement("s");
2754
+ var samp = domElement("samp");
2755
+ var script$1 = domElement("script");
2756
+ var search = domElement("search");
2757
+ var section = domElement("section");
2758
+ var select = domElement("select");
2759
+ var slot = domElement("slot");
2760
+ var small = domElement("small");
2761
+ var source = domElement("source");
2762
+ var span = domElement("span");
2763
+ var strong = domElement("strong");
2764
+ var style$1 = domElement("style");
2765
+ var sub = domElement("sub");
2766
+ var summary = domElement("summary");
2767
+ var sup = domElement("sup");
2768
+ var table = domElement("table");
2769
+ var tbody = domElement("tbody");
2770
+ var td = domElement("td");
2771
+ var template = domElement("template");
2772
+ var textarea = domElement("textarea");
2773
+ var tfoot = domElement("tfoot");
2774
+ var th = domElement("th");
2775
+ var thead = domElement("thead");
2776
+ var time = domElement("time");
2777
+ var title$1 = domElement("title");
2778
+ var tr = domElement("tr");
2779
+ var track = domElement("track");
2780
+ var u = domElement("u");
2781
+ var ul = domElement("ul");
2782
+ var cvar = domElement("var");
2783
+ var video = domElement("video");
2784
+ var wbr = domElement("wbr");
2785
+ //#endregion
2786
+ //#region src/DOM/elements/SVGElements.ts
2787
+ var a = svgElement("a");
2788
+ var animate = svgElement("animate");
2789
+ var animateMotion = svgElement("animateMotion");
2790
+ var animateTransform = svgElement("animateTransform");
2791
+ var circle = svgElement("circle");
2792
+ var clipPath = svgElement("clipPath");
2793
+ var defs = svgElement("defs");
2794
+ var desc = svgElement("desc");
2795
+ var ellipse = svgElement("ellipse");
2796
+ var feBlend = svgElement("feBlend");
2797
+ var feColorMatrix = svgElement("feColorMatrix");
2798
+ var feComponentTransfer = svgElement("feComponentTransfer");
2799
+ var feComposite = svgElement("feComposite");
2800
+ var feConvolveMatrix = svgElement("feConvolveMatrix");
2801
+ var feDiffuseLighting = svgElement("feDiffuseLighting");
2802
+ var feDisplacementMap = svgElement("feDisplacementMap");
2803
+ var feDistantLight = svgElement("feDistantLight");
2804
+ var feDropShadow = svgElement("feDropShadow");
2805
+ var feFlood = svgElement("feFlood");
2806
+ var feFuncA = svgElement("feFuncA");
2807
+ var feFuncB = svgElement("feFuncB");
2808
+ var feFuncG = svgElement("feFuncG");
2809
+ var feFuncR = svgElement("feFuncR");
2810
+ var feGaussianBlur = svgElement("feGaussianBlur");
2811
+ var feImage = svgElement("feImage");
2812
+ var feMerge = svgElement("feMerge");
2813
+ var feMergeNode = svgElement("feMergeNode");
2814
+ var feMorphology = svgElement("feMorphology");
2815
+ var feOffset = svgElement("feOffset");
2816
+ var fePointLight = svgElement("fePointLight");
2817
+ var feSpecularLighting = svgElement("feSpecularLighting");
2818
+ var feSpotLight = svgElement("feSpotLight");
2819
+ var feTile = svgElement("feTile");
2820
+ var feTurbulence = svgElement("feTurbulence");
2821
+ var filter = svgElement("filter");
2822
+ var foreignObject = svgElement("foreignObject");
2823
+ var g = svgElement("g");
2824
+ var image = svgElement("image");
2825
+ var line = svgElement("line");
2826
+ var linearGradient = svgElement("linearGradient");
2827
+ var marker = svgElement("marker");
2828
+ var mask = svgElement("mask");
2829
+ var metadata = svgElement("metadata");
2830
+ var mpath = svgElement("mpath");
2831
+ var path = svgElement("path");
2832
+ var pattern = svgElement("pattern");
2833
+ var polygon = svgElement("polygon");
2834
+ var polyline = svgElement("polyline");
2835
+ var radialGradient = svgElement("radialGradient");
2836
+ var rect = svgElement("rect");
2837
+ var script = svgElement("script");
2838
+ var set = svgElement("set");
2839
+ var stop = svgElement("stop");
2840
+ var style = svgElement("style");
2841
+ var svg = svgElement("svg");
2842
+ var cswitch = svgElement("switch");
2843
+ var symbol = svgElement("symbol");
2844
+ var text = svgElement("text");
2845
+ var textPath = svgElement("textPath");
2846
+ var title = svgElement("title");
2847
+ var tspan = svgElement("tspan");
2848
+ var use = svgElement("use");
2849
+ var view = svgElement("view");
2850
+ //#endregion
2851
+ //#region src/DOM/server/serverNodes.ts
2852
+ var ELEMENT_NODE = 1;
2853
+ var TEXT_NODE = 3;
2854
+ var COMMENT_NODE = 8;
2855
+ var ServerNode = class {
2856
+ parentNode;
2857
+ remove() {
2858
+ this.parentNode?.removeChild(this);
2859
+ }
2860
+ };
2861
+ var CharacterDataNode = class extends ServerNode {
2862
+ data;
2863
+ constructor(data) {
2864
+ super();
2865
+ this.data = data;
2866
+ }
2867
+ get textContent() {
2868
+ return this.data;
2869
+ }
2870
+ set textContent(value) {
2871
+ this.data = String(value);
2872
+ }
2873
+ };
2874
+ var ServerText = class extends CharacterDataNode {
2875
+ get nodeType() {
2876
+ return TEXT_NODE;
2877
+ }
2878
+ };
2879
+ var ServerComment = class extends CharacterDataNode {
2880
+ get nodeType() {
2881
+ return COMMENT_NODE;
2882
+ }
2883
+ };
2884
+ var ServerStyle = class {
2885
+ el;
2886
+ props = /* @__PURE__ */ new Map();
2887
+ constructor(el) {
2888
+ this.el = el;
2889
+ }
2890
+ setProperty(name, value) {
2891
+ if (value == null || value === "") this.props.delete(name);
2892
+ else this.props.set(name, String(value));
2893
+ let text = "";
2894
+ for (const [k, v] of this.props) text += `${text ? " " : ""}${k}: ${v};`;
2895
+ if (text) this.el.attrs.set("style", text);
2896
+ else this.el.attrs.delete("style");
2897
+ }
2898
+ };
2899
+ var ServerElement = class extends ServerNode {
2900
+ tagName;
2901
+ attrs = /* @__PURE__ */ new Map();
2902
+ childNodes = [];
2903
+ style;
2904
+ html;
2905
+ constructor(tagName) {
2906
+ super();
2907
+ this.tagName = tagName;
2908
+ this.style = new ServerStyle(this);
2909
+ }
2910
+ get nodeType() {
2911
+ return ELEMENT_NODE;
2912
+ }
2913
+ setAttribute(name, value) {
2914
+ this.attrs.set(name, String(value));
2915
+ }
2916
+ removeAttribute(name) {
2917
+ this.attrs.delete(name);
2918
+ }
2919
+ set innerHTML(markup) {
2920
+ this.html = String(markup);
2921
+ this.childNodes.length = 0;
2922
+ }
2923
+ insertBefore(node, ref) {
2924
+ const at = ref ? this.childNodes.indexOf(ref) : -1;
2925
+ if (at < 0) this.childNodes.push(node);
2926
+ else this.childNodes.splice(at, 0, node);
2927
+ if (node instanceof ServerNode) node.parentNode = this;
2928
+ return node;
2929
+ }
2930
+ removeChild(node) {
2931
+ const at = this.childNodes.indexOf(node);
2932
+ if (at >= 0) this.childNodes.splice(at, 1);
2933
+ if (node instanceof ServerNode && node.parentNode === this) node.parentNode = void 0;
2934
+ return node;
2935
+ }
2936
+ };
2937
+ var serverDocument = {
2938
+ createElement: (tagName) => new ServerElement(tagName),
2939
+ createTextNode: (data) => new ServerText(data),
2940
+ createComment: (data) => new ServerComment(data)
2941
+ };
2942
+ //#endregion
2943
+ //#region src/DOM/server/serialize.ts
2944
+ var voidElements;
2945
+ var isVoidElement = (tag) => (voidElements ??= /* @__PURE__ */ new Set([
2946
+ "area",
2947
+ "base",
2948
+ "br",
2949
+ "col",
2950
+ "embed",
2951
+ "hr",
2952
+ "img",
2953
+ "input",
2954
+ "link",
2955
+ "meta",
2956
+ "source",
2957
+ "track",
2958
+ "wbr"
2959
+ ])).has(tag);
2960
+ var escapeText = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\u00A0/g, "&nbsp;");
2961
+ var escapeAttribute = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\u00A0/g, "&nbsp;");
2962
+ var serializeNode = (node, out) => {
2963
+ if (node instanceof ServerElement) {
2964
+ const tag = node.tagName;
2965
+ out.push(`<${tag}`);
2966
+ for (const [name, value] of node.attrs) out.push(` ${name}="${escapeAttribute(value)}"`);
2967
+ out.push(">");
2968
+ if (isVoidElement(tag)) return;
2969
+ serializeContent(node, out);
2970
+ out.push(`</${tag}>`);
2971
+ } else if (node instanceof ServerComment) out.push(`<!--${node.data}-->`);
2972
+ else if (node instanceof ServerText) out.push(escapeText(node.data));
2973
+ else {
2974
+ const real = node;
2975
+ if (real.nodeType === 1) out.push(real.outerHTML);
2976
+ else if (real.nodeType === 8) out.push(`<!--${real.data}-->`);
2977
+ else out.push(escapeText(real.data));
2978
+ }
2979
+ };
2980
+ var serializeContent = (el, out) => {
2981
+ if (el.html !== void 0) out.push(el.html);
2982
+ else for (const child of el.childNodes) serializeNode(child, out);
2983
+ };
2984
+ var serializeChildren = (el) => {
2985
+ const out = [];
2986
+ serializeContent(el, out);
2987
+ return out.join("");
2988
+ };
2989
+ //#endregion
2990
+ //#region src/server.ts
2991
+ var renderToString = (...children) => {
2992
+ const root = new RootController("", [{
2993
+ mode: "render",
2994
+ doc: serverDocument
2995
+ }, ...children]);
2996
+ flush();
2997
+ return serializeChildren(root.renderedRoot());
2998
+ };
2999
+ //#endregion
3000
+ export { script as $, table as $n, h4 as $t, feMorphology as A, p as An, col as At, image as B, script$1 as Bn, div as Bt, feFuncB as C, nav as Cn, isState as Cr, body as Ct, feImage as D, optgroup as Dn, flush as Dr, caption as Dt, feGaussianBlur as E, ol as En, subscribe as Er, canvas as Et, feTile as F, rp as Fn, dd as Ft, metadata as G, small as Gn, fieldset as Gt, linearGradient as H, section as Hn, dt as Ht, feTurbulence as I, rt as In, del as It, pattern as J, strong as Jn, footer as Jt, mpath as K, source as Kn, figcaption as Kt, filter as L, ruby as Ln, details as Lt, fePointLight as M, pre as Mn, cvar as Mt, feSpecularLighting as N, progress as Nn, data as Nt, feMerge as O, option as On, cite as Ot, feSpotLight as P, q as Pn, datalist as Pt, rect as Q, sup as Qn, h3 as Qt, foreignObject as R, s as Rn, dfn as Rt, feFuncA as S, meter as Sn, findState as Sr, blockquote as St, feFuncR as T, object as Tn, state as Tr, button as Tt, marker as U, select as Un, em as Ut, line as V, search as Vn, dl as Vt, mask as W, slot as Wn, embed as Wt, polyline as X, sub as Xn, h1 as Xt, polygon as Y, style$1 as Yn, form as Yt, radialGradient as Z, summary as Zn, h2 as Zt, feDiffuseLighting as _, main as _n, SnapseRoot as _r, audio as _t, animateTransform as a, hr as an, th as ar, text as at, feDropShadow as b, menu as bn, svgElement as br, bdi as bt, cswitch as c, iframe as cn, title$1 as cr, tspan as ct, ellipse as d, ins as dn, u as dr, a$1 as dt, h5 as en, tbody as er, set as et, feBlend as f, kbd as fn, ul as fr, abbr as ft, feConvolveMatrix as g, link as gn, compute as gr, aside as gt, feComposite as h, li as hn, TrackHistory as hr, article as ht, animateMotion as i, hgroup as in, tfoot as ir, symbol as it, feOffset as j, picture as jn, colgroup as jt, feMergeNode as k, output as kn, code as kt, defs as l, img as ln, tr as lr, use as lt, feComponentTransfer as m, legend as mn, wbr as mr, area as mt, a as n, head as nn, template as nr, style as nt, circle as o, html as on, thead as or, textPath as ot, feColorMatrix as p, label as pn, video as pr, address as pt, path as q, span as qn, figure as qt, animate as r, header as rn, textarea as rr, svg as rt, clipPath as s, i as sn, time as sr, title as st, renderToString as t, h6 as tn, td as tr, stop as tt, desc as u, input as un, track as ur, view as ut, feDisplacementMap as v, map as vn, component as vr, b as vt, feFuncG as w, noscript as wn, peek as wr, br as wt, feFlood as x, meta as xn, CircularDependencyError as xr, bdo as xt, feDistantLight as y, mark as yn, domElement as yr, base as yt, g as z, samp as zn, dialog as zt };
3001
+
3002
+ //# sourceMappingURL=snapseCore-DpadpXgD.js.map