@almadar/ui 2.15.8 → 2.15.10

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 (125) hide show
  1. package/dist/components/atoms/ContentSection.d.ts +16 -0
  2. package/dist/components/atoms/SectionHeader.d.ts +14 -0
  3. package/dist/components/atoms/StatCard.d.ts +13 -0
  4. package/dist/components/atoms/index.d.ts +3 -0
  5. package/dist/components/atoms/svg/SvgBranch.d.ts +12 -0
  6. package/dist/components/atoms/svg/SvgConnection.d.ts +13 -0
  7. package/dist/components/atoms/svg/SvgFlow.d.ts +10 -0
  8. package/dist/components/atoms/svg/SvgGrid.d.ts +14 -0
  9. package/dist/components/atoms/svg/SvgLobe.d.ts +13 -0
  10. package/dist/components/atoms/svg/SvgMesh.d.ts +12 -0
  11. package/dist/components/atoms/svg/SvgMorph.d.ts +11 -0
  12. package/dist/components/atoms/svg/SvgNode.d.ts +12 -0
  13. package/dist/components/atoms/svg/SvgPulse.d.ts +12 -0
  14. package/dist/components/atoms/svg/SvgRing.d.ts +13 -0
  15. package/dist/components/atoms/svg/SvgShield.d.ts +11 -0
  16. package/dist/components/atoms/svg/SvgStack.d.ts +13 -0
  17. package/dist/components/atoms/svg/index.d.ts +12 -0
  18. package/dist/{chunk-ACUO2BBW.js → components/index.cjs} +24764 -16677
  19. package/dist/components/index.js +37757 -889
  20. package/dist/components/molecules/AnimatedCounter.d.ts +18 -0
  21. package/dist/components/molecules/ArticleSection.d.ts +18 -0
  22. package/dist/components/molecules/CTABanner.d.ts +31 -0
  23. package/dist/components/molecules/CaseStudyCard.d.ts +24 -0
  24. package/dist/components/molecules/CodeExample.d.ts +23 -0
  25. package/dist/components/molecules/CommunityLinks.d.ts +25 -0
  26. package/dist/components/molecules/DocBreadcrumb.d.ts +20 -0
  27. package/dist/components/molecules/DocCodeBlock.d.ts +13 -0
  28. package/dist/components/molecules/DocPagination.d.ts +14 -0
  29. package/dist/components/molecules/DocSearch.d.ts +15 -0
  30. package/dist/components/molecules/DocSidebar.d.ts +24 -0
  31. package/dist/components/molecules/DocTOC.d.ts +24 -0
  32. package/dist/components/molecules/FeatureCard.d.ts +26 -0
  33. package/dist/components/molecules/FeatureGrid.d.ts +19 -0
  34. package/dist/components/molecules/GradientDivider.d.ts +14 -0
  35. package/dist/components/molecules/HeroSection.d.ts +36 -0
  36. package/dist/components/molecules/InstallBox.d.ts +16 -0
  37. package/dist/components/molecules/MarketingFooter.d.ts +27 -0
  38. package/dist/components/molecules/PricingCard.d.ts +21 -0
  39. package/dist/components/molecules/PricingGrid.d.ts +13 -0
  40. package/dist/components/molecules/PullQuote.d.ts +14 -0
  41. package/dist/components/molecules/ServiceCatalog.d.ts +19 -0
  42. package/dist/components/molecules/ShowcaseCard.d.ts +20 -0
  43. package/dist/components/molecules/SocialProof.d.ts +25 -0
  44. package/dist/components/molecules/SplitSection.d.ts +21 -0
  45. package/dist/components/molecules/StatsGrid.d.ts +17 -0
  46. package/dist/components/molecules/StepFlow.d.ts +20 -0
  47. package/dist/components/molecules/TagCloud.d.ts +18 -0
  48. package/dist/components/molecules/TeamCard.d.ts +18 -0
  49. package/dist/components/molecules/index.d.ts +19 -0
  50. package/dist/components/molecules/svg/AIGenerates.d.ts +7 -0
  51. package/dist/components/molecules/svg/ClosedCircuit.d.ts +7 -0
  52. package/dist/components/molecules/svg/CommunityOwnership.d.ts +7 -0
  53. package/dist/components/molecules/svg/CompileAnywhere.d.ts +7 -0
  54. package/dist/components/molecules/svg/ComposableModels.d.ts +7 -0
  55. package/dist/components/molecules/svg/DescribeProveDeploy.d.ts +7 -0
  56. package/dist/components/molecules/svg/DomainGrid.d.ts +7 -0
  57. package/dist/components/molecules/svg/EventBus.d.ts +7 -0
  58. package/dist/components/molecules/svg/OrbitalUnit.d.ts +7 -0
  59. package/dist/components/molecules/svg/PlanVerifyRemember.d.ts +7 -0
  60. package/dist/components/molecules/svg/ProveCorrect.d.ts +7 -0
  61. package/dist/components/molecules/svg/ServiceLayers.d.ts +7 -0
  62. package/dist/components/molecules/svg/SharedReality.d.ts +7 -0
  63. package/dist/components/molecules/svg/StandardLibrary.d.ts +7 -0
  64. package/dist/components/molecules/svg/StateMachine.d.ts +7 -0
  65. package/dist/components/molecules/svg/WorldModel.d.ts +7 -0
  66. package/dist/components/molecules/svg/index.d.ts +16 -0
  67. package/dist/components/organisms/CaseStudyOrganism.d.ts +19 -0
  68. package/dist/components/organisms/FeatureGridOrganism.d.ts +20 -0
  69. package/dist/components/organisms/HeroOrganism.d.ts +18 -0
  70. package/dist/components/organisms/PricingOrganism.d.ts +19 -0
  71. package/dist/components/organisms/ShowcaseOrganism.d.ts +20 -0
  72. package/dist/components/organisms/StatsOrganism.d.ts +17 -0
  73. package/dist/components/organisms/StepFlowOrganism.d.ts +20 -0
  74. package/dist/components/organisms/TeamOrganism.d.ts +18 -0
  75. package/dist/components/organisms/game/three/index.cjs +2525 -0
  76. package/dist/components/organisms/game/three/index.js +1795 -50
  77. package/dist/components/organisms/index.d.ts +9 -0
  78. package/dist/components/organisms/marketing-types.d.ts +87 -0
  79. package/dist/components/templates/AboutPageTemplate.d.ts +26 -0
  80. package/dist/components/templates/FeatureDetailPageTemplate.d.ts +27 -0
  81. package/dist/components/templates/LandingPageTemplate.d.ts +31 -0
  82. package/dist/components/templates/PricingPageTemplate.d.ts +26 -0
  83. package/dist/components/templates/index.d.ts +4 -0
  84. package/dist/context/index.cjs +550 -0
  85. package/dist/context/index.js +420 -6
  86. package/dist/docs/index.cjs +4015 -0
  87. package/dist/docs/index.d.cts +412 -0
  88. package/dist/docs/index.d.ts +29 -0
  89. package/dist/docs/index.js +3977 -0
  90. package/dist/hooks/index.cjs +2606 -0
  91. package/dist/hooks/index.js +2535 -8
  92. package/dist/illustrations/index.cjs +3004 -0
  93. package/dist/illustrations/index.d.cts +261 -0
  94. package/dist/illustrations/index.d.ts +35 -0
  95. package/dist/illustrations/index.js +2971 -0
  96. package/dist/{chunk-XL7WB2O5.js → lib/index.cjs} +454 -274
  97. package/dist/lib/index.js +1407 -3
  98. package/dist/locales/index.cjs +340 -0
  99. package/dist/locales/index.js +105 -2
  100. package/dist/marketing/index.cjs +4683 -0
  101. package/dist/marketing/index.d.cts +831 -0
  102. package/dist/marketing/index.d.ts +62 -0
  103. package/dist/marketing/index.js +4626 -0
  104. package/dist/providers/index.cjs +4811 -0
  105. package/dist/providers/index.js +4765 -11
  106. package/dist/{chunk-K2D5D3WK.js → renderer/index.cjs} +101 -42
  107. package/dist/renderer/index.js +1036 -2
  108. package/dist/runtime/index.cjs +4400 -0
  109. package/dist/runtime/index.js +3615 -19
  110. package/dist/{chunk-N7MVUW4R.js → stores/index.cjs} +24 -1
  111. package/dist/stores/index.js +194 -2
  112. package/dist/tsup.config.d.ts +2 -1
  113. package/package.json +27 -12
  114. package/tailwind-preset.cjs +9 -0
  115. package/themes/index.css +22 -20
  116. package/dist/chunk-3HJHHULT.js +0 -93
  117. package/dist/chunk-3JGAROCW.js +0 -149
  118. package/dist/chunk-4N3BAPDB.js +0 -1667
  119. package/dist/chunk-CDIOHSKG.js +0 -661
  120. package/dist/chunk-DKQN5FVU.js +0 -279
  121. package/dist/chunk-JJHCOO34.js +0 -375
  122. package/dist/chunk-PKBMQBKP.js +0 -5
  123. package/dist/chunk-QIABKRCN.js +0 -107
  124. package/dist/chunk-SD3KVCY6.js +0 -1465
  125. package/dist/chunk-YXZM3WCF.js +0 -222
package/dist/lib/index.js CHANGED
@@ -1,3 +1,1407 @@
1
- export { ApiError, apiClient } from '../chunk-3HJHHULT.js';
2
- export { DEFAULT_CONFIG, bindCanvasCapture, bindEventBus, bindTraitStateGetter, clearDebugEvents, clearEntityProvider, clearGuardHistory, clearTicks, clearTraits, clearVerification, cn, debug, debugCollision, debugError, debugGameState, debugGroup, debugGroupEnd, debugInput, debugPhysics, debugTable, debugTime, debugTimeEnd, debugWarn, extractOutputsFromTransitions, extractStateMachine, formatGuard, formatNestedFieldLabel, getAllChecks, getAllTicks, getAllTraits, getBridgeHealth, getDebugEvents, getEffectSummary, getEntitiesByType, getEntityById, getEntitySnapshot, getEventsBySource, getEventsByType, getGuardEvaluationsForTrait, getGuardHistory, getNestedValue, getRecentEvents, getRecentGuardEvaluations, getSnapshot, getSummary, getTick, getTrait, getTransitions, getTransitionsForTrait, initDebugShortcut, isDebugEnabled, logDebugEvent, logEffectExecuted, logError, logEventFired, logInfo, logStateChange, logWarning, onDebugToggle, parseContentSegments, parseMarkdownWithCodeBlocks, recordGuardEvaluation, recordTransition, registerCheck, registerTick, registerTrait, renderStateMachineToDomData, renderStateMachineToSvg, setDebugEnabled, setEntityProvider, setTickActive, subscribeToDebugEvents, subscribeToGuardChanges, subscribeToTickChanges, subscribeToTraitChanges, subscribeToVerification, toggleDebug, unregisterTick, unregisterTrait, updateAssetStatus, updateBridgeHealth, updateCheck, updateGuardResult, updateTickExecution, updateTraitState, waitForTransition } from '../chunk-XL7WB2O5.js';
3
- import '../chunk-PKBMQBKP.js';
1
+ import { clsx } from 'clsx';
2
+ import { twMerge } from 'tailwind-merge';
3
+
4
+ function cn(...inputs) {
5
+ return twMerge(clsx(inputs));
6
+ }
7
+
8
+ // lib/api-client.ts
9
+ var API_BASE_URL = typeof process !== "undefined" && process.env?.VITE_API_URL ? process.env.VITE_API_URL : "/api";
10
+ var ApiError = class extends Error {
11
+ constructor(status, statusText, message) {
12
+ super(message || `API Error: ${status} ${statusText}`);
13
+ this.status = status;
14
+ this.statusText = statusText;
15
+ this.name = "ApiError";
16
+ }
17
+ };
18
+ async function handleResponse(response) {
19
+ if (!response.ok) {
20
+ let message;
21
+ try {
22
+ const errorData = await response.json();
23
+ message = errorData.message || errorData.error;
24
+ } catch {
25
+ }
26
+ throw new ApiError(response.status, response.statusText, message);
27
+ }
28
+ const text = await response.text();
29
+ if (!text) {
30
+ return void 0;
31
+ }
32
+ return JSON.parse(text);
33
+ }
34
+ function getHeaders() {
35
+ const headers = {
36
+ "Content-Type": "application/json"
37
+ };
38
+ const token = typeof localStorage !== "undefined" ? localStorage.getItem("authToken") : null;
39
+ if (token) {
40
+ headers["Authorization"] = `Bearer ${token}`;
41
+ }
42
+ return headers;
43
+ }
44
+ var apiClient = {
45
+ /**
46
+ * GET request
47
+ */
48
+ async get(endpoint) {
49
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
50
+ method: "GET",
51
+ headers: getHeaders()
52
+ });
53
+ return handleResponse(response);
54
+ },
55
+ /**
56
+ * POST request
57
+ */
58
+ async post(endpoint, data) {
59
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
60
+ method: "POST",
61
+ headers: getHeaders(),
62
+ body: data ? JSON.stringify(data) : void 0
63
+ });
64
+ return handleResponse(response);
65
+ },
66
+ /**
67
+ * PUT request
68
+ */
69
+ async put(endpoint, data) {
70
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
71
+ method: "PUT",
72
+ headers: getHeaders(),
73
+ body: data ? JSON.stringify(data) : void 0
74
+ });
75
+ return handleResponse(response);
76
+ },
77
+ /**
78
+ * PATCH request
79
+ */
80
+ async patch(endpoint, data) {
81
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
82
+ method: "PATCH",
83
+ headers: getHeaders(),
84
+ body: data ? JSON.stringify(data) : void 0
85
+ });
86
+ return handleResponse(response);
87
+ },
88
+ /**
89
+ * DELETE request
90
+ */
91
+ async delete(endpoint) {
92
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
93
+ method: "DELETE",
94
+ headers: getHeaders()
95
+ });
96
+ return handleResponse(response);
97
+ }
98
+ };
99
+
100
+ // lib/debug.ts
101
+ var DEBUG_ENABLED = typeof window !== "undefined" && (localStorage.getItem("debug") === "true" || process.env.NODE_ENV === "development");
102
+ function isDebugEnabled() {
103
+ return DEBUG_ENABLED;
104
+ }
105
+ function debug(...args) {
106
+ if (DEBUG_ENABLED) {
107
+ console.log("[DEBUG]", ...args);
108
+ }
109
+ }
110
+ function debugGroup(label) {
111
+ if (DEBUG_ENABLED) {
112
+ console.group(`[DEBUG] ${label}`);
113
+ }
114
+ }
115
+ function debugGroupEnd() {
116
+ if (DEBUG_ENABLED) {
117
+ console.groupEnd();
118
+ }
119
+ }
120
+ function debugWarn(...args) {
121
+ if (DEBUG_ENABLED) {
122
+ console.warn("[DEBUG]", ...args);
123
+ }
124
+ }
125
+ function debugError(...args) {
126
+ if (DEBUG_ENABLED) {
127
+ console.error("[DEBUG]", ...args);
128
+ }
129
+ }
130
+ function debugTable(data) {
131
+ if (DEBUG_ENABLED) {
132
+ console.table(data);
133
+ }
134
+ }
135
+ function debugTime(label) {
136
+ if (DEBUG_ENABLED) {
137
+ console.time(`[DEBUG] ${label}`);
138
+ }
139
+ }
140
+ function debugTimeEnd(label) {
141
+ if (DEBUG_ENABLED) {
142
+ console.timeEnd(`[DEBUG] ${label}`);
143
+ }
144
+ }
145
+ function debugInput(inputType, data) {
146
+ if (DEBUG_ENABLED) {
147
+ console.log(`[DEBUG:INPUT] ${inputType}:`, data);
148
+ }
149
+ }
150
+ function debugCollision(entityA, entityB, details) {
151
+ if (DEBUG_ENABLED) {
152
+ console.log(
153
+ `[DEBUG:COLLISION] ${entityA.type || entityA.id} <-> ${entityB.type || entityB.id}`,
154
+ details ?? ""
155
+ );
156
+ }
157
+ }
158
+ function debugPhysics(entityId, physics) {
159
+ if (DEBUG_ENABLED) {
160
+ console.log(`[DEBUG:PHYSICS] ${entityId}:`, physics);
161
+ }
162
+ }
163
+ function debugGameState(stateName, value) {
164
+ if (DEBUG_ENABLED) {
165
+ console.log(`[DEBUG:GAME_STATE] ${stateName}:`, value);
166
+ }
167
+ }
168
+
169
+ // lib/debugUtils.ts
170
+ var DEBUG_STORAGE_KEY = "orbital-debug";
171
+ var listeners = /* @__PURE__ */ new Set();
172
+ function isDebugEnabled2() {
173
+ if (typeof window === "undefined") return false;
174
+ return localStorage.getItem(DEBUG_STORAGE_KEY) === "true";
175
+ }
176
+ function setDebugEnabled(enabled) {
177
+ if (typeof window === "undefined") return;
178
+ localStorage.setItem(DEBUG_STORAGE_KEY, String(enabled));
179
+ listeners.forEach((listener) => listener(enabled));
180
+ }
181
+ function toggleDebug() {
182
+ const newValue = !isDebugEnabled2();
183
+ setDebugEnabled(newValue);
184
+ return newValue;
185
+ }
186
+ function onDebugToggle(listener) {
187
+ listeners.add(listener);
188
+ return () => listeners.delete(listener);
189
+ }
190
+ function initDebugShortcut() {
191
+ if (typeof window === "undefined") return () => {
192
+ };
193
+ const handleKeyDown = (e) => {
194
+ if (e.ctrlKey && e.shiftKey && e.key === "D") {
195
+ e.preventDefault();
196
+ toggleDebug();
197
+ }
198
+ };
199
+ window.addEventListener("keydown", handleKeyDown);
200
+ return () => window.removeEventListener("keydown", handleKeyDown);
201
+ }
202
+
203
+ // lib/entityDebug.ts
204
+ var entityProvider = null;
205
+ function setEntityProvider(provider) {
206
+ entityProvider = provider;
207
+ }
208
+ function clearEntityProvider() {
209
+ entityProvider = null;
210
+ }
211
+ function getEntitySnapshot() {
212
+ if (!entityProvider) {
213
+ return null;
214
+ }
215
+ const entities = entityProvider();
216
+ return {
217
+ entities,
218
+ timestamp: Date.now(),
219
+ totalCount: entities.length,
220
+ singletons: {},
221
+ runtime: entities.map((e) => ({ id: e.id, type: e.type, data: e.fields })),
222
+ persistent: {}
223
+ };
224
+ }
225
+ function getEntityById(id) {
226
+ if (!entityProvider) {
227
+ return void 0;
228
+ }
229
+ return entityProvider().find((e) => e.id === id);
230
+ }
231
+ function getEntitiesByType(type) {
232
+ if (!entityProvider) {
233
+ return [];
234
+ }
235
+ return entityProvider().filter((e) => e.type === type);
236
+ }
237
+
238
+ // lib/debugRegistry.ts
239
+ var events = [];
240
+ var listeners2 = /* @__PURE__ */ new Set();
241
+ var MAX_EVENTS = 500;
242
+ function notifyListeners() {
243
+ listeners2.forEach((listener) => listener());
244
+ }
245
+ function logDebugEvent(type, source, message, data) {
246
+ const event = {
247
+ id: `event-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
248
+ type,
249
+ source,
250
+ message,
251
+ data,
252
+ timestamp: Date.now()
253
+ };
254
+ events.unshift(event);
255
+ if (events.length > MAX_EVENTS) {
256
+ events.pop();
257
+ }
258
+ notifyListeners();
259
+ }
260
+ function logStateChange(source, from, to, event) {
261
+ logDebugEvent("state-change", source, `${from} \u2192 ${to}`, { from, to, event });
262
+ }
263
+ function logEventFired(source, eventName, payload) {
264
+ logDebugEvent("event-fired", source, eventName, { eventName, payload });
265
+ }
266
+ function logEffectExecuted(source, effectType, details) {
267
+ logDebugEvent("effect-executed", source, effectType, { effectType, details });
268
+ }
269
+ function logError(source, message, error) {
270
+ logDebugEvent("error", source, message, { error });
271
+ }
272
+ function logWarning(source, message, data) {
273
+ logDebugEvent("warning", source, message, data);
274
+ }
275
+ function logInfo(source, message, data) {
276
+ logDebugEvent("info", source, message, data);
277
+ }
278
+ function getDebugEvents() {
279
+ return [...events];
280
+ }
281
+ function getRecentEvents(count) {
282
+ return events.slice(0, count);
283
+ }
284
+ function getEventsByType(type) {
285
+ return events.filter((e) => e.type === type);
286
+ }
287
+ function getEventsBySource(source) {
288
+ return events.filter((e) => e.source === source);
289
+ }
290
+ function subscribeToDebugEvents(listener) {
291
+ listeners2.add(listener);
292
+ return () => listeners2.delete(listener);
293
+ }
294
+ function clearDebugEvents() {
295
+ events.length = 0;
296
+ notifyListeners();
297
+ }
298
+
299
+ // lib/guardRegistry.ts
300
+ var guardHistory = [];
301
+ var listeners3 = /* @__PURE__ */ new Set();
302
+ var MAX_HISTORY = 100;
303
+ function notifyListeners2() {
304
+ listeners3.forEach((listener) => listener());
305
+ }
306
+ function recordGuardEvaluation(evaluation) {
307
+ const entry = {
308
+ ...evaluation,
309
+ id: `guard-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
310
+ timestamp: Date.now()
311
+ };
312
+ guardHistory.unshift(entry);
313
+ if (guardHistory.length > MAX_HISTORY) {
314
+ guardHistory.pop();
315
+ }
316
+ notifyListeners2();
317
+ }
318
+ function getGuardHistory() {
319
+ return [...guardHistory];
320
+ }
321
+ function getRecentGuardEvaluations(count) {
322
+ return guardHistory.slice(0, count);
323
+ }
324
+ function getGuardEvaluationsForTrait(traitName) {
325
+ return guardHistory.filter((g) => g.traitName === traitName);
326
+ }
327
+ function subscribeToGuardChanges(listener) {
328
+ listeners3.add(listener);
329
+ return () => listeners3.delete(listener);
330
+ }
331
+ function clearGuardHistory() {
332
+ guardHistory.length = 0;
333
+ notifyListeners2();
334
+ }
335
+
336
+ // lib/tickRegistry.ts
337
+ var ticks = /* @__PURE__ */ new Map();
338
+ var listeners4 = /* @__PURE__ */ new Set();
339
+ function notifyListeners3() {
340
+ listeners4.forEach((listener) => listener());
341
+ }
342
+ function registerTick(tick) {
343
+ ticks.set(tick.id, tick);
344
+ notifyListeners3();
345
+ }
346
+ function updateTickExecution(id, timestamp) {
347
+ const tick = ticks.get(id);
348
+ if (tick) {
349
+ tick.lastExecuted = timestamp;
350
+ tick.nextExecution = timestamp + tick.interval;
351
+ tick.executionCount++;
352
+ notifyListeners3();
353
+ }
354
+ }
355
+ function setTickActive(id, isActive) {
356
+ const tick = ticks.get(id);
357
+ if (tick) {
358
+ tick.isActive = isActive;
359
+ notifyListeners3();
360
+ }
361
+ }
362
+ function unregisterTick(id) {
363
+ ticks.delete(id);
364
+ notifyListeners3();
365
+ }
366
+ function getAllTicks() {
367
+ return Array.from(ticks.values());
368
+ }
369
+ function getTick(id) {
370
+ return ticks.get(id);
371
+ }
372
+ function subscribeToTickChanges(listener) {
373
+ listeners4.add(listener);
374
+ return () => listeners4.delete(listener);
375
+ }
376
+ function clearTicks() {
377
+ ticks.clear();
378
+ notifyListeners3();
379
+ }
380
+
381
+ // lib/traitRegistry.ts
382
+ var traits = /* @__PURE__ */ new Map();
383
+ var listeners5 = /* @__PURE__ */ new Set();
384
+ function notifyListeners4() {
385
+ listeners5.forEach((listener) => listener());
386
+ }
387
+ function registerTrait(info) {
388
+ traits.set(info.id, info);
389
+ notifyListeners4();
390
+ }
391
+ function updateTraitState(id, newState) {
392
+ const trait = traits.get(id);
393
+ if (trait) {
394
+ trait.currentState = newState;
395
+ trait.transitionCount++;
396
+ notifyListeners4();
397
+ }
398
+ }
399
+ function updateGuardResult(traitId, guardName, result) {
400
+ const trait = traits.get(traitId);
401
+ if (trait) {
402
+ const guard = trait.guards.find((g) => g.name === guardName);
403
+ if (guard) {
404
+ guard.lastResult = result;
405
+ notifyListeners4();
406
+ }
407
+ }
408
+ }
409
+ function unregisterTrait(id) {
410
+ traits.delete(id);
411
+ notifyListeners4();
412
+ }
413
+ function getAllTraits() {
414
+ return Array.from(traits.values());
415
+ }
416
+ function getTrait(id) {
417
+ return traits.get(id);
418
+ }
419
+ function subscribeToTraitChanges(listener) {
420
+ listeners5.add(listener);
421
+ return () => listeners5.delete(listener);
422
+ }
423
+ function clearTraits() {
424
+ traits.clear();
425
+ notifyListeners4();
426
+ }
427
+
428
+ // lib/verificationRegistry.ts
429
+ var checks = /* @__PURE__ */ new Map();
430
+ var transitions = [];
431
+ var bridgeHealth = null;
432
+ var MAX_TRANSITIONS = 500;
433
+ var listeners6 = /* @__PURE__ */ new Set();
434
+ function notifyListeners5() {
435
+ listeners6.forEach((l) => l());
436
+ exposeOnWindow();
437
+ }
438
+ function registerCheck(id, label, status = "pending", details) {
439
+ checks.set(id, { id, label, status, details, updatedAt: Date.now() });
440
+ notifyListeners5();
441
+ }
442
+ function updateCheck(id, status, details) {
443
+ const check = checks.get(id);
444
+ if (check) {
445
+ check.status = status;
446
+ if (details !== void 0) check.details = details;
447
+ check.updatedAt = Date.now();
448
+ } else {
449
+ checks.set(id, { id, label: id, status, details, updatedAt: Date.now() });
450
+ }
451
+ notifyListeners5();
452
+ }
453
+ function getAllChecks() {
454
+ return Array.from(checks.values());
455
+ }
456
+ function recordTransition(trace) {
457
+ const entry = {
458
+ ...trace,
459
+ id: `t-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
460
+ };
461
+ transitions.push(entry);
462
+ if (transitions.length > MAX_TRANSITIONS) {
463
+ transitions.shift();
464
+ }
465
+ if (entry.event === "INIT") {
466
+ const hasFetch = entry.effects.some((e) => e.type === "fetch");
467
+ const checkId = `init-fetch-${entry.traitName}`;
468
+ if (hasFetch) {
469
+ registerCheck(
470
+ checkId,
471
+ `INIT transition for "${entry.traitName}" has fetch effect`,
472
+ "pass"
473
+ );
474
+ } else {
475
+ const hasRenderUI = entry.effects.some((e) => e.type === "render-ui");
476
+ if (hasRenderUI) {
477
+ registerCheck(
478
+ checkId,
479
+ `INIT transition for "${entry.traitName}" missing fetch effect`,
480
+ "fail",
481
+ "Entity-bound render-ui without a fetch effect will show empty data"
482
+ );
483
+ }
484
+ }
485
+ }
486
+ const failedEffects = entry.effects.filter((e) => e.status === "failed");
487
+ if (failedEffects.length > 0) {
488
+ registerCheck(
489
+ `effects-${entry.id}`,
490
+ `Effects failed in ${entry.traitName}: ${entry.from} -> ${entry.to}`,
491
+ "fail",
492
+ failedEffects.map((e) => `${e.type}: ${e.error}`).join("; ")
493
+ );
494
+ }
495
+ notifyListeners5();
496
+ }
497
+ function getTransitions() {
498
+ return [...transitions];
499
+ }
500
+ function getTransitionsForTrait(traitName) {
501
+ return transitions.filter((t) => t.traitName === traitName);
502
+ }
503
+ function updateBridgeHealth(health) {
504
+ bridgeHealth = { ...health };
505
+ const checkId = "server-bridge";
506
+ if (health.connected) {
507
+ registerCheck(checkId, "Server bridge connected", "pass");
508
+ } else {
509
+ registerCheck(
510
+ checkId,
511
+ "Server bridge disconnected",
512
+ "fail",
513
+ health.lastError || "Bridge is not connected"
514
+ );
515
+ }
516
+ notifyListeners5();
517
+ }
518
+ function getBridgeHealth() {
519
+ return bridgeHealth ? { ...bridgeHealth } : null;
520
+ }
521
+ function getSummary() {
522
+ const allChecks = getAllChecks();
523
+ return {
524
+ totalChecks: allChecks.length,
525
+ passed: allChecks.filter((c) => c.status === "pass").length,
526
+ failed: allChecks.filter((c) => c.status === "fail").length,
527
+ warnings: allChecks.filter((c) => c.status === "warn").length,
528
+ pending: allChecks.filter((c) => c.status === "pending").length
529
+ };
530
+ }
531
+ function getSnapshot() {
532
+ return {
533
+ checks: getAllChecks(),
534
+ transitions: getTransitions(),
535
+ bridge: getBridgeHealth(),
536
+ summary: getSummary()
537
+ };
538
+ }
539
+ function subscribeToVerification(listener) {
540
+ listeners6.add(listener);
541
+ return () => listeners6.delete(listener);
542
+ }
543
+ function exposeOnWindow() {
544
+ if (typeof window === "undefined") return;
545
+ if (!window.__orbitalVerification) {
546
+ window.__orbitalVerification = {
547
+ getSnapshot,
548
+ getChecks: getAllChecks,
549
+ getTransitions,
550
+ getBridge: getBridgeHealth,
551
+ getSummary,
552
+ waitForTransition
553
+ };
554
+ }
555
+ }
556
+ function waitForTransition(event, timeoutMs = 1e4) {
557
+ return new Promise((resolve) => {
558
+ const existing = transitions.find((t) => t.event === event);
559
+ if (existing) {
560
+ resolve(existing);
561
+ return;
562
+ }
563
+ const timeout = setTimeout(() => {
564
+ unsub();
565
+ resolve(null);
566
+ }, timeoutMs);
567
+ const unsub = subscribeToVerification(() => {
568
+ const found = transitions.find((t) => t.event === event);
569
+ if (found) {
570
+ clearTimeout(timeout);
571
+ unsub();
572
+ resolve(found);
573
+ }
574
+ });
575
+ });
576
+ }
577
+ function bindEventBus(eventBus) {
578
+ if (typeof window === "undefined") return;
579
+ exposeOnWindow();
580
+ if (window.__orbitalVerification) {
581
+ window.__orbitalVerification.sendEvent = (event, payload) => {
582
+ const prefixed = event.startsWith("UI:") ? event : `UI:${event}`;
583
+ eventBus.emit(prefixed, payload);
584
+ };
585
+ const eventLog = [];
586
+ window.__orbitalVerification.eventLog = eventLog;
587
+ window.__orbitalVerification.clearEventLog = () => {
588
+ eventLog.length = 0;
589
+ };
590
+ if (eventBus.onAny) {
591
+ eventBus.onAny((event) => {
592
+ if (eventLog.length < 200) {
593
+ eventLog.push({
594
+ type: event.type,
595
+ payload: event.payload,
596
+ timestamp: Date.now()
597
+ });
598
+ }
599
+ });
600
+ }
601
+ }
602
+ }
603
+ function bindTraitStateGetter(getter) {
604
+ if (typeof window === "undefined") return;
605
+ exposeOnWindow();
606
+ if (window.__orbitalVerification) {
607
+ window.__orbitalVerification.getTraitState = getter;
608
+ }
609
+ }
610
+ function bindCanvasCapture(captureFn) {
611
+ if (typeof window === "undefined") return;
612
+ exposeOnWindow();
613
+ if (window.__orbitalVerification) {
614
+ window.__orbitalVerification.captureFrame = captureFn;
615
+ }
616
+ }
617
+ function updateAssetStatus(url, status) {
618
+ if (typeof window === "undefined") return;
619
+ exposeOnWindow();
620
+ if (window.__orbitalVerification) {
621
+ if (!window.__orbitalVerification.assetStatus) {
622
+ window.__orbitalVerification.assetStatus = {};
623
+ }
624
+ window.__orbitalVerification.assetStatus[url] = status;
625
+ }
626
+ }
627
+ function clearVerification() {
628
+ checks.clear();
629
+ transitions.length = 0;
630
+ bridgeHealth = null;
631
+ notifyListeners5();
632
+ }
633
+ exposeOnWindow();
634
+
635
+ // lib/getNestedValue.ts
636
+ function getNestedValue(obj, path) {
637
+ if (obj === null || obj === void 0 || !path) {
638
+ return void 0;
639
+ }
640
+ if (!path.includes(".")) {
641
+ return obj[path];
642
+ }
643
+ const parts = path.split(".");
644
+ let value = obj;
645
+ for (const part of parts) {
646
+ if (value === null || value === void 0) {
647
+ return void 0;
648
+ }
649
+ if (typeof value !== "object") {
650
+ return void 0;
651
+ }
652
+ value = value[part];
653
+ }
654
+ return value;
655
+ }
656
+ function formatNestedFieldLabel(path) {
657
+ const lastPart = path.includes(".") ? path.split(".").pop() : path;
658
+ return lastPart.replace(/([A-Z])/g, " $1").replace(/^./, (str) => str.toUpperCase()).replace(/Id$/, "").trim();
659
+ }
660
+
661
+ // lib/visualizer/index.ts
662
+ function formatSExprGuardToDomain(guard, _entityName) {
663
+ if (Array.isArray(guard)) {
664
+ const [op, ...args] = guard;
665
+ return `${op}(${args.map((a) => JSON.stringify(a)).join(", ")})`;
666
+ }
667
+ return JSON.stringify(guard);
668
+ }
669
+ function formatSExprEffectToDomain(effect, _entityName) {
670
+ if (Array.isArray(effect)) {
671
+ const [op, ...args] = effect;
672
+ return `${op}(${args.map((a) => JSON.stringify(a)).join(", ")})`;
673
+ }
674
+ return JSON.stringify(effect);
675
+ }
676
+ function isArraySExpr(expr) {
677
+ return Array.isArray(expr);
678
+ }
679
+ var DEFAULT_CONFIG = {
680
+ nodeRadius: 70,
681
+ nodeSpacing: 650,
682
+ // Increased to give more room for transitions
683
+ initialIndicatorOffset: 45,
684
+ arrowSize: 12,
685
+ colors: {
686
+ background: "#0d1117",
687
+ node: "#161b22",
688
+ nodeBorder: "#30363d",
689
+ nodeText: "#e6edf3",
690
+ initialNode: "#238636",
691
+ finalNode: "#f85149",
692
+ arrow: "#8b949e",
693
+ arrowText: "#8b949e",
694
+ effectText: "#ffb86c",
695
+ guardText: "#ff79c6",
696
+ initial: "#238636"
697
+ },
698
+ fonts: {
699
+ node: '18px "Inter", sans-serif',
700
+ event: '16px "JetBrains Mono", monospace',
701
+ effect: '14px "JetBrains Mono", monospace'
702
+ }
703
+ };
704
+ function isBinding(val) {
705
+ return typeof val === "string" && val.startsWith("@");
706
+ }
707
+ function parseBinding(binding) {
708
+ if (!isBinding(binding)) return null;
709
+ const withoutAt = binding.substring(1);
710
+ const parts = withoutAt.split(".");
711
+ return {
712
+ root: parts[0],
713
+ path: parts.slice(1),
714
+ raw: binding
715
+ };
716
+ }
717
+ function formatGuard(guard) {
718
+ let text = "";
719
+ if (typeof guard === "string") {
720
+ text = guard;
721
+ } else if (Array.isArray(guard)) {
722
+ text = formatSExprCompact(guard);
723
+ }
724
+ return text ? `[${text}]` : "";
725
+ }
726
+ function formatGuardHuman(guard, entityName) {
727
+ if (!guard) return "";
728
+ if (typeof guard === "string") {
729
+ return `if ${guard}`;
730
+ }
731
+ if (isArraySExpr(guard)) {
732
+ return formatSExprGuardToDomain(guard);
733
+ }
734
+ return "";
735
+ }
736
+ function formatEffectsHuman(effects, entityName) {
737
+ if (!Array.isArray(effects) || effects.length === 0) return [];
738
+ return effects.map((effect) => {
739
+ if (isArraySExpr(effect)) {
740
+ return formatSExprEffectToDomain(effect);
741
+ }
742
+ return String(effect);
743
+ }).filter(Boolean);
744
+ }
745
+ function formatSExprCompact(expr) {
746
+ if (!Array.isArray(expr) || expr.length === 0) return "[]";
747
+ const op = expr[0];
748
+ const args = expr.slice(1);
749
+ const formattedArgs = args.map((a) => {
750
+ if (isBinding(a)) {
751
+ const parsed = parseBinding(a);
752
+ if (parsed && parsed.path.length > 0) {
753
+ return `${parsed.root}.${parsed.path.join(".")}`;
754
+ }
755
+ return parsed?.root || a;
756
+ }
757
+ if (typeof a === "string") return a;
758
+ if (typeof a === "number" || typeof a === "boolean") return String(a);
759
+ if (Array.isArray(a)) return formatSExprCompact(a);
760
+ return "{...}";
761
+ });
762
+ return `${op} ${formattedArgs.join(" ")}`;
763
+ }
764
+ function getEffectSummary(effects) {
765
+ if (!Array.isArray(effects) || effects.length === 0) return "";
766
+ const setFields = [];
767
+ const otherEffects = [];
768
+ effects.forEach((effect) => {
769
+ if (!Array.isArray(effect)) return;
770
+ const op = effect[0];
771
+ if (op === "set" && effect[1] && typeof effect[1] === "string") {
772
+ const parsed = parseBinding(effect[1]);
773
+ if (parsed && parsed.path.length > 0) {
774
+ setFields.push(parsed.path[parsed.path.length - 1]);
775
+ } else {
776
+ setFields.push("field");
777
+ }
778
+ } else {
779
+ otherEffects.push(effect);
780
+ }
781
+ });
782
+ const summaries = [];
783
+ if (setFields.length > 0) {
784
+ summaries.push(`\u2192 ${setFields.join(", ")}`);
785
+ }
786
+ otherEffects.forEach((effect) => {
787
+ const op = effect[0];
788
+ switch (op) {
789
+ case "emit":
790
+ summaries.push(`\u2191 ${effect[1] || "event"}`);
791
+ break;
792
+ case "notify":
793
+ summaries.push(`\u{1F4E7} ${effect[1] || ""}`);
794
+ break;
795
+ case "persist":
796
+ summaries.push(`\u{1F4BE} ${effect[1] || "save"}`);
797
+ break;
798
+ case "navigate":
799
+ summaries.push(`\u{1F517} nav`);
800
+ break;
801
+ case "spawn":
802
+ summaries.push(`+ ${effect[1] || "spawn"}`);
803
+ break;
804
+ case "despawn":
805
+ summaries.push(`- despawn`);
806
+ break;
807
+ default:
808
+ summaries.push(op);
809
+ }
810
+ });
811
+ return summaries.join(" | ");
812
+ }
813
+ function extractOutputsFromTransitions(transitions2) {
814
+ const outputs = /* @__PURE__ */ new Set();
815
+ transitions2.forEach((t) => {
816
+ if (t.effects) {
817
+ t.effects.forEach((effect) => {
818
+ if (Array.isArray(effect)) {
819
+ const op = effect[0];
820
+ if (["emit", "notify", "persist", "navigate", "call-service"].includes(op)) {
821
+ if (isArraySExpr(effect)) {
822
+ const humanText = formatSExprEffectToDomain(effect);
823
+ outputs.add(humanText);
824
+ }
825
+ }
826
+ }
827
+ });
828
+ }
829
+ });
830
+ return Array.from(outputs);
831
+ }
832
+ function getNodeRadius(stateName, config) {
833
+ const baseRadius = config.nodeRadius;
834
+ const textLength = stateName.length;
835
+ if (textLength > 12) return baseRadius + 25;
836
+ if (textLength > 8) return baseRadius + 15;
837
+ if (textLength > 6) return baseRadius + 8;
838
+ return baseRadius;
839
+ }
840
+ function calculateLayout(states, transitions2, options, config) {
841
+ const positions = {};
842
+ const entityBoxWidth = options.hasEntity ? 200 : 0;
843
+ const outputBoxWidth = options.hasOutputs ? 200 : 0;
844
+ const leftOffset = 100 + entityBoxWidth;
845
+ const initialState = states.find((s) => s.isInitial) || states[0];
846
+ states.filter((s) => s.isFinal);
847
+ states.filter((s) => !s.isInitial && !s.isFinal);
848
+ let maxLabelLength = 0;
849
+ transitions2.forEach((t) => {
850
+ if (t.effects && t.effects.length > 0) {
851
+ const summary = getEffectSummary(t.effects);
852
+ maxLabelLength = Math.max(maxLabelLength, summary.length);
853
+ }
854
+ if (t.guard) {
855
+ const guardStr = formatGuard(t.guard);
856
+ maxLabelLength = Math.max(maxLabelLength, guardStr.length);
857
+ }
858
+ if (t.event) {
859
+ maxLabelLength = Math.max(maxLabelLength, t.event.length);
860
+ }
861
+ });
862
+ const labelWidth = Math.min(maxLabelLength * 10, 350);
863
+ const dynamicSpacing = Math.min(Math.max(config.nodeSpacing, labelWidth + 100), 400);
864
+ const stateColumn = {};
865
+ if (initialState) {
866
+ const queue = [{ name: initialState.name, col: 0 }];
867
+ const visited = /* @__PURE__ */ new Set();
868
+ while (queue.length > 0) {
869
+ const { name, col } = queue.shift();
870
+ if (visited.has(name)) continue;
871
+ visited.add(name);
872
+ if (stateColumn[name] === void 0) {
873
+ stateColumn[name] = col;
874
+ }
875
+ transitions2.forEach((t) => {
876
+ if (t.from === name && t.from !== t.to && !visited.has(t.to)) {
877
+ queue.push({ name: t.to, col: col + 1 });
878
+ }
879
+ });
880
+ }
881
+ }
882
+ states.forEach((s) => {
883
+ if (stateColumn[s.name] === void 0) {
884
+ stateColumn[s.name] = 0;
885
+ }
886
+ });
887
+ const columns = {};
888
+ Object.entries(stateColumn).forEach(([name, col]) => {
889
+ if (!columns[col]) columns[col] = [];
890
+ columns[col].push(name);
891
+ });
892
+ Object.values(columns).forEach((stateNames) => {
893
+ stateNames.sort((a, b) => {
894
+ const stateA = states.find((s) => s.name === a);
895
+ const stateB = states.find((s) => s.name === b);
896
+ if (stateA?.isInitial) return -1;
897
+ if (stateB?.isInitial) return 1;
898
+ if (stateA?.isFinal && !stateB?.isFinal) return 1;
899
+ if (stateB?.isFinal && !stateA?.isFinal) return -1;
900
+ return a.localeCompare(b);
901
+ });
902
+ });
903
+ const numColumns = Math.max(...Object.keys(columns).map(Number)) + 1;
904
+ const maxRowsInColumn = Math.max(...Object.values(columns).map((arr) => arr.length));
905
+ const minVerticalSpacing = 420;
906
+ const tooltipPadding = 150;
907
+ const width = Math.max(1400, numColumns * dynamicSpacing + entityBoxWidth + outputBoxWidth + 400);
908
+ const height = Math.max(1e3, maxRowsInColumn * minVerticalSpacing + 350 + tooltipPadding);
909
+ Object.entries(columns).forEach(([colStr, stateNames]) => {
910
+ const col = parseInt(colStr);
911
+ const x = leftOffset + col * dynamicSpacing;
912
+ const numInColumn = stateNames.length;
913
+ const verticalSpacing = Math.max(minVerticalSpacing, height / (numInColumn + 1));
914
+ stateNames.forEach((stateName, rowIndex) => {
915
+ const state = states.find((s) => s.name === stateName);
916
+ if (state) {
917
+ const y = verticalSpacing * (rowIndex + 1);
918
+ positions[stateName] = { x, y, state };
919
+ }
920
+ });
921
+ });
922
+ return { positions, width, height: height + 60 };
923
+ }
924
+ function escapeXml(unsafe) {
925
+ return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
926
+ }
927
+ function createArrowMarkerSvg(id, color, config) {
928
+ return `<marker id="${id}" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="${config.arrowSize}" markerHeight="${config.arrowSize}" orient="auto-start-reverse">
929
+ <path d="M 0 0 L 10 5 L 0 10 z" fill="${color}"/>
930
+ </marker>`;
931
+ }
932
+ function drawStateSvg(name, x, y, state, config) {
933
+ const radius = getNodeRadius(name, config);
934
+ let borderColor = config.colors.nodeBorder;
935
+ let borderWidth = 2;
936
+ if (state.isInitial) {
937
+ borderColor = config.colors.initialNode;
938
+ borderWidth = 3;
939
+ } else if (state.isFinal) {
940
+ borderColor = config.colors.finalNode;
941
+ borderWidth = 3;
942
+ }
943
+ let svg = `<g class="state-node">
944
+ <circle cx="${x}" cy="${y}" r="${radius}" fill="${config.colors.node}" stroke="${borderColor}" stroke-width="${borderWidth}"/>`;
945
+ if (state.isFinal) {
946
+ svg += `<circle cx="${x}" cy="${y}" r="${radius - 6}" fill="none" stroke="${borderColor}" stroke-width="2"/>`;
947
+ }
948
+ if (state.isInitial) {
949
+ svg += `<path d="M ${x - radius - config.initialIndicatorOffset} ${y} L ${x - radius - 5} ${y}" stroke="${config.colors.initial}" stroke-width="2" fill="none" marker-end="url(#arrow-initial)"/>`;
950
+ }
951
+ svg += `<text x="${x}" y="${y + 7}" text-anchor="middle" fill="${config.colors.nodeText}" font-family="Inter, sans-serif" font-size="18px" font-weight="600">${escapeXml(name)}</text>`;
952
+ svg += `</g>`;
953
+ return svg;
954
+ }
955
+ function drawTransitionPathSvg(from, to, transitions2, positions, config) {
956
+ const fromPos = positions[from];
957
+ const toPos = positions[to];
958
+ if (!fromPos || !toPos) return "";
959
+ const relevantTransitions = transitions2.filter((t) => t.from === from && t.to === to);
960
+ if (relevantTransitions.length === 0) return "";
961
+ const fromRadius = getNodeRadius(from, config);
962
+ const toRadius = getNodeRadius(to, config);
963
+ const dx = toPos.x - fromPos.x;
964
+ const dy = toPos.y - fromPos.y;
965
+ const dist = Math.sqrt(dx * dx + dy * dy);
966
+ if (dist === 0) return "";
967
+ const nx = dx / dist;
968
+ const ny = dy / dist;
969
+ const startX = fromPos.x + nx * fromRadius;
970
+ const startY = fromPos.y + ny * fromRadius;
971
+ const endX = toPos.x - nx * (toRadius + 5);
972
+ const endY = toPos.y - ny * (toRadius + 5);
973
+ const hasReverse = transitions2.some((t) => t.from === to && t.to === from);
974
+ const isReverse = hasReverse && from > to;
975
+ const baseOffset = hasReverse ? 50 : 30;
976
+ const curveOffset = baseOffset + (relevantTransitions.length > 1 ? 20 : 0);
977
+ const curveDirection = isReverse ? 1 : -1;
978
+ const midX = (startX + endX) / 2;
979
+ const midY = (startY + endY) / 2 + curveOffset * curveDirection;
980
+ return `<path class="transition-path" data-from="${from}" data-to="${to}" d="M ${startX} ${startY} Q ${midX} ${midY} ${endX} ${endY}" stroke="${config.colors.arrow}" stroke-width="1.5" fill="none" marker-end="url(#arrow)"/>`;
981
+ }
982
+ function drawTransitionLabelsSvg(from, to, transitions2, positions, config) {
983
+ const fromPos = positions[from];
984
+ const toPos = positions[to];
985
+ if (!fromPos || !toPos) return "";
986
+ const relevantTransitions = transitions2.filter((t) => t.from === from && t.to === to);
987
+ if (relevantTransitions.length === 0) return "";
988
+ const fromRadius = getNodeRadius(from, config);
989
+ const toRadius = getNodeRadius(to, config);
990
+ const dx = toPos.x - fromPos.x;
991
+ const dy = toPos.y - fromPos.y;
992
+ const dist = Math.sqrt(dx * dx + dy * dy);
993
+ if (dist === 0) return "";
994
+ const nx = dx / dist;
995
+ const ny = dy / dist;
996
+ const startX = fromPos.x + nx * fromRadius;
997
+ const startY = fromPos.y + ny * fromRadius;
998
+ const endX = toPos.x - nx * (toRadius + 5);
999
+ const endY = toPos.y - ny * (toRadius + 5);
1000
+ const hasReverse = transitions2.some((t) => t.from === to && t.to === from);
1001
+ const isReverse = hasReverse && from > to;
1002
+ const baseOffset = hasReverse ? 50 : 40;
1003
+ const curveOffset = baseOffset + (relevantTransitions.length > 1 ? 25 : 0);
1004
+ const curveDirection = isReverse ? 1 : -1;
1005
+ const midX = (startX + endX) / 2;
1006
+ const midY = (startY + endY) / 2 + curveOffset * curveDirection;
1007
+ let svg = "";
1008
+ relevantTransitions.forEach((transition, index) => {
1009
+ const blockOffset = index * 60 * curveDirection;
1010
+ const dataAttrs = `data-from="${from}" data-to="${to}" data-event="${transition.event}"`;
1011
+ const labelY = midY + curveDirection * 5 + blockOffset;
1012
+ svg += `<g class="transition-group" ${dataAttrs}>`;
1013
+ svg += `<text class="transition-label transition-event" x="${midX}" y="${labelY}" text-anchor="middle" fill="${config.colors.arrowText}" font-family="JetBrains Mono, monospace" font-size="14px" font-weight="600">${escapeXml(transition.event)}</text>`;
1014
+ const hasGuard = !!transition.guard;
1015
+ const guardText = hasGuard ? formatGuardHuman(transition.guard) : "";
1016
+ const effectLines = transition.effects ? formatEffectsHuman(transition.effects) : [];
1017
+ const hasEffects = effectLines.length > 0;
1018
+ if (hasGuard || hasEffects) {
1019
+ const tooltipStartY = labelY + 20 * curveDirection;
1020
+ const lineHeight = 18;
1021
+ const padding = 12;
1022
+ let maxTextWidth = 0;
1023
+ if (guardText) maxTextWidth = Math.max(maxTextWidth, guardText.length * 7);
1024
+ effectLines.forEach((line) => {
1025
+ maxTextWidth = Math.max(maxTextWidth, line.length * 7);
1026
+ });
1027
+ const boxWidth = Math.max(180, Math.min(maxTextWidth + padding * 2 + 20, 400));
1028
+ const numLines = (hasGuard ? 1 : 0) + effectLines.length;
1029
+ const boxHeight = numLines * lineHeight + padding * 2;
1030
+ const boxY = curveDirection > 0 ? tooltipStartY : tooltipStartY - boxHeight;
1031
+ svg += `<g class="transition-detail">`;
1032
+ svg += `<rect x="${midX - boxWidth / 2}" y="${boxY}" width="${boxWidth}" height="${boxHeight}" fill="rgba(22, 27, 34, 0.95)" stroke="${config.colors.nodeBorder}" stroke-width="1" rx="6"/>`;
1033
+ let currentY = boxY + padding + 12;
1034
+ if (hasGuard && guardText) {
1035
+ svg += `<text x="${midX - boxWidth / 2 + padding}" y="${currentY}" fill="${config.colors.guardText}" font-family="Inter, sans-serif" font-size="12px">`;
1036
+ svg += `<tspan font-weight="600">Guard:</tspan> ${escapeXml(guardText)}</text>`;
1037
+ currentY += lineHeight;
1038
+ }
1039
+ if (hasEffects) {
1040
+ effectLines.forEach((effectText, idx) => {
1041
+ const prefix = idx === 0 ? "Then: " : " ";
1042
+ svg += `<text x="${midX - boxWidth / 2 + padding}" y="${currentY}" fill="${config.colors.effectText}" font-family="Inter, sans-serif" font-size="12px">`;
1043
+ svg += `<tspan font-weight="${idx === 0 ? "600" : "400"}">${prefix}</tspan>${escapeXml(effectText)}</text>`;
1044
+ currentY += lineHeight;
1045
+ });
1046
+ }
1047
+ svg += `</g>`;
1048
+ }
1049
+ svg += `</g>`;
1050
+ });
1051
+ return svg;
1052
+ }
1053
+ function drawEntityInputSvg(entity, x, y, _height) {
1054
+ const fieldCount = entity.fields ? entity.fields.length : 0;
1055
+ const boxWidth = 160;
1056
+ const boxHeight = Math.max(80, fieldCount * 22 + 50);
1057
+ const boxY = y - boxHeight / 2;
1058
+ let svg = `<g class="entity-input">
1059
+ <rect x="${x}" y="${boxY}" width="${boxWidth}" height="${boxHeight}" fill="#1a1f2e" stroke="#4a9eff" stroke-width="2" rx="8"/>
1060
+ <text x="${x + boxWidth / 2}" y="${boxY + 24}" text-anchor="middle" fill="#4a9eff" font-family="Inter, sans-serif" font-size="14px" font-weight="600">\u{1F4E6} ${escapeXml(entity.name || "Entity")}</text>`;
1061
+ if (entity.fields && entity.fields.length > 0) {
1062
+ entity.fields.forEach((field, idx) => {
1063
+ const fieldName = typeof field === "string" ? field : field.name;
1064
+ svg += `<text x="${x + 12}" y="${boxY + 48 + idx * 20}" fill="#8b949e" font-family="JetBrains Mono, monospace" font-size="11px">\u2022 ${escapeXml(fieldName)}</text>`;
1065
+ });
1066
+ }
1067
+ svg += `<path d="M ${x + boxWidth + 5} ${y} L ${x + boxWidth + 40} ${y}" stroke="#4a9eff" stroke-width="2" fill="none" marker-end="url(#arrow-input)"/>`;
1068
+ svg += `</g>`;
1069
+ return svg;
1070
+ }
1071
+ function drawOutputsSvg(outputs, x, y, height) {
1072
+ if (!outputs || outputs.length === 0) return "";
1073
+ const maxOutputLength = Math.max(...outputs.map((o) => o.length));
1074
+ const boxWidth = Math.max(200, maxOutputLength * 7 + 30);
1075
+ const lineHeight = 22;
1076
+ const boxHeight = outputs.length * lineHeight + 50;
1077
+ const boxY = y - boxHeight / 2;
1078
+ let svg = `<g class="outputs">
1079
+ <rect x="${x}" y="${boxY}" width="${boxWidth}" height="${boxHeight}" fill="#1a1f2e" stroke="#ffb86c" stroke-width="2" rx="8"/>
1080
+ <text x="${x + boxWidth / 2}" y="${boxY + 24}" text-anchor="middle" fill="#ffb86c" font-family="Inter, sans-serif" font-size="13px" font-weight="600">\u{1F4E4} External Effects</text>`;
1081
+ outputs.forEach((output, idx) => {
1082
+ svg += `<text x="${x + 12}" y="${boxY + 48 + idx * lineHeight}" fill="#e6edf3" font-family="Inter, sans-serif" font-size="11px">\u2022 ${escapeXml(output)}</text>`;
1083
+ });
1084
+ svg += `</g>`;
1085
+ return svg;
1086
+ }
1087
+ function drawLegendSvg(y, config) {
1088
+ const items = [
1089
+ { label: "Initial", color: config.colors.initialNode },
1090
+ { label: "Final", color: config.colors.finalNode },
1091
+ { label: "State", color: config.colors.nodeBorder }
1092
+ ];
1093
+ let svg = `<g class="legend">`;
1094
+ let x = 20;
1095
+ items.forEach((item) => {
1096
+ svg += `<circle cx="${x}" cy="${y}" r="6" fill="${config.colors.node}" stroke="${item.color}" stroke-width="2"/>`;
1097
+ svg += `<text x="${x + 12}" y="${y + 4}" fill="${config.colors.arrowText}" font-family="Inter, sans-serif" font-size="10px">${escapeXml(item.label)}</text>`;
1098
+ x += 70;
1099
+ });
1100
+ svg += `</g>`;
1101
+ return svg;
1102
+ }
1103
+ function renderStateMachineToSvg(stateMachine, options = {}, config = DEFAULT_CONFIG) {
1104
+ const states = stateMachine.states || [];
1105
+ const transitions2 = stateMachine.transitions || [];
1106
+ const title = options.title || "";
1107
+ const entity = options.entity;
1108
+ const outputs = extractOutputsFromTransitions(transitions2);
1109
+ const layoutOptions = {
1110
+ hasEntity: !!entity,
1111
+ hasOutputs: outputs.length > 0
1112
+ };
1113
+ const { positions, width, height } = calculateLayout(states, transitions2, layoutOptions, config);
1114
+ let svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height + 40}" viewBox="0 0 ${width} ${height + 40}" class="orbital-state-machine" style="display: block; max-width: none;">`;
1115
+ svg += `<defs>`;
1116
+ svg += createArrowMarkerSvg("arrow", config.colors.arrow, config);
1117
+ svg += createArrowMarkerSvg("arrow-initial", config.colors.initial, config);
1118
+ svg += createArrowMarkerSvg("arrow-input", "#4a9eff", config);
1119
+ svg += createArrowMarkerSvg("arrow-output", "#ffb86c", config);
1120
+ svg += `</defs>`;
1121
+ svg += `<rect x="0" y="0" width="${width}" height="${height + 40}" fill="${config.colors.background}" rx="8"/>`;
1122
+ if (title) {
1123
+ svg += `<text x="${width / 2}" y="20" text-anchor="middle" fill="${config.colors.nodeText}" font-family="Inter, sans-serif" font-size="14px" font-weight="600">${escapeXml(title)}</text>`;
1124
+ }
1125
+ const offsetY = title ? 30 : 0;
1126
+ svg += `<g transform="translate(0, ${offsetY})">`;
1127
+ if (entity) {
1128
+ svg += drawEntityInputSvg(entity, 20, height / 2);
1129
+ }
1130
+ const drawnPairs = /* @__PURE__ */ new Set();
1131
+ transitions2.forEach((transition) => {
1132
+ const pairKey = `${transition.from}->${transition.to}`;
1133
+ if (!drawnPairs.has(pairKey)) {
1134
+ drawnPairs.add(pairKey);
1135
+ svg += drawTransitionPathSvg(transition.from, transition.to, transitions2, positions, config);
1136
+ }
1137
+ });
1138
+ for (const [name, pos] of Object.entries(positions)) {
1139
+ svg += drawStateSvg(name, pos.x, pos.y, pos.state, config);
1140
+ }
1141
+ drawnPairs.clear();
1142
+ transitions2.forEach((transition) => {
1143
+ const pairKey = `${transition.from}->${transition.to}`;
1144
+ if (!drawnPairs.has(pairKey)) {
1145
+ drawnPairs.add(pairKey);
1146
+ svg += drawTransitionLabelsSvg(transition.from, transition.to, transitions2, positions, config);
1147
+ }
1148
+ });
1149
+ if (outputs.length > 0) {
1150
+ const maxX = Math.max(...Object.values(positions).map((p) => p.x));
1151
+ svg += drawOutputsSvg(outputs, maxX + config.nodeRadius + 60, height / 2);
1152
+ }
1153
+ svg += `</g>`;
1154
+ svg += drawLegendSvg(height + 25, config);
1155
+ svg += `</svg>`;
1156
+ return svg;
1157
+ }
1158
+ function extractStateMachine(data) {
1159
+ if (!data || typeof data !== "object") return null;
1160
+ const obj = data;
1161
+ if (obj.states && obj.transitions) {
1162
+ return obj;
1163
+ }
1164
+ if (obj.stateMachine) {
1165
+ return obj.stateMachine;
1166
+ }
1167
+ if (Array.isArray(obj.traits)) {
1168
+ const traitWithSM = obj.traits.find(
1169
+ (t) => typeof t === "object" && t !== null && "stateMachine" in t
1170
+ );
1171
+ if (traitWithSM && typeof traitWithSM === "object" && "stateMachine" in traitWithSM) {
1172
+ return traitWithSM.stateMachine;
1173
+ }
1174
+ }
1175
+ return null;
1176
+ }
1177
+ function calculateTransitionPathData(from, to, transitions2, positions, config) {
1178
+ const fromPos = positions[from];
1179
+ const toPos = positions[to];
1180
+ if (!fromPos || !toPos) return null;
1181
+ const relevantTransitions = transitions2.filter((t) => t.from === from && t.to === to);
1182
+ if (relevantTransitions.length === 0) return null;
1183
+ const fromRadius = getNodeRadius(from, config);
1184
+ const toRadius = getNodeRadius(to, config);
1185
+ if (from === to) {
1186
+ const loopRadius = 50;
1187
+ const cx = fromPos.x;
1188
+ const cy = fromPos.y - fromRadius - loopRadius;
1189
+ const startAngle = -0.5;
1190
+ const endAngle = 0.5;
1191
+ const startX2 = fromPos.x + Math.cos(-Math.PI / 2 + startAngle) * fromRadius;
1192
+ const startY2 = fromPos.y + Math.sin(-Math.PI / 2 + startAngle) * fromRadius;
1193
+ const endX2 = fromPos.x + Math.cos(-Math.PI / 2 + endAngle) * fromRadius;
1194
+ const endY2 = fromPos.y + Math.sin(-Math.PI / 2 + endAngle) * fromRadius;
1195
+ const pathData = `M ${startX2} ${startY2} A ${loopRadius} ${loopRadius} 0 1 1 ${endX2} ${endY2}`;
1196
+ return {
1197
+ pathData,
1198
+ labelX: cx,
1199
+ labelY: cy - loopRadius * 0.5
1200
+ };
1201
+ }
1202
+ const dx = toPos.x - fromPos.x;
1203
+ const dy = toPos.y - fromPos.y;
1204
+ const dist = Math.sqrt(dx * dx + dy * dy);
1205
+ if (dist === 0) return null;
1206
+ const nx = dx / dist;
1207
+ const ny = dy / dist;
1208
+ const startX = fromPos.x + nx * fromRadius;
1209
+ const startY = fromPos.y + ny * fromRadius;
1210
+ const endX = toPos.x - nx * (toRadius + 5);
1211
+ const endY = toPos.y - ny * (toRadius + 5);
1212
+ const hasReverse = transitions2.some((t) => t.from === to && t.to === from);
1213
+ const isReverse = hasReverse && from > to;
1214
+ const baseOffset = hasReverse ? 50 : 30;
1215
+ const curveOffset = baseOffset + (relevantTransitions.length > 1 ? 20 : 0);
1216
+ const curveDirection = isReverse ? 1 : -1;
1217
+ const midX = (startX + endX) / 2;
1218
+ const midY = (startY + endY) / 2 + curveOffset * curveDirection;
1219
+ return {
1220
+ pathData: `M ${startX} ${startY} Q ${midX} ${midY} ${endX} ${endY}`,
1221
+ labelX: midX,
1222
+ labelY: midY + curveDirection * 5
1223
+ };
1224
+ }
1225
+ function renderStateMachineToDomData(stateMachine, options = {}, config = DEFAULT_CONFIG) {
1226
+ const states = stateMachine.states || [];
1227
+ const transitions2 = stateMachine.transitions || [];
1228
+ const title = options.title || "";
1229
+ const entity = options.entity;
1230
+ const outputs = extractOutputsFromTransitions(transitions2);
1231
+ const layoutOptions = {
1232
+ hasEntity: !!entity,
1233
+ hasOutputs: outputs.length > 0
1234
+ };
1235
+ const { positions, width, height } = calculateLayout(states, transitions2, layoutOptions, config);
1236
+ const domStates = Object.entries(positions).map(([name, pos]) => ({
1237
+ id: `state-${name}`,
1238
+ name,
1239
+ x: pos.x,
1240
+ y: pos.y,
1241
+ radius: getNodeRadius(name, config),
1242
+ isInitial: pos.state.isInitial ?? false,
1243
+ isFinal: pos.state.isFinal ?? false,
1244
+ description: pos.state.description
1245
+ }));
1246
+ const domPaths = [];
1247
+ const domLabels = [];
1248
+ const drawnPairs = /* @__PURE__ */ new Set();
1249
+ transitions2.forEach((transition, idx) => {
1250
+ const pairKey = `${transition.from}->${transition.to}`;
1251
+ if (!drawnPairs.has(pairKey)) {
1252
+ drawnPairs.add(pairKey);
1253
+ const pathData2 = calculateTransitionPathData(
1254
+ transition.from,
1255
+ transition.to,
1256
+ transitions2,
1257
+ positions,
1258
+ config
1259
+ );
1260
+ if (pathData2) {
1261
+ domPaths.push({
1262
+ id: `path-${transition.from}-${transition.to}`,
1263
+ from: transition.from,
1264
+ to: transition.to,
1265
+ pathData: pathData2.pathData,
1266
+ labelX: pathData2.labelX,
1267
+ labelY: pathData2.labelY
1268
+ });
1269
+ }
1270
+ }
1271
+ const guardText = transition.guard ? formatGuardHuman(transition.guard) : void 0;
1272
+ const effectTexts = transition.effects ? formatEffectsHuman(transition.effects) : [];
1273
+ const hasDetails = !!guardText || effectTexts.length > 0;
1274
+ const pathData = calculateTransitionPathData(
1275
+ transition.from,
1276
+ transition.to,
1277
+ transitions2,
1278
+ positions,
1279
+ config
1280
+ );
1281
+ if (pathData) {
1282
+ const sameEventIndex = domLabels.filter(
1283
+ (l) => l.from === transition.from && l.to === transition.to
1284
+ ).length;
1285
+ const labelOffset = sameEventIndex * 60;
1286
+ domLabels.push({
1287
+ id: `label-${transition.from}-${transition.to}-${idx}`,
1288
+ from: transition.from,
1289
+ to: transition.to,
1290
+ event: transition.event,
1291
+ x: pathData.labelX,
1292
+ y: pathData.labelY + labelOffset,
1293
+ guardText,
1294
+ effectTexts,
1295
+ hasDetails
1296
+ });
1297
+ }
1298
+ });
1299
+ let domEntity;
1300
+ if (entity) {
1301
+ const fieldCount = entity.fields ? entity.fields.length : 0;
1302
+ const boxWidth = 160;
1303
+ const boxHeight = Math.max(80, fieldCount * 22 + 50);
1304
+ domEntity = {
1305
+ name: entity.name || "Entity",
1306
+ fields: entity.fields?.map((f) => typeof f === "string" ? f : f.name) || [],
1307
+ x: 20,
1308
+ y: height / 2 - boxHeight / 2,
1309
+ width: boxWidth,
1310
+ height: boxHeight
1311
+ };
1312
+ }
1313
+ let domOutputs;
1314
+ if (outputs.length > 0) {
1315
+ const maxX = Math.max(...Object.values(positions).map((p) => p.x));
1316
+ const maxOutputLength = Math.max(...outputs.map((o) => o.length));
1317
+ const boxWidth = Math.max(200, maxOutputLength * 7 + 30);
1318
+ const lineHeight = 22;
1319
+ const boxHeight = outputs.length * lineHeight + 50;
1320
+ domOutputs = {
1321
+ outputs,
1322
+ x: maxX + config.nodeRadius + 300,
1323
+ y: height / 2 - boxHeight / 2,
1324
+ width: boxWidth,
1325
+ height: boxHeight
1326
+ };
1327
+ }
1328
+ return {
1329
+ width,
1330
+ height: height + 40,
1331
+ title: title || void 0,
1332
+ states: domStates,
1333
+ paths: domPaths,
1334
+ labels: domLabels,
1335
+ entity: domEntity,
1336
+ outputs: domOutputs,
1337
+ config
1338
+ };
1339
+ }
1340
+
1341
+ // lib/parseContentSegments.ts
1342
+ function tryParseOrbitalSchema(code) {
1343
+ try {
1344
+ const parsed = JSON.parse(code);
1345
+ if (parsed.states && parsed.transitions || Array.isArray(parsed.orbitals)) {
1346
+ return parsed;
1347
+ }
1348
+ } catch {
1349
+ }
1350
+ return null;
1351
+ }
1352
+ function parseMarkdownWithCodeBlocks(content) {
1353
+ if (!content) return [];
1354
+ const segments = [];
1355
+ const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g;
1356
+ let lastIndex = 0;
1357
+ let match;
1358
+ while ((match = codeBlockRegex.exec(content)) !== null) {
1359
+ const before = content.slice(lastIndex, match.index);
1360
+ if (before.trim()) {
1361
+ segments.push({ type: "markdown", content: before });
1362
+ }
1363
+ const language = match[1] || "text";
1364
+ const code = match[2].trim();
1365
+ if (language === "json" || language === "orb") {
1366
+ const schema = tryParseOrbitalSchema(code);
1367
+ if (schema) {
1368
+ segments.push({ type: "orbital", language, content: code, schema });
1369
+ lastIndex = codeBlockRegex.lastIndex;
1370
+ continue;
1371
+ }
1372
+ }
1373
+ segments.push({ type: "code", language, content: code });
1374
+ lastIndex = codeBlockRegex.lastIndex;
1375
+ }
1376
+ const remaining = content.slice(lastIndex);
1377
+ if (remaining.trim()) {
1378
+ segments.push({ type: "markdown", content: remaining });
1379
+ }
1380
+ return segments;
1381
+ }
1382
+ function parseContentSegments(content) {
1383
+ if (!content) return [];
1384
+ const segments = [];
1385
+ const tagRegex = /<question>([\s\S]*?)<\/question>\s*<answer>([\s\S]*?)<\/answer>/gi;
1386
+ let lastIndex = 0;
1387
+ let match;
1388
+ while ((match = tagRegex.exec(content)) !== null) {
1389
+ const before = content.slice(lastIndex, match.index);
1390
+ if (before.trim()) {
1391
+ segments.push(...parseMarkdownWithCodeBlocks(before));
1392
+ }
1393
+ segments.push({
1394
+ type: "quiz",
1395
+ question: match[1].trim(),
1396
+ answer: match[2].trim()
1397
+ });
1398
+ lastIndex = tagRegex.lastIndex;
1399
+ }
1400
+ const remaining = content.slice(lastIndex);
1401
+ if (remaining.trim()) {
1402
+ segments.push(...parseMarkdownWithCodeBlocks(remaining));
1403
+ }
1404
+ return segments;
1405
+ }
1406
+
1407
+ export { ApiError, DEFAULT_CONFIG, apiClient, bindCanvasCapture, bindEventBus, bindTraitStateGetter, clearDebugEvents, clearEntityProvider, clearGuardHistory, clearTicks, clearTraits, clearVerification, cn, debug, debugCollision, debugError, debugGameState, debugGroup, debugGroupEnd, debugInput, debugPhysics, debugTable, debugTime, debugTimeEnd, debugWarn, extractOutputsFromTransitions, extractStateMachine, formatGuard, formatNestedFieldLabel, getAllChecks, getAllTicks, getAllTraits, getBridgeHealth, getDebugEvents, getEffectSummary, getEntitiesByType, getEntityById, getEntitySnapshot, getEventsBySource, getEventsByType, getGuardEvaluationsForTrait, getGuardHistory, getNestedValue, getRecentEvents, getRecentGuardEvaluations, getSnapshot, getSummary, getTick, getTrait, getTransitions, getTransitionsForTrait, initDebugShortcut, isDebugEnabled, logDebugEvent, logEffectExecuted, logError, logEventFired, logInfo, logStateChange, logWarning, onDebugToggle, parseContentSegments, parseMarkdownWithCodeBlocks, recordGuardEvaluation, recordTransition, registerCheck, registerTick, registerTrait, renderStateMachineToDomData, renderStateMachineToSvg, setDebugEnabled, setEntityProvider, setTickActive, subscribeToDebugEvents, subscribeToGuardChanges, subscribeToTickChanges, subscribeToTraitChanges, subscribeToVerification, toggleDebug, unregisterTick, unregisterTrait, updateAssetStatus, updateBridgeHealth, updateCheck, updateGuardResult, updateTickExecution, updateTraitState, waitForTransition };