@the-w1zard/the-cloud 1.0.2 → 1.0.4

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 (43) hide show
  1. package/dist/index.js +25850 -8
  2. package/package.json +12 -4
  3. package/dist/hooks/callback.d.ts +0 -1
  4. package/dist/hooks/callback.js +0 -13
  5. package/dist/hooks/compose-event-handlers.d.ts +0 -10
  6. package/dist/hooks/compose-event-handlers.js +0 -10
  7. package/dist/hooks/core/index.d.ts +0 -1
  8. package/dist/hooks/core/index.js +0 -1
  9. package/dist/hooks/core/use-id.d.ts +0 -1
  10. package/dist/hooks/core/use-id.js +0 -4
  11. package/dist/hooks/core/use-reducer.d.ts +0 -1
  12. package/dist/hooks/core/use-reducer.js +0 -14
  13. package/dist/hooks/core/use-ref.d.ts +0 -92
  14. package/dist/hooks/core/use-ref.js +0 -559
  15. package/dist/hooks/core/use-state2.d.ts +0 -1
  16. package/dist/hooks/core/use-state2.js +0 -15
  17. package/dist/hooks/deferred_value.d.ts +0 -1
  18. package/dist/hooks/deferred_value.js +0 -12
  19. package/dist/hooks/effect.d.ts +0 -1
  20. package/dist/hooks/effect.js +0 -37
  21. package/dist/hooks/hooks.d.ts +0 -1
  22. package/dist/hooks/hooks.js +0 -1
  23. package/dist/hooks/impertaive_handle.d.ts +0 -3
  24. package/dist/hooks/impertaive_handle.js +0 -24
  25. package/dist/hooks/index.d.ts +0 -1
  26. package/dist/hooks/index.js +0 -4
  27. package/dist/hooks/init_hooks.d.ts +0 -285
  28. package/dist/hooks/init_hooks.js +0 -285
  29. package/dist/hooks/lazy.d.ts +0 -3
  30. package/dist/hooks/lazy.js +0 -15
  31. package/dist/hooks/memo.d.ts +0 -2
  32. package/dist/hooks/memo.js +0 -44
  33. package/dist/hooks/rect.d.ts +0 -24
  34. package/dist/hooks/rect.js +0 -77
  35. package/dist/hooks/state.d.ts +0 -1
  36. package/dist/hooks/state.js +0 -34
  37. package/dist/hooks/suspense.d.ts +0 -4
  38. package/dist/hooks/suspense.js +0 -10
  39. package/dist/hooks/types.d.ts +0 -25
  40. package/dist/hooks/types.js +0 -1
  41. package/dist/index.d.ts +0 -8
  42. package/dist/the-cloud.d.ts +0 -406
  43. package/dist/the-cloud.js +0 -1386
package/dist/the-cloud.js DELETED
@@ -1,1386 +0,0 @@
1
- // IMPORTS
2
- // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════
3
- import store from "#STR";
4
- import { BYTE_ID } from "#HPR";
5
- import { TIERED_QUEUE } from "#SS";
6
- const __sid = new BYTE_ID();
7
- export function _sidi() {
8
- return __sid.b();
9
- }
10
- // #endregion
11
- // SAURON
12
- // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════
13
- const queues = {
14
- immediate: new Map(), 'user-blocking': new Map(), normal: new Map(), background: new Map(), idle: new Map()
15
- };
16
- class SAURON {
17
- root;
18
- constructor(root = null) {
19
- this.root = root;
20
- this.r = root.r;
21
- this.s = root.s;
22
- this.m = root.m;
23
- this.k = root.k;
24
- }
25
- online = false;
26
- r = 'THE_WIZARD_ROOT_REG';
27
- m = 'SAURON_MASTER_REG';
28
- s = "__SAURON__";
29
- k = "__SAURON__";
30
- u = undefined;
31
- uuuu = [this.u, this.u, this.u, this.u];
32
- UUUU = [this.s, this.m, this.r];
33
- uuu = [this.u, this.u, this.u];
34
- UUU = [this.s, this.m, this.r];
35
- uu = [this.u, this.u];
36
- UU = [this.m, this.r];
37
- _localChange = false;
38
- _channel = null;
39
- init_hooks_context = false;
40
- batchDepth = 0;
41
- openScopes = new Set();
42
- dirty = new Set();
43
- _flushScheduled = false;
44
- _adapter = null;
45
- _currentHookState = null;
46
- _currentComponent = null;
47
- PRIORITY_ORDER = ["immediate", "user-blocking", "normal", "background", "idle"];
48
- GLOBAL_SCOPE = Symbol("global-scope");
49
- scopeCursors = { immediate: 0, "user-blocking": 0, normal: 0, background: 0, idle: 0 };
50
- currentScope = this.GLOBAL_SCOPE;
51
- loopScheduled = false;
52
- _subscribers = new Map();
53
- __subscribers = new Map();
54
- _externalSubscribers = new Map();
55
- _components = new Map();
56
- _pendingNotifications = new Set();
57
- externalSubscribers = new Set();
58
- instanceId = `instance_${Date.now()}_${Math.random().toString(36).slice(2)}`;
59
- _root = {
60
- id: store.get('THE_WIZARD_ROOT_REG') ?? 'THE_WIZARD_ROOT_REG',
61
- hooks: new Map(),
62
- unmount: new Set(),
63
- contextProviders: new Map()
64
- };
65
- FULFIL_THIS_SAURON_DEPOT(r) {
66
- this.root = r;
67
- }
68
- getNestedMap(s = this.s, m = this.m, r = this.r) {
69
- let root = globalThis[r]; // STATE_CONTEXT === "sauron" ? : null;
70
- if (!root) {
71
- root = new Map();
72
- globalThis[r] = root;
73
- }
74
- let masterMap = root.get(m);
75
- if (!masterMap) {
76
- masterMap = new Map();
77
- root.set(m, masterMap);
78
- }
79
- let slaveMap = masterMap.get(s);
80
- if (!slaveMap) {
81
- slaveMap = new Map();
82
- masterMap.set(s, slaveMap);
83
- }
84
- return slaveMap;
85
- }
86
- getMetadata(s = this.s, m = this.m, r = this.r) {
87
- let root = globalThis[r]; // STATE_CONTEXT === "sauron" ? : null;
88
- if (!root) {
89
- root = new Map();
90
- globalThis[r] = root;
91
- }
92
- let masterMap = root.get(m);
93
- if (!masterMap) {
94
- masterMap = new Map();
95
- root.set(m, masterMap);
96
- }
97
- let metaMap = masterMap.get(s);
98
- if (!metaMap) {
99
- metaMap = {
100
- _batches: new Set(),
101
- _batchQueue: new Map(),
102
- _batchOpts: new Map(),
103
- _history: new Map(),
104
- _timeTravel: new Map(),
105
- _globalListeners: new Set(),
106
- _global_subscribers: new Map(),
107
- _waiters: new Map(),
108
- _sys: new Map(),
109
- _sealed: new Set(),
110
- _frozen: new Set(),
111
- _keyContracts: new Map(),
112
- _conflicts: new Map(),
113
- _conflictStrategies: new Map(),
114
- _causal: new Map(),
115
- _scopes: new Map(),
116
- _msgHandlers: new Map(),
117
- _lastWriteSource: new Map(),
118
- _mainMap: new Map(),
119
- _tupleCache: new Map(),
120
- _weakMap: new WeakMap(),
121
- _boundaries: new WeakMap(),
122
- };
123
- masterMap.set(s, metaMap);
124
- }
125
- return metaMap;
126
- }
127
- onFlush(cb) {
128
- this.dirty.add(cb);
129
- this.scheduleDrain();
130
- }
131
- scheduleDrain() {
132
- if (this._flushScheduled)
133
- return;
134
- this._flushScheduled = true;
135
- queueMicrotask(this.drain);
136
- }
137
- drain() {
138
- this._flushScheduled = false;
139
- if (this.dirty.size === 0)
140
- return;
141
- // An explicit openBatch() scope is still open (deliberately spanning an await) —
142
- // don't drop the pending callbacks, just wait for closeBatch() to let them through.
143
- if (this.openScopes.size > 0) {
144
- this.scheduleDrain();
145
- return;
146
- }
147
- const callbacks = this.dirty;
148
- this.dirty = new Set();
149
- for (const cb of callbacks)
150
- cb();
151
- }
152
- microtask(fn) {
153
- queueMicrotask(fn);
154
- }
155
- batch(fn) {
156
- this.batchDepth++;
157
- try {
158
- return fn();
159
- }
160
- finally {
161
- this.batchDepth--;
162
- if (this.batchDepth === 0) {
163
- this.flush();
164
- }
165
- }
166
- }
167
- openBatch() {
168
- const scope = Symbol("batch-scope");
169
- this.openScopes.add(scope);
170
- return scope;
171
- }
172
- closeBatch(scope) {
173
- this.openScopes.delete(scope);
174
- if (this.openScopes.size === 0 && this.dirty.size > 0) {
175
- this.scheduleDrain();
176
- }
177
- }
178
- isBatching() {
179
- return this.batchDepth > 0 || this.openScopes.size > 0;
180
- }
181
- flushSync() {
182
- if (this.openScopes.size > 0)
183
- return;
184
- this._flushScheduled = false;
185
- if (this.dirty.size === 0)
186
- return;
187
- const callbacks = this.dirty;
188
- this.dirty = new Set();
189
- for (const cb of callbacks)
190
- cb();
191
- }
192
- flush(fn) {
193
- if (!fn) {
194
- this.flushSync();
195
- return;
196
- }
197
- this.batchDepth++;
198
- let result;
199
- try {
200
- result = fn();
201
- }
202
- finally {
203
- this.batchDepth--;
204
- }
205
- this.flushSync();
206
- return result;
207
- }
208
- enqueue(task) {
209
- if (task.priority === "immediate") {
210
- this.microtask(() => this.runOne(task));
211
- return;
212
- }
213
- const tier = queues[task.priority];
214
- if (!tier.has(task.scope))
215
- tier.set(task.scope, []);
216
- tier.get(task.scope).push(task);
217
- this.scheduleLoop();
218
- }
219
- scheduleLoop() {
220
- if (this.loopScheduled)
221
- return;
222
- this.loopScheduled = true;
223
- setImmediate(this.drainOne);
224
- }
225
- pickNext() {
226
- for (const p of this.PRIORITY_ORDER) {
227
- if (p === "immediate")
228
- continue;
229
- const tier = queues[p];
230
- if (tier.size === 0)
231
- continue;
232
- const scopes = Array.from(tier.keys());
233
- const idx = this.scopeCursors[p] % scopes.length;
234
- const scope = scopes[idx];
235
- const list = tier.get(scope);
236
- const task = list.shift();
237
- if (list.length === 0)
238
- tier.delete(scope);
239
- this.scopeCursors[p] = idx + 1;
240
- return MaybePromise(task);
241
- }
242
- return undefined;
243
- }
244
- runOne(task) {
245
- if (task.cancelled || task.signal?.aborted)
246
- return;
247
- const prev = this.currentScope;
248
- this.currentScope = task.scope;
249
- try {
250
- task.fn();
251
- }
252
- finally {
253
- this.currentScope = prev;
254
- }
255
- }
256
- drainOne() {
257
- this.loopScheduled = false;
258
- const task = this.pickNext();
259
- if (task)
260
- this.runOne(task);
261
- if (Object.values(queues).some((m) => m.size > 0))
262
- this.scheduleLoop();
263
- }
264
- schedule(fn, opts = {}) {
265
- const task = { priority: opts.priority ?? "normal", scope: opts.scope ?? this.currentScope, fn, signal: opts.signal, cancelled: false };
266
- // signals.chains().sc.addEventListener('abort', () => { task.cancelled = true })
267
- this.enqueue(task);
268
- const self = this;
269
- return {
270
- cancel() {
271
- task.cancelled = true;
272
- },
273
- reprioritize(next) {
274
- if (task.cancelled || next === task.priority)
275
- return;
276
- const old = queues[task.priority].get(task.scope);
277
- if (old) {
278
- const i = old.indexOf(task);
279
- if (i !== -1)
280
- old.splice(i, 1);
281
- if (old.length === 0)
282
- queues[task.priority].delete(task.scope);
283
- }
284
- task.priority = next;
285
- self.enqueue(task);
286
- },
287
- };
288
- }
289
- withRequestScope(requestId, fn) {
290
- const prev = this.currentScope;
291
- this.currentScope = requestId;
292
- try {
293
- return fn();
294
- }
295
- finally {
296
- this.currentScope = prev;
297
- }
298
- }
299
- yieldToScheduler() {
300
- return new Promise((resolve) => {
301
- this.schedule(() => resolve(), { priority: "normal", scope: this.currentScope });
302
- });
303
- }
304
- scheduleChunked(work, opts = {}) {
305
- const iterator = Symbol.iterator in work ? work[Symbol.iterator]() : work;
306
- const chunkBudgetMs = opts.chunkBudgetMs ?? 5;
307
- const scope = opts.scope ?? this.currentScope;
308
- let cancelled = false;
309
- let priority = opts.priority ?? "normal";
310
- const self = this;
311
- function runChunk() {
312
- if (cancelled)
313
- return;
314
- const start = performance.now();
315
- while (true) {
316
- const { value: step, done } = iterator.next();
317
- if (done)
318
- return;
319
- step();
320
- const elapsed = performance.now() - start;
321
- if (elapsed >= chunkBudgetMs)
322
- break;
323
- }
324
- if (!cancelled)
325
- self.schedule(runChunk, { priority, scope });
326
- }
327
- this.schedule(runChunk, { priority, scope });
328
- return {
329
- cancel() {
330
- cancelled = true;
331
- },
332
- reprioritize(next) {
333
- priority = next;
334
- },
335
- };
336
- }
337
- // SAURON
338
- _globalNotifyCache = new WeakMap();
339
- _notifyCache = new WeakMap();
340
- scheduleGlobalNotify(key, meta, opts) {
341
- let cache = this._globalNotifyCache.get(meta);
342
- if (!cache) {
343
- cache = new Map();
344
- this._globalNotifyCache.set(meta, cache);
345
- }
346
- let fn = cache.get(key);
347
- if (!fn) {
348
- fn = () => {
349
- cache.delete(key);
350
- const finalVal = this.store.get(key, opts);
351
- const waiters = meta._waiters.get(key);
352
- if (waiters) {
353
- for (const resolveFn of waiters) {
354
- try {
355
- resolveFn(finalVal);
356
- }
357
- catch (err) {
358
- console.error(`[Sauron Waiter Error]:`, err);
359
- }
360
- }
361
- meta._waiters.delete(key);
362
- }
363
- for (const listener of meta._globalListeners) {
364
- try {
365
- listener(key, finalVal);
366
- }
367
- catch (err) {
368
- console.error(`[Sauron Global Listener Error]:`, err);
369
- }
370
- }
371
- };
372
- cache.set(key, fn);
373
- }
374
- this.onFlush(fn);
375
- }
376
- scheduleNotify(key, _listeners, _state) {
377
- let cache = this._notifyCache.get(_listeners);
378
- if (!cache) {
379
- cache = new Map();
380
- this._notifyCache.set(_listeners, cache);
381
- }
382
- let fn = cache.get(key);
383
- if (!fn) {
384
- fn = () => {
385
- cache.delete(key);
386
- const val = _state.get(key);
387
- _listeners.get(key)?.forEach((l) => l(val));
388
- };
389
- cache.set(key, fn);
390
- }
391
- this.onFlush(fn);
392
- }
393
- store = {
394
- get: (key, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
395
- const { sl_reg, ms_reg, globalKey } = opts;
396
- const _state = this.getNestedMap(sl_reg, ms_reg, globalKey);
397
- const _persistent = this.getNestedMap(`${sl_reg}_PERSISTENT`, ms_reg, globalKey);
398
- const _persistKeys = this.getNestedMap(`${sl_reg}_PERSIST_KEYS`, ms_reg, globalKey);
399
- // recordDependency(key)
400
- if (_state.has(key))
401
- return MaybePromise(_state.get(key));
402
- if (_persistKeys.has(key) && _persistent.has(key)) {
403
- const v = _persistent.get(key);
404
- _state.set(key, v);
405
- return MaybePromise(v);
406
- }
407
- return undefined;
408
- },
409
- set: (key, value, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r, triggerRender: true, cap: 200 }) => {
410
- const { triggerRender = true, sl_reg, ms_reg, globalKey, cap } = opts;
411
- const _state = this.getNestedMap(sl_reg, ms_reg, globalKey);
412
- const _persistent = this.getNestedMap(`${sl_reg}_PERSISTENT`, ms_reg, globalKey);
413
- const _persistKeys = this.getNestedMap(`${sl_reg}_PERSIST_KEYS`, ms_reg, globalKey);
414
- const _listeners = this.getNestedMap(`${sl_reg}_LISTENERS`, ms_reg, globalKey);
415
- const prev = _state.get(key);
416
- const next = typeof value === "function" ? value(prev) : value;
417
- if (Object.is(prev, next))
418
- return;
419
- // TIME TRAVEL
420
- if (!this.root.TIME_TRAVEL._time_travel_reverting) {
421
- const meta = this.getMetadata(sl_reg, ms_reg, globalKey);
422
- let hist = meta._history.get(key);
423
- if (!hist) {
424
- hist = [];
425
- meta._history.set(key, hist);
426
- }
427
- const lastActive = hist.findLastIndex((e) => !e.undone) ?? -1;
428
- if (lastActive < hist.length - 1)
429
- hist.length = lastActive + 1; // truncate redo tail
430
- hist.push({ k: (hist[hist.length - 1]?.k ?? 0) + 1, prev, next, ts: Date.now(), undone: false });
431
- const cap_val = cap ?? 200;
432
- while (hist.length > cap_val)
433
- hist.shift();
434
- }
435
- _state.set(key, next);
436
- if (_persistKeys.has(key))
437
- _persistent.set(key, next);
438
- if (triggerRender)
439
- this.scheduleGlobalNotify(key, this.getMetadata(sl_reg, ms_reg, globalKey), opts);
440
- if (triggerRender)
441
- this.scheduleNotify(key, _listeners, _state);
442
- return MaybePromise(next);
443
- },
444
- subscribe: (key, listener, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
445
- const { sl_reg, ms_reg, globalKey } = opts;
446
- const _listeners = this.getNestedMap(`${sl_reg}_LISTENERS`, ms_reg, globalKey);
447
- if (!_listeners.has(key))
448
- _listeners.set(key, new Set());
449
- _listeners.get(key).add(listener);
450
- return () => {
451
- _listeners.get(key)?.delete(listener);
452
- if (_listeners.get(key)?.size === 0)
453
- _listeners.delete(key);
454
- };
455
- },
456
- delete: (key, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
457
- const { sl_reg, ms_reg, globalKey } = opts;
458
- const _state = this.getNestedMap(sl_reg, ms_reg, globalKey);
459
- const _persistent = this.getNestedMap(`${sl_reg}_PERSISTENT`, ms_reg, globalKey);
460
- const _persistKeys = this.getNestedMap(`${sl_reg}_PERSIST_KEYS`, ms_reg, globalKey);
461
- const _listeners = this.getNestedMap(`${sl_reg}_LISTENERS`, ms_reg, globalKey);
462
- const existed = _state.delete(key);
463
- if (_persistKeys.has(key)) {
464
- _persistKeys.delete(key);
465
- _persistent.delete(key);
466
- }
467
- _listeners.get(key)?.forEach((l) => l(undefined));
468
- _listeners.delete(key);
469
- return MaybePromise(existed);
470
- },
471
- entries: (opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
472
- const { sl_reg, ms_reg, globalKey } = opts;
473
- const _state = this.getNestedMap(sl_reg, ms_reg, globalKey);
474
- return MaybePromise(Array.from(_state.entries()));
475
- },
476
- persist: (key, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
477
- const { sl_reg, ms_reg, globalKey } = opts;
478
- const _persistKeys = this.getNestedMap(`${sl_reg}_PERSIST_KEYS`, ms_reg, globalKey);
479
- _persistKeys.set(key, true);
480
- },
481
- unpersist: (key, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
482
- const { sl_reg, ms_reg, globalKey } = opts;
483
- const _persistent = this.getNestedMap(`${sl_reg}_PERSISTENT`, ms_reg, globalKey);
484
- const _persistKeys = this.getNestedMap(`${sl_reg}_PERSIST_KEYS`, ms_reg, globalKey);
485
- _persistKeys.delete(key);
486
- _persistent.delete(key);
487
- },
488
- has: (key, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
489
- const { sl_reg, ms_reg, globalKey } = opts;
490
- const _state = this.getNestedMap(sl_reg, ms_reg, globalKey);
491
- const _persistent = this.getNestedMap(`${sl_reg}_PERSISTENT`, ms_reg, globalKey);
492
- const _persistKeys = this.getNestedMap(`${sl_reg}_PERSIST_KEYS`, ms_reg, globalKey);
493
- return _state.has(key) || (_persistKeys.has(key) && _persistent.has(key));
494
- },
495
- clear: (opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
496
- const { sl_reg, ms_reg, globalKey } = opts;
497
- const _state = this.getNestedMap(sl_reg, ms_reg, globalKey);
498
- const _listeners = this.getNestedMap(`${sl_reg}_LISTENERS`, ms_reg, globalKey);
499
- _state.clear();
500
- _listeners.clear();
501
- },
502
- clearPersistent: (opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
503
- const { sl_reg, ms_reg, globalKey } = opts;
504
- const _persistent = this.getNestedMap(`${sl_reg}_PERSISTENT`, ms_reg, globalKey);
505
- const _persistKeys = this.getNestedMap(`${sl_reg}_PERSIST_KEYS`, ms_reg, globalKey);
506
- _persistent.clear();
507
- _persistKeys.clear();
508
- },
509
- _emit: (key, sl_reg = this.s, ms_reg = this.m, globalKey = this.r) => {
510
- const opts = { sl_reg, ms_reg, globalKey };
511
- const _state = this.getNestedMap(sl_reg, ms_reg, globalKey);
512
- const _listeners = this.getNestedMap(`${sl_reg}_LISTENERS`, ms_reg, globalKey);
513
- const meta = this.getMetadata(sl_reg, ms_reg, globalKey);
514
- this.scheduleNotify(key, _listeners, _state);
515
- this.scheduleGlobalNotify(key, meta, opts);
516
- },
517
- };
518
- state = {
519
- get: (key, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
520
- return MaybePromise(this.store.get(key, opts));
521
- },
522
- set: (key, value, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
523
- const { sl_reg, ms_reg, globalKey, triggerRender = true } = opts;
524
- this.store.set(key, value, { triggerRender, sl_reg, ms_reg, globalKey });
525
- return MaybePromise(value);
526
- },
527
- delete: (key, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
528
- const { sl_reg, ms_reg, globalKey } = opts;
529
- const meta = this.getMetadata(sl_reg, ms_reg, globalKey);
530
- const deleted = this.store.delete(key, opts);
531
- if (deleted) {
532
- for (const listener of meta._globalListeners) {
533
- try {
534
- listener(key, undefined);
535
- }
536
- catch (err) {
537
- console.error(`[Sauron Global Listener Error]:`, err);
538
- }
539
- }
540
- }
541
- return deleted;
542
- },
543
- getByPrefix: (prefix, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
544
- return this.store
545
- .entries(opts)
546
- .filter(([key]) => typeof key === "string" && key.startsWith(prefix))
547
- .map(([key, value]) => ({ key: key, value }));
548
- },
549
- getAll: (opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
550
- const result = {};
551
- for (const [key, value] of this.store.entries(opts)) {
552
- result[key] = value;
553
- }
554
- return result;
555
- },
556
- subscribe: (key, listener, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
557
- return this.store.subscribe(key, listener, opts);
558
- },
559
- subscribeAll: (listener, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
560
- const { sl_reg, ms_reg, globalKey } = opts;
561
- const meta = this.getMetadata(sl_reg, ms_reg, globalKey);
562
- meta._globalListeners.add(listener);
563
- return () => {
564
- meta._globalListeners.delete(listener);
565
- };
566
- },
567
- clear: (opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
568
- const { sl_reg, ms_reg, globalKey } = opts;
569
- const meta = this.getMetadata(sl_reg, ms_reg, globalKey);
570
- this.store.clear(opts);
571
- meta._waiters.clear();
572
- meta._globalListeners.clear();
573
- },
574
- waitFor: (key, opts = { sl_reg: this.s, ms_reg: this.m, globalKey: this.r }) => {
575
- const { sl_reg, ms_reg, globalKey } = opts;
576
- const meta = this.getMetadata(sl_reg, ms_reg, globalKey);
577
- // If it already exists, resolve immediately
578
- const existing = this.state.get(key, opts);
579
- if (existing !== undefined)
580
- return Promise.resolve(existing);
581
- return new Promise((resolve) => {
582
- if (!meta._waiters.has(key))
583
- meta._waiters.set(key, new Set());
584
- meta._waiters.get(key).add(resolve);
585
- });
586
- },
587
- };
588
- /** public store2 = (() => {
589
- const sa = {
590
- get: <T = A>(key: SignalKey, opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },) => {
591
- const { s, m, r, } = opts;
592
- const atom = this.root.SIGNALS.create<T>(key, undefined, undefined, s, m, r,) as SIGNAL_CELL;
593
- return atom ? atom.node : undefined;
594
- },
595
- set: <T = A>(key: SignalKey, value: A, opts: { triggerRender?: boolean; cap?: number; source?: string; } & ScopeOptions = { s: this.s, m: this.m, r: this.r, triggerRender: true, cap: 200, },): T | undefined => {
596
- const { triggerRender = true, cap = 200, source = "state.set", s, m, r, } = opts;
597
- const atom = this.root.SIGNALS.create(key, typeof value === "function" ? value() : value, opts, s, m, r,);
598
- atom.historyMax = cap;
599
- const next = atom.write((previous: A) => typeof value === "function" ? (value as (prev: T | undefined) => T)(previous) : value, { source, triggerRender },);
600
- const listeners = this.__subscribers.get(r)?.get(m)?.get(s)?.get(key);
601
- if (listeners) {
602
- for (const listener of listeners) {
603
- try { listener(next); }
604
- catch (error) { console.error(`[Sauron:state.subscribeAll] listener failed for "${String(atom.key)}":`, error,); }
605
- }
606
- }
607
- return MaybePromise(next);
608
- },
609
-
610
- subscribe: <T = A>(key: SignalKey, listener: (value: T) => void, opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): Unsubscribe => {
611
- let msMap = this.__subscribers.get(opts.r);
612
-
613
- if (!msMap) { msMap = new Map(); this.__subscribers.set(opts.r, msMap); }
614
- let slMap = msMap.get(opts.m);
615
- if (!slMap) { slMap = new Map(); msMap.set(opts.m, slMap); }
616
- let keyMap = slMap.get(opts.s);
617
- if (!keyMap) { keyMap = new Map(); slMap.set(opts.s, keyMap); }
618
- let listeners = keyMap.get(key);
619
- if (!listeners) { listeners = new Set(); keyMap.set(key, listeners); }
620
-
621
- listeners.add(listener);
622
-
623
- return () => {
624
- listeners!.delete(listener);
625
- if (listeners!.size === 0) { keyMap!.delete(key); }
626
- if (keyMap!.size === 0) { slMap!.delete(opts.s); }
627
- if (slMap!.size === 0) { msMap!.delete(opts.m); }
628
- if (msMap!.size === 0) { this.__subscribers.delete(opts.r); }
629
- };
630
- },
631
-
632
- delete: (key: SignalKey, opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, }): boolean => {
633
- const { s, m, r } = opts;
634
- const registry = this.root.SIGNALS.atom_reg(s, m, r);
635
- const atom = this.root.SIGNALS.get(key, s, m, r);
636
- if (!atom) return false;
637
- const previous = atom.peek();
638
- const resolvedKey = this.root.SIGNALS.resolveKey(key, s, m, r);
639
- const listeners = this.__subscribers.get(r)?.get(m)?.get(s)?.get(key);
640
- if (listeners) for (const listener of listeners) {
641
- try { listener({ key: atom.key, previous, current: undefined, version: atom.version + 1, timestamp: Date.now(), source: "state.delete" }); }
642
- catch (error) { console.error(`[Sauron:state.delete] listener failed for "${String(key)}":`, error); }
643
- }
644
- const subscribers = this._externalSubscribers.get(r)?.get(m)?.get(s)?.get(key);
645
- if (subscribers) for (const notify of subscribers) {
646
- try { notify(undefined); }
647
- catch (error) { console.error(`[Sauron:state.delete] external subscriber failed for "${String(key)}":`, error); }
648
- }
649
- registry.delete(resolvedKey);
650
- return MaybePromise(true);
651
- },
652
- entries: <T = A>(opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): [SignalKey, T][] => {
653
- const { s, m, r, } = opts;
654
- const registry = this.root.SIGNALS.atom_reg(s, m, r,);
655
- return MaybePromise([...registry.entries()].map(([key, atom]) => [key, atom.read() as T,]),
656
- );
657
- },
658
- persist: (key: SignalKey, opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): void => {
659
- const atom = this.root.SIGNALS.atom_reg(opts.s, opts.m, opts.r,).get(key);
660
- if (!atom) return;
661
- atom.persisted = true;
662
- setSS(String(atom.key), atom.peek(),);
663
- },
664
- unpersist: (key: SignalKey, opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): void => {
665
- const atom = this.root.SIGNALS.get(key, opts.s, opts.m, opts.r,);
666
- if (!atom) return;
667
- atom.persisted = false;
668
- deleteSS(String(atom.key));
669
- },
670
- has: (key: SignalKey, opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): boolean => {
671
- const registry = this.root.SIGNALS.atom_reg(opts.s, opts.m, opts.r,);
672
- const resolvedKey = this.root.SIGNALS.resolveKey(key, opts.s, opts.m, opts.r,);
673
- return registry.has(resolvedKey);
674
- },
675
- clear: (opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): void => {
676
- const registry = this.root.SIGNALS.atom_reg(opts.s, opts.m, opts.r,);
677
- for (const atom of registry.values()) {
678
- for (const notify of atom.externalSubscribers) {
679
- try {
680
- notify();
681
- } catch (error) {
682
- console.error(
683
- `[Sauron:state.clear] external subscriber failed:`,
684
- error,
685
- );
686
- }
687
- }
688
-
689
- atom.listeners.clear();
690
- atom.externalSubscribers.clear();
691
- atom.waiters.clear();
692
- }
693
-
694
- registry.clear();
695
- },
696
- clearPersistent: (opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): void => {
697
- const registry = this.root.SIGNALS.atom_reg(opts.s, opts.m, opts.r,);
698
-
699
- for (const atom of registry.values()) {
700
- if (!atom.persisted) continue;
701
-
702
- atom.persisted = false;
703
- deleteSS(String(atom.key));
704
- }
705
- },
706
- _emit: (key: SignalKey, s = this.s, m = this.m, r = this.r,): void => {
707
- const atom = this.root.SIGNALS.atom_reg(s, m, r,).get('_LISTENERS').get(key);
708
- if (!atom) return;
709
- const value = atom.peek();
710
- for (const listener of atom.listeners) {
711
- listener({ key: atom.key, previous: value, current: value, version: atom.version, timestamp: Date.now(), source: "state.emit", });
712
- }
713
-
714
- for (const notify of atom.externalSubscribers) { notify(); }
715
- },
716
- };
717
- return sa
718
- })();
719
- public state2 = (() => {
720
- const sa = {
721
- get: <T = A>(key: SignalKey, opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): T | undefined => {
722
- return MaybePromise(this.store.get<T>(key, opts) as T);
723
- },
724
- set: <T = A>(key: SignalKey, value: T | ((prev: T | undefined) => T), opts: { triggerRender?: boolean; } & ScopeOptions = { s: this.s, m: this.m, r: this.r, },) => {
725
- this.store.set(key, value, { triggerRender: opts.triggerRender ?? true, s: opts.s, m: opts.m, r: opts.r, source: "state.set", });
726
- return MaybePromise(value as T);
727
- },
728
- delete: (key: SignalKey, opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): boolean => {
729
- return this.store.delete(key, opts);
730
- },
731
- getByPrefix: <T = A>(prefix: string, opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },) => {
732
- return this.store.entries<T>(opts).filter(([key]) => { return typeof key === "string" && key.startsWith(prefix); }).map(([key, value]) => ({ key: key as string, value, }));
733
- },
734
- getAll: <T = A>(opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): Record<string | symbol, T> => {
735
- const result: Record<string | symbol, T> = {};
736
- for (const [key, value] of this.store.entries<T>(opts)) { result[key] = value; }
737
- return result;
738
- },
739
- subscribe: <T = A>(key: SignalKey, listener: (value: T) => void, opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): Unsubscribe => {
740
- return this.store.subscribe<T>(key, listener, opts);
741
- },
742
- subscribeAll: (listener: (key: SignalKey, value: unknown) => void, opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): Unsubscribe => {
743
- const scope = this.root.SIGNALS.get(opts.s, opts.m, opts.r,);
744
- return () => { scope.listeners.delete(listener); };
745
- },
746
- clear: (opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): void => {
747
- this.store.clear(opts);
748
- },
749
- waitFor: <T = A>(key: SignalKey, opts: ScopeOptions = { s: this.s, m: this.m, r: this.r, },): Promise<T> => {
750
- const atom = this.root.SIGNALS.get(opts.s, opts.m, opts.r,);
751
- if (!atom) { return new Promise<T>(() => { }); }
752
-
753
- if (atom.hasWritten) {
754
- return Promise.resolve(atom.read());
755
- }
756
-
757
- return atom.waitForNext();
758
- },
759
- };
760
- return sa
761
- })(); */
762
- _devRecord = null;
763
- devRecord(componentId, hookName, sauronId, key, value) {
764
- return this._devRecord?.(componentId, hookName, sauronId, key, value);
765
- }
766
- registerDevRecorder(fn) {
767
- this._devRecord = fn;
768
- }
769
- rerender = (key) => {
770
- if (key !== undefined) {
771
- // const hs = graphHookStates.get(key);
772
- // if (hs) notifyHook(`${GRAPH_BRIDGE_COMPONENT_ID}:${key}`);
773
- this.notifyHook(key);
774
- }
775
- else {
776
- this.flushSync();
777
- }
778
- };
779
- flushHookKey = (key) => {
780
- const [componentId] = key.split(":");
781
- /**
782
- * Store/global synthetic hook keys do not map to a component hook state.
783
- * They simply notify subscribers.
784
- */
785
- if (componentId === "store") {
786
- this._subscribers.get(key)?.forEach((callback) => {
787
- if (typeof callback !== "function")
788
- return;
789
- callback();
790
- this.onFlush(callback);
791
- });
792
- return;
793
- }
794
- const component = this._components.get(componentId) ?? this._root;
795
- const hook = component?.hooks.get(key);
796
- /**
797
- * Prefer direct DOM binding updates where bindings exist.
798
- */
799
- if (hook?.bindings && hook.bindings.size > 0) {
800
- for (const binding of hook.bindings) {
801
- if (!binding.active)
802
- continue;
803
- binding.update(binding.node, hook.value);
804
- }
805
- return;
806
- }
807
- this._subscribers.get(key)?.forEach((callback) => {
808
- if (typeof callback !== "function")
809
- return;
810
- callback();
811
- this.onFlush(callback);
812
- });
813
- };
814
- _flushHookNotifications = () => {
815
- this._flushScheduled = false;
816
- const keys = Array.from(this._pendingNotifications);
817
- this._pendingNotifications.clear();
818
- for (const key of keys) {
819
- this.flushHookKey(key);
820
- }
821
- };
822
- getCurrentComponent = () => {
823
- if (this.root.isReact === true && this.root.IS_THE_WIZARD === false) {
824
- if (this._currentComponent)
825
- return this._currentComponent;
826
- return this._root;
827
- }
828
- else {
829
- if (!this.init_hooks_context) {
830
- this.set("_root", this._root, true, this.s, this.m, this.r);
831
- this.init_hooks_context = true;
832
- }
833
- const updated_ctx = this.get("_root", this.s, this.m, this.r);
834
- if (updated_ctx && updated_ctx.id === this.r)
835
- return updated_ctx;
836
- else
837
- return this._root;
838
- }
839
- };
840
- unmountComponent(id) {
841
- const instance = this._components.get(id);
842
- if (!instance)
843
- return;
844
- for (const dispose of instance.unmount) {
845
- try {
846
- dispose();
847
- }
848
- catch (error) {
849
- console.error(`[THE_CLOUD][UNMOUNT] cleanup failed for "${id}":`, error);
850
- }
851
- }
852
- instance.unmount.clear();
853
- for (const hook of instance.hooks.values()) {
854
- try {
855
- hook.cleanup?.();
856
- }
857
- catch (error) {
858
- console.error(`[THE_CLOUD][UNMOUNT] hook cleanup failed for "${id}":`, error);
859
- }
860
- }
861
- instance.hooks.clear();
862
- this._components.delete(id);
863
- }
864
- mountComponent(id, renderFn) {
865
- const instance = {
866
- id,
867
- hooks: new Map(),
868
- unmount: new Set(),
869
- render: renderFn,
870
- };
871
- this._components.set(id, instance);
872
- return instance;
873
- }
874
- hmrPreserve() {
875
- const snapshot = new Map();
876
- this._components.forEach((instance, id) => {
877
- const hooks = new Map();
878
- instance.hooks.forEach((state, key) => {
879
- hooks.set(key, state.value);
880
- });
881
- snapshot.set(id, hooks);
882
- });
883
- return snapshot;
884
- }
885
- hmrRestore(snapshot) {
886
- snapshot.forEach((hooks, id) => {
887
- const instance = this._components.get(id);
888
- if (!instance)
889
- return;
890
- hooks.forEach((value, key) => {
891
- const state = instance.hooks.get(key);
892
- if (state)
893
- state.value = value;
894
- });
895
- });
896
- }
897
- subscribeToHook(key, cb) {
898
- if (!this._subscribers.has(key))
899
- this._subscribers.set(key, new Set());
900
- this._subscribers.get(key).add(cb);
901
- return () => {
902
- this._subscribers.get(key)?.delete(cb);
903
- if (this._subscribers.get(key)?.size === 0)
904
- this._subscribers.delete(key);
905
- };
906
- }
907
- notifyHook(key) {
908
- this._pendingNotifications.add(key);
909
- if (!this._flushScheduled) {
910
- this._flushScheduled = true;
911
- queueMicrotask(this._flushHookNotifications);
912
- }
913
- }
914
- endHookDependencyCapture() {
915
- this._currentHookState = null;
916
- }
917
- beginHookDependencyCapture(hook) {
918
- this._currentHookState = hook;
919
- }
920
- registerDOMBinding(node, update) {
921
- const hook = this._currentHookState;
922
- if (!hook)
923
- return;
924
- const binding = { node, update, active: true };
925
- if (!hook.bindings) {
926
- hook.bindings = new Set();
927
- }
928
- hook.bindings.add(binding);
929
- const anyNode = node;
930
- if (!anyNode.__sauron_bindings__) {
931
- anyNode.__sauron_bindings__ = new Set();
932
- }
933
- anyNode.__sauron_bindings__.add(hook);
934
- return () => {
935
- if (!binding.active)
936
- return;
937
- binding.active = false;
938
- hook.bindings?.delete(binding);
939
- anyNode.__sauron_bindings__?.delete(hook);
940
- };
941
- }
942
- setCurrentComponent(instance) {
943
- this._currentComponent = instance;
944
- }
945
- registerDOMRef(name, node) {
946
- if (!this._currentHookState)
947
- return;
948
- if (!this._currentHookState.domRefs)
949
- this._currentHookState.domRefs = new Map();
950
- this._currentHookState.domRefs.set(name, node);
951
- }
952
- getDOMRef(name) {
953
- if (!this._currentHookState || !this._currentHookState.domRefs)
954
- return undefined;
955
- return this._currentHookState.domRefs.get(name);
956
- }
957
- registerAdapter(adapter) {
958
- this._adapter = adapter;
959
- }
960
- _reactHookCursor = 0;
961
- _currentRenderInstanceCheck = null;
962
- _isReactRenderContext() {
963
- const _react = this.root.isReact;
964
- if (!_react)
965
- return false;
966
- if (this.root.IS_THE_WIZARD)
967
- return false;
968
- try {
969
- _react.useState;
970
- // If useState is callable without throwing, we're in a React render context
971
- // We probe by checking if the dispatcher is active via a known internal
972
- const internals = _react.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
973
- const dispatcher = internals?.ReactCurrentDispatcher?.current ?? internals?.H;
974
- return !!dispatcher;
975
- }
976
- catch (e) {
977
- // log(`[THE_CLOUD][_IS_REACT_RENDER_CONTEXT]`, { error: e, }, t.error)
978
- return false;
979
- }
980
- }
981
- createHook(hookName, sauronId, initializer, updater, triggerRender = true) {
982
- if (this.root.isReact === true && this.root.IS_THE_WIZARD === false) {
983
- try {
984
- const isReact = this._isReactRenderContext();
985
- const { instance, forceUpdate } = isReact && this._adapter ? this._adapter.getComponentInstance() : { instance: this.getCurrentComponent(), forceUpdate: undefined };
986
- const component = instance;
987
- // ─── THE TARGETED FIX ───────────────────────────────────────────────────────
988
- // Use sequential indexing when in React so it matches React's rendering slots.
989
- // Otherwise, use Sauron's default compilation ID string.
990
- const stableSlotId = isReact ? `seq-${this._reactHookCursor++}` : sauronId;
991
- const key = `${component.id}:${hookName}:${stableSlotId}`;
992
- // ────────────────────────────────────────────────────────────────────────────
993
- if (!this._components.has(component.id)) {
994
- this._components.set(component.id, component);
995
- }
996
- if (!component.hooks.has(key)) {
997
- const state = initializer();
998
- component.hooks.set(key, state);
999
- if (component.render) {
1000
- const unsub = this.subscribeToHook(key, () => component.render?.());
1001
- component.unmount.add(unsub);
1002
- }
1003
- }
1004
- if (isReact && this._adapter && forceUpdate) {
1005
- this._adapter.onHookSubscribe(key, forceUpdate);
1006
- }
1007
- const notify = (k) => {
1008
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
1009
- const state = component.hooks.get(k);
1010
- this.devRecord(component.id, hookName, stableSlotId, k, state?.value);
1011
- }
1012
- this.notifyHook(k);
1013
- };
1014
- const hookState = component.hooks.get(key);
1015
- this.beginHookDependencyCapture(hookState);
1016
- try {
1017
- return updater(hookState, key, notify);
1018
- }
1019
- finally {
1020
- this.endHookDependencyCapture();
1021
- }
1022
- }
1023
- catch (e) {
1024
- // log(`[THE_CLOUD][CREATE_HOOK]`, { error: e, }, t.error)
1025
- return e.error;
1026
- }
1027
- }
1028
- else {
1029
- try {
1030
- const component = this.getCurrentComponent();
1031
- const key = `${component.id}:${hookName}:${sauronId}`;
1032
- if (!this._components.has(component.id)) {
1033
- this._components.set(component.id, component);
1034
- }
1035
- if (!component.hooks.has(key)) {
1036
- const state = initializer();
1037
- component.hooks.set(key, state);
1038
- if (triggerRender && component.render) {
1039
- const unsub = this.subscribeToHook(key, () => component.render?.());
1040
- component.unmount.add(unsub);
1041
- }
1042
- }
1043
- const notify = (k) => {
1044
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
1045
- const state = component.hooks.get(k);
1046
- this.devRecord(component.id, hookName, sauronId, k, state?.value);
1047
- }
1048
- if (triggerRender)
1049
- this.notifyHook(k);
1050
- };
1051
- const hookState = component.hooks.get(key);
1052
- this.beginHookDependencyCapture(hookState);
1053
- try {
1054
- return updater(hookState, key, notify);
1055
- }
1056
- finally {
1057
- this.endHookDependencyCapture();
1058
- }
1059
- }
1060
- catch (e) {
1061
- // log(`[THE_CLOUD][CREATE_HOOK]`, { error: e, }, t.error)
1062
- return e.error;
1063
- }
1064
- }
1065
- }
1066
- _broadcastSS(key, value, storageType, fn, path, domain, options) {
1067
- this._localChange = true;
1068
- this._channel?.postMessage({ key, value, storageType, fn, path, domain, options });
1069
- }
1070
- getChain(key, s, m, r, chain) {
1071
- return MaybePromise(this.state.get(key, { s, m, r }));
1072
- }
1073
- getReChain(key, s, m, r) {
1074
- return MaybePromise(this.state.get(key, { s, m, r }));
1075
- }
1076
- get(key, s, m, r) {
1077
- return MaybePromise(this.state.get(key, { s, m, r }));
1078
- }
1079
- getSauron(key, s, m, r) {
1080
- return MaybePromise(this.state.get(key, { s, m, r }));
1081
- }
1082
- getAll(opts) {
1083
- return this.state.getAll(opts);
1084
- }
1085
- getAllSauron(opts) {
1086
- return this.state.getAll(opts);
1087
- }
1088
- async getMany(keys, s, m, r) {
1089
- if (!Array.isArray(keys) || keys.length === 0) {
1090
- return {};
1091
- }
1092
- const result = {};
1093
- const promises = keys.map(async (key) => {
1094
- const value = await this.get(key, s, m, r);
1095
- return { key, value };
1096
- });
1097
- const results = await Promise.all(promises);
1098
- for (const { key, value } of results) {
1099
- result[key] = value;
1100
- }
1101
- return result;
1102
- }
1103
- setChain(label, value, triggerRender = true, s, m, r) {
1104
- return MaybePromise(this.state.set(label, value, { triggerRender, s, m, r }));
1105
- }
1106
- set(label, value, triggerRender = true, s, m, r) {
1107
- this._broadcastSS(label, value, "sauron", "set");
1108
- return MaybePromise(this.state.set(label, value, { triggerRender, s, m, r }));
1109
- }
1110
- setSauron(label, value, triggerRender = true, s, m, r) {
1111
- this._broadcastSS(label, value, "sauron", "set");
1112
- return MaybePromise(this.state.set(label, value, { triggerRender, s, m, r }));
1113
- }
1114
- async setMany(entries) {
1115
- if (!entries || typeof entries !== "object") {
1116
- return;
1117
- }
1118
- // Batch all sets without triggering renders until the end
1119
- const entriesArray = Object.entries(entries);
1120
- for (let i = 0; i < entriesArray.length; i++) {
1121
- const [key, value] = entriesArray[i];
1122
- // Only trigger render on the last item to avoid multiple renders
1123
- const triggerRender = i === entriesArray.length - 1;
1124
- this.set(key, value, triggerRender);
1125
- }
1126
- }
1127
- subChain(label, fn, s, m, r) {
1128
- return MaybePromise(this.state.subscribe(label, fn, { s, m, r }));
1129
- }
1130
- sub(label, fn, s, m, r) {
1131
- if (!label || !fn)
1132
- return () => { };
1133
- return MaybePromise(this.state.subscribe(label, fn, { s, m, r }));
1134
- }
1135
- /**
1136
- * subSauronInfinity<MyType>('myKey', (value) => {
1137
- console.log(value) // every value
1138
- })
1139
- */
1140
- subSauron(k, fn, s, m, r) {
1141
- if (!k || !fn)
1142
- return () => { };
1143
- return MaybePromise(this.state.subscribe(k, fn, { s, m, r }));
1144
- }
1145
- subAll(fn, s, m, r) {
1146
- if (!fn)
1147
- return () => { };
1148
- return this.state.subscribeAll(fn, { s, m, r });
1149
- }
1150
- subAllSauron(fn, s, m, r) {
1151
- if (!fn)
1152
- return () => { };
1153
- return this.state.subscribeAll(fn, { s, m, r });
1154
- }
1155
- delSauron(label, s, m, r) {
1156
- if (!label)
1157
- return false;
1158
- const v = this.state.delete(label, { s, m, r });
1159
- this._broadcastSS(label, undefined, "sauron", "delete");
1160
- return v;
1161
- }
1162
- deleteSauron(label, s, m, r) {
1163
- if (!label)
1164
- return false;
1165
- const v = this.state.delete(label, { s, m, r });
1166
- this._broadcastSS(label, undefined, "sauron", "delete");
1167
- return v;
1168
- }
1169
- deleteChain(label, s, m, r) {
1170
- return MaybePromise(this.state.delete(label, { s, m, r }));
1171
- }
1172
- async deleteMany(keys, s, m, r) {
1173
- if (!Array.isArray(keys) || keys.length === 0) {
1174
- return false;
1175
- }
1176
- let allDeleted = true;
1177
- // Batch all deletes without triggering renders until the end
1178
- for (let i = 0; i < keys.length; i++) {
1179
- const deleted = this.delSauron(keys[i], s, m, r);
1180
- if (!deleted) {
1181
- allDeleted = false;
1182
- }
1183
- }
1184
- return allDeleted;
1185
- }
1186
- waitFor(label, s, m, r) {
1187
- return this.state.waitFor(label, { s, m, r });
1188
- }
1189
- waitForSauron(label, s, m, r) {
1190
- return this.state.waitFor(label, { s, m, r });
1191
- }
1192
- }
1193
- // #endregion
1194
- // TIME TRAVEL
1195
- // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════
1196
- class DRSTimeTravel {
1197
- root;
1198
- _time_travel_reverting = false;
1199
- constructor(root) {
1200
- this.root = root;
1201
- }
1202
- get sauron() {
1203
- return this.root.SAURON;
1204
- }
1205
- defaultChannels = () => ({
1206
- r: this.sauron.r,
1207
- m: this.sauron.m,
1208
- s: '_TC_TIME_TRAVEL_',
1209
- });
1210
- resolveChannels = (channels = this.defaultChannels()) => ({
1211
- ...this.defaultChannels(),
1212
- ...channels,
1213
- });
1214
- resolveHistory = (key, channels = this.defaultChannels()) => {
1215
- const { s, m, r } = this.resolveChannels(channels);
1216
- const meta = this.root.SAURON.getMetadata(s, m, r);
1217
- return meta._history.get(key);
1218
- };
1219
- history = (key, channels = this.defaultChannels()) => {
1220
- return this.resolveHistory(key, channels) ?? [];
1221
- };
1222
- replay = (key, value, channels, source) => {
1223
- const { s, m, r } = this.resolveChannels(channels);
1224
- this._time_travel_reverting = true;
1225
- try {
1226
- this.sauron.store.set(key, value, {
1227
- sl_reg: s,
1228
- ms_reg: m,
1229
- globalKey: r,
1230
- triggerRender: true,
1231
- });
1232
- return value;
1233
- }
1234
- finally {
1235
- this._time_travel_reverting = false;
1236
- }
1237
- };
1238
- graft = (drs) => {
1239
- drs.time_travel = {
1240
- back: this.back,
1241
- forward: this.forward,
1242
- goto: this.goto,
1243
- history: this.history,
1244
- };
1245
- return drs.time_travel;
1246
- };
1247
- back = (key, steps = 1, channels = this.defaultChannels()) => {
1248
- const history = this.resolveHistory(key, channels);
1249
- if (!history?.length || steps <= 0)
1250
- return undefined;
1251
- const { s, m, r } = this.resolveChannels(channels);
1252
- const meta = this.root.SAURON.getMetadata(s, m, r);
1253
- const index = meta._timeTravel.get(key) ?? history.length - 1;
1254
- const targetIndex = Math.max(0, index - steps);
1255
- if (targetIndex === index)
1256
- return undefined;
1257
- meta._timeTravel.set(key, targetIndex);
1258
- for (let i = 0; i < history.length; i++) {
1259
- history[i].undone = i > targetIndex;
1260
- }
1261
- return this.replay(key, history[targetIndex].next, channels, "time-travel.back");
1262
- };
1263
- forward = (key, steps = 1, channels = this.defaultChannels()) => {
1264
- const history = this.resolveHistory(key, channels);
1265
- if (!history?.length || steps <= 0)
1266
- return undefined;
1267
- const { s, m, r } = this.resolveChannels(channels);
1268
- const meta = this.root.SAURON.getMetadata(s, m, r);
1269
- const index = meta._timeTravel.get(key) ?? history.length - 1;
1270
- const targetIndex = Math.min(history.length - 1, index + steps);
1271
- if (targetIndex === index)
1272
- return undefined;
1273
- meta._timeTravel.set(key, targetIndex);
1274
- for (let i = 0; i < history.length; i++) {
1275
- history[i].undone = i > targetIndex;
1276
- }
1277
- return this.replay(key, history[targetIndex].next, channels, "time-travel.forward");
1278
- };
1279
- goto = (key, sequence, channels = this.defaultChannels()) => {
1280
- const history = this.resolveHistory(key, channels);
1281
- if (!history?.length)
1282
- return undefined;
1283
- const { s, m, r } = this.resolveChannels(channels);
1284
- const meta = this.root.SAURON.getMetadata(s, m, r);
1285
- const targetIndex = history.findIndex((entry) => entry.k === sequence);
1286
- const index = meta._timeTravel.get(key) ?? history.length - 1;
1287
- if (targetIndex < 0 || targetIndex === index)
1288
- return undefined;
1289
- meta._timeTravel.set(key, targetIndex);
1290
- for (let i = 0; i < history.length; i++) {
1291
- history[i].undone = i > targetIndex;
1292
- }
1293
- return this.replay(key, history[targetIndex].next, channels, "time-travel.goto");
1294
- };
1295
- }
1296
- // #endregion
1297
- // ROOT
1298
- // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════
1299
- export class ROOT {
1300
- SAURON;
1301
- TIME_TRAVEL;
1302
- SIGNALS;
1303
- r = 'TW_ROOT_REG';
1304
- m = 'TW_MASTER_REG';
1305
- s = '_TC_ROOT_';
1306
- isReact = false;
1307
- IS_THE_WIZARD = true;
1308
- constructor() {
1309
- this.SAURON = new SAURON(this);
1310
- this.TIME_TRAVEL = new DRSTimeTravel(this);
1311
- // this.SIGNALS = new SIGNALS(this)
1312
- this.s = store.get('SAURON_SLAVE_REG') ?? '_TC_ROOT_';
1313
- this.m = store.get('SAURON_MASTER_REG') ?? 'TW_MASTER_REG';
1314
- this.r = store.get('THE_WIZARD_ROOT_REG') ?? 'TW_ROOT_REG';
1315
- this.SIGNALS.r = this.r;
1316
- this.SIGNALS.m = this.m;
1317
- this.SIGNALS.r = this.r;
1318
- this.SIGNALS.m = this.m;
1319
- this.SIGNALS.hub.STATE_CONTEXT = store.get('STATE_CONTEXT') ?? 'sauron';
1320
- this.SAURON.root = this;
1321
- this.TIME_TRAVEL.root = this;
1322
- }
1323
- }
1324
- export const root = new ROOT();
1325
- // #endregion
1326
- // [SIGNALS]
1327
- // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════
1328
- // #endregion
1329
- export const signals = root.SIGNALS;
1330
- export const _root = root.SAURON._root;
1331
- export const getNestedMap = root.SAURON.getNestedMap;
1332
- export const getMetadata = root.SAURON.getMetadata;
1333
- export const scheduleGlobalNotify = root.SAURON.scheduleGlobalNotify;
1334
- export const scheduleNotify = root.SAURON.scheduleNotify;
1335
- //export const store = root.SAURON.store
1336
- export const state = root.SAURON.state;
1337
- export const _devRecord = root.SAURON._devRecord;
1338
- export const devRecord = root.SAURON.devRecord;
1339
- export const registerDevRecorder = root.SAURON.registerDevRecorder;
1340
- export const rerender = root.SAURON.rerender;
1341
- export const flushHookKey = root.SAURON.flushHookKey;
1342
- export const _flushHookNotifications = root.SAURON._flushHookNotifications;
1343
- export const getCurrentComponent = root.SAURON.getCurrentComponent;
1344
- export const unmountComponent = root.SAURON.unmountComponent;
1345
- export const mountComponent = root.SAURON.mountComponent;
1346
- export const hmrPreserve = root.SAURON.hmrPreserve;
1347
- export const hmrRestore = root.SAURON.hmrRestore;
1348
- export const subscribeToHook = root.SAURON.subscribeToHook;
1349
- export const notifyHook = root.SAURON.notifyHook;
1350
- export const endHookDependencyCapture = root.SAURON.endHookDependencyCapture;
1351
- export const beginHookDependencyCapture = root.SAURON.beginHookDependencyCapture;
1352
- export const registerDOMBinding = root.SAURON.registerDOMBinding;
1353
- export const setCurrentComponent = root.SAURON.setCurrentComponent;
1354
- export const registerDOMRef = root.SAURON.registerDOMRef;
1355
- export const getDOMRef = root.SAURON.getDOMRef;
1356
- export const registerAdapter = root.SAURON.registerAdapter;
1357
- export const _reactHookCursor = root.SAURON._reactHookCursor;
1358
- export const _currentRenderInstanceCheck = root.SAURON._currentRenderInstanceCheck;
1359
- export const _isReactRenderContext = root.SAURON._isReactRenderContext;
1360
- export const createHook = root.SAURON.createHook;
1361
- export const _broadcastSS = root.SAURON._broadcastSS;
1362
- export const getChain = root.SAURON.getChain;
1363
- export const getReChain = root.SAURON.getReChain;
1364
- export const get = root.SAURON.get;
1365
- export const getSauron = root.SAURON.getSauron;
1366
- export const getAll = root.SAURON.getAll;
1367
- export const getAllSauron = root.SAURON.getAllSauron;
1368
- export const getMany = root.SAURON.getMany;
1369
- export const setChain = root.SAURON.setChain;
1370
- export const set = root.SAURON.set;
1371
- export const setSauron = root.SAURON.setSauron;
1372
- export const setMany = root.SAURON.setMany;
1373
- export const subChain = root.SAURON.subChain;
1374
- export const sub = root.SAURON.sub;
1375
- export const subSauron = root.SAURON.subSauron;
1376
- export const subAll = root.SAURON.subAll;
1377
- export const subAllSauron = root.SAURON.subAllSauron;
1378
- export const delSauron = root.SAURON.delSauron;
1379
- export const deleteSauron = root.SAURON.deleteSauron;
1380
- export const deleteChain = root.SAURON.deleteChain;
1381
- export const deleteMany = root.SAURON.deleteMany;
1382
- export const waitFor = root.SAURON.waitFor;
1383
- export const waitForSauron = root.SAURON.waitForSauron;
1384
- const chh = root.SAURON.createHook;
1385
- globalThis.createHook = chh;
1386
- globalThis._sid = _sidi;