@almadar/ui 2.15.7 → 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 (127) 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-K43H3ZDY.js → components/index.cjs} +24780 -16651
  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/UISlotRenderer.d.ts +1 -0
  76. package/dist/components/organisms/game/three/index.cjs +2525 -0
  77. package/dist/components/organisms/game/three/index.js +1795 -50
  78. package/dist/components/organisms/index.d.ts +9 -0
  79. package/dist/components/organisms/marketing-types.d.ts +87 -0
  80. package/dist/components/templates/AboutPageTemplate.d.ts +26 -0
  81. package/dist/components/templates/DashboardLayout.d.ts +2 -1
  82. package/dist/components/templates/FeatureDetailPageTemplate.d.ts +27 -0
  83. package/dist/components/templates/LandingPageTemplate.d.ts +31 -0
  84. package/dist/components/templates/PricingPageTemplate.d.ts +26 -0
  85. package/dist/components/templates/index.d.ts +4 -0
  86. package/dist/context/index.cjs +550 -0
  87. package/dist/context/index.js +420 -6
  88. package/dist/docs/index.cjs +4015 -0
  89. package/dist/docs/index.d.cts +412 -0
  90. package/dist/docs/index.d.ts +29 -0
  91. package/dist/docs/index.js +3977 -0
  92. package/dist/hooks/index.cjs +2606 -0
  93. package/dist/hooks/index.js +2535 -8
  94. package/dist/illustrations/index.cjs +3004 -0
  95. package/dist/illustrations/index.d.cts +261 -0
  96. package/dist/illustrations/index.d.ts +35 -0
  97. package/dist/illustrations/index.js +2971 -0
  98. package/dist/{chunk-XL7WB2O5.js → lib/index.cjs} +454 -274
  99. package/dist/lib/index.js +1407 -3
  100. package/dist/locales/index.cjs +340 -0
  101. package/dist/locales/index.js +105 -2
  102. package/dist/marketing/index.cjs +4683 -0
  103. package/dist/marketing/index.d.cts +831 -0
  104. package/dist/marketing/index.d.ts +62 -0
  105. package/dist/marketing/index.js +4626 -0
  106. package/dist/providers/index.cjs +4811 -0
  107. package/dist/providers/index.js +4765 -11
  108. package/dist/{chunk-K2D5D3WK.js → renderer/index.cjs} +101 -42
  109. package/dist/renderer/index.js +1036 -2
  110. package/dist/runtime/index.cjs +4400 -0
  111. package/dist/runtime/index.js +3615 -19
  112. package/dist/{chunk-N7MVUW4R.js → stores/index.cjs} +24 -1
  113. package/dist/stores/index.js +194 -2
  114. package/dist/tsup.config.d.ts +2 -1
  115. package/package.json +27 -12
  116. package/tailwind-preset.cjs +27 -2
  117. package/themes/index.css +22 -20
  118. package/dist/chunk-3HJHHULT.js +0 -93
  119. package/dist/chunk-3JGAROCW.js +0 -149
  120. package/dist/chunk-4N3BAPDB.js +0 -1667
  121. package/dist/chunk-CDIOHSKG.js +0 -661
  122. package/dist/chunk-DKQN5FVU.js +0 -279
  123. package/dist/chunk-GF6RQBO7.js +0 -375
  124. package/dist/chunk-PKBMQBKP.js +0 -5
  125. package/dist/chunk-QIABKRCN.js +0 -107
  126. package/dist/chunk-SD3KVCY6.js +0 -1465
  127. package/dist/chunk-YXZM3WCF.js +0 -222
@@ -1,8 +1,2535 @@
1
- export { ENTITY_EVENTS, useAgentChat, useCompile, useConnectGitHub, useCreateEntity, useDeepAgentGeneration, useDeleteEntity, useDisconnectGitHub, useEntities, useEntitiesByType, useEntity as useEntityById, useEntityMutations, useExtensions, useFileEditor, useFileSystem, useGitHubBranches, useGitHubRepo, useGitHubRepos, useGitHubStatus, useInput, useOrbitalHistory, useOrbitalMutations, usePhysics, usePinchZoom, usePlayer, usePreview, useResolvedEntity, useSelectedEntity, useSendOrbitalEvent, useSingletonEntity, useUIEvents, useUpdateEntity, useValidation } from '../chunk-SD3KVCY6.js';
2
- export { clearEntities, getAllEntities, getByType, getEntity, getSingleton, removeEntity, spawnEntity, updateEntity, updateSingleton } from '../chunk-N7MVUW4R.js';
3
- import '../chunk-3HJHHULT.js';
4
- export { EntityDataProvider, I18nProvider, createTranslate, entityDataKeys, parseQueryBinding, useAuthContext, useDragReorder, useEntity, useEntityDataAdapter, useEntityDetail, useEntityList, useEntityListSuspense, useEntitySuspense, useInfiniteScroll, useLongPress, usePullToRefresh, useQuerySingleton, useSwipeGesture, useTranslate } from '../chunk-CDIOHSKG.js';
5
- export { useEmitEvent, useEventBus, useEventListener } from '../chunk-YXZM3WCF.js';
6
- export { DEFAULT_SLOTS, useUISlotManager } from '../chunk-3JGAROCW.js';
7
- import '../chunk-QIABKRCN.js';
8
- import '../chunk-PKBMQBKP.js';
1
+ import React3, { createContext, useCallback, useState, useEffect, useMemo, useContext, useRef, useSyncExternalStore } from 'react';
2
+ import 'react/jsx-runtime';
3
+ import { useQueryClient, useMutation, useQuery } from '@tanstack/react-query';
4
+
5
+ function useOrbitalHistory(options) {
6
+ const { appId, authToken, userId, onHistoryChange, onRevertSuccess } = options;
7
+ const getHeaders2 = useCallback(() => {
8
+ const headers = {
9
+ "Content-Type": "application/json"
10
+ };
11
+ if (authToken) {
12
+ headers["Authorization"] = `Bearer ${authToken}`;
13
+ }
14
+ if (userId) {
15
+ headers["x-user-id"] = userId;
16
+ }
17
+ return headers;
18
+ }, [authToken, userId]);
19
+ const [timeline, setTimeline] = useState([]);
20
+ const [currentVersion, setCurrentVersion] = useState(1);
21
+ const [isLoading, setIsLoading] = useState(false);
22
+ const [error, setError] = useState(null);
23
+ const refresh = useCallback(async () => {
24
+ if (!appId) return;
25
+ setIsLoading(true);
26
+ setError(null);
27
+ try {
28
+ const headers = getHeaders2();
29
+ const [changesetsRes, snapshotsRes] = await Promise.all([
30
+ fetch(`/api/graphs/${appId}/history/changesets`, { headers }),
31
+ fetch(`/api/graphs/${appId}/history/snapshots`, { headers })
32
+ ]);
33
+ if (!changesetsRes.ok) {
34
+ throw new Error(`Failed to fetch changesets: ${changesetsRes.status}`);
35
+ }
36
+ if (!snapshotsRes.ok) {
37
+ throw new Error(`Failed to fetch snapshots: ${snapshotsRes.status}`);
38
+ }
39
+ const changesetsData = await changesetsRes.json();
40
+ const snapshotsData = await snapshotsRes.json();
41
+ const changesetItems = (changesetsData.changesets || []).map((cs) => ({
42
+ id: cs.id,
43
+ type: "changeset",
44
+ version: cs.version,
45
+ timestamp: cs.timestamp,
46
+ description: `Version ${cs.version}`,
47
+ source: cs.source,
48
+ summary: cs.summary
49
+ }));
50
+ const snapshotItems = (snapshotsData.snapshots || []).map((snap) => ({
51
+ id: snap.id,
52
+ type: "snapshot",
53
+ version: snap.version,
54
+ timestamp: snap.timestamp,
55
+ description: snap.reason || `Snapshot v${snap.version}`,
56
+ reason: snap.reason
57
+ }));
58
+ const mergedTimeline = [...changesetItems, ...snapshotItems].sort(
59
+ (a, b) => b.timestamp - a.timestamp
60
+ );
61
+ setTimeline(mergedTimeline);
62
+ if (mergedTimeline.length > 0) {
63
+ setCurrentVersion(mergedTimeline[0].version);
64
+ }
65
+ } catch (err) {
66
+ console.error("[useOrbitalHistory] Failed to load history:", err);
67
+ setError(err instanceof Error ? err.message : "Failed to load history");
68
+ } finally {
69
+ setIsLoading(false);
70
+ }
71
+ }, [appId, getHeaders2]);
72
+ const revertToSnapshot = useCallback(async (snapshotId) => {
73
+ if (!appId) {
74
+ return { success: false, error: "No app ID provided" };
75
+ }
76
+ try {
77
+ const response = await fetch(`/api/graphs/${appId}/history/revert/${snapshotId}`, {
78
+ method: "POST",
79
+ headers: getHeaders2()
80
+ });
81
+ if (!response.ok) {
82
+ const errorData = await response.json().catch(() => ({}));
83
+ throw new Error(errorData.error || `Failed to revert: ${response.status}`);
84
+ }
85
+ const data = await response.json();
86
+ if (data.success && data.schema) {
87
+ await refresh();
88
+ onRevertSuccess?.(data.schema);
89
+ return {
90
+ success: true,
91
+ restoredSchema: data.schema
92
+ };
93
+ }
94
+ return {
95
+ success: false,
96
+ error: data.error || "Unknown error during revert"
97
+ };
98
+ } catch (err) {
99
+ console.error("[useOrbitalHistory] Failed to revert:", err);
100
+ return {
101
+ success: false,
102
+ error: err instanceof Error ? err.message : "Failed to revert"
103
+ };
104
+ }
105
+ }, [appId, getHeaders2, refresh, onRevertSuccess]);
106
+ useEffect(() => {
107
+ if (appId && authToken && userId) {
108
+ refresh();
109
+ }
110
+ }, [appId, authToken, userId]);
111
+ useEffect(() => {
112
+ onHistoryChange?.(timeline);
113
+ }, [timeline]);
114
+ return {
115
+ timeline,
116
+ currentVersion,
117
+ isLoading,
118
+ error,
119
+ revertToSnapshot,
120
+ refresh
121
+ };
122
+ }
123
+ function useFileSystem() {
124
+ const [status, setStatus] = useState("idle");
125
+ const [error, setError] = useState(null);
126
+ const [isLoading, setIsLoading] = useState(false);
127
+ const [files, setFiles] = useState([]);
128
+ const [selectedFile, setSelectedFile] = useState(null);
129
+ const [selectedPath, setSelectedPath] = useState(null);
130
+ const [previewUrl, setPreviewUrl] = useState(null);
131
+ const [fileContents, setFileContents] = useState(/* @__PURE__ */ new Map());
132
+ const boot = useCallback(async () => {
133
+ setStatus("booting");
134
+ setError(null);
135
+ setIsLoading(true);
136
+ try {
137
+ console.log("[useFileSystem] Booting WebContainer...");
138
+ await new Promise((resolve) => setTimeout(resolve, 100));
139
+ setStatus("ready");
140
+ } catch (err) {
141
+ setError(err instanceof Error ? err.message : "Failed to boot");
142
+ setStatus("error");
143
+ } finally {
144
+ setIsLoading(false);
145
+ }
146
+ }, []);
147
+ const mountFiles = useCallback(async (filesToMount) => {
148
+ setIsLoading(true);
149
+ try {
150
+ let filesArray;
151
+ if (Array.isArray(filesToMount)) {
152
+ filesArray = filesToMount;
153
+ } else {
154
+ filesArray = [];
155
+ const flattenTree = (obj, basePath = "") => {
156
+ for (const [key, value] of Object.entries(obj)) {
157
+ const path = basePath ? `${basePath}/${key}` : key;
158
+ if (value && typeof value === "object" && "file" in value) {
159
+ const fileObj = value;
160
+ filesArray.push({ path, content: fileObj.file.contents || "" });
161
+ } else if (value && typeof value === "object" && "directory" in value) {
162
+ const dirObj = value;
163
+ flattenTree(dirObj.directory, path);
164
+ }
165
+ }
166
+ };
167
+ flattenTree(filesToMount);
168
+ }
169
+ const newContents = /* @__PURE__ */ new Map();
170
+ for (const file of filesArray) {
171
+ newContents.set(file.path, file.content);
172
+ }
173
+ setFileContents(newContents);
174
+ const newTree = [];
175
+ for (const file of filesArray) {
176
+ const parts = file.path.split("/").filter(Boolean);
177
+ let current = newTree;
178
+ for (let i = 0; i < parts.length; i++) {
179
+ const part = parts[i];
180
+ const isFile = i === parts.length - 1;
181
+ const currentPath = "/" + parts.slice(0, i + 1).join("/");
182
+ let node = current.find((n) => n.name === part);
183
+ if (!node) {
184
+ node = {
185
+ path: currentPath,
186
+ name: part,
187
+ type: isFile ? "file" : "directory",
188
+ children: isFile ? void 0 : []
189
+ };
190
+ current.push(node);
191
+ }
192
+ if (!isFile && node && node.children) {
193
+ current = node.children;
194
+ }
195
+ }
196
+ }
197
+ setFiles(newTree);
198
+ setStatus("running");
199
+ } catch (err) {
200
+ console.error("[useFileSystem] Failed to mount files:", err);
201
+ } finally {
202
+ setIsLoading(false);
203
+ }
204
+ }, []);
205
+ const readFile = useCallback(async (path) => {
206
+ return fileContents.get(path) || "";
207
+ }, [fileContents]);
208
+ const writeFile = useCallback(async (path, content) => {
209
+ setFileContents((prev) => {
210
+ const next = new Map(prev);
211
+ next.set(path, content);
212
+ return next;
213
+ });
214
+ }, []);
215
+ const selectFile = useCallback(async (path) => {
216
+ const content = fileContents.get(path) || "";
217
+ const ext = path.split(".").pop()?.toLowerCase() || "";
218
+ const languageMap = {
219
+ ts: "typescript",
220
+ tsx: "typescript",
221
+ js: "javascript",
222
+ jsx: "javascript",
223
+ json: "json",
224
+ md: "markdown",
225
+ css: "css",
226
+ html: "html",
227
+ orb: "json"
228
+ };
229
+ setSelectedPath(path);
230
+ setSelectedFile({
231
+ path,
232
+ content,
233
+ language: languageMap[ext] || "plaintext",
234
+ isDirty: false
235
+ });
236
+ }, [fileContents]);
237
+ const updateContent = useCallback((pathOrContent, contentArg) => {
238
+ const path = contentArg !== void 0 ? pathOrContent : selectedPath;
239
+ const content = contentArg !== void 0 ? contentArg : pathOrContent;
240
+ if (!path) {
241
+ console.warn("[useFileSystem] updateContent called without path and no file selected");
242
+ return;
243
+ }
244
+ setFileContents((prev) => {
245
+ const next = new Map(prev);
246
+ next.set(path, content);
247
+ return next;
248
+ });
249
+ if (selectedPath === path) {
250
+ setSelectedFile((prev) => prev ? { ...prev, content, isDirty: true } : null);
251
+ }
252
+ }, [selectedPath]);
253
+ const updateSelectedContent = useCallback((content) => {
254
+ setSelectedFile((prev) => prev ? { ...prev, content, isDirty: true } : null);
255
+ }, []);
256
+ const refreshTree = useCallback(async () => {
257
+ console.log("[useFileSystem] Refreshing tree");
258
+ }, []);
259
+ const runCommand = useCallback(async (command) => {
260
+ console.log("[useFileSystem] Running command:", command);
261
+ return { exitCode: 0, output: "" };
262
+ }, []);
263
+ const startDevServer = useCallback(async () => {
264
+ console.log("[useFileSystem] Starting dev server");
265
+ setPreviewUrl("http://localhost:5173");
266
+ }, []);
267
+ return {
268
+ status,
269
+ error,
270
+ isLoading,
271
+ files,
272
+ selectedFile,
273
+ selectedPath,
274
+ previewUrl,
275
+ boot,
276
+ mountFiles,
277
+ readFile,
278
+ writeFile,
279
+ selectFile,
280
+ updateContent,
281
+ updateSelectedContent,
282
+ refreshTree,
283
+ runCommand,
284
+ startDevServer
285
+ };
286
+ }
287
+ var defaultManifest = {
288
+ languages: {
289
+ typescript: { extensions: [".ts", ".tsx"], icon: "ts", color: "#3178c6" },
290
+ javascript: { extensions: [".js", ".jsx"], icon: "js", color: "#f7df1e" },
291
+ json: { extensions: [".json", ".orb"], icon: "json", color: "#000000" },
292
+ css: { extensions: [".css"], icon: "css", color: "#264de4" },
293
+ html: { extensions: [".html"], icon: "html", color: "#e34c26" },
294
+ markdown: { extensions: [".md", ".mdx"], icon: "md", color: "#083fa1" }
295
+ },
296
+ extensions: []
297
+ };
298
+ function useExtensions(options) {
299
+ const { appId, loadOnMount = true } = options;
300
+ const [extensions, setExtensions] = useState([]);
301
+ const [manifest] = useState(defaultManifest);
302
+ const [isLoading, setIsLoading] = useState(false);
303
+ const [error, setError] = useState(null);
304
+ const loadExtension = useCallback(async (extensionId) => {
305
+ console.log("[useExtensions] Loading extension:", extensionId);
306
+ }, []);
307
+ const loadExtensions = useCallback(async () => {
308
+ setIsLoading(true);
309
+ setError(null);
310
+ try {
311
+ const defaultExtensions = [
312
+ { id: "typescript", name: "TypeScript", language: "typescript", loaded: true },
313
+ { id: "javascript", name: "JavaScript", language: "javascript", loaded: true },
314
+ { id: "json", name: "JSON", language: "json", loaded: true },
315
+ { id: "css", name: "CSS", language: "css", loaded: true },
316
+ { id: "html", name: "HTML", language: "html", loaded: true },
317
+ { id: "markdown", name: "Markdown", language: "markdown", loaded: true }
318
+ ];
319
+ setExtensions(defaultExtensions);
320
+ } catch (err) {
321
+ setError(err instanceof Error ? err.message : "Failed to load extensions");
322
+ } finally {
323
+ setIsLoading(false);
324
+ }
325
+ }, []);
326
+ const getExtensionForFile = useCallback((filename) => {
327
+ const ext = filename.split(".").pop()?.toLowerCase();
328
+ if (!ext) return null;
329
+ const languageMap = {
330
+ ts: "typescript",
331
+ tsx: "typescript",
332
+ js: "javascript",
333
+ jsx: "javascript",
334
+ json: "json",
335
+ md: "markdown",
336
+ css: "css",
337
+ html: "html",
338
+ orb: "json"
339
+ };
340
+ const language = languageMap[ext];
341
+ if (!language) return null;
342
+ return extensions.find((e) => e.language === language) || null;
343
+ }, [extensions]);
344
+ useEffect(() => {
345
+ if (!appId || !loadOnMount) return;
346
+ const loadExtensions2 = async () => {
347
+ setIsLoading(true);
348
+ setError(null);
349
+ try {
350
+ const defaultExtensions = [
351
+ { id: "typescript", name: "TypeScript", language: "typescript", loaded: true },
352
+ { id: "javascript", name: "JavaScript", language: "javascript", loaded: true },
353
+ { id: "json", name: "JSON", language: "json", loaded: true },
354
+ { id: "css", name: "CSS", language: "css", loaded: true },
355
+ { id: "html", name: "HTML", language: "html", loaded: true },
356
+ { id: "markdown", name: "Markdown", language: "markdown", loaded: true }
357
+ ];
358
+ setExtensions(defaultExtensions);
359
+ } catch (err) {
360
+ setError(err instanceof Error ? err.message : "Failed to load extensions");
361
+ } finally {
362
+ setIsLoading(false);
363
+ }
364
+ };
365
+ loadExtensions2();
366
+ }, [appId, loadOnMount]);
367
+ return {
368
+ extensions,
369
+ manifest,
370
+ isLoading,
371
+ error,
372
+ loadExtension,
373
+ loadExtensions,
374
+ getExtensionForFile
375
+ };
376
+ }
377
+ function useFileEditor(options) {
378
+ const { extensions, fileSystem, onSchemaUpdate } = options;
379
+ const [openFiles, setOpenFiles] = useState([]);
380
+ const [activeFilePath, setActiveFilePath] = useState(null);
381
+ const [isSaving, setIsSaving] = useState(false);
382
+ const activeFile = openFiles.find((f) => f.path === activeFilePath) || null;
383
+ const openFile = useCallback(async (path) => {
384
+ const existing = openFiles.find((f) => f.path === path);
385
+ if (existing) {
386
+ setActiveFilePath(path);
387
+ return;
388
+ }
389
+ try {
390
+ const content = await fileSystem.readFile(path);
391
+ const ext = extensions.getExtensionForFile(path);
392
+ const newFile = {
393
+ path,
394
+ content,
395
+ isDirty: false,
396
+ language: ext?.language
397
+ };
398
+ setOpenFiles((prev) => [...prev, newFile]);
399
+ setActiveFilePath(path);
400
+ } catch (err) {
401
+ console.error("[useFileEditor] Failed to open file:", err);
402
+ }
403
+ }, [openFiles, fileSystem, extensions]);
404
+ const closeFile = useCallback((path) => {
405
+ setOpenFiles((prev) => prev.filter((f) => f.path !== path));
406
+ if (activeFilePath === path) {
407
+ const remaining = openFiles.filter((f) => f.path !== path);
408
+ setActiveFilePath(remaining.length > 0 ? remaining[0].path : null);
409
+ }
410
+ }, [activeFilePath, openFiles]);
411
+ const setActiveFile = useCallback((path) => {
412
+ setActiveFilePath(path);
413
+ }, []);
414
+ const updateFileContent = useCallback((path, content) => {
415
+ setOpenFiles(
416
+ (prev) => prev.map(
417
+ (f) => f.path === path ? { ...f, content, isDirty: true } : f
418
+ )
419
+ );
420
+ }, []);
421
+ const handleFileEdit = useCallback(async (path, content) => {
422
+ try {
423
+ await fileSystem.writeFile(path, content);
424
+ let action = "saved";
425
+ if (path.endsWith(".orb") || path.endsWith("schema.json")) {
426
+ try {
427
+ const schema = JSON.parse(content);
428
+ await onSchemaUpdate?.(schema);
429
+ action = "updated_schema";
430
+ } catch {
431
+ }
432
+ } else if (path.includes("/extensions/")) {
433
+ action = path.endsWith(".new") ? "converted_extension" : "saved_extension";
434
+ }
435
+ return { success: true, action };
436
+ } catch (err) {
437
+ return {
438
+ success: false,
439
+ error: err instanceof Error ? err.message : "Failed to save file"
440
+ };
441
+ }
442
+ }, [fileSystem, onSchemaUpdate]);
443
+ const saveFile = useCallback(async (path) => {
444
+ const file = openFiles.find((f) => f.path === path);
445
+ if (!file) return;
446
+ setIsSaving(true);
447
+ try {
448
+ await fileSystem.writeFile(path, file.content);
449
+ setOpenFiles(
450
+ (prev) => prev.map(
451
+ (f) => f.path === path ? { ...f, isDirty: false } : f
452
+ )
453
+ );
454
+ if (path.endsWith(".orb") || path.endsWith("schema.json")) {
455
+ try {
456
+ const schema = JSON.parse(file.content);
457
+ await onSchemaUpdate?.(schema);
458
+ } catch {
459
+ }
460
+ }
461
+ } catch (err) {
462
+ console.error("[useFileEditor] Failed to save file:", err);
463
+ } finally {
464
+ setIsSaving(false);
465
+ }
466
+ }, [openFiles, fileSystem, onSchemaUpdate]);
467
+ const saveAllFiles = useCallback(async () => {
468
+ setIsSaving(true);
469
+ try {
470
+ const dirtyFiles = openFiles.filter((f) => f.isDirty);
471
+ for (const file of dirtyFiles) {
472
+ await saveFile(file.path);
473
+ }
474
+ } finally {
475
+ setIsSaving(false);
476
+ }
477
+ }, [openFiles, saveFile]);
478
+ return {
479
+ openFiles,
480
+ activeFile,
481
+ isSaving,
482
+ openFile,
483
+ closeFile,
484
+ setActiveFile,
485
+ updateFileContent,
486
+ handleFileEdit,
487
+ saveFile,
488
+ saveAllFiles
489
+ };
490
+ }
491
+ function useCompile() {
492
+ const [isCompiling, setIsCompiling] = useState(false);
493
+ const [stage, setStage] = useState("idle");
494
+ const [lastResult, setLastResult] = useState(null);
495
+ const [error, setError] = useState(null);
496
+ const compileSchema = useCallback(async (schema) => {
497
+ setIsCompiling(true);
498
+ setStage("compiling");
499
+ setError(null);
500
+ try {
501
+ console.log("[useCompile] Compiling schema:", schema.name);
502
+ const result = {
503
+ success: true,
504
+ files: []
505
+ };
506
+ setLastResult(result);
507
+ setStage("done");
508
+ return result;
509
+ } catch (err) {
510
+ const errorMessage = err instanceof Error ? err.message : "Compilation failed";
511
+ setError(errorMessage);
512
+ setStage("error");
513
+ setLastResult({ success: false, errors: [errorMessage] });
514
+ return null;
515
+ } finally {
516
+ setIsCompiling(false);
517
+ }
518
+ }, []);
519
+ return {
520
+ isCompiling,
521
+ stage,
522
+ lastResult,
523
+ error,
524
+ compileSchema
525
+ };
526
+ }
527
+ function usePreview(options) {
528
+ const [previewUrl, setPreviewUrl] = useState(null);
529
+ const [isLoading, setIsLoading] = useState(!!options?.appId);
530
+ const [error, setError] = useState(null);
531
+ const [loadError, setLoadError] = useState(null);
532
+ const [app, setApp] = useState(null);
533
+ const [isFullscreen, setIsFullscreen] = useState(false);
534
+ const [isExecutingEvent, setIsExecutingEvent] = useState(false);
535
+ const [errorToast, setErrorToast] = useState(null);
536
+ const [currentStateName, setCurrentStateName] = useState(null);
537
+ const [notificationsList, setNotificationsList] = useState([]);
538
+ const [isPanelOpen, setIsPanelOpen] = useState(false);
539
+ const notifications = useMemo(() => ({
540
+ notifications: notificationsList,
541
+ isPanelOpen,
542
+ closePanel: () => setIsPanelOpen(false),
543
+ dismissNotification: (id) => {
544
+ setNotificationsList((prev) => prev.filter((n) => n.id !== id));
545
+ },
546
+ markAsRead: (id) => {
547
+ setNotificationsList(
548
+ (prev) => prev.map((n) => n.id === id ? { ...n, read: true } : n)
549
+ );
550
+ },
551
+ clearAll: () => setNotificationsList([])
552
+ }), [notificationsList, isPanelOpen]);
553
+ useEffect(() => {
554
+ const appId = options?.appId;
555
+ if (!appId) {
556
+ setApp(null);
557
+ setIsLoading(false);
558
+ return;
559
+ }
560
+ console.log("[usePreview] Setting up preview for app:", appId);
561
+ setPreviewUrl(`/api/orbitals/${appId}`);
562
+ setIsLoading(false);
563
+ }, [options?.appId]);
564
+ const startPreview = useCallback(async () => {
565
+ console.log("[usePreview] startPreview called");
566
+ }, []);
567
+ const stopPreview = useCallback(async () => {
568
+ setIsLoading(true);
569
+ try {
570
+ console.log("[usePreview] Stopping preview server...");
571
+ setPreviewUrl(null);
572
+ setApp(null);
573
+ } finally {
574
+ setIsLoading(false);
575
+ }
576
+ }, []);
577
+ const refresh = useCallback(async () => {
578
+ if (!previewUrl) return;
579
+ console.log("[usePreview] Refreshing preview...");
580
+ setPreviewUrl(`${previewUrl.split("?")[0]}?t=${Date.now()}`);
581
+ }, [previewUrl]);
582
+ const handleRefresh = useCallback(async () => {
583
+ console.log("[usePreview] Handle refresh...");
584
+ await refresh();
585
+ }, [refresh]);
586
+ const handleReset = useCallback(async () => {
587
+ console.log("[usePreview] Resetting preview...");
588
+ setError(null);
589
+ setLoadError(null);
590
+ setErrorToast(null);
591
+ setIsExecutingEvent(false);
592
+ setCurrentStateName(null);
593
+ }, []);
594
+ const toggleFullscreen = useCallback(() => {
595
+ setIsFullscreen((prev) => !prev);
596
+ }, []);
597
+ const dismissErrorToast = useCallback(() => {
598
+ setErrorToast(null);
599
+ }, []);
600
+ return {
601
+ previewUrl,
602
+ isLoading,
603
+ error,
604
+ loadError,
605
+ app,
606
+ isFullscreen,
607
+ isExecutingEvent,
608
+ errorToast,
609
+ currentStateName,
610
+ notifications,
611
+ startPreview,
612
+ stopPreview,
613
+ refresh,
614
+ handleRefresh,
615
+ handleReset,
616
+ toggleFullscreen,
617
+ setErrorToast,
618
+ dismissErrorToast
619
+ };
620
+ }
621
+ function useAgentChat(options) {
622
+ const [messages, setMessages] = useState([]);
623
+ const [status, setStatus] = useState("idle");
624
+ const [activities, setActivities] = useState([]);
625
+ const [todos, setTodos] = useState([]);
626
+ const [schemaDiffs, setSchemaDiffs] = useState([]);
627
+ const [isLoading, setIsLoading] = useState(false);
628
+ const [error, setError] = useState(null);
629
+ const [threadId] = useState(null);
630
+ const [interrupt, setInterrupt] = useState(null);
631
+ const sendMessage = useCallback(async (content) => {
632
+ setIsLoading(true);
633
+ setStatus("running");
634
+ setError(null);
635
+ try {
636
+ const userMessage = {
637
+ id: Date.now().toString(),
638
+ role: "user",
639
+ content,
640
+ timestamp: Date.now()
641
+ };
642
+ setMessages((prev) => [...prev, userMessage]);
643
+ console.log("[useAgentChat] Sending message:", content);
644
+ const assistantMessage = {
645
+ id: (Date.now() + 1).toString(),
646
+ role: "assistant",
647
+ content: "Agent chat is not yet implemented.",
648
+ timestamp: Date.now()
649
+ };
650
+ setMessages((prev) => [...prev, assistantMessage]);
651
+ setStatus("idle");
652
+ options?.onComplete?.();
653
+ } catch (err) {
654
+ setError(err instanceof Error ? err.message : "Failed to send message");
655
+ setStatus("error");
656
+ } finally {
657
+ setIsLoading(false);
658
+ }
659
+ }, [options]);
660
+ const startGeneration = useCallback(async (skill, prompt, genOptions) => {
661
+ setStatus("running");
662
+ setIsLoading(true);
663
+ setError(null);
664
+ const skillName = Array.isArray(skill) ? skill[0] : skill;
665
+ try {
666
+ console.log("[useAgentChat] Starting generation:", skillName, prompt, genOptions);
667
+ await new Promise((resolve) => setTimeout(resolve, 100));
668
+ setStatus("complete");
669
+ options?.onComplete?.();
670
+ } catch (err) {
671
+ setError(err instanceof Error ? err.message : "Generation failed");
672
+ setStatus("error");
673
+ } finally {
674
+ setIsLoading(false);
675
+ }
676
+ }, [options]);
677
+ const continueConversation = useCallback(async (message) => {
678
+ console.log("[useAgentChat] Continue conversation", message);
679
+ }, []);
680
+ const resumeWithDecision = useCallback(async (decisions) => {
681
+ console.log("[useAgentChat] Resume with decision:", decisions);
682
+ setInterrupt(null);
683
+ }, []);
684
+ const cancel = useCallback(() => {
685
+ setStatus("idle");
686
+ setIsLoading(false);
687
+ setInterrupt(null);
688
+ }, []);
689
+ const clearMessages = useCallback(() => {
690
+ setMessages([]);
691
+ }, []);
692
+ const clearHistory = useCallback(() => {
693
+ setMessages([]);
694
+ setActivities([]);
695
+ setTodos([]);
696
+ setSchemaDiffs([]);
697
+ setError(null);
698
+ }, []);
699
+ return {
700
+ messages,
701
+ status,
702
+ activities,
703
+ todos,
704
+ schemaDiffs,
705
+ isLoading,
706
+ error,
707
+ threadId,
708
+ interrupt,
709
+ sendMessage,
710
+ startGeneration,
711
+ continueConversation,
712
+ resumeWithDecision,
713
+ cancel,
714
+ clearMessages,
715
+ clearHistory
716
+ };
717
+ }
718
+ function useValidation() {
719
+ const [result, setResult] = useState(null);
720
+ const [isValidating, setIsValidating] = useState(false);
721
+ const [error, setError] = useState(null);
722
+ const [stage, setStage] = useState("idle");
723
+ const [isFixing, setIsFixing] = useState(false);
724
+ const [progressMessage, setProgressMessage] = useState(null);
725
+ const validate = useCallback(async (appId) => {
726
+ setIsValidating(true);
727
+ setError(null);
728
+ setStage("validating");
729
+ setProgressMessage("Validating schema...");
730
+ try {
731
+ console.log("[useValidation] Validating app:", appId);
732
+ const validationResult = {
733
+ valid: true,
734
+ errors: [],
735
+ warnings: []
736
+ };
737
+ setResult(validationResult);
738
+ setStage("complete");
739
+ setProgressMessage(null);
740
+ return validationResult;
741
+ } catch (err) {
742
+ const errorMessage = err instanceof Error ? err.message : "Validation failed";
743
+ setError(errorMessage);
744
+ const failedResult = {
745
+ valid: false,
746
+ errors: [{ code: "VALIDATION_ERROR", message: errorMessage, severity: "error" }],
747
+ warnings: []
748
+ };
749
+ setResult(failedResult);
750
+ setStage("complete");
751
+ setProgressMessage(null);
752
+ return failedResult;
753
+ } finally {
754
+ setIsValidating(false);
755
+ }
756
+ }, []);
757
+ const clearResult = useCallback(() => {
758
+ setResult(null);
759
+ setError(null);
760
+ }, []);
761
+ const reset = useCallback(() => {
762
+ setResult(null);
763
+ setError(null);
764
+ setStage("idle");
765
+ setIsFixing(false);
766
+ setProgressMessage(null);
767
+ setIsValidating(false);
768
+ }, []);
769
+ return {
770
+ result,
771
+ isValidating,
772
+ error,
773
+ stage,
774
+ isFixing,
775
+ progressMessage,
776
+ errors: result?.errors ?? [],
777
+ warnings: result?.warnings ?? [],
778
+ isValid: result?.valid ?? false,
779
+ validate,
780
+ clearResult,
781
+ reset
782
+ };
783
+ }
784
+ function useDeepAgentGeneration() {
785
+ const [requests, setRequests] = useState([]);
786
+ const [currentRequest, setCurrentRequest] = useState(null);
787
+ const [isGenerating, setIsGenerating] = useState(false);
788
+ const [isLoading, setIsLoading] = useState(false);
789
+ const [isComplete, setIsComplete] = useState(false);
790
+ const [progress, setProgress] = useState({ stage: "idle", percent: 0, message: "" });
791
+ const [error, setError] = useState(null);
792
+ const [interrupt, setInterrupt] = useState(null);
793
+ const generate = useCallback(async (prompt) => {
794
+ setIsGenerating(true);
795
+ setIsLoading(true);
796
+ setIsComplete(false);
797
+ setError(null);
798
+ setProgress({ stage: "starting", percent: 0, message: "Starting generation..." });
799
+ const request = {
800
+ id: Date.now().toString(),
801
+ prompt,
802
+ status: "running"
803
+ };
804
+ setCurrentRequest(request);
805
+ setRequests((prev) => [...prev, request]);
806
+ try {
807
+ console.log("[useDeepAgentGeneration] Generating from prompt:", prompt);
808
+ await new Promise((resolve) => setTimeout(resolve, 100));
809
+ request.status = "completed";
810
+ setCurrentRequest(request);
811
+ setIsComplete(true);
812
+ setProgress({ stage: "complete", percent: 100, message: "Generation complete" });
813
+ return null;
814
+ } catch (err) {
815
+ const errorMessage = err instanceof Error ? err.message : "Generation failed";
816
+ setError(errorMessage);
817
+ request.status = "failed";
818
+ request.error = errorMessage;
819
+ setCurrentRequest(request);
820
+ return null;
821
+ } finally {
822
+ setIsGenerating(false);
823
+ setIsLoading(false);
824
+ }
825
+ }, []);
826
+ const startGeneration = useCallback(async (skill, prompt, _options) => {
827
+ console.log("[useDeepAgentGeneration] Starting generation with skill:", skill);
828
+ await generate(prompt);
829
+ }, [generate]);
830
+ const cancelGeneration = useCallback(() => {
831
+ if (currentRequest) {
832
+ currentRequest.status = "failed";
833
+ currentRequest.error = "Cancelled by user";
834
+ setCurrentRequest(null);
835
+ }
836
+ setIsGenerating(false);
837
+ setIsLoading(false);
838
+ setIsComplete(false);
839
+ setProgress({ stage: "idle", percent: 0, message: "" });
840
+ }, [currentRequest]);
841
+ const clearRequests = useCallback(() => {
842
+ setRequests([]);
843
+ setCurrentRequest(null);
844
+ setError(null);
845
+ setProgress({ stage: "idle", percent: 0, message: "" });
846
+ setIsComplete(false);
847
+ }, []);
848
+ const submitInterruptDecisions = useCallback((decisions) => {
849
+ console.log("[useDeepAgentGeneration] Submitting interrupt decisions:", decisions);
850
+ setInterrupt(null);
851
+ }, []);
852
+ return {
853
+ requests,
854
+ currentRequest,
855
+ isGenerating,
856
+ isLoading,
857
+ isComplete,
858
+ progress,
859
+ error,
860
+ interrupt,
861
+ generate,
862
+ startGeneration,
863
+ cancelGeneration,
864
+ clearRequests,
865
+ submitInterruptDecisions
866
+ };
867
+ }
868
+ var EventBusContext = createContext(null);
869
+
870
+ // hooks/useEventBus.ts
871
+ function getGlobalEventBus() {
872
+ if (typeof window !== "undefined") {
873
+ return window.__kflowEventBus ?? null;
874
+ }
875
+ return null;
876
+ }
877
+ var fallbackListeners = /* @__PURE__ */ new Map();
878
+ var fallbackAnyListeners = /* @__PURE__ */ new Set();
879
+ var fallbackEventBus = {
880
+ emit: (type, payload) => {
881
+ const event = {
882
+ type,
883
+ payload,
884
+ timestamp: Date.now()
885
+ };
886
+ const handlers = fallbackListeners.get(type);
887
+ if (handlers) {
888
+ handlers.forEach((handler) => {
889
+ try {
890
+ handler(event);
891
+ } catch (error) {
892
+ console.error(`[EventBus] Error in listener for '${type}':`, error);
893
+ }
894
+ });
895
+ }
896
+ fallbackAnyListeners.forEach((handler) => {
897
+ try {
898
+ handler(event);
899
+ } catch (error) {
900
+ console.error(`[EventBus] Error in onAny listener for '${type}':`, error);
901
+ }
902
+ });
903
+ },
904
+ on: (type, listener) => {
905
+ if (!fallbackListeners.has(type)) {
906
+ fallbackListeners.set(type, /* @__PURE__ */ new Set());
907
+ }
908
+ fallbackListeners.get(type).add(listener);
909
+ return () => {
910
+ const handlers = fallbackListeners.get(type);
911
+ if (handlers) {
912
+ handlers.delete(listener);
913
+ if (handlers.size === 0) {
914
+ fallbackListeners.delete(type);
915
+ }
916
+ }
917
+ };
918
+ },
919
+ once: (type, listener) => {
920
+ const wrappedListener = (event) => {
921
+ fallbackListeners.get(type)?.delete(wrappedListener);
922
+ listener(event);
923
+ };
924
+ return fallbackEventBus.on(type, wrappedListener);
925
+ },
926
+ hasListeners: (type) => {
927
+ const handlers = fallbackListeners.get(type);
928
+ return handlers !== void 0 && handlers.size > 0;
929
+ },
930
+ onAny: (listener) => {
931
+ fallbackAnyListeners.add(listener);
932
+ return () => {
933
+ fallbackAnyListeners.delete(listener);
934
+ };
935
+ }
936
+ };
937
+ function useEventBus() {
938
+ const context = useContext(EventBusContext);
939
+ return context ?? getGlobalEventBus() ?? fallbackEventBus;
940
+ }
941
+ function useEventListener(event, handler) {
942
+ const eventBus = useEventBus();
943
+ const handlerRef = useRef(handler);
944
+ handlerRef.current = handler;
945
+ useEffect(() => {
946
+ const wrappedHandler = (evt) => {
947
+ handlerRef.current(evt);
948
+ };
949
+ const unsub = eventBus.on(event, wrappedHandler);
950
+ return () => {
951
+ if (typeof unsub === "function") unsub();
952
+ };
953
+ }, [event, eventBus]);
954
+ }
955
+ function useEmitEvent() {
956
+ const eventBus = useEventBus();
957
+ return useCallback(
958
+ (type, payload) => {
959
+ eventBus.emit(type, payload);
960
+ },
961
+ [eventBus]
962
+ );
963
+ }
964
+ var DEFAULT_SLOTS = {
965
+ main: null,
966
+ sidebar: null,
967
+ modal: null,
968
+ drawer: null,
969
+ overlay: null,
970
+ center: null,
971
+ toast: null,
972
+ "hud-top": null,
973
+ "hud-bottom": null,
974
+ "hud-left": null,
975
+ "hud-right": null,
976
+ floating: null
977
+ };
978
+ var idCounter = 0;
979
+ function generateId() {
980
+ return `slot-content-${++idCounter}-${Date.now()}`;
981
+ }
982
+ function useUISlotManager() {
983
+ const [slots, setSlots] = useState(DEFAULT_SLOTS);
984
+ const subscribersRef = useRef(/* @__PURE__ */ new Set());
985
+ const timersRef = useRef(/* @__PURE__ */ new Map());
986
+ useEffect(() => {
987
+ return () => {
988
+ timersRef.current.forEach((timer) => clearTimeout(timer));
989
+ timersRef.current.clear();
990
+ };
991
+ }, []);
992
+ const notifySubscribers = useCallback((slot, content) => {
993
+ subscribersRef.current.forEach((callback) => {
994
+ try {
995
+ callback(slot, content);
996
+ } catch (error) {
997
+ console.error("[UISlots] Subscriber error:", error);
998
+ }
999
+ });
1000
+ }, []);
1001
+ const render = useCallback((config) => {
1002
+ const id = generateId();
1003
+ const content = {
1004
+ id,
1005
+ pattern: config.pattern,
1006
+ props: config.props ?? {},
1007
+ priority: config.priority ?? 0,
1008
+ animation: config.animation ?? "fade",
1009
+ onDismiss: config.onDismiss,
1010
+ sourceTrait: config.sourceTrait
1011
+ };
1012
+ if (config.autoDismissMs && config.autoDismissMs > 0) {
1013
+ content.autoDismissAt = Date.now() + config.autoDismissMs;
1014
+ const timer = setTimeout(() => {
1015
+ setSlots((prev) => {
1016
+ if (prev[config.target]?.id === id) {
1017
+ content.onDismiss?.();
1018
+ notifySubscribers(config.target, null);
1019
+ return { ...prev, [config.target]: null };
1020
+ }
1021
+ return prev;
1022
+ });
1023
+ timersRef.current.delete(id);
1024
+ }, config.autoDismissMs);
1025
+ timersRef.current.set(id, timer);
1026
+ }
1027
+ setSlots((prev) => {
1028
+ const existing = prev[config.target];
1029
+ if (existing && existing.priority > content.priority) {
1030
+ console.warn(
1031
+ `[UISlots] Slot "${config.target}" already has higher priority content (${existing.priority} > ${content.priority})`
1032
+ );
1033
+ return prev;
1034
+ }
1035
+ notifySubscribers(config.target, content);
1036
+ return { ...prev, [config.target]: content };
1037
+ });
1038
+ return id;
1039
+ }, [notifySubscribers]);
1040
+ const clear = useCallback((slot) => {
1041
+ setSlots((prev) => {
1042
+ const content = prev[slot];
1043
+ if (content) {
1044
+ const timer = timersRef.current.get(content.id);
1045
+ if (timer) {
1046
+ clearTimeout(timer);
1047
+ timersRef.current.delete(content.id);
1048
+ }
1049
+ content.onDismiss?.();
1050
+ notifySubscribers(slot, null);
1051
+ }
1052
+ return { ...prev, [slot]: null };
1053
+ });
1054
+ }, [notifySubscribers]);
1055
+ const clearById = useCallback((id) => {
1056
+ setSlots((prev) => {
1057
+ const entry = Object.entries(prev).find(([, content]) => content?.id === id);
1058
+ if (entry) {
1059
+ const [slot, content] = entry;
1060
+ const timer = timersRef.current.get(id);
1061
+ if (timer) {
1062
+ clearTimeout(timer);
1063
+ timersRef.current.delete(id);
1064
+ }
1065
+ content.onDismiss?.();
1066
+ notifySubscribers(slot, null);
1067
+ return { ...prev, [slot]: null };
1068
+ }
1069
+ return prev;
1070
+ });
1071
+ }, [notifySubscribers]);
1072
+ const clearAll = useCallback(() => {
1073
+ timersRef.current.forEach((timer) => clearTimeout(timer));
1074
+ timersRef.current.clear();
1075
+ setSlots((prev) => {
1076
+ Object.entries(prev).forEach(([slot, content]) => {
1077
+ if (content) {
1078
+ content.onDismiss?.();
1079
+ notifySubscribers(slot, null);
1080
+ }
1081
+ });
1082
+ return DEFAULT_SLOTS;
1083
+ });
1084
+ }, [notifySubscribers]);
1085
+ const subscribe2 = useCallback((callback) => {
1086
+ subscribersRef.current.add(callback);
1087
+ return () => {
1088
+ subscribersRef.current.delete(callback);
1089
+ };
1090
+ }, []);
1091
+ const hasContent = useCallback((slot) => {
1092
+ return slots[slot] !== null;
1093
+ }, [slots]);
1094
+ const getContent = useCallback((slot) => {
1095
+ return slots[slot];
1096
+ }, [slots]);
1097
+ return {
1098
+ slots,
1099
+ render,
1100
+ clear,
1101
+ clearById,
1102
+ clearAll,
1103
+ subscribe: subscribe2,
1104
+ hasContent,
1105
+ getContent
1106
+ };
1107
+ }
1108
+ var SelectionContext = createContext(null);
1109
+
1110
+ // hooks/useUIEvents.ts
1111
+ var UI_EVENT_MAP = {
1112
+ // Form/CRUD events
1113
+ "UI:SAVE": "SAVE",
1114
+ "UI:CANCEL": "CANCEL",
1115
+ "UI:CLOSE": "CLOSE",
1116
+ "UI:VIEW": "VIEW",
1117
+ "UI:EDIT": "EDIT",
1118
+ "UI:DELETE": "DELETE",
1119
+ "UI:CREATE": "CREATE",
1120
+ "UI:SELECT": "SELECT",
1121
+ "UI:DESELECT": "DESELECT",
1122
+ "UI:SUBMIT": "SAVE",
1123
+ "UI:UPDATE_STATUS": "UPDATE_STATUS",
1124
+ "UI:SEARCH": "SEARCH",
1125
+ "UI:CLEAR_SEARCH": "CLEAR_SEARCH",
1126
+ "UI:ADD": "CREATE",
1127
+ // Game events (for closed circuit with GameMenu, GamePauseOverlay, GameOverScreen)
1128
+ "UI:PAUSE": "PAUSE",
1129
+ "UI:RESUME": "RESUME",
1130
+ "UI:RESTART": "RESTART",
1131
+ "UI:GAME_OVER": "GAME_OVER",
1132
+ "UI:START": "START",
1133
+ "UI:QUIT": "QUIT",
1134
+ "UI:INIT": "INIT"
1135
+ };
1136
+ function useUIEvents(dispatch, validEvents, eventBusInstance) {
1137
+ const defaultEventBus = useEventBus();
1138
+ const eventBus = eventBusInstance ?? defaultEventBus;
1139
+ const validEventsKey = validEvents ? validEvents.slice().sort().join(",") : "";
1140
+ const stableValidEvents = useMemo(
1141
+ () => validEvents,
1142
+ [validEventsKey]
1143
+ // intentional — validEventsKey is the stable dep, not validEvents array ref
1144
+ );
1145
+ useEffect(() => {
1146
+ const unsubscribes = [];
1147
+ Object.entries(UI_EVENT_MAP).forEach(([uiEvent, smEvent]) => {
1148
+ const handler = (event) => {
1149
+ if (!stableValidEvents || stableValidEvents.includes(smEvent)) {
1150
+ dispatch(smEvent, event.payload);
1151
+ }
1152
+ };
1153
+ const unsubscribe = eventBus.on(uiEvent, handler);
1154
+ unsubscribes.push(unsubscribe);
1155
+ });
1156
+ const genericHandler = (event) => {
1157
+ const eventName = event.payload?.event;
1158
+ if (eventName) {
1159
+ const smEvent = eventName;
1160
+ if (!stableValidEvents || stableValidEvents.includes(smEvent)) {
1161
+ dispatch(smEvent, event.payload);
1162
+ }
1163
+ }
1164
+ };
1165
+ const genericUnsubscribe = eventBus.on("UI:DISPATCH", genericHandler);
1166
+ unsubscribes.push(genericUnsubscribe);
1167
+ if (stableValidEvents) {
1168
+ stableValidEvents.forEach((smEvent) => {
1169
+ const uiPrefixedEvent = `UI:${smEvent}`;
1170
+ const alreadyMapped = Object.keys(UI_EVENT_MAP).includes(uiPrefixedEvent);
1171
+ if (!alreadyMapped) {
1172
+ const directHandler = (event) => {
1173
+ dispatch(smEvent, event.payload);
1174
+ };
1175
+ const unsubscribePrefixed = eventBus.on(
1176
+ uiPrefixedEvent,
1177
+ directHandler
1178
+ );
1179
+ unsubscribes.push(unsubscribePrefixed);
1180
+ const unsubscribeDirect = eventBus.on(smEvent, directHandler);
1181
+ unsubscribes.push(unsubscribeDirect);
1182
+ }
1183
+ });
1184
+ }
1185
+ return () => {
1186
+ unsubscribes.forEach((unsub) => {
1187
+ if (typeof unsub === "function") unsub();
1188
+ });
1189
+ };
1190
+ }, [eventBus, dispatch, stableValidEvents]);
1191
+ }
1192
+ function useSelectedEntity(eventBusInstance) {
1193
+ const defaultEventBus = useEventBus();
1194
+ const eventBus = eventBusInstance ?? defaultEventBus;
1195
+ const selectionContext = useSelectionContext();
1196
+ const [localSelected, setLocalSelected] = useState(null);
1197
+ const usingContext = selectionContext !== null;
1198
+ useEffect(() => {
1199
+ if (usingContext) return;
1200
+ const handleSelect = (event) => {
1201
+ const row = event.payload?.row;
1202
+ if (row) {
1203
+ setLocalSelected(row);
1204
+ }
1205
+ };
1206
+ const handleDeselect = () => {
1207
+ setLocalSelected(null);
1208
+ };
1209
+ const unsubSelect = eventBus.on("UI:SELECT", handleSelect);
1210
+ const unsubView = eventBus.on("UI:VIEW", handleSelect);
1211
+ const unsubDeselect = eventBus.on("UI:DESELECT", handleDeselect);
1212
+ const unsubClose = eventBus.on("UI:CLOSE", handleDeselect);
1213
+ const unsubCancel = eventBus.on("UI:CANCEL", handleDeselect);
1214
+ return () => {
1215
+ [unsubSelect, unsubView, unsubDeselect, unsubClose, unsubCancel].forEach(
1216
+ (unsub) => {
1217
+ if (typeof unsub === "function") unsub();
1218
+ }
1219
+ );
1220
+ };
1221
+ }, [eventBus, usingContext]);
1222
+ if (selectionContext) {
1223
+ return [selectionContext.selected, selectionContext.setSelected];
1224
+ }
1225
+ return [localSelected, setLocalSelected];
1226
+ }
1227
+ function useSelectionContext() {
1228
+ const context = useContext(SelectionContext);
1229
+ return context;
1230
+ }
1231
+ var EntityDataContext = createContext(null);
1232
+ function EntityDataProvider({
1233
+ adapter,
1234
+ children
1235
+ }) {
1236
+ return React3.createElement(
1237
+ EntityDataContext.Provider,
1238
+ { value: adapter },
1239
+ children
1240
+ );
1241
+ }
1242
+ function useEntityDataAdapter() {
1243
+ return useContext(EntityDataContext);
1244
+ }
1245
+ var entityDataKeys = {
1246
+ all: ["entities"],
1247
+ lists: () => [...entityDataKeys.all, "list"],
1248
+ list: (entity, filters) => [...entityDataKeys.lists(), entity, filters],
1249
+ details: () => [...entityDataKeys.all, "detail"],
1250
+ detail: (entity, id) => [...entityDataKeys.details(), entity, id]
1251
+ };
1252
+ function useEntityList(entity, options = {}) {
1253
+ const { skip = false } = options;
1254
+ const adapter = useContext(EntityDataContext);
1255
+ const adapterData = useMemo(() => {
1256
+ if (!adapter || !entity || skip) return [];
1257
+ return adapter.getData(entity);
1258
+ }, [adapter, entity, skip, adapter?.isLoading]);
1259
+ const [stubData, setStubData] = useState([]);
1260
+ const [stubLoading, setStubLoading] = useState(!skip && !!entity && !adapter);
1261
+ const [stubError, setStubError] = useState(null);
1262
+ useEffect(() => {
1263
+ if (adapter || skip || !entity) {
1264
+ setStubLoading(false);
1265
+ return;
1266
+ }
1267
+ setStubLoading(true);
1268
+ const t = setTimeout(() => {
1269
+ setStubData([]);
1270
+ setStubLoading(false);
1271
+ }, 100);
1272
+ return () => clearTimeout(t);
1273
+ }, [entity, skip, adapter]);
1274
+ if (adapter) {
1275
+ return {
1276
+ data: adapterData,
1277
+ isLoading: adapter.isLoading,
1278
+ error: adapter.error ? new Error(adapter.error) : null,
1279
+ refetch: () => {
1280
+ }
1281
+ };
1282
+ }
1283
+ return { data: stubData, isLoading: stubLoading, error: stubError, refetch: () => {
1284
+ } };
1285
+ }
1286
+ function useEntity(entity, id) {
1287
+ const adapter = useContext(EntityDataContext);
1288
+ const adapterData = useMemo(() => {
1289
+ if (!adapter || !entity || !id) return null;
1290
+ return adapter.getById(entity, id) ?? null;
1291
+ }, [adapter, entity, id, adapter?.isLoading]);
1292
+ const [stubData, setStubData] = useState(null);
1293
+ const [stubLoading, setStubLoading] = useState(!!entity && !!id && !adapter);
1294
+ const [stubError, setStubError] = useState(null);
1295
+ useEffect(() => {
1296
+ if (adapter || !entity || !id) {
1297
+ setStubLoading(false);
1298
+ return;
1299
+ }
1300
+ setStubLoading(true);
1301
+ const t = setTimeout(() => {
1302
+ setStubData(null);
1303
+ setStubLoading(false);
1304
+ }, 100);
1305
+ return () => clearTimeout(t);
1306
+ }, [entity, id, adapter]);
1307
+ if (adapter) {
1308
+ return {
1309
+ data: adapterData,
1310
+ isLoading: adapter.isLoading,
1311
+ error: adapter.error ? new Error(adapter.error) : null
1312
+ };
1313
+ }
1314
+ return { data: stubData, isLoading: stubLoading, error: stubError };
1315
+ }
1316
+ function useEntityDetail(entity, id) {
1317
+ const result = useEntity(entity, id);
1318
+ return { ...result, refetch: () => {
1319
+ } };
1320
+ }
1321
+ var suspenseCache = /* @__PURE__ */ new Map();
1322
+ function getSuspenseCacheKey(entity, type, id) {
1323
+ return id ? `${type}:${entity}:${id}` : `${type}:${entity}`;
1324
+ }
1325
+ function useEntityListSuspense(entity) {
1326
+ const adapter = useContext(EntityDataContext);
1327
+ if (adapter) {
1328
+ if (adapter.isLoading) {
1329
+ const cacheKey2 = getSuspenseCacheKey(entity, "list");
1330
+ let entry2 = suspenseCache.get(cacheKey2);
1331
+ if (!entry2 || entry2.status === "resolved") {
1332
+ let resolve;
1333
+ const promise = new Promise((r) => {
1334
+ resolve = r;
1335
+ });
1336
+ entry2 = { promise, status: "pending" };
1337
+ suspenseCache.set(cacheKey2, entry2);
1338
+ const check = setInterval(() => {
1339
+ if (!adapter.isLoading) {
1340
+ clearInterval(check);
1341
+ entry2.status = "resolved";
1342
+ resolve();
1343
+ }
1344
+ }, 50);
1345
+ }
1346
+ if (entry2.status === "pending") {
1347
+ throw entry2.promise;
1348
+ }
1349
+ }
1350
+ if (adapter.error) {
1351
+ throw new Error(adapter.error);
1352
+ }
1353
+ return {
1354
+ data: adapter.getData(entity),
1355
+ refetch: () => {
1356
+ }
1357
+ };
1358
+ }
1359
+ const cacheKey = getSuspenseCacheKey(entity, "list");
1360
+ let entry = suspenseCache.get(cacheKey);
1361
+ if (!entry) {
1362
+ let resolve;
1363
+ const promise = new Promise((r) => {
1364
+ resolve = r;
1365
+ setTimeout(() => {
1366
+ entry.status = "resolved";
1367
+ resolve();
1368
+ }, 100);
1369
+ });
1370
+ entry = { promise, status: "pending" };
1371
+ suspenseCache.set(cacheKey, entry);
1372
+ }
1373
+ if (entry.status === "pending") {
1374
+ throw entry.promise;
1375
+ }
1376
+ return { data: [], refetch: () => {
1377
+ } };
1378
+ }
1379
+ function useEntitySuspense(entity, id) {
1380
+ const adapter = useContext(EntityDataContext);
1381
+ if (adapter) {
1382
+ if (adapter.isLoading) {
1383
+ const cacheKey2 = getSuspenseCacheKey(entity, "detail", id);
1384
+ let entry2 = suspenseCache.get(cacheKey2);
1385
+ if (!entry2 || entry2.status === "resolved") {
1386
+ let resolve;
1387
+ const promise = new Promise((r) => {
1388
+ resolve = r;
1389
+ });
1390
+ entry2 = { promise, status: "pending" };
1391
+ suspenseCache.set(cacheKey2, entry2);
1392
+ const check = setInterval(() => {
1393
+ if (!adapter.isLoading) {
1394
+ clearInterval(check);
1395
+ entry2.status = "resolved";
1396
+ resolve();
1397
+ }
1398
+ }, 50);
1399
+ }
1400
+ if (entry2.status === "pending") {
1401
+ throw entry2.promise;
1402
+ }
1403
+ }
1404
+ if (adapter.error) {
1405
+ throw new Error(adapter.error);
1406
+ }
1407
+ return {
1408
+ data: adapter.getById(entity, id) ?? null,
1409
+ refetch: () => {
1410
+ }
1411
+ };
1412
+ }
1413
+ const cacheKey = getSuspenseCacheKey(entity, "detail", id);
1414
+ let entry = suspenseCache.get(cacheKey);
1415
+ if (!entry) {
1416
+ let resolve;
1417
+ const promise = new Promise((r) => {
1418
+ resolve = r;
1419
+ setTimeout(() => {
1420
+ entry.status = "resolved";
1421
+ resolve();
1422
+ }, 100);
1423
+ });
1424
+ entry = { promise, status: "pending" };
1425
+ suspenseCache.set(cacheKey, entry);
1426
+ }
1427
+ if (entry.status === "pending") {
1428
+ throw entry.promise;
1429
+ }
1430
+ return { data: null, refetch: () => {
1431
+ } };
1432
+ }
1433
+ var queryStores = /* @__PURE__ */ new Map();
1434
+ function getOrCreateStore(query) {
1435
+ if (!queryStores.has(query)) {
1436
+ queryStores.set(query, {
1437
+ search: "",
1438
+ filters: {},
1439
+ sortField: void 0,
1440
+ sortDirection: void 0,
1441
+ listeners: /* @__PURE__ */ new Set()
1442
+ });
1443
+ }
1444
+ return queryStores.get(query);
1445
+ }
1446
+ function useQuerySingleton(query) {
1447
+ const [, forceUpdate] = useState({});
1448
+ if (!query) {
1449
+ return null;
1450
+ }
1451
+ const store = useMemo(() => getOrCreateStore(query), [query]);
1452
+ useMemo(() => {
1453
+ const listener = () => forceUpdate({});
1454
+ store.listeners.add(listener);
1455
+ return () => {
1456
+ store.listeners.delete(listener);
1457
+ };
1458
+ }, [store]);
1459
+ const notifyListeners = useCallback(() => {
1460
+ store.listeners.forEach((listener) => listener());
1461
+ }, [store]);
1462
+ const setSearch = useCallback((value) => {
1463
+ store.search = value;
1464
+ notifyListeners();
1465
+ }, [store, notifyListeners]);
1466
+ const setFilter = useCallback((key, value) => {
1467
+ store.filters = { ...store.filters, [key]: value };
1468
+ notifyListeners();
1469
+ }, [store, notifyListeners]);
1470
+ const clearFilters = useCallback(() => {
1471
+ store.filters = {};
1472
+ store.search = "";
1473
+ notifyListeners();
1474
+ }, [store, notifyListeners]);
1475
+ const setSort = useCallback((field, direction) => {
1476
+ store.sortField = field;
1477
+ store.sortDirection = direction;
1478
+ notifyListeners();
1479
+ }, [store, notifyListeners]);
1480
+ return {
1481
+ search: store.search,
1482
+ setSearch,
1483
+ filters: store.filters,
1484
+ setFilter,
1485
+ clearFilters,
1486
+ sortField: store.sortField,
1487
+ sortDirection: store.sortDirection,
1488
+ setSort
1489
+ };
1490
+ }
1491
+ function parseQueryBinding(binding) {
1492
+ const cleaned = binding.startsWith("@") ? binding.slice(1) : binding;
1493
+ const parts = cleaned.split(".");
1494
+ return {
1495
+ query: parts[0],
1496
+ field: parts.length > 1 ? parts.slice(1).join(".") : void 0
1497
+ };
1498
+ }
1499
+
1500
+ // lib/api-client.ts
1501
+ var API_BASE_URL = typeof process !== "undefined" && process.env?.VITE_API_URL ? process.env.VITE_API_URL : "/api";
1502
+ var ApiError = class extends Error {
1503
+ constructor(status, statusText, message) {
1504
+ super(message || `API Error: ${status} ${statusText}`);
1505
+ this.status = status;
1506
+ this.statusText = statusText;
1507
+ this.name = "ApiError";
1508
+ }
1509
+ };
1510
+ async function handleResponse(response) {
1511
+ if (!response.ok) {
1512
+ let message;
1513
+ try {
1514
+ const errorData = await response.json();
1515
+ message = errorData.message || errorData.error;
1516
+ } catch {
1517
+ }
1518
+ throw new ApiError(response.status, response.statusText, message);
1519
+ }
1520
+ const text = await response.text();
1521
+ if (!text) {
1522
+ return void 0;
1523
+ }
1524
+ return JSON.parse(text);
1525
+ }
1526
+ function getHeaders() {
1527
+ const headers = {
1528
+ "Content-Type": "application/json"
1529
+ };
1530
+ const token = typeof localStorage !== "undefined" ? localStorage.getItem("authToken") : null;
1531
+ if (token) {
1532
+ headers["Authorization"] = `Bearer ${token}`;
1533
+ }
1534
+ return headers;
1535
+ }
1536
+ var apiClient = {
1537
+ /**
1538
+ * GET request
1539
+ */
1540
+ async get(endpoint) {
1541
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
1542
+ method: "GET",
1543
+ headers: getHeaders()
1544
+ });
1545
+ return handleResponse(response);
1546
+ },
1547
+ /**
1548
+ * POST request
1549
+ */
1550
+ async post(endpoint, data) {
1551
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
1552
+ method: "POST",
1553
+ headers: getHeaders(),
1554
+ body: data ? JSON.stringify(data) : void 0
1555
+ });
1556
+ return handleResponse(response);
1557
+ },
1558
+ /**
1559
+ * PUT request
1560
+ */
1561
+ async put(endpoint, data) {
1562
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
1563
+ method: "PUT",
1564
+ headers: getHeaders(),
1565
+ body: data ? JSON.stringify(data) : void 0
1566
+ });
1567
+ return handleResponse(response);
1568
+ },
1569
+ /**
1570
+ * PATCH request
1571
+ */
1572
+ async patch(endpoint, data) {
1573
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
1574
+ method: "PATCH",
1575
+ headers: getHeaders(),
1576
+ body: data ? JSON.stringify(data) : void 0
1577
+ });
1578
+ return handleResponse(response);
1579
+ },
1580
+ /**
1581
+ * DELETE request
1582
+ */
1583
+ async delete(endpoint) {
1584
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
1585
+ method: "DELETE",
1586
+ headers: getHeaders()
1587
+ });
1588
+ return handleResponse(response);
1589
+ }
1590
+ };
1591
+ var ENTITY_EVENTS = {
1592
+ CREATE: "ENTITY_CREATE",
1593
+ UPDATE: "ENTITY_UPDATE",
1594
+ DELETE: "ENTITY_DELETE"
1595
+ };
1596
+ async function sendOrbitalEvent(orbitalName, eventPayload) {
1597
+ const response = await apiClient.post(
1598
+ `/orbitals/${orbitalName}/events`,
1599
+ eventPayload
1600
+ );
1601
+ return response;
1602
+ }
1603
+ function useOrbitalMutations(entityName, orbitalName, options) {
1604
+ const queryClient = useQueryClient();
1605
+ const events = {
1606
+ create: options?.events?.create || ENTITY_EVENTS.CREATE,
1607
+ update: options?.events?.update || ENTITY_EVENTS.UPDATE,
1608
+ delete: options?.events?.delete || ENTITY_EVENTS.DELETE
1609
+ };
1610
+ const log = (message, data) => {
1611
+ if (options?.debug) {
1612
+ console.log(`[useOrbitalMutations:${orbitalName}] ${message}`, data ?? "");
1613
+ }
1614
+ };
1615
+ const createMutation = useMutation({
1616
+ mutationFn: async (data) => {
1617
+ log("Creating entity", data);
1618
+ return sendOrbitalEvent(orbitalName, {
1619
+ event: events.create,
1620
+ payload: { data, entityType: entityName }
1621
+ });
1622
+ },
1623
+ onSuccess: (response) => {
1624
+ log("Create succeeded", response);
1625
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
1626
+ },
1627
+ onError: (error) => {
1628
+ console.error(`[useOrbitalMutations] Create failed:`, error);
1629
+ }
1630
+ });
1631
+ const updateMutation = useMutation({
1632
+ mutationFn: async ({
1633
+ id,
1634
+ data
1635
+ }) => {
1636
+ log(`Updating entity ${id}`, data);
1637
+ return sendOrbitalEvent(orbitalName, {
1638
+ event: events.update,
1639
+ entityId: id,
1640
+ payload: { data, entityType: entityName }
1641
+ });
1642
+ },
1643
+ onSuccess: (response, variables) => {
1644
+ log("Update succeeded", response);
1645
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
1646
+ queryClient.invalidateQueries({
1647
+ queryKey: entityDataKeys.detail(entityName, variables.id)
1648
+ });
1649
+ },
1650
+ onError: (error) => {
1651
+ console.error(`[useOrbitalMutations] Update failed:`, error);
1652
+ }
1653
+ });
1654
+ const deleteMutation = useMutation({
1655
+ mutationFn: async (id) => {
1656
+ log(`Deleting entity ${id}`);
1657
+ return sendOrbitalEvent(orbitalName, {
1658
+ event: events.delete,
1659
+ entityId: id,
1660
+ payload: { entityType: entityName }
1661
+ });
1662
+ },
1663
+ onSuccess: (response, id) => {
1664
+ log("Delete succeeded", response);
1665
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
1666
+ queryClient.removeQueries({ queryKey: entityDataKeys.detail(entityName, id) });
1667
+ },
1668
+ onError: (error) => {
1669
+ console.error(`[useOrbitalMutations] Delete failed:`, error);
1670
+ }
1671
+ });
1672
+ return {
1673
+ // Async functions
1674
+ createEntity: async (data) => {
1675
+ return createMutation.mutateAsync(data);
1676
+ },
1677
+ updateEntity: async (id, data) => {
1678
+ if (!id) {
1679
+ console.warn("[useOrbitalMutations] Cannot update without ID");
1680
+ return;
1681
+ }
1682
+ return updateMutation.mutateAsync({ id, data });
1683
+ },
1684
+ deleteEntity: async (id) => {
1685
+ if (!id) {
1686
+ console.warn("[useOrbitalMutations] Cannot delete without ID");
1687
+ return;
1688
+ }
1689
+ return deleteMutation.mutateAsync(id);
1690
+ },
1691
+ // Mutation objects for fine-grained control
1692
+ createMutation,
1693
+ updateMutation,
1694
+ deleteMutation,
1695
+ // Aggregate states
1696
+ isCreating: createMutation.isPending,
1697
+ isUpdating: updateMutation.isPending,
1698
+ isDeleting: deleteMutation.isPending,
1699
+ isMutating: createMutation.isPending || updateMutation.isPending || deleteMutation.isPending,
1700
+ // Errors
1701
+ createError: createMutation.error,
1702
+ updateError: updateMutation.error,
1703
+ deleteError: deleteMutation.error
1704
+ };
1705
+ }
1706
+ function useSendOrbitalEvent(orbitalName) {
1707
+ const mutation = useMutation({
1708
+ mutationFn: async (payload) => {
1709
+ return sendOrbitalEvent(orbitalName, payload);
1710
+ }
1711
+ });
1712
+ return {
1713
+ sendEvent: async (event, payload, entityId) => {
1714
+ return mutation.mutateAsync({ event, payload, entityId });
1715
+ },
1716
+ isPending: mutation.isPending,
1717
+ error: mutation.error,
1718
+ data: mutation.data
1719
+ };
1720
+ }
1721
+
1722
+ // hooks/useEntityMutations.ts
1723
+ function entityToCollection(entityName) {
1724
+ return entityName.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase() + "-list";
1725
+ }
1726
+ function useCreateEntity(entityName) {
1727
+ const queryClient = useQueryClient();
1728
+ const collection = entityToCollection(entityName);
1729
+ return useMutation({
1730
+ mutationFn: async (data) => {
1731
+ console.log(`[useCreateEntity] Creating ${entityName}:`, data);
1732
+ const response = await apiClient.post(
1733
+ `/${collection}`,
1734
+ data
1735
+ );
1736
+ return response.data;
1737
+ },
1738
+ onSuccess: () => {
1739
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
1740
+ },
1741
+ onError: (error) => {
1742
+ console.error(`[useCreateEntity] Failed to create ${entityName}:`, error);
1743
+ }
1744
+ });
1745
+ }
1746
+ function useUpdateEntity(entityName) {
1747
+ const queryClient = useQueryClient();
1748
+ const collection = entityToCollection(entityName);
1749
+ return useMutation({
1750
+ mutationFn: async ({ id, data }) => {
1751
+ console.log(`[useUpdateEntity] Updating ${entityName} ${id}:`, data);
1752
+ const response = await apiClient.patch(
1753
+ `/${collection}/${id}`,
1754
+ data
1755
+ );
1756
+ return response.data;
1757
+ },
1758
+ onSuccess: (_, variables) => {
1759
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
1760
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.detail(entityName, variables.id) });
1761
+ },
1762
+ onError: (error) => {
1763
+ console.error(`[useUpdateEntity] Failed to update ${entityName}:`, error);
1764
+ }
1765
+ });
1766
+ }
1767
+ function useDeleteEntity(entityName) {
1768
+ const queryClient = useQueryClient();
1769
+ const collection = entityToCollection(entityName);
1770
+ return useMutation({
1771
+ mutationFn: async (id) => {
1772
+ console.log(`[useDeleteEntity] Deleting ${entityName} ${id}`);
1773
+ await apiClient.delete(`/${collection}/${id}`);
1774
+ return { id };
1775
+ },
1776
+ onSuccess: (_, id) => {
1777
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
1778
+ queryClient.removeQueries({ queryKey: entityDataKeys.detail(entityName, id) });
1779
+ },
1780
+ onError: (error) => {
1781
+ console.error(`[useDeleteEntity] Failed to delete ${entityName}:`, error);
1782
+ }
1783
+ });
1784
+ }
1785
+ async function sendOrbitalMutation(orbitalName, event, entityId, payload) {
1786
+ const response = await apiClient.post(
1787
+ `/orbitals/${orbitalName}/events`,
1788
+ { event, entityId, payload }
1789
+ );
1790
+ return response;
1791
+ }
1792
+ function useEntityMutations(entityName, options) {
1793
+ const queryClient = useQueryClient();
1794
+ const useOrbitalRoute = !!options?.orbitalName;
1795
+ const events = {
1796
+ create: options?.events?.create || ENTITY_EVENTS.CREATE,
1797
+ update: options?.events?.update || ENTITY_EVENTS.UPDATE,
1798
+ delete: options?.events?.delete || ENTITY_EVENTS.DELETE
1799
+ };
1800
+ const createMutation = useCreateEntity(entityName);
1801
+ const updateMutation = useUpdateEntity(entityName);
1802
+ const deleteMutation = useDeleteEntity(entityName);
1803
+ const orbitalCreateMutation = useMutation({
1804
+ mutationFn: async (data) => {
1805
+ return sendOrbitalMutation(options.orbitalName, events.create, void 0, {
1806
+ data,
1807
+ entityType: entityName
1808
+ });
1809
+ },
1810
+ onSuccess: () => {
1811
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
1812
+ }
1813
+ });
1814
+ const orbitalUpdateMutation = useMutation({
1815
+ mutationFn: async ({ id, data }) => {
1816
+ return sendOrbitalMutation(options.orbitalName, events.update, id, {
1817
+ data,
1818
+ entityType: entityName
1819
+ });
1820
+ },
1821
+ onSuccess: (_, variables) => {
1822
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
1823
+ queryClient.invalidateQueries({
1824
+ queryKey: entityDataKeys.detail(entityName, variables.id)
1825
+ });
1826
+ }
1827
+ });
1828
+ const orbitalDeleteMutation = useMutation({
1829
+ mutationFn: async (id) => {
1830
+ return sendOrbitalMutation(options.orbitalName, events.delete, id, {
1831
+ entityType: entityName
1832
+ });
1833
+ },
1834
+ onSuccess: (_, id) => {
1835
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
1836
+ queryClient.removeQueries({ queryKey: entityDataKeys.detail(entityName, id) });
1837
+ }
1838
+ });
1839
+ const activeMutations = {
1840
+ create: useOrbitalRoute ? orbitalCreateMutation : createMutation,
1841
+ update: useOrbitalRoute ? orbitalUpdateMutation : updateMutation,
1842
+ delete: useOrbitalRoute ? orbitalDeleteMutation : deleteMutation
1843
+ };
1844
+ return {
1845
+ // Async functions that can be called directly
1846
+ // Accepts either (data) or (entityName, data) for compiler compatibility
1847
+ createEntity: async (entityOrData, data) => {
1848
+ const actualData = typeof entityOrData === "string" ? data : entityOrData;
1849
+ if (!actualData) {
1850
+ console.warn("[useEntityMutations] Cannot create entity without data");
1851
+ return;
1852
+ }
1853
+ return activeMutations.create.mutateAsync(actualData);
1854
+ },
1855
+ updateEntity: async (id, data) => {
1856
+ if (!id) {
1857
+ console.warn("[useEntityMutations] Cannot update entity without ID");
1858
+ return;
1859
+ }
1860
+ return activeMutations.update.mutateAsync({ id, data });
1861
+ },
1862
+ deleteEntity: async (id) => {
1863
+ if (!id) {
1864
+ console.warn("[useEntityMutations] Cannot delete entity without ID");
1865
+ return;
1866
+ }
1867
+ return activeMutations.delete.mutateAsync(id);
1868
+ },
1869
+ // Mutation states for UI feedback
1870
+ isCreating: activeMutations.create.isPending,
1871
+ isUpdating: activeMutations.update.isPending,
1872
+ isDeleting: activeMutations.delete.isPending,
1873
+ createError: activeMutations.create.error,
1874
+ updateError: activeMutations.update.error,
1875
+ deleteError: activeMutations.delete.error
1876
+ };
1877
+ }
1878
+
1879
+ // stores/entityStore.ts
1880
+ var entities = /* @__PURE__ */ new Map();
1881
+ var listeners = /* @__PURE__ */ new Set();
1882
+ var idCounter2 = 0;
1883
+ function subscribe(listener) {
1884
+ listeners.add(listener);
1885
+ return () => listeners.delete(listener);
1886
+ }
1887
+ function notify() {
1888
+ listeners.forEach((listener) => listener());
1889
+ }
1890
+ function getEntity(id) {
1891
+ return entities.get(id);
1892
+ }
1893
+ function getByType(type) {
1894
+ const types = Array.isArray(type) ? type : [type];
1895
+ return [...entities.values()].filter((e) => types.includes(e.type));
1896
+ }
1897
+ function getAllEntities() {
1898
+ return [...entities.values()];
1899
+ }
1900
+ function getSingleton(type) {
1901
+ return [...entities.values()].find((e) => e.type === type);
1902
+ }
1903
+ function spawnEntity(config) {
1904
+ const id = config.id ?? `entity_${++idCounter2}`;
1905
+ const entity = { ...config, id };
1906
+ entities = new Map(entities);
1907
+ entities.set(id, entity);
1908
+ notify();
1909
+ return id;
1910
+ }
1911
+ function updateEntity(id, updates) {
1912
+ const entity = entities.get(id);
1913
+ if (entity) {
1914
+ entities = new Map(entities);
1915
+ entities.set(id, { ...entity, ...updates });
1916
+ notify();
1917
+ }
1918
+ }
1919
+ function updateSingleton(type, updates) {
1920
+ const entity = getSingleton(type);
1921
+ if (entity) {
1922
+ updateEntity(entity.id, updates);
1923
+ }
1924
+ }
1925
+ function removeEntity(id) {
1926
+ if (entities.has(id)) {
1927
+ entities = new Map(entities);
1928
+ entities.delete(id);
1929
+ notify();
1930
+ }
1931
+ }
1932
+ function clearEntities() {
1933
+ entities = /* @__PURE__ */ new Map();
1934
+ notify();
1935
+ }
1936
+ function getSnapshot() {
1937
+ return entities;
1938
+ }
1939
+
1940
+ // hooks/useEntities.ts
1941
+ function useEntities() {
1942
+ const entities2 = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
1943
+ return {
1944
+ entities: entities2,
1945
+ getEntity,
1946
+ getByType,
1947
+ getAllEntities,
1948
+ getSingleton,
1949
+ spawnEntity,
1950
+ updateEntity,
1951
+ updateSingleton,
1952
+ removeEntity,
1953
+ clearEntities
1954
+ };
1955
+ }
1956
+ function useEntity2(id) {
1957
+ const entities2 = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
1958
+ return entities2.get(id);
1959
+ }
1960
+ function useEntitiesByType(type) {
1961
+ const entities2 = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
1962
+ return [...entities2.values()].filter((e) => e.type === type);
1963
+ }
1964
+ function useSingletonEntity(type) {
1965
+ const entities2 = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
1966
+ return [...entities2.values()].find((e) => e.type === type);
1967
+ }
1968
+ function usePlayer() {
1969
+ const player = useSingletonEntity("Player");
1970
+ const update = useCallback((updates) => {
1971
+ if (player) updateEntity(player.id, updates);
1972
+ }, [player?.id]);
1973
+ return { player, updatePlayer: update };
1974
+ }
1975
+ function usePhysics() {
1976
+ const physics = useSingletonEntity("Physics");
1977
+ const update = useCallback((updates) => {
1978
+ if (physics) updateEntity(physics.id, updates);
1979
+ }, [physics?.id]);
1980
+ return { physics, updatePhysics: update };
1981
+ }
1982
+ function useInput() {
1983
+ const input = useSingletonEntity("Input");
1984
+ const update = useCallback((updates) => {
1985
+ if (input) updateEntity(input.id, updates);
1986
+ }, [input?.id]);
1987
+ return { input, updateInput: update };
1988
+ }
1989
+
1990
+ // locales/en.json
1991
+ var en_default = {
1992
+ $meta: { locale: "en", direction: "ltr" },
1993
+ "common.save": "Save",
1994
+ "common.cancel": "Cancel",
1995
+ "common.delete": "Delete",
1996
+ "common.close": "Close",
1997
+ "common.confirm": "Are you sure?",
1998
+ "common.create": "Create",
1999
+ "common.edit": "Edit",
2000
+ "common.view": "View",
2001
+ "common.add": "Add",
2002
+ "common.remove": "Remove",
2003
+ "common.search": "Search...",
2004
+ "common.filter": "Filter",
2005
+ "common.actions": "Actions",
2006
+ "common.yes": "Yes",
2007
+ "common.no": "No",
2008
+ "common.selected": "selected",
2009
+ "common.ok": "OK",
2010
+ "common.done": "Done",
2011
+ "common.apply": "Apply",
2012
+ "common.reset": "Reset",
2013
+ "common.refresh": "Refresh",
2014
+ "common.export": "Export",
2015
+ "common.import": "Import",
2016
+ "common.copy": "Copy",
2017
+ "common.settings": "Settings",
2018
+ "nav.previous": "Previous",
2019
+ "nav.next": "Next",
2020
+ "nav.back": "Back",
2021
+ "nav.home": "Home",
2022
+ "form.submit": "Submit",
2023
+ "form.saving": "Saving...",
2024
+ "form.required": "This field is required",
2025
+ "form.invalidEmail": "Enter a valid email address",
2026
+ "form.selectPlaceholder": "Select {{label}}...",
2027
+ "form.searchPlaceholder": "Search {{entity}}...",
2028
+ "table.empty.title": "No items found",
2029
+ "table.empty.description": "No items to display.",
2030
+ "table.search.placeholder": "Search...",
2031
+ "table.pagination.showing": "Showing {{start}} to {{end}} of {{total}} results",
2032
+ "table.pagination.page": "Page {{page}} of {{totalPages}}",
2033
+ "table.bulk.selected": "{{count}} selected",
2034
+ "table.loading": "Loading...",
2035
+ "status.loading": "Loading...",
2036
+ "status.scheduled": "Scheduled",
2037
+ "status.inProgress": "In Progress",
2038
+ "status.completed": "Completed",
2039
+ "status.cancelled": "Cancelled",
2040
+ "status.pending": "Pending",
2041
+ "status.active": "Active",
2042
+ "status.inactive": "Inactive",
2043
+ "status.draft": "Draft",
2044
+ "status.archived": "Archived",
2045
+ "error.generic": "Something went wrong",
2046
+ "error.retry": "Try again",
2047
+ "error.notFound": "Not found",
2048
+ "error.loadFailed": "Failed to load: {{message}}",
2049
+ "error.configMissing": "Configuration not found for: {{id}}",
2050
+ "common.loading": "Loading...",
2051
+ "common.showMore": "Show More",
2052
+ "common.showLess": "Show Less",
2053
+ "common.noResults": "No results found",
2054
+ "common.saveChanges": "Save Changes",
2055
+ "common.retry": "Retry",
2056
+ "common.open": "Open",
2057
+ "common.back": "Back",
2058
+ "empty.noItems": "No items",
2059
+ "empty.noData": "No data available",
2060
+ "empty.noItemsYet": "No items yet",
2061
+ "empty.noItemsAdded": "No items added yet",
2062
+ "empty.noOptionsFound": "No options found",
2063
+ "list.addItemPlaceholder": "Add new item...",
2064
+ "error.occurred": "An error occurred",
2065
+ "error.failedToLoad": "Failed to load data",
2066
+ "wizard.back": "Back",
2067
+ "wizard.next": "Next",
2068
+ "wizard.complete": "Complete",
2069
+ "wizard.stepOf": "Step {{current}} of {{total}}",
2070
+ "pagination.previous": "Previous",
2071
+ "pagination.next": "Next",
2072
+ "pagination.total": "Total:",
2073
+ "pagination.show": "Show:",
2074
+ "pagination.goTo": "Go to:",
2075
+ "pagination.go": "Go",
2076
+ "auth.signIn": "Sign in",
2077
+ "auth.signOut": "Sign out",
2078
+ "dialog.confirm": "Confirm",
2079
+ "dialog.cancel": "Cancel",
2080
+ "dialog.loading": "Loading...",
2081
+ "dialog.delete.title": "Delete {{item}}?",
2082
+ "dialog.delete.message": "This action cannot be undone.",
2083
+ "trait.availableActions": "Available Actions",
2084
+ "trait.transitions": "Transitions",
2085
+ "trait.availableNow": "Available now",
2086
+ "book.startReading": "Start Reading",
2087
+ "book.tableOfContents": "Table of Contents",
2088
+ "book.partNumber": "Part {{number}}",
2089
+ "book.print": "Print",
2090
+ "book.previousPage": "Previous page",
2091
+ "book.nextPage": "Next page",
2092
+ "quiz.showAnswer": "Show answer",
2093
+ "quiz.hideAnswer": "Hide answer"
2094
+ };
2095
+
2096
+ // hooks/useTranslate.ts
2097
+ var { $meta: _meta, ...coreMessages } = en_default;
2098
+ var coreLocale = coreMessages;
2099
+ var I18nContext = createContext({
2100
+ locale: "en",
2101
+ direction: "ltr",
2102
+ t: (key) => coreLocale[key] ?? key
2103
+ // core locale fallback
2104
+ });
2105
+ I18nContext.displayName = "I18nContext";
2106
+ var I18nProvider = I18nContext.Provider;
2107
+ function useTranslate() {
2108
+ return useContext(I18nContext);
2109
+ }
2110
+ function createTranslate(messages) {
2111
+ return (key, params) => {
2112
+ let msg = messages[key] ?? coreLocale[key] ?? key;
2113
+ if (params) {
2114
+ for (const [k, v] of Object.entries(params)) {
2115
+ msg = msg.split(`{{${k}}}`).join(String(v));
2116
+ }
2117
+ }
2118
+ return msg;
2119
+ };
2120
+ }
2121
+ function useResolvedEntity(entity, data) {
2122
+ const shouldFetch = !data && !!entity;
2123
+ const fetched = useEntityList(entity, { skip: !shouldFetch });
2124
+ return useMemo(() => {
2125
+ if (data) {
2126
+ return {
2127
+ data,
2128
+ isLocal: true,
2129
+ isLoading: false,
2130
+ error: null
2131
+ };
2132
+ }
2133
+ return {
2134
+ data: fetched.data,
2135
+ isLocal: false,
2136
+ isLoading: fetched.isLoading,
2137
+ error: fetched.error
2138
+ };
2139
+ }, [data, fetched.data, fetched.isLoading, fetched.error]);
2140
+ }
2141
+
2142
+ // hooks/useAuthContext.ts
2143
+ function useAuthContext() {
2144
+ return {
2145
+ user: null,
2146
+ loading: false,
2147
+ signIn: void 0,
2148
+ signOut: void 0
2149
+ };
2150
+ }
2151
+ function useSwipeGesture(callbacks, options = {}) {
2152
+ const { threshold = 50, velocityThreshold = 0.3, preventDefault = false } = options;
2153
+ const startX = useRef(0);
2154
+ const startY = useRef(0);
2155
+ const startTime = useRef(0);
2156
+ const currentX = useRef(0);
2157
+ const tracking = useRef(false);
2158
+ const offsetXRef = useRef(0);
2159
+ const isSwipingRef = useRef(false);
2160
+ const onPointerDown = useCallback((e) => {
2161
+ startX.current = e.clientX;
2162
+ startY.current = e.clientY;
2163
+ currentX.current = e.clientX;
2164
+ startTime.current = Date.now();
2165
+ tracking.current = true;
2166
+ isSwipingRef.current = false;
2167
+ offsetXRef.current = 0;
2168
+ e.target.setPointerCapture?.(e.pointerId);
2169
+ }, []);
2170
+ const onPointerMove = useCallback((e) => {
2171
+ if (!tracking.current) return;
2172
+ if (preventDefault) e.preventDefault();
2173
+ currentX.current = e.clientX;
2174
+ const dx = e.clientX - startX.current;
2175
+ const dy = e.clientY - startY.current;
2176
+ if (Math.abs(dx) > 10 && Math.abs(dx) > Math.abs(dy)) {
2177
+ isSwipingRef.current = true;
2178
+ offsetXRef.current = dx;
2179
+ }
2180
+ }, [preventDefault]);
2181
+ const onPointerUp = useCallback((e) => {
2182
+ if (!tracking.current) return;
2183
+ tracking.current = false;
2184
+ const dx = e.clientX - startX.current;
2185
+ const dy = e.clientY - startY.current;
2186
+ const elapsed = Date.now() - startTime.current;
2187
+ const velocity = Math.abs(dx) / Math.max(elapsed, 1);
2188
+ offsetXRef.current = 0;
2189
+ isSwipingRef.current = false;
2190
+ if (Math.abs(dx) < threshold && velocity < velocityThreshold) return;
2191
+ if (Math.abs(dx) > Math.abs(dy)) {
2192
+ if (dx < -threshold) callbacks.onSwipeLeft?.();
2193
+ else if (dx > threshold) callbacks.onSwipeRight?.();
2194
+ } else {
2195
+ if (dy < -threshold) callbacks.onSwipeUp?.();
2196
+ else if (dy > threshold) callbacks.onSwipeDown?.();
2197
+ }
2198
+ }, [threshold, velocityThreshold, callbacks]);
2199
+ const onPointerCancel = useCallback(() => {
2200
+ tracking.current = false;
2201
+ offsetXRef.current = 0;
2202
+ isSwipingRef.current = false;
2203
+ }, []);
2204
+ return {
2205
+ onPointerDown,
2206
+ onPointerMove,
2207
+ onPointerUp,
2208
+ onPointerCancel,
2209
+ offsetX: offsetXRef.current,
2210
+ isSwiping: isSwipingRef.current
2211
+ };
2212
+ }
2213
+ function useLongPress(onLongPress, options = {}) {
2214
+ const { duration = 500, moveThreshold = 10 } = options;
2215
+ const timerRef = useRef(null);
2216
+ const startPos = useRef({ x: 0, y: 0 });
2217
+ const isPressedRef = useRef(false);
2218
+ const firedRef = useRef(false);
2219
+ const cancel = useCallback(() => {
2220
+ if (timerRef.current) {
2221
+ clearTimeout(timerRef.current);
2222
+ timerRef.current = null;
2223
+ }
2224
+ isPressedRef.current = false;
2225
+ }, []);
2226
+ const onPointerDown = useCallback((e) => {
2227
+ firedRef.current = false;
2228
+ startPos.current = { x: e.clientX, y: e.clientY };
2229
+ isPressedRef.current = true;
2230
+ timerRef.current = setTimeout(() => {
2231
+ firedRef.current = true;
2232
+ isPressedRef.current = false;
2233
+ onLongPress();
2234
+ }, duration);
2235
+ }, [duration, onLongPress]);
2236
+ const onPointerMove = useCallback((e) => {
2237
+ if (!isPressedRef.current) return;
2238
+ const dx = e.clientX - startPos.current.x;
2239
+ const dy = e.clientY - startPos.current.y;
2240
+ if (Math.sqrt(dx * dx + dy * dy) > moveThreshold) {
2241
+ cancel();
2242
+ }
2243
+ }, [moveThreshold, cancel]);
2244
+ const onPointerUp = useCallback(() => {
2245
+ cancel();
2246
+ }, [cancel]);
2247
+ const onPointerCancel = useCallback(() => {
2248
+ cancel();
2249
+ }, [cancel]);
2250
+ return {
2251
+ onPointerDown,
2252
+ onPointerMove,
2253
+ onPointerUp,
2254
+ onPointerCancel,
2255
+ isPressed: isPressedRef.current
2256
+ };
2257
+ }
2258
+ function useDragReorder(initialItems, onReorder) {
2259
+ const [items, setItems] = useState(initialItems);
2260
+ const [dragIndex, setDragIndex] = useState(-1);
2261
+ const [dragOverIndex, setDragOverIndex] = useState(-1);
2262
+ const itemsRef = useRef(initialItems);
2263
+ if (initialItems !== itemsRef.current) {
2264
+ itemsRef.current = initialItems;
2265
+ setItems(initialItems);
2266
+ }
2267
+ const isDragging = dragIndex >= 0;
2268
+ const handleDragStart = useCallback((index) => (e) => {
2269
+ e.preventDefault();
2270
+ setDragIndex(index);
2271
+ setDragOverIndex(index);
2272
+ e.target.setPointerCapture?.(e.pointerId);
2273
+ }, []);
2274
+ const handleDragMove = useCallback((index) => (e) => {
2275
+ if (dragIndex < 0) return;
2276
+ const target = document.elementFromPoint(e.clientX, e.clientY);
2277
+ if (!target) return;
2278
+ let el = target;
2279
+ while (el && !el.dataset.dragIndex) {
2280
+ el = el.parentElement;
2281
+ }
2282
+ if (el?.dataset.dragIndex) {
2283
+ const overIndex = parseInt(el.dataset.dragIndex, 10);
2284
+ if (!isNaN(overIndex) && overIndex !== dragOverIndex) {
2285
+ setDragOverIndex(overIndex);
2286
+ }
2287
+ }
2288
+ }, [dragIndex, dragOverIndex]);
2289
+ const handleDragEnd = useCallback(() => {
2290
+ if (dragIndex >= 0 && dragOverIndex >= 0 && dragIndex !== dragOverIndex) {
2291
+ const newItems = [...items];
2292
+ const [movedItem] = newItems.splice(dragIndex, 1);
2293
+ newItems.splice(dragOverIndex, 0, movedItem);
2294
+ setItems(newItems);
2295
+ onReorder(dragIndex, dragOverIndex, items[dragIndex]);
2296
+ }
2297
+ setDragIndex(-1);
2298
+ setDragOverIndex(-1);
2299
+ }, [dragIndex, dragOverIndex, items, onReorder]);
2300
+ const getDragHandleProps = useCallback((index) => ({
2301
+ onPointerDown: handleDragStart(index),
2302
+ style: { cursor: "grab", touchAction: "none" },
2303
+ "aria-grabbed": dragIndex === index,
2304
+ role: "button"
2305
+ }), [handleDragStart, dragIndex]);
2306
+ const getItemProps = useCallback((index) => ({
2307
+ onPointerMove: handleDragMove(index),
2308
+ onPointerUp: handleDragEnd,
2309
+ "aria-dropeffect": "move",
2310
+ "data-drag-index": String(index),
2311
+ style: {
2312
+ opacity: dragIndex === index ? 0.5 : 1,
2313
+ transition: isDragging ? "transform 150ms ease" : void 0,
2314
+ transform: isDragging && dragOverIndex >= 0 ? index === dragIndex ? "scale(1.02)" : index > dragIndex && index <= dragOverIndex ? "translateY(-100%)" : index < dragIndex && index >= dragOverIndex ? "translateY(100%)" : void 0 : void 0
2315
+ }
2316
+ }), [handleDragMove, handleDragEnd, dragIndex, dragOverIndex, isDragging]);
2317
+ return {
2318
+ items,
2319
+ dragIndex,
2320
+ dragOverIndex,
2321
+ isDragging,
2322
+ getDragHandleProps,
2323
+ getItemProps
2324
+ };
2325
+ }
2326
+ function useInfiniteScroll(onLoadMore, options = {}) {
2327
+ const { rootMargin = "200px", hasMore = true, isLoading = false } = options;
2328
+ const observerRef = useRef(null);
2329
+ const callbackRef = useRef(onLoadMore);
2330
+ callbackRef.current = onLoadMore;
2331
+ const hasMoreRef = useRef(hasMore);
2332
+ hasMoreRef.current = hasMore;
2333
+ const isLoadingRef = useRef(isLoading);
2334
+ isLoadingRef.current = isLoading;
2335
+ useEffect(() => {
2336
+ return () => {
2337
+ observerRef.current?.disconnect();
2338
+ };
2339
+ }, []);
2340
+ const sentinelRef = useCallback((node) => {
2341
+ observerRef.current?.disconnect();
2342
+ if (!node) return;
2343
+ observerRef.current = new IntersectionObserver(
2344
+ (entries) => {
2345
+ const entry = entries[0];
2346
+ if (entry.isIntersecting && hasMoreRef.current && !isLoadingRef.current) {
2347
+ callbackRef.current();
2348
+ }
2349
+ },
2350
+ { rootMargin }
2351
+ );
2352
+ observerRef.current.observe(node);
2353
+ }, [rootMargin]);
2354
+ return { sentinelRef };
2355
+ }
2356
+ function usePullToRefresh(onRefresh, options = {}) {
2357
+ const { threshold = 60, maxPull = 120 } = options;
2358
+ const [pullDistance, setPullDistance] = useState(0);
2359
+ const [isPulling, setIsPulling] = useState(false);
2360
+ const [isRefreshing, setIsRefreshing] = useState(false);
2361
+ const startY = useRef(0);
2362
+ const scrollTopRef = useRef(0);
2363
+ const onTouchStart = useCallback((e) => {
2364
+ const container = e.currentTarget;
2365
+ scrollTopRef.current = container.scrollTop;
2366
+ if (scrollTopRef.current <= 0) {
2367
+ startY.current = e.touches[0].clientY;
2368
+ setIsPulling(true);
2369
+ }
2370
+ }, []);
2371
+ const onTouchMove = useCallback((e) => {
2372
+ if (!isPulling || isRefreshing) return;
2373
+ const container = e.currentTarget;
2374
+ if (container.scrollTop > 0) {
2375
+ setPullDistance(0);
2376
+ return;
2377
+ }
2378
+ const dy = e.touches[0].clientY - startY.current;
2379
+ if (dy > 0) {
2380
+ const distance = Math.min(dy * 0.5, maxPull);
2381
+ setPullDistance(distance);
2382
+ }
2383
+ }, [isPulling, isRefreshing, maxPull]);
2384
+ const onTouchEnd = useCallback(() => {
2385
+ if (!isPulling) return;
2386
+ setIsPulling(false);
2387
+ if (pullDistance >= threshold && !isRefreshing) {
2388
+ setIsRefreshing(true);
2389
+ setPullDistance(threshold);
2390
+ onRefresh();
2391
+ } else {
2392
+ setPullDistance(0);
2393
+ }
2394
+ }, [isPulling, pullDistance, threshold, isRefreshing, onRefresh]);
2395
+ const endRefresh = useCallback(() => {
2396
+ setIsRefreshing(false);
2397
+ setPullDistance(0);
2398
+ }, []);
2399
+ const containerProps = {
2400
+ onTouchStart,
2401
+ onTouchMove,
2402
+ onTouchEnd,
2403
+ style: {
2404
+ transform: pullDistance > 0 ? `translateY(${pullDistance}px)` : void 0,
2405
+ transition: isPulling ? "none" : "transform 300ms ease-out"
2406
+ }
2407
+ };
2408
+ return {
2409
+ pullDistance,
2410
+ isPulling,
2411
+ isRefreshing,
2412
+ containerProps,
2413
+ endRefresh
2414
+ };
2415
+ }
2416
+ function getDistance(touches) {
2417
+ const dx = touches[0].clientX - touches[1].clientX;
2418
+ const dy = touches[0].clientY - touches[1].clientY;
2419
+ return Math.sqrt(dx * dx + dy * dy);
2420
+ }
2421
+ function usePinchZoom(options = {}) {
2422
+ const { minScale = 0.5, maxScale = 4 } = options;
2423
+ const [scale, setScale] = useState(1);
2424
+ const [isPinching, setIsPinching] = useState(false);
2425
+ const initialDistance = useRef(0);
2426
+ const initialScale = useRef(1);
2427
+ const onTouchStart = useCallback((e) => {
2428
+ if (e.touches.length === 2) {
2429
+ initialDistance.current = getDistance(e.touches);
2430
+ initialScale.current = scale;
2431
+ setIsPinching(true);
2432
+ }
2433
+ }, [scale]);
2434
+ const onTouchMove = useCallback((e) => {
2435
+ if (e.touches.length !== 2 || !isPinching) return;
2436
+ e.preventDefault();
2437
+ const currentDistance = getDistance(e.touches);
2438
+ const ratio = currentDistance / initialDistance.current;
2439
+ const newScale = Math.min(maxScale, Math.max(minScale, initialScale.current * ratio));
2440
+ setScale(newScale);
2441
+ }, [isPinching, minScale, maxScale]);
2442
+ const onTouchEnd = useCallback(() => {
2443
+ setIsPinching(false);
2444
+ }, []);
2445
+ const resetZoom = useCallback(() => {
2446
+ setScale(1);
2447
+ }, []);
2448
+ return {
2449
+ scale,
2450
+ isPinching,
2451
+ gestureProps: {
2452
+ onTouchStart,
2453
+ onTouchMove,
2454
+ onTouchEnd
2455
+ },
2456
+ resetZoom
2457
+ };
2458
+ }
2459
+ var API_BASE = typeof process !== "undefined" && process.env?.VITE_API_URL ? process.env.VITE_API_URL : "http://localhost:3000";
2460
+ function getUserId() {
2461
+ return localStorage.getItem("userId") || "anonymous";
2462
+ }
2463
+ async function fetchWithAuth(endpoint, options) {
2464
+ const userId = getUserId();
2465
+ const response = await fetch(`${API_BASE}${endpoint}`, {
2466
+ ...options,
2467
+ headers: {
2468
+ "Content-Type": "application/json",
2469
+ "x-user-id": userId,
2470
+ ...options?.headers
2471
+ }
2472
+ });
2473
+ if (!response.ok) {
2474
+ const error = await response.json().catch(() => ({ error: response.statusText }));
2475
+ throw new Error(error.error || error.message || "Request failed");
2476
+ }
2477
+ return response.json();
2478
+ }
2479
+ function useGitHubStatus() {
2480
+ return useQuery({
2481
+ queryKey: ["github", "status"],
2482
+ queryFn: () => fetchWithAuth("/api/github/status"),
2483
+ staleTime: 6e4,
2484
+ // 1 minute
2485
+ retry: false
2486
+ });
2487
+ }
2488
+ function useConnectGitHub() {
2489
+ const connectGitHub = useCallback(() => {
2490
+ const userId = getUserId();
2491
+ const state = btoa(JSON.stringify({ userId, returnUrl: window.location.href }));
2492
+ window.location.href = `${API_BASE}/api/github/oauth/authorize?state=${state}`;
2493
+ }, []);
2494
+ return { connectGitHub };
2495
+ }
2496
+ function useDisconnectGitHub() {
2497
+ const queryClient = useQueryClient();
2498
+ return useMutation({
2499
+ mutationFn: () => fetchWithAuth("/api/github/disconnect", { method: "POST" }),
2500
+ onSuccess: () => {
2501
+ queryClient.invalidateQueries({ queryKey: ["github", "status"] });
2502
+ queryClient.removeQueries({ queryKey: ["github", "repos"] });
2503
+ }
2504
+ });
2505
+ }
2506
+ function useGitHubRepos(page = 1, perPage = 30) {
2507
+ return useQuery({
2508
+ queryKey: ["github", "repos", page, perPage],
2509
+ queryFn: () => fetchWithAuth(`/api/github/repos?page=${page}&per_page=${perPage}`),
2510
+ enabled: true,
2511
+ // Only fetch if user is connected
2512
+ staleTime: 3e5
2513
+ // 5 minutes
2514
+ });
2515
+ }
2516
+ function useGitHubRepo(owner, repo, enabled = true) {
2517
+ return useQuery({
2518
+ queryKey: ["github", "repo", owner, repo],
2519
+ queryFn: () => fetchWithAuth(`/api/github/repos/${owner}/${repo}`),
2520
+ enabled: enabled && !!owner && !!repo,
2521
+ staleTime: 3e5
2522
+ // 5 minutes
2523
+ });
2524
+ }
2525
+ function useGitHubBranches(owner, repo, enabled = true) {
2526
+ return useQuery({
2527
+ queryKey: ["github", "branches", owner, repo],
2528
+ queryFn: () => fetchWithAuth(`/api/github/repos/${owner}/${repo}/branches`),
2529
+ enabled: enabled && !!owner && !!repo,
2530
+ staleTime: 6e4
2531
+ // 1 minute
2532
+ });
2533
+ }
2534
+
2535
+ export { DEFAULT_SLOTS, ENTITY_EVENTS, EntityDataProvider, I18nProvider, clearEntities, createTranslate, entityDataKeys, getAllEntities, getByType, getEntity, getSingleton, parseQueryBinding, removeEntity, spawnEntity, updateEntity, updateSingleton, useAgentChat, useAuthContext, useCompile, useConnectGitHub, useCreateEntity, useDeepAgentGeneration, useDeleteEntity, useDisconnectGitHub, useDragReorder, useEmitEvent, useEntities, useEntitiesByType, useEntity, useEntity2 as useEntityById, useEntityDataAdapter, useEntityDetail, useEntityList, useEntityListSuspense, useEntityMutations, useEntitySuspense, useEventBus, useEventListener, useExtensions, useFileEditor, useFileSystem, useGitHubBranches, useGitHubRepo, useGitHubRepos, useGitHubStatus, useInfiniteScroll, useInput, useLongPress, useOrbitalHistory, useOrbitalMutations, usePhysics, usePinchZoom, usePlayer, usePreview, usePullToRefresh, useQuerySingleton, useResolvedEntity, useSelectedEntity, useSendOrbitalEvent, useSingletonEntity, useSwipeGesture, useTranslate, useUIEvents, useUISlotManager, useUpdateEntity, useValidation };