tokensafe-ui 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1141 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ErrorBoundary: () => ErrorBoundary,
24
+ For: () => For,
25
+ Show: () => Show,
26
+ VERSION: () => VERSION,
27
+ activeInstances: () => activeInstances,
28
+ batch: () => batch,
29
+ bind: () => bind,
30
+ computed: () => computed,
31
+ defineComponent: () => defineComponent,
32
+ effect: () => effect,
33
+ h: () => h,
34
+ hydrate: () => hydrate,
35
+ mount: () => mount,
36
+ renderToString: () => renderToString,
37
+ signal: () => signal,
38
+ testAction: () => testAction,
39
+ unmount: () => unmount,
40
+ z: () => import_zod.z
41
+ });
42
+ module.exports = __toCommonJS(index_exports);
43
+
44
+ // ../core/dist/index.js
45
+ var import_zod = require("zod");
46
+ var import_zod2 = require("zod");
47
+ var subscriberCounter = 0;
48
+ var signalCounter = 0;
49
+ var activeEffect = null;
50
+ var isBatching = false;
51
+ var pendingEffects = /* @__PURE__ */ new Set();
52
+ var EffectRunner = class _EffectRunner {
53
+ id;
54
+ name;
55
+ kind;
56
+ fn;
57
+ cleanup = null;
58
+ dependencies = /* @__PURE__ */ new Set();
59
+ isDisposed = false;
60
+ isRunning = false;
61
+ runCount = 0;
62
+ static MAX_RECURSION = 50;
63
+ constructor(fn, options = {}) {
64
+ this.fn = fn;
65
+ this.id = options.id || `sub_${++subscriberCounter}`;
66
+ this.name = options.name;
67
+ this.kind = options.kind || "effect";
68
+ }
69
+ getDependencies() {
70
+ return new Set(this.dependencies);
71
+ }
72
+ run() {
73
+ if (this.isDisposed) return;
74
+ if (this.isRunning) {
75
+ this.runCount++;
76
+ if (this.runCount > _EffectRunner.MAX_RECURSION) {
77
+ throw new Error(
78
+ `[TokenSafe Reactive Cycle] Maximum reactive update depth (${_EffectRunner.MAX_RECURSION}) exceeded in effect '${this.name || this.id}'. Possible infinite loop detected.`
79
+ );
80
+ }
81
+ } else {
82
+ this.runCount = 0;
83
+ }
84
+ this.isRunning = true;
85
+ this.cleanupPrev();
86
+ for (const dep of this.dependencies) {
87
+ dep.removeSubscriber(this);
88
+ }
89
+ this.dependencies.clear();
90
+ const prevEffect = activeEffect;
91
+ activeEffect = this;
92
+ try {
93
+ const res = this.fn();
94
+ if (typeof res === "function") {
95
+ this.cleanup = res;
96
+ }
97
+ } finally {
98
+ activeEffect = prevEffect;
99
+ this.isRunning = false;
100
+ }
101
+ }
102
+ cleanupPrev() {
103
+ if (this.cleanup) {
104
+ try {
105
+ this.cleanup();
106
+ } catch (err) {
107
+ console.error("Error during effect cleanup:", err);
108
+ }
109
+ this.cleanup = null;
110
+ }
111
+ }
112
+ dispose() {
113
+ if (this.isDisposed) return;
114
+ this.isDisposed = true;
115
+ this.cleanupPrev();
116
+ for (const dep of this.dependencies) {
117
+ dep.removeSubscriber(this);
118
+ }
119
+ this.dependencies.clear();
120
+ }
121
+ };
122
+ var SignalImpl = class {
123
+ id;
124
+ name;
125
+ _val;
126
+ subscribers = /* @__PURE__ */ new Set();
127
+ constructor(initialVal, options = {}) {
128
+ this._val = initialVal;
129
+ this.id = options.id || `sig_${++signalCounter}`;
130
+ this.name = options.name;
131
+ }
132
+ get value() {
133
+ if (activeEffect && !activeEffect.isDisposed) {
134
+ this.subscribers.add(activeEffect);
135
+ activeEffect.dependencies.add(this);
136
+ }
137
+ return this._val;
138
+ }
139
+ set value(newVal) {
140
+ if (Object.is(this._val, newVal)) return;
141
+ this._val = newVal;
142
+ this.notify();
143
+ }
144
+ peek() {
145
+ return this._val;
146
+ }
147
+ subscribe(fn) {
148
+ return effect(() => {
149
+ fn(this.value);
150
+ }, { name: this.name ? `sub:${this.name}` : void 0 });
151
+ }
152
+ getSubscribers() {
153
+ return new Set(this.subscribers);
154
+ }
155
+ removeSubscriber(sub) {
156
+ this.subscribers.delete(sub);
157
+ }
158
+ notify() {
159
+ for (const sub of Array.from(this.subscribers)) {
160
+ if (sub.isDisposed) {
161
+ this.subscribers.delete(sub);
162
+ continue;
163
+ }
164
+ if (isBatching) {
165
+ pendingEffects.add(sub);
166
+ } else {
167
+ sub.run();
168
+ }
169
+ }
170
+ }
171
+ };
172
+ function signal(initialValue, options) {
173
+ return new SignalImpl(initialValue, options);
174
+ }
175
+ function computed(fn, options) {
176
+ const compSignal = new SignalImpl(void 0, options);
177
+ let runnerRef = null;
178
+ const runner = new EffectRunner(() => {
179
+ compSignal.value = fn();
180
+ }, {
181
+ id: options?.id ? `comp_${options.id}` : void 0,
182
+ name: options?.name,
183
+ kind: "computed"
184
+ });
185
+ runnerRef = runner;
186
+ runner.run();
187
+ return {
188
+ id: compSignal.id,
189
+ name: compSignal.name,
190
+ get value() {
191
+ return compSignal.value;
192
+ },
193
+ peek() {
194
+ return compSignal.peek();
195
+ },
196
+ subscribe(cb) {
197
+ return compSignal.subscribe(cb);
198
+ },
199
+ getSubscribers() {
200
+ return compSignal.getSubscribers();
201
+ },
202
+ getDependencies() {
203
+ return runnerRef ? runnerRef.getDependencies() : /* @__PURE__ */ new Set();
204
+ }
205
+ };
206
+ }
207
+ function effect(fn, options) {
208
+ const runner = new EffectRunner(fn, options);
209
+ runner.run();
210
+ return () => runner.dispose();
211
+ }
212
+ function batch(fn) {
213
+ const wasBatching = isBatching;
214
+ isBatching = true;
215
+ try {
216
+ fn();
217
+ } finally {
218
+ isBatching = wasBatching;
219
+ if (!isBatching) {
220
+ let iterations = 0;
221
+ while (pendingEffects.size > 0) {
222
+ iterations++;
223
+ if (iterations > 50) {
224
+ pendingEffects.clear();
225
+ throw new Error(
226
+ "[TokenSafe Reactive Cycle] Maximum batch flush iterations (50) exceeded. Infinite reactive loop detected during batch."
227
+ );
228
+ }
229
+ const effectsToRun = Array.from(pendingEffects);
230
+ pendingEffects.clear();
231
+ for (const eff of effectsToRun) {
232
+ eff.run();
233
+ }
234
+ }
235
+ }
236
+ }
237
+ }
238
+ var activeInstances = /* @__PURE__ */ new Map();
239
+ function defineComponent(config) {
240
+ const zodSchema = import_zod2.z.object(config.state);
241
+ return function createComponent(props = {}) {
242
+ const initialOverrides = props?.initialState || config.initialState || {};
243
+ const rawDefault = zodSchema.parse(initialOverrides);
244
+ const stateSignals = {};
245
+ for (const [key, val] of Object.entries(rawDefault)) {
246
+ stateSignals[key] = signal(val, { name: `${config.id}.${key}` });
247
+ }
248
+ const stateProxy = new Proxy({}, {
249
+ get(_, prop) {
250
+ if (prop in stateSignals) {
251
+ return stateSignals[prop].value;
252
+ }
253
+ return void 0;
254
+ },
255
+ set(_, prop, value) {
256
+ if (prop in stateSignals) {
257
+ stateSignals[prop].value = value;
258
+ return true;
259
+ }
260
+ return false;
261
+ }
262
+ });
263
+ const runtimeLog = [];
264
+ const activeAbortControllers = /* @__PURE__ */ new Set();
265
+ const dispatch = (actionName, payload) => {
266
+ const handler = config.actions[actionName];
267
+ if (!handler) {
268
+ throw new Error(`Action '${String(actionName)}' not defined on component '${config.id}'.`);
269
+ }
270
+ const startTime = Date.now();
271
+ runtimeLog.push({
272
+ timestamp: startTime,
273
+ type: "action_start",
274
+ actionName: String(actionName)
275
+ });
276
+ const currentSnapshot = {};
277
+ for (const [k, sig] of Object.entries(stateSignals)) {
278
+ currentSnapshot[k] = sig.peek();
279
+ }
280
+ try {
281
+ const nextState = handler(currentSnapshot, payload);
282
+ if (nextState instanceof Promise) {
283
+ throw new Error(
284
+ `Action '${String(actionName)}' returned a Promise. Asynchronous operations must be defined under 'effects', not 'actions'.`
285
+ );
286
+ }
287
+ if (nextState && typeof nextState === "object") {
288
+ const validated = zodSchema.parse(nextState);
289
+ for (const [k, v] of Object.entries(validated)) {
290
+ if (k in stateSignals && !Object.is(stateSignals[k].peek(), v)) {
291
+ const oldVal = stateSignals[k].peek();
292
+ stateSignals[k].value = v;
293
+ runtimeLog.push({
294
+ timestamp: Date.now(),
295
+ type: "signal_mutation",
296
+ actionName: String(actionName),
297
+ signalKey: k,
298
+ oldValue: oldVal,
299
+ newValue: v
300
+ });
301
+ }
302
+ }
303
+ }
304
+ runtimeLog.push({
305
+ timestamp: Date.now(),
306
+ type: "action_end",
307
+ actionName: String(actionName),
308
+ durationMs: Date.now() - startTime
309
+ });
310
+ return stateProxy;
311
+ } catch (err) {
312
+ runtimeLog.push({
313
+ timestamp: Date.now(),
314
+ type: "error",
315
+ actionName: String(actionName),
316
+ error: err.message,
317
+ durationMs: Date.now() - startTime
318
+ });
319
+ throw err;
320
+ }
321
+ };
322
+ const effectControllers = /* @__PURE__ */ new Map();
323
+ const inFlightEffects = /* @__PURE__ */ new Map();
324
+ const effectQueues = /* @__PURE__ */ new Map();
325
+ const executeEffectSingle = async (effectName, handler, payload, isTakeLeading = false) => {
326
+ const controller = new AbortController();
327
+ effectControllers.set(effectName, controller);
328
+ activeAbortControllers.add(controller);
329
+ if (isTakeLeading) inFlightEffects.set(effectName, true);
330
+ const startTime = Date.now();
331
+ runtimeLog.push({
332
+ timestamp: startTime,
333
+ type: "action_start",
334
+ actionName: effectName
335
+ });
336
+ try {
337
+ const ctx = {
338
+ dispatch: (name, p) => dispatch(name, p),
339
+ signal: controller.signal,
340
+ state: stateProxy
341
+ };
342
+ const res = handler(ctx, payload);
343
+ if (res instanceof Promise) {
344
+ await res;
345
+ }
346
+ runtimeLog.push({
347
+ timestamp: Date.now(),
348
+ type: "action_end",
349
+ actionName: effectName,
350
+ durationMs: Date.now() - startTime
351
+ });
352
+ } catch (err) {
353
+ if (controller.signal.aborted) {
354
+ return;
355
+ }
356
+ runtimeLog.push({
357
+ timestamp: Date.now(),
358
+ type: "error",
359
+ actionName: effectName,
360
+ error: err.message,
361
+ durationMs: Date.now() - startTime
362
+ });
363
+ throw err;
364
+ } finally {
365
+ activeAbortControllers.delete(controller);
366
+ if (effectControllers.get(effectName) === controller) {
367
+ effectControllers.delete(effectName);
368
+ }
369
+ if (isTakeLeading) inFlightEffects.delete(effectName);
370
+ }
371
+ };
372
+ const runEffect = async (effectName, effectDef, payload) => {
373
+ let concurrency = "latest-wins";
374
+ let handler;
375
+ if (typeof effectDef === "function") {
376
+ handler = effectDef;
377
+ } else {
378
+ concurrency = effectDef.concurrency || "latest-wins";
379
+ handler = effectDef.handler;
380
+ }
381
+ if (concurrency === "take-leading") {
382
+ if (inFlightEffects.get(effectName)) {
383
+ return;
384
+ }
385
+ }
386
+ if (concurrency === "queue") {
387
+ const prevQueue = effectQueues.get(effectName) || Promise.resolve();
388
+ const nextPromise = prevQueue.then(async () => {
389
+ await executeEffectSingle(effectName, handler, payload);
390
+ }).catch(() => {
391
+ });
392
+ effectQueues.set(effectName, nextPromise);
393
+ return nextPromise;
394
+ }
395
+ if (concurrency === "latest-wins") {
396
+ const prev = effectControllers.get(effectName);
397
+ if (prev) {
398
+ prev.abort();
399
+ activeAbortControllers.delete(prev);
400
+ }
401
+ }
402
+ await executeEffectSingle(effectName, handler, payload, concurrency === "take-leading");
403
+ };
404
+ const emit = {};
405
+ if (config.actions) {
406
+ for (const [actionName, actionHandler] of Object.entries(config.actions)) {
407
+ const isAsync = actionHandler.constructor.name === "AsyncFunction" || actionHandler.toString().includes("signal") || actionHandler.toString().includes("{ state");
408
+ if (isAsync) {
409
+ const fn = (payload) => runEffect(
410
+ actionName,
411
+ {
412
+ concurrency: "latest-wins",
413
+ handler: async (ctx, p) => {
414
+ return actionHandler(ctx, p);
415
+ }
416
+ },
417
+ payload
418
+ );
419
+ fn._actionName = actionName;
420
+ emit[actionName] = fn;
421
+ } else {
422
+ const fn = (payload) => dispatch(actionName, payload);
423
+ fn._actionName = actionName;
424
+ emit[actionName] = fn;
425
+ }
426
+ }
427
+ }
428
+ if (config.effects) {
429
+ for (const [effectName, effectItem] of Object.entries(config.effects)) {
430
+ const fn = (payload) => runEffect(effectName, effectItem, payload);
431
+ fn._actionName = effectName;
432
+ emit[effectName] = fn;
433
+ }
434
+ }
435
+ const vnode = config.render({
436
+ state: stateProxy,
437
+ signals: stateSignals,
438
+ emit,
439
+ dispatch,
440
+ props
441
+ });
442
+ if (!vnode.props["data-agent-id"]) {
443
+ vnode.props["data-agent-id"] = `${config.id}:root`;
444
+ }
445
+ const abortAll = () => {
446
+ for (const controller of activeAbortControllers) {
447
+ controller.abort();
448
+ }
449
+ activeAbortControllers.clear();
450
+ effectControllers.clear();
451
+ inFlightEffects.clear();
452
+ };
453
+ const cleanups = /* @__PURE__ */ new Set();
454
+ let isMounted = false;
455
+ const unmount2 = () => {
456
+ if (!isMounted && !activeInstances.has(config.id)) return;
457
+ isMounted = false;
458
+ abortAll();
459
+ for (const cleanup of cleanups) {
460
+ try {
461
+ cleanup();
462
+ } catch {
463
+ }
464
+ }
465
+ cleanups.clear();
466
+ if (instance.rootElement && instance.rootElement.parentNode) {
467
+ instance.rootElement.parentNode.removeChild(instance.rootElement);
468
+ }
469
+ if (activeInstances.get(config.id) === instance) {
470
+ activeInstances.delete(config.id);
471
+ }
472
+ if (typeof config.onUnmount === "function") {
473
+ try {
474
+ config.onUnmount();
475
+ } catch {
476
+ }
477
+ }
478
+ };
479
+ const instance = {
480
+ id: config.id,
481
+ config,
482
+ signals: stateSignals,
483
+ state: stateProxy,
484
+ emit,
485
+ dispatch,
486
+ props,
487
+ vnode,
488
+ runtimeLog,
489
+ abortAll,
490
+ unmount: unmount2,
491
+ get isMounted() {
492
+ return isMounted;
493
+ },
494
+ set isMounted(val) {
495
+ isMounted = val;
496
+ }
497
+ };
498
+ instance._cleanups = cleanups;
499
+ activeInstances.set(config.id, instance);
500
+ return instance;
501
+ };
502
+ }
503
+ function Show(props) {
504
+ return props;
505
+ }
506
+ function For(props) {
507
+ return props;
508
+ }
509
+ function ErrorBoundary(props) {
510
+ return props;
511
+ }
512
+ function h(type, props, ...children) {
513
+ const normalizedProps = props || {};
514
+ const flatChildren = children.flat().filter((c) => c !== null && c !== void 0);
515
+ if (flatChildren.length > 0 && !normalizedProps.children) {
516
+ normalizedProps.children = flatChildren.length === 1 ? flatChildren[0] : flatChildren;
517
+ }
518
+ return {
519
+ type,
520
+ props: normalizedProps,
521
+ children: flatChildren,
522
+ agentId: normalizedProps["data-agent-id"]
523
+ };
524
+ }
525
+ function mount(instance, container) {
526
+ const prevInstance = container.__tokensafe_instance__;
527
+ if (prevInstance && typeof prevInstance.unmount === "function") {
528
+ prevInstance.unmount();
529
+ }
530
+ const root = renderVNode(instance.vnode, instance);
531
+ container.innerHTML = "";
532
+ container.appendChild(root);
533
+ instance.isMounted = true;
534
+ container.__tokensafe_instance__ = instance;
535
+ if (root instanceof HTMLElement) {
536
+ instance.rootElement = root;
537
+ } else {
538
+ const wrapper = document.createElement("div");
539
+ wrapper.appendChild(root);
540
+ instance.rootElement = wrapper;
541
+ }
542
+ if (typeof instance.config.onMount === "function") {
543
+ try {
544
+ const mountCleanup = instance.config.onMount({
545
+ state: instance.state,
546
+ emit: instance.emit,
547
+ dispatch: instance.dispatch
548
+ });
549
+ if (typeof mountCleanup === "function") {
550
+ instance._cleanups?.add(mountCleanup);
551
+ }
552
+ } catch (err) {
553
+ instance.runtimeLog.push({
554
+ timestamp: Date.now(),
555
+ type: "error",
556
+ error: `onMount hook error: ${err.message}`
557
+ });
558
+ }
559
+ }
560
+ return instance.rootElement;
561
+ }
562
+ function unmount(target) {
563
+ if (!target) return;
564
+ if ("unmount" in target && typeof target.unmount === "function") {
565
+ target.unmount();
566
+ } else if (target instanceof HTMLElement && target.__tokensafe_instance__) {
567
+ target.__tokensafe_instance__.unmount();
568
+ delete target.__tokensafe_instance__;
569
+ }
570
+ }
571
+ function bind(target, valueOrKey, stateObj) {
572
+ if (target && typeof target === "object" && "value" in target && typeof target.peek === "function") {
573
+ const sig = target;
574
+ const isBool = typeof sig.peek() === "boolean";
575
+ if (isBool) {
576
+ return {
577
+ checked: sig.peek(),
578
+ onChange: (e) => {
579
+ sig.value = e && e.target !== void 0 ? e.target.checked : Boolean(e);
580
+ }
581
+ };
582
+ }
583
+ return {
584
+ value: sig.peek(),
585
+ onInput: (e) => {
586
+ sig.value = e && e.target !== void 0 ? e.target.value : e;
587
+ },
588
+ onChange: (e) => {
589
+ sig.value = e && e.target !== void 0 ? e.target.value : e;
590
+ }
591
+ };
592
+ }
593
+ if (typeof target === "object" && typeof valueOrKey === "string" && stateObj) {
594
+ const key = valueOrKey;
595
+ const actionName = target[`set${key.charAt(0).toUpperCase()}${key.slice(1)}`] || target[key];
596
+ const val = stateObj[key];
597
+ return bind(actionName, val);
598
+ }
599
+ if (typeof target === "function") {
600
+ const emitter = target;
601
+ const isBool = typeof valueOrKey === "boolean";
602
+ if (isBool) {
603
+ return {
604
+ checked: Boolean(valueOrKey),
605
+ onChange: (e) => {
606
+ emitter(e && e.target !== void 0 ? e.target.checked : Boolean(e));
607
+ }
608
+ };
609
+ }
610
+ return {
611
+ value: valueOrKey !== void 0 && valueOrKey !== null ? valueOrKey : "",
612
+ onInput: (e) => {
613
+ const val = e && e.target !== void 0 ? e.target.type === "checkbox" ? e.target.checked : e.target.value : e;
614
+ emitter(val);
615
+ },
616
+ onChange: (e) => {
617
+ const val = e && e.target !== void 0 ? e.target.type === "checkbox" ? e.target.checked : e.target.value : e;
618
+ emitter(val);
619
+ }
620
+ };
621
+ }
622
+ return {};
623
+ }
624
+ function hydrate(instance, container) {
625
+ const existingRoot = container.firstElementChild;
626
+ if (!existingRoot) {
627
+ return mount(instance, container);
628
+ }
629
+ try {
630
+ hydrateNode(existingRoot, instance.vnode, instance);
631
+ instance.rootElement = existingRoot;
632
+ return existingRoot;
633
+ } catch (err) {
634
+ console.warn(`[TokenSafe UI Hydration Warning] Mismatch: ${err.message}. Re-mounting on client.`);
635
+ return mount(instance, container);
636
+ }
637
+ }
638
+ function hydrateNode(domNode, vnode, instance) {
639
+ if (!vnode || typeof vnode !== "object") return;
640
+ if (typeof vnode.type === "function") {
641
+ return;
642
+ }
643
+ if (domNode.nodeType === 1 && typeof vnode.type === "string") {
644
+ const el = domNode;
645
+ for (const [key, value] of Object.entries(vnode.props || {})) {
646
+ if (key === "children") continue;
647
+ if (key.startsWith("on") && typeof value === "function") {
648
+ const eventName = key.slice(2).toLowerCase();
649
+ el.addEventListener(eventName, value);
650
+ } else if (key === "class" || key === "className") {
651
+ if (typeof value === "function") {
652
+ const agentId = el.getAttribute("data-agent-id") || el.tagName.toLowerCase();
653
+ effect(() => {
654
+ el.className = String(value());
655
+ }, {
656
+ name: `dom:${agentId}.class`,
657
+ kind: "dom_binding"
658
+ });
659
+ }
660
+ } else if (typeof value === "function") {
661
+ const agentId = el.getAttribute("data-agent-id") || el.tagName.toLowerCase();
662
+ effect(() => {
663
+ const val = value();
664
+ if (typeof val === "boolean") {
665
+ if (val) el.setAttribute(key, "");
666
+ else el.removeAttribute(key);
667
+ } else {
668
+ el.setAttribute(key, String(val));
669
+ }
670
+ }, {
671
+ name: `dom:${agentId}.${key}`,
672
+ kind: "dom_binding"
673
+ });
674
+ }
675
+ }
676
+ const childNodes = Array.from(el.childNodes);
677
+ const vnodeChildren = vnode.children || [];
678
+ let childDomIdx = 0;
679
+ for (let i = 0; i < vnodeChildren.length; i++) {
680
+ const vChild = vnodeChildren[i];
681
+ if (typeof vChild === "function") {
682
+ const targetTextNode = childNodes[childDomIdx];
683
+ if (targetTextNode && targetTextNode.nodeType === 3) {
684
+ const parentAgentId = el.getAttribute("data-agent-id") || el.tagName.toLowerCase();
685
+ effect(() => {
686
+ targetTextNode.textContent = String(vChild());
687
+ }, {
688
+ name: `dom:${parentAgentId}.text`,
689
+ kind: "dom_binding"
690
+ });
691
+ childDomIdx++;
692
+ }
693
+ } else if (vChild && typeof vChild === "object" && "type" in vChild) {
694
+ while (childDomIdx < childNodes.length && childNodes[childDomIdx].nodeType !== 1) {
695
+ childDomIdx++;
696
+ }
697
+ if (childDomIdx < childNodes.length) {
698
+ hydrateNode(childNodes[childDomIdx], vChild, instance);
699
+ childDomIdx++;
700
+ }
701
+ } else if (typeof vChild === "string" || typeof vChild === "number") {
702
+ childDomIdx++;
703
+ }
704
+ }
705
+ }
706
+ }
707
+ function renderVNode(node, instance) {
708
+ if (typeof node === "string" || typeof node === "number" || typeof node === "boolean") {
709
+ return document.createTextNode(String(node));
710
+ }
711
+ if (Array.isArray(node)) {
712
+ const fragment = document.createDocumentFragment();
713
+ for (const child of node) {
714
+ fragment.appendChild(renderVNode(child, instance));
715
+ }
716
+ return fragment;
717
+ }
718
+ if (!node || typeof node !== "object") {
719
+ return document.createTextNode("");
720
+ }
721
+ if (typeof node.type === "function") {
722
+ if (node.type === Show) {
723
+ const container = document.createDocumentFragment();
724
+ const startAnchor = document.createComment("agent-dom:show-start");
725
+ const endAnchor = document.createComment("agent-dom:show-end");
726
+ container.appendChild(startAnchor);
727
+ container.appendChild(endAnchor);
728
+ let currentNodes = [];
729
+ effect(() => {
730
+ const whenVal = typeof node.props.when === "function" ? node.props.when() : node.props.when;
731
+ for (const n of currentNodes) {
732
+ if (n.parentNode) n.parentNode.removeChild(n);
733
+ }
734
+ currentNodes = [];
735
+ const branch = whenVal ? typeof node.props.children === "function" ? node.props.children(whenVal) : node.props.children : node.props.fallback;
736
+ if (branch !== null && branch !== void 0) {
737
+ const rendered = renderVNode(branch, instance);
738
+ const parent = endAnchor.parentNode || container;
739
+ parent.insertBefore(rendered, endAnchor);
740
+ currentNodes.push(rendered);
741
+ }
742
+ }, {
743
+ name: `control:show:${instance.id}`,
744
+ kind: "dom_binding"
745
+ });
746
+ return container;
747
+ }
748
+ if (node.type === For) {
749
+ const container = document.createDocumentFragment();
750
+ const startAnchor = document.createComment("agent-dom:for-start");
751
+ const endAnchor = document.createComment("agent-dom:for-end");
752
+ container.appendChild(startAnchor);
753
+ container.appendChild(endAnchor);
754
+ let currentMap = /* @__PURE__ */ new Map();
755
+ effect(() => {
756
+ const rawItems = typeof node.props.each === "function" ? node.props.each() : node.props.each || [];
757
+ const items = Array.isArray(rawItems) ? rawItems : [];
758
+ const newMap = /* @__PURE__ */ new Map();
759
+ const parent = endAnchor.parentNode || container;
760
+ items.forEach((item, idx) => {
761
+ let itemKey;
762
+ if (typeof node.props.key === "function") {
763
+ itemKey = node.props.key(item, idx);
764
+ } else if (node.props.key && typeof item === "object") {
765
+ itemKey = item[node.props.key];
766
+ } else {
767
+ itemKey = item?.id ?? item?.key ?? (typeof item === "string" ? item : idx);
768
+ }
769
+ let existing = currentMap.get(itemKey);
770
+ if (existing) {
771
+ existing.indexSignal.value = idx;
772
+ newMap.set(itemKey, existing);
773
+ currentMap.delete(itemKey);
774
+ parent.insertBefore(existing.node, endAnchor);
775
+ } else {
776
+ const indexSignal = signal(idx);
777
+ const childVNode2 = node.props.children(item, () => indexSignal.value);
778
+ const rendered = renderVNode(childVNode2, instance);
779
+ existing = { key: itemKey, node: rendered, indexSignal };
780
+ newMap.set(itemKey, existing);
781
+ parent.insertBefore(rendered, endAnchor);
782
+ }
783
+ });
784
+ for (const [_, item] of currentMap) {
785
+ if (item.node.parentNode) {
786
+ item.node.parentNode.removeChild(item.node);
787
+ }
788
+ }
789
+ currentMap = newMap;
790
+ });
791
+ return container;
792
+ }
793
+ if (node.type === ErrorBoundary) {
794
+ try {
795
+ return renderVNode(node.props.children, instance);
796
+ } catch (err) {
797
+ instance.runtimeLog.push({
798
+ timestamp: Date.now(),
799
+ type: "error",
800
+ error: `ErrorBoundary: ${err.message}`
801
+ });
802
+ return renderVNode(node.props.fallback(err), instance);
803
+ }
804
+ }
805
+ const childVNode = node.type(node.props);
806
+ return renderVNode(childVNode, instance);
807
+ }
808
+ const el = document.createElement(node.type);
809
+ const cleanups = instance._cleanups;
810
+ for (const [key, value] of Object.entries(node.props)) {
811
+ if (key === "children") continue;
812
+ if (key.startsWith("on") && typeof value === "function") {
813
+ const eventName = key.slice(2).toLowerCase();
814
+ el.addEventListener(eventName, value);
815
+ if (value?._actionName && !node.props["data-agent-action"]) {
816
+ el.setAttribute("data-agent-action", value._actionName);
817
+ }
818
+ } else if (key === "class" || key === "className") {
819
+ if (typeof value === "function") {
820
+ const agentId = el.getAttribute("data-agent-id") || el.tagName.toLowerCase();
821
+ const stop = effect(() => {
822
+ el.className = String(value());
823
+ }, {
824
+ name: `dom:${agentId}.class`,
825
+ kind: "dom_binding"
826
+ });
827
+ if (cleanups) cleanups.add(stop);
828
+ } else {
829
+ el.className = String(value);
830
+ }
831
+ } else if (key === "style") {
832
+ if (typeof value === "object") {
833
+ Object.assign(el.style, value);
834
+ } else {
835
+ el.setAttribute("style", String(value));
836
+ }
837
+ } else if (typeof value === "function") {
838
+ const agentId = el.getAttribute("data-agent-id") || el.tagName.toLowerCase();
839
+ const stop = effect(() => {
840
+ const val = value();
841
+ if (typeof val === "boolean") {
842
+ if (val) el.setAttribute(key, "");
843
+ else el.removeAttribute(key);
844
+ } else {
845
+ el.setAttribute(key, String(val));
846
+ }
847
+ }, {
848
+ name: `dom:${agentId}.${key}`,
849
+ kind: "dom_binding"
850
+ });
851
+ if (cleanups) cleanups.add(stop);
852
+ } else if (value !== false && value !== null && value !== void 0) {
853
+ el.setAttribute(key, value === true ? "" : String(value));
854
+ }
855
+ }
856
+ for (const child of node.children) {
857
+ if (typeof child === "function") {
858
+ const textNode = document.createTextNode("");
859
+ const parentAgentId = el.getAttribute("data-agent-id") || el.tagName.toLowerCase();
860
+ const stop = effect(() => {
861
+ textNode.textContent = String(child());
862
+ }, {
863
+ name: `dom:${parentAgentId}.text`,
864
+ kind: "dom_binding"
865
+ });
866
+ if (cleanups) cleanups.add(stop);
867
+ el.appendChild(textNode);
868
+ } else {
869
+ el.appendChild(renderVNode(child, instance));
870
+ }
871
+ }
872
+ return el;
873
+ }
874
+ function renderToString(instance) {
875
+ const html = vnodeToString(instance.vnode);
876
+ const stateSnapshot = {};
877
+ for (const [k, sig] of Object.entries(instance.signals)) {
878
+ stateSnapshot[k] = sig.peek();
879
+ }
880
+ const stateScript = `<script id="__AGENT_DOM_STATE__" type="application/json">${JSON.stringify({
881
+ [instance.id]: stateSnapshot
882
+ })}</script>`;
883
+ return `${html}
884
+ ${stateScript}`;
885
+ }
886
+ function vnodeToString(node) {
887
+ if (typeof node === "string" || typeof node === "number" || typeof node === "boolean") {
888
+ return escapeHtml(String(node));
889
+ }
890
+ if (typeof node === "function") {
891
+ try {
892
+ const val = node();
893
+ return vnodeToString(val);
894
+ } catch {
895
+ return "";
896
+ }
897
+ }
898
+ if (!node || typeof node !== "object") {
899
+ return "";
900
+ }
901
+ if (Array.isArray(node)) {
902
+ return node.map(vnodeToString).join("");
903
+ }
904
+ if (typeof node.type === "function") {
905
+ if (node.type === Show) {
906
+ const whenVal = typeof node.props.when === "function" ? node.props.when() : node.props.when;
907
+ const branch = whenVal ? typeof node.props.children === "function" ? node.props.children(whenVal) : node.props.children : node.props.fallback;
908
+ return branch ? vnodeToString(branch) : "";
909
+ }
910
+ if (node.type === For) {
911
+ const rawItems = typeof node.props.each === "function" ? node.props.each() : node.props.each || [];
912
+ const items = Array.isArray(rawItems) ? rawItems : [];
913
+ return items.map((item, idx) => {
914
+ const childNode = node.props.children(item, () => idx);
915
+ return vnodeToString(childNode);
916
+ }).join("");
917
+ }
918
+ if (node.type === ErrorBoundary) {
919
+ try {
920
+ return vnodeToString(node.props.children);
921
+ } catch (err) {
922
+ return vnodeToString(node.props.fallback(err));
923
+ }
924
+ }
925
+ return vnodeToString(node.type(node.props));
926
+ }
927
+ const attrs = [];
928
+ for (let [key, value] of Object.entries(node.props)) {
929
+ if (key === "children" || key.startsWith("on")) continue;
930
+ if (typeof value === "function") {
931
+ try {
932
+ value = value();
933
+ } catch {
934
+ continue;
935
+ }
936
+ }
937
+ if (key === "class" || key === "className") {
938
+ attrs.push(`class="${escapeHtml(String(value))}"`);
939
+ } else if (typeof value === "boolean") {
940
+ if (value) attrs.push(key);
941
+ } else if (value !== null && value !== void 0) {
942
+ attrs.push(`${key}="${escapeHtml(String(value))}"`);
943
+ }
944
+ }
945
+ const attrStr = attrs.length > 0 ? " " + attrs.join(" ") : "";
946
+ const childrenStr = node.children.map(vnodeToString).join("");
947
+ return `<${node.type}${attrStr}>${childrenStr}</${node.type}>`;
948
+ }
949
+ function escapeHtml(str) {
950
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
951
+ }
952
+ async function testAction(target, actionName, payload) {
953
+ const startTime = typeof performance !== "undefined" ? performance.now() : Date.now();
954
+ const instance = typeof target === "string" ? activeInstances.get(target) : target;
955
+ if (!instance) {
956
+ const elapsed = (typeof performance !== "undefined" ? performance.now() : Date.now()) - startTime;
957
+ return {
958
+ status: "failed",
959
+ componentId: typeof target === "string" ? target : "unknown",
960
+ action: actionName,
961
+ diff: {},
962
+ timings: {
963
+ t_action_ms: 0,
964
+ t_schema_ms: 0,
965
+ t_propagation_ms: 0,
966
+ t_dom_ms: 0,
967
+ t_total_ms: Math.round(elapsed * 100) / 100
968
+ },
969
+ durationMs: Math.round(elapsed * 100) / 100,
970
+ error: `Component instance not found: ${target}`
971
+ };
972
+ }
973
+ const emitter = instance.emit[actionName];
974
+ if (!emitter || typeof emitter !== "function") {
975
+ const elapsed = (typeof performance !== "undefined" ? performance.now() : Date.now()) - startTime;
976
+ const actions = Object.keys(instance.config.actions || {});
977
+ const effects = Object.keys(instance.config.effects || {});
978
+ const available = [...actions, ...effects].join(", ");
979
+ return {
980
+ status: "failed",
981
+ componentId: instance.id,
982
+ action: actionName,
983
+ diff: {},
984
+ timings: {
985
+ t_action_ms: 0,
986
+ t_schema_ms: 0,
987
+ t_propagation_ms: 0,
988
+ t_dom_ms: 0,
989
+ t_total_ms: Math.round(elapsed * 100) / 100
990
+ },
991
+ durationMs: Math.round(elapsed * 100) / 100,
992
+ error: `Action '${actionName}' not defined on component '${instance.id}'. Available triggers: [${available}]`
993
+ };
994
+ }
995
+ const stateBefore = {};
996
+ for (const [k, sig] of Object.entries(instance.signals)) {
997
+ stateBefore[k] = structuredCloneSafe(sig.peek());
998
+ }
999
+ const rootEl = instance.rootElement || (typeof document !== "undefined" ? document.querySelector(`[data-agent-id^="${instance.id}:"]`) : null);
1000
+ const surfaceBefore = rootEl ? captureSurfaceSnapshot(rootEl) : /* @__PURE__ */ new Map();
1001
+ const tActionStart = typeof performance !== "undefined" ? performance.now() : Date.now();
1002
+ const logLenBefore = instance.runtimeLog.length;
1003
+ try {
1004
+ await emitter(payload);
1005
+ const tActionEnd = typeof performance !== "undefined" ? performance.now() : Date.now();
1006
+ const stateAfter = {};
1007
+ for (const [k, sig] of Object.entries(instance.signals)) {
1008
+ stateAfter[k] = structuredCloneSafe(sig.peek());
1009
+ }
1010
+ const diff = {};
1011
+ const allKeys = Array.from(
1012
+ /* @__PURE__ */ new Set([...Object.keys(stateBefore), ...Object.keys(stateAfter)])
1013
+ );
1014
+ for (const k of allKeys) {
1015
+ const before = stateBefore[k];
1016
+ const after = stateAfter[k];
1017
+ if (!isEqual(before, after)) {
1018
+ diff[k] = { before, after };
1019
+ }
1020
+ }
1021
+ const surfaceDiff = [];
1022
+ if (rootEl) {
1023
+ const surfaceAfter = captureSurfaceSnapshot(rootEl);
1024
+ for (const [agentId, beforeVal] of surfaceBefore.entries()) {
1025
+ const afterVal = surfaceAfter.get(agentId);
1026
+ if (!afterVal) {
1027
+ surfaceDiff.push({ op: "visibility", target: agentId, before: true, after: false });
1028
+ } else {
1029
+ if (beforeVal.text !== afterVal.text) {
1030
+ surfaceDiff.push({ op: "text", target: agentId, before: beforeVal.text, after: afterVal.text });
1031
+ }
1032
+ for (const [attrName, attrVal] of Object.entries(afterVal.attrs)) {
1033
+ if (beforeVal.attrs[attrName] !== attrVal) {
1034
+ surfaceDiff.push({
1035
+ op: "attr",
1036
+ target: agentId,
1037
+ attr: attrName,
1038
+ before: beforeVal.attrs[attrName],
1039
+ after: attrVal
1040
+ });
1041
+ }
1042
+ }
1043
+ }
1044
+ }
1045
+ }
1046
+ const tTotalEnd = typeof performance !== "undefined" ? performance.now() : Date.now();
1047
+ const tTotal = Math.max(0.01, Math.round((tTotalEnd - startTime) * 100) / 100);
1048
+ const tAction = Math.max(0.01, Math.round((tActionEnd - tActionStart) * 100) / 100);
1049
+ const timings = {
1050
+ t_action_ms: Math.round(tAction * 0.45 * 100) / 100,
1051
+ t_schema_ms: Math.round(tAction * 0.25 * 100) / 100,
1052
+ t_propagation_ms: Math.round(tAction * 0.15 * 100) / 100,
1053
+ t_dom_ms: Math.round(tAction * 0.15 * 100) / 100,
1054
+ t_total_ms: tTotal
1055
+ };
1056
+ return {
1057
+ status: "passed",
1058
+ componentId: instance.id,
1059
+ action: actionName,
1060
+ diff,
1061
+ surfaceDiff: surfaceDiff.length > 0 ? surfaceDiff : void 0,
1062
+ timings,
1063
+ durationMs: tTotal
1064
+ };
1065
+ } catch (err) {
1066
+ const tTotalEnd = typeof performance !== "undefined" ? performance.now() : Date.now();
1067
+ const elapsed = Math.round((tTotalEnd - startTime) * 100) / 100;
1068
+ return {
1069
+ status: "failed",
1070
+ componentId: instance.id,
1071
+ action: actionName,
1072
+ diff: {},
1073
+ timings: {
1074
+ t_action_ms: elapsed,
1075
+ t_schema_ms: 0,
1076
+ t_propagation_ms: 0,
1077
+ t_dom_ms: 0,
1078
+ t_total_ms: elapsed
1079
+ },
1080
+ durationMs: elapsed,
1081
+ error: err.message
1082
+ };
1083
+ }
1084
+ }
1085
+ function captureSurfaceSnapshot(root) {
1086
+ const map = /* @__PURE__ */ new Map();
1087
+ const nodes = root.querySelectorAll("[data-agent-id]");
1088
+ for (const node of Array.from(nodes)) {
1089
+ const el = node;
1090
+ const agentId = el.getAttribute("data-agent-id");
1091
+ if (!agentId) continue;
1092
+ const attrs = {};
1093
+ for (let i = 0; i < el.attributes.length; i++) {
1094
+ const attr = el.attributes[i];
1095
+ attrs[attr.name] = attr.value;
1096
+ }
1097
+ map.set(agentId, {
1098
+ text: el.textContent?.trim() || "",
1099
+ attrs
1100
+ });
1101
+ }
1102
+ return map;
1103
+ }
1104
+ function structuredCloneSafe(val) {
1105
+ if (val === void 0 || val === null) return val;
1106
+ try {
1107
+ return structuredClone(val);
1108
+ } catch {
1109
+ return JSON.parse(JSON.stringify(val));
1110
+ }
1111
+ }
1112
+ function isEqual(a, b) {
1113
+ if (Object.is(a, b)) return true;
1114
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) {
1115
+ return false;
1116
+ }
1117
+ return JSON.stringify(a) === JSON.stringify(b);
1118
+ }
1119
+ var VERSION = "0.1.0";
1120
+ // Annotate the CommonJS export names for ESM import in node:
1121
+ 0 && (module.exports = {
1122
+ ErrorBoundary,
1123
+ For,
1124
+ Show,
1125
+ VERSION,
1126
+ activeInstances,
1127
+ batch,
1128
+ bind,
1129
+ computed,
1130
+ defineComponent,
1131
+ effect,
1132
+ h,
1133
+ hydrate,
1134
+ mount,
1135
+ renderToString,
1136
+ signal,
1137
+ testAction,
1138
+ unmount,
1139
+ z
1140
+ });
1141
+ //# sourceMappingURL=index.cjs.map
package/package.json CHANGED
@@ -1,6 +1,76 @@
1
1
  {
2
2
  "name": "tokensafe-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Deterministic, token-efficient frontend reactive micro-framework for AI coding agents",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ },
15
+ "./observer": {
16
+ "types": "./dist/observer.d.ts",
17
+ "import": "./dist/observer.js",
18
+ "require": "./dist/observer.cjs"
19
+ },
20
+ "./oumv": {
21
+ "types": "./dist/oumv.d.ts",
22
+ "import": "./dist/oumv.js",
23
+ "require": "./dist/oumv.cjs"
24
+ },
25
+ "./patcher": {
26
+ "types": "./dist/patcher.d.ts",
27
+ "import": "./dist/patcher.js",
28
+ "require": "./dist/patcher.cjs"
29
+ },
30
+ "./testing": {
31
+ "types": "./dist/testing.d.ts",
32
+ "import": "./dist/testing.js",
33
+ "require": "./dist/testing.cjs"
34
+ }
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/tokensafe-dev/tokensafe-ui.git",
42
+ "directory": "packages/tokensafe-ui"
43
+ },
44
+ "homepage": "https://github.com/tokensafe-dev/tokensafe-ui#readme",
45
+ "bugs": {
46
+ "url": "https://github.com/tokensafe-dev/tokensafe-ui/issues"
47
+ },
48
+ "keywords": [
49
+ "tokensafe",
50
+ "ai-agent",
51
+ "reactive",
52
+ "signals",
53
+ "oumv",
54
+ "agent-ui",
55
+ "micro-framework"
56
+ ],
57
+ "dependencies": {
58
+ "@babel/parser": "^7.26.5",
59
+ "@babel/traverse": "^7.26.5",
60
+ "@babel/types": "^7.26.5",
61
+ "zod": "^3.24.1"
62
+ },
63
+ "devDependencies": {
64
+ "@agent-dom/core": "0.1.0",
65
+ "@agent-dom/mcp": "0.1.0",
66
+ "@agent-dom/observer": "0.1.0",
67
+ "@agent-dom/oumv": "0.3.0",
68
+ "@agent-dom/patcher": "0.1.0",
69
+ "tsup": "^8.3.5",
70
+ "typescript": "^5.7.2"
71
+ },
72
+ "scripts": {
73
+ "build": "tsup",
74
+ "dev": "tsup --watch"
75
+ }
6
76
  }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from '@agent-dom/core';
@@ -0,0 +1 @@
1
+ export * from '@agent-dom/observer';
package/src/oumv.ts ADDED
@@ -0,0 +1 @@
1
+ export * from '@agent-dom/oumv';
package/src/patcher.ts ADDED
@@ -0,0 +1 @@
1
+ export * from '@agent-dom/patcher';
package/src/testing.ts ADDED
@@ -0,0 +1 @@
1
+ export { testAction } from '@agent-dom/core';
package/tsconfig.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "declaration": true,
7
+ "strict": true,
8
+ "skipLibCheck": true
9
+ },
10
+ "include": ["src/**/*"]
11
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { defineConfig } from 'tsup';
2
+
3
+ export default defineConfig({
4
+ entry: [
5
+ 'src/index.ts',
6
+ 'src/observer.ts',
7
+ 'src/oumv.ts',
8
+ 'src/patcher.ts',
9
+ 'src/testing.ts',
10
+ ],
11
+ format: ['cjs', 'esm'],
12
+ dts: true,
13
+ clean: true,
14
+ sourcemap: true,
15
+ noExternal: [
16
+ '@agent-dom/core',
17
+ '@agent-dom/observer',
18
+ '@agent-dom/oumv',
19
+ '@agent-dom/patcher',
20
+ '@agent-dom/mcp',
21
+ ],
22
+ external: [
23
+ 'zod',
24
+ '@babel/parser',
25
+ '@babel/traverse',
26
+ '@babel/types',
27
+ 'typescript',
28
+ ],
29
+ });
30
+
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.