@mdxui/do 2.1.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +115 -323
  2. package/dist/{agents-xcIn2dUB.d.ts → agents-2_r9e9i7.d.ts} +213 -2
  3. package/dist/app/index.d.ts +347 -0
  4. package/dist/app/index.js +14 -0
  5. package/dist/app/index.js.map +1 -0
  6. package/dist/breadcrumbs-C9Qn3S7d.d.ts +81 -0
  7. package/dist/capnweb-client-Bq78FtEA.d.ts +229 -0
  8. package/dist/chunk-3XKYQRXY.js +192 -0
  9. package/dist/chunk-3XKYQRXY.js.map +1 -0
  10. package/dist/chunk-4KXVN3EQ.js +56 -0
  11. package/dist/chunk-4KXVN3EQ.js.map +1 -0
  12. package/dist/chunk-5SHZZC7L.js +234 -0
  13. package/dist/chunk-5SHZZC7L.js.map +1 -0
  14. package/dist/chunk-7UFINK3Q.js +1994 -0
  15. package/dist/chunk-7UFINK3Q.js.map +1 -0
  16. package/dist/chunk-JJLAES6W.js +76 -0
  17. package/dist/chunk-JJLAES6W.js.map +1 -0
  18. package/dist/chunk-KT52UU3U.js +985 -0
  19. package/dist/chunk-KT52UU3U.js.map +1 -0
  20. package/dist/chunk-LJIWB7KE.js +95 -0
  21. package/dist/chunk-LJIWB7KE.js.map +1 -0
  22. package/dist/chunk-NA652ART.js +596 -0
  23. package/dist/chunk-NA652ART.js.map +1 -0
  24. package/dist/chunk-OVLO7UOH.js +1071 -0
  25. package/dist/chunk-OVLO7UOH.js.map +1 -0
  26. package/dist/chunk-VRLUXCLD.js +31 -0
  27. package/dist/chunk-VRLUXCLD.js.map +1 -0
  28. package/dist/chunk-WMNT4OIE.js +249 -0
  29. package/dist/chunk-WMNT4OIE.js.map +1 -0
  30. package/dist/chunk-Y52IEYVM.js +131 -0
  31. package/dist/chunk-Y52IEYVM.js.map +1 -0
  32. package/dist/components/index.d.ts +14 -732
  33. package/dist/components/index.js +3 -6
  34. package/dist/config-CxvpD8Y6.d.ts +111 -0
  35. package/dist/{do-CaQVueZw.d.ts → do-D27i5bU0.d.ts} +32 -33
  36. package/dist/errors-DratdVIz.d.ts +346 -0
  37. package/dist/hooks/index.d.ts +450 -691
  38. package/dist/hooks/index.js +6 -4
  39. package/dist/hooks/things/index.d.ts +298 -0
  40. package/dist/hooks/things/index.js +8 -0
  41. package/dist/hooks/things/index.js.map +1 -0
  42. package/dist/index.d.ts +62 -989
  43. package/dist/index.js +12 -839
  44. package/dist/index.js.map +1 -1
  45. package/dist/lib/index.d.ts +798 -0
  46. package/dist/lib/index.js +6 -0
  47. package/dist/lib/index.js.map +1 -0
  48. package/dist/providers/index.d.ts +130 -34
  49. package/dist/providers/index.js +3 -2
  50. package/dist/query-keys-CZNFikIi.d.ts +153 -0
  51. package/dist/schemas/index.d.ts +5 -5
  52. package/dist/schemas/index.js +2 -2
  53. package/dist/schemas/index.js.map +1 -1
  54. package/dist/{thing-DtI25yZh.d.ts → thing-BF25aUtJ.d.ts} +72 -72
  55. package/dist/types/index.d.ts +693 -658
  56. package/dist/types/index.js +1 -2
  57. package/dist/views/index.d.ts +131 -0
  58. package/dist/views/index.js +11 -0
  59. package/dist/views/index.js.map +1 -0
  60. package/package.json +39 -17
  61. package/dist/__test-utils__/index.d.ts +0 -399
  62. package/dist/__test-utils__/index.js +0 -34641
  63. package/dist/__test-utils__/index.js.map +0 -1
  64. package/dist/chunk-EEDMN7UF.js +0 -1351
  65. package/dist/chunk-EEDMN7UF.js.map +0 -1
  66. package/dist/chunk-G3PMV62Z.js +0 -33
  67. package/dist/chunk-G3PMV62Z.js.map +0 -1
  68. package/dist/chunk-NXPXL5NA.js +0 -3789
  69. package/dist/chunk-NXPXL5NA.js.map +0 -1
  70. package/dist/chunk-PC5FJY6M.js +0 -20
  71. package/dist/chunk-PC5FJY6M.js.map +0 -1
  72. package/dist/chunk-XF6LKY2M.js +0 -445
  73. package/dist/chunk-XF6LKY2M.js.map +0 -1
  74. package/dist/magic-string.es-J7BYFTTJ.js +0 -1307
  75. package/dist/magic-string.es-J7BYFTTJ.js.map +0 -1
@@ -0,0 +1,1071 @@
1
+ import { retryWithBackoff } from './chunk-Y52IEYVM.js';
2
+ import { newWebSocketRpcSession } from 'capnweb';
3
+ import { useState, useRef, useCallback, useEffect } from 'react';
4
+
5
+ function createCapnwebClient(baseUrl, options = {}) {
6
+ const httpUrl = `${baseUrl.replace(/\/$/, "").replace(/\/rpc$/, "")}/rpc`;
7
+ const wsUrl = httpUrl.replace(/^http/, "ws");
8
+ const rpcUrl = options.authToken ? `${wsUrl}?token=${encodeURIComponent(options.authToken)}` : wsUrl;
9
+ const session = newWebSocketRpcSession(rpcUrl);
10
+ const rpc = session;
11
+ return {
12
+ /**
13
+ * Namespace operations
14
+ */
15
+ Namespace: {
16
+ async list(_params) {
17
+ return [{ id: "default", name: "default" }];
18
+ }
19
+ },
20
+ /**
21
+ * Schema operations
22
+ */
23
+ Schema: {
24
+ async discover(_params) {
25
+ try {
26
+ const schemas = await rpc.getSchemas();
27
+ return {
28
+ namespaces: ["default"],
29
+ types: schemas ?? [],
30
+ schemas: schemas ?? []
31
+ };
32
+ } catch (error) {
33
+ console.error("[@mdxui/do] Failed to get schemas:", error);
34
+ return { namespaces: ["default"], types: [], schemas: [] };
35
+ }
36
+ },
37
+ async get(params) {
38
+ try {
39
+ const result = await rpc.getSchema(params.type);
40
+ return result;
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+ },
46
+ /**
47
+ * Thing operations
48
+ */
49
+ Thing: {
50
+ async types(params) {
51
+ try {
52
+ const schemas = await rpc.getSchemas();
53
+ return (schemas ?? []).map((name) => ({
54
+ name,
55
+ ns: params.ns || "default"
56
+ }));
57
+ } catch (error) {
58
+ console.error("[@mdxui/do] Failed to get types:", error);
59
+ return [];
60
+ }
61
+ },
62
+ async list(params) {
63
+ try {
64
+ const options2 = {};
65
+ if (params.type) options2.type = params.type;
66
+ if (params.limit !== void 0) options2.limit = params.limit;
67
+ if (params.offset !== void 0) options2.offset = params.offset;
68
+ const result = await rpc.list(options2);
69
+ if (Array.isArray(result)) {
70
+ return { data: result, total: result.length };
71
+ }
72
+ if (result) {
73
+ const items = result.data || result.items || result.result || [];
74
+ return { data: items, total: result.count ?? items.length };
75
+ }
76
+ return { data: [], total: 0 };
77
+ } catch (error) {
78
+ console.error("[@mdxui/do] Failed to list things:", error);
79
+ return { data: [], total: 0 };
80
+ }
81
+ },
82
+ async get(params) {
83
+ try {
84
+ const result = await rpc.get({ type: params.type, id: params.id });
85
+ return result;
86
+ } catch {
87
+ return null;
88
+ }
89
+ },
90
+ async create(params) {
91
+ const result = await rpc.create({ type: params.type, data: params.data });
92
+ return result;
93
+ },
94
+ async update(params) {
95
+ const result = await rpc.update({ type: params.type, id: params.id, data: params.data });
96
+ return result;
97
+ },
98
+ async delete(params) {
99
+ await rpc.delete({ type: params.type, id: params.id });
100
+ return { success: true };
101
+ },
102
+ async versions(_params) {
103
+ return [];
104
+ },
105
+ async stats(_params) {
106
+ try {
107
+ const options2 = {};
108
+ if (_params.type) options2.type = _params.type;
109
+ const result = await rpc.getStats(options2);
110
+ return {
111
+ total: result?.total ?? 0,
112
+ byType: result?.byType ?? {}
113
+ };
114
+ } catch (error) {
115
+ console.error("[@mdxui/do] Failed to get stats:", error);
116
+ return { total: 0, byType: {} };
117
+ }
118
+ }
119
+ },
120
+ /**
121
+ * SQL operations (not supported by capnweb servers)
122
+ */
123
+ SQL: {
124
+ async execute(_params) {
125
+ throw new Error("SQL execution is not supported by this server");
126
+ }
127
+ },
128
+ // Required for interface compatibility
129
+ dup: () => createCapnwebClient(baseUrl, options),
130
+ onRpcBroken: (callback) => {
131
+ if ("onRpcBroken" in session && typeof session.onRpcBroken === "function") {
132
+ session.onRpcBroken(callback);
133
+ }
134
+ },
135
+ [Symbol.dispose]: () => {
136
+ if (Symbol.dispose in session) {
137
+ session[Symbol.dispose]();
138
+ }
139
+ }
140
+ };
141
+ }
142
+ function $CapnwebContext(url, options) {
143
+ return createCapnwebClient(url, options);
144
+ }
145
+
146
+ // src/lib/json-rpc-client.ts
147
+ var endpointCache = /* @__PURE__ */ new Map();
148
+ function createJsonRpcClient(baseUrl, options = {}) {
149
+ const rpcUrl = baseUrl.replace(/\/$/, "").replace(/\/rpc$/, "");
150
+ function getAuthHeaders() {
151
+ if (options.authToken) {
152
+ return { Authorization: `Bearer ${options.authToken}` };
153
+ }
154
+ return {};
155
+ }
156
+ async function rpcCall(method, args = []) {
157
+ const response = await fetch(`${rpcUrl}/rpc`, {
158
+ method: "POST",
159
+ headers: {
160
+ "Content-Type": "application/json",
161
+ ...getAuthHeaders()
162
+ },
163
+ body: JSON.stringify({ method, args })
164
+ });
165
+ if (!response.ok) {
166
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
167
+ }
168
+ const data = await response.json();
169
+ if (data.error) {
170
+ throw new Error(data.error.message || data.error.code);
171
+ }
172
+ return data.result;
173
+ }
174
+ async function restCall(path, init) {
175
+ const response = await fetch(`${rpcUrl}${path}`, {
176
+ ...init,
177
+ headers: {
178
+ "Content-Type": "application/json",
179
+ ...getAuthHeaders(),
180
+ ...init?.headers
181
+ }
182
+ });
183
+ if (!response.ok) {
184
+ const method = init?.method?.toUpperCase() ?? "GET";
185
+ if (response.status === 404 && method === "GET") {
186
+ return { data: [], count: 0 };
187
+ }
188
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
189
+ }
190
+ return response.json();
191
+ }
192
+ return {
193
+ /**
194
+ * Namespace operations
195
+ */
196
+ Namespace: {
197
+ async list(_params) {
198
+ return [{ id: "default", name: "default" }];
199
+ }
200
+ },
201
+ /**
202
+ * Schema operations
203
+ */
204
+ Schema: {
205
+ async discover(_params) {
206
+ const schemas = await rpcCall("schemas.list", []);
207
+ return {
208
+ namespaces: ["default"],
209
+ types: schemas,
210
+ schemas
211
+ };
212
+ },
213
+ async get(params) {
214
+ const result = await rpcCall("schemas.get", [params.type]);
215
+ return result;
216
+ }
217
+ },
218
+ /**
219
+ * Thing operations (maps to REST endpoints)
220
+ */
221
+ Thing: {
222
+ async types(params) {
223
+ try {
224
+ const schemas = await rpcCall("schemas.list", []);
225
+ let validEndpoints = endpointCache.get(rpcUrl);
226
+ if (!validEndpoints) {
227
+ validEndpoints = /* @__PURE__ */ new Set();
228
+ const probeResults = await Promise.all(
229
+ schemas.map(async (type) => {
230
+ const endpoint = getEndpointForType(type);
231
+ try {
232
+ const response = await fetch(`${rpcUrl}${endpoint}`, { method: "HEAD" });
233
+ return { type, exists: response.ok };
234
+ } catch {
235
+ try {
236
+ const response = await fetch(`${rpcUrl}${endpoint}?limit=0`);
237
+ return { type, exists: response.ok };
238
+ } catch {
239
+ return { type, exists: false };
240
+ }
241
+ }
242
+ })
243
+ );
244
+ for (const { type, exists } of probeResults) {
245
+ if (exists) {
246
+ validEndpoints.add(type);
247
+ }
248
+ }
249
+ endpointCache.set(rpcUrl, validEndpoints);
250
+ }
251
+ return Array.from(validEndpoints).map((name) => ({
252
+ name,
253
+ ns: params.ns || "default"
254
+ }));
255
+ } catch {
256
+ return ["Noun", "Verb", "Action", "Function"].map((name) => ({
257
+ name,
258
+ ns: params.ns || "default"
259
+ }));
260
+ }
261
+ },
262
+ async list(params) {
263
+ const endpoint = getEndpointForType(params.type || "Thing");
264
+ const response = await restCall(endpoint);
265
+ const items = response.data || response.items || response.result || [];
266
+ return {
267
+ data: items,
268
+ total: response.count ?? items.length
269
+ };
270
+ },
271
+ async get(params) {
272
+ const endpoint = getEndpointForType(params.type);
273
+ const response = await restCall(`${endpoint}/${params.id}`);
274
+ return response.data;
275
+ },
276
+ async create(params) {
277
+ const endpoint = getEndpointForType(params.type);
278
+ const response = await restCall(endpoint, {
279
+ method: "POST",
280
+ body: JSON.stringify(params.data)
281
+ });
282
+ return response.data;
283
+ },
284
+ async update(params) {
285
+ const endpoint = getEndpointForType(params.type);
286
+ const response = await restCall(`${endpoint}/${params.id}`, {
287
+ method: "PUT",
288
+ body: JSON.stringify(params.data)
289
+ });
290
+ return response.data;
291
+ },
292
+ async delete(params) {
293
+ const endpoint = getEndpointForType(params.type);
294
+ await restCall(`${endpoint}/${params.id}`, { method: "DELETE" });
295
+ return { success: true };
296
+ },
297
+ async versions(_params) {
298
+ return [];
299
+ },
300
+ async stats(_params) {
301
+ let validEndpoints = endpointCache.get(rpcUrl);
302
+ if (!validEndpoints) {
303
+ await this.types({ ns: _params.ns });
304
+ validEndpoints = endpointCache.get(rpcUrl) || /* @__PURE__ */ new Set();
305
+ }
306
+ const types = Array.from(validEndpoints);
307
+ const results = await Promise.all(
308
+ types.map(async (type) => {
309
+ const endpoint = getEndpointForType(type);
310
+ const response = await restCall(endpoint).catch(() => ({ count: 0 }));
311
+ return { type, count: response.count || 0 };
312
+ })
313
+ );
314
+ const byType = {};
315
+ let total = 0;
316
+ for (const { type, count } of results) {
317
+ byType[type] = count;
318
+ total += count;
319
+ }
320
+ return { total, byType };
321
+ }
322
+ },
323
+ /**
324
+ * SQL operations
325
+ */
326
+ SQL: {
327
+ async execute(params) {
328
+ const startTime = Date.now();
329
+ try {
330
+ const result = await rpcCall("sql.execute", [params.query, params.params || []]);
331
+ return {
332
+ rows: result.rows ?? [],
333
+ columns: result.columns ?? [],
334
+ rowsAffected: result.rowsAffected,
335
+ executionTimeMs: result.executionTimeMs ?? Date.now() - startTime
336
+ };
337
+ } catch (rpcError) {
338
+ const errorMessage = rpcError instanceof Error ? rpcError.message : String(rpcError);
339
+ const isNotSupported = errorMessage.includes("not found") || errorMessage.includes("not supported") || errorMessage.includes("unknown method");
340
+ try {
341
+ const response = await restCall("/sql", {
342
+ method: "POST",
343
+ body: JSON.stringify({ query: params.query, params: params.params })
344
+ });
345
+ return {
346
+ rows: response.rows ?? [],
347
+ columns: response.columns ?? [],
348
+ rowsAffected: response.rowsAffected,
349
+ executionTimeMs: Date.now() - startTime
350
+ };
351
+ } catch (restError) {
352
+ if (isNotSupported) {
353
+ throw new Error(
354
+ "SQL execution is not supported by this server. The server does not expose sql.execute RPC method or /sql REST endpoint."
355
+ );
356
+ }
357
+ throw restError;
358
+ }
359
+ }
360
+ }
361
+ },
362
+ // Required for interface compatibility
363
+ dup: () => createJsonRpcClient(baseUrl, options),
364
+ onRpcBroken: (_callback) => {
365
+ },
366
+ [Symbol.dispose]: () => {
367
+ }
368
+ };
369
+ }
370
+ function getEndpointForType(type) {
371
+ const typeMap = {
372
+ Noun: "/nouns",
373
+ Verb: "/verbs",
374
+ Action: "/actions",
375
+ Function: "/functions",
376
+ Event: "/events",
377
+ Relationship: "/relationships",
378
+ Thing: "/things",
379
+ Workflow: "/workflows"
380
+ };
381
+ return typeMap[type] || `/${type}`;
382
+ }
383
+ function $JsonRpcContext(url, options) {
384
+ return createJsonRpcClient(url, options);
385
+ }
386
+
387
+ // src/lib/mock-data.ts
388
+ var idCounter = 0;
389
+ function generateId(prefix = "mock") {
390
+ return `${prefix}_${Date.now().toString(36)}_${(++idCounter).toString(36)}`;
391
+ }
392
+ var mockProperties = {
393
+ User: [
394
+ { name: "email", label: "Email", description: "Email address", rangeIncludes: ["string"], domainIncludes: ["User"], required: true, isArray: false },
395
+ { name: "role", label: "Role", description: "User role", rangeIncludes: ["string"], domainIncludes: ["User"], required: false, isArray: false },
396
+ { name: "avatar", label: "Avatar", description: "Profile picture URL", rangeIncludes: ["string"], domainIncludes: ["User"], required: false, isArray: false },
397
+ { name: "status", label: "Status", description: "Account status", rangeIncludes: ["string"], domainIncludes: ["User"], required: false, isArray: false }
398
+ ],
399
+ Project: [
400
+ { name: "description", label: "Description", description: "Project description", rangeIncludes: ["string"], domainIncludes: ["Project"], required: false, isArray: false },
401
+ { name: "status", label: "Status", description: "Project status", rangeIncludes: ["string"], domainIncludes: ["Project"], required: true, isArray: false },
402
+ { name: "owner", label: "Owner", description: "Project owner", rangeIncludes: ["User"], domainIncludes: ["Project"], required: true, isArray: false },
403
+ { name: "tags", label: "Tags", description: "Project tags", rangeIncludes: ["string"], domainIncludes: ["Project"], required: false, isArray: true }
404
+ ],
405
+ Task: [
406
+ { name: "description", label: "Description", description: "Task description", rangeIncludes: ["string"], domainIncludes: ["Task"], required: false, isArray: false },
407
+ { name: "status", label: "Status", description: "Task status", rangeIncludes: ["string"], domainIncludes: ["Task"], required: true, isArray: false },
408
+ { name: "priority", label: "Priority", description: "Task priority", rangeIncludes: ["string"], domainIncludes: ["Task"], required: false, isArray: false },
409
+ { name: "assignee", label: "Assignee", description: "Assigned user", rangeIncludes: ["User"], domainIncludes: ["Task"], required: false, isArray: false },
410
+ { name: "project", label: "Project", description: "Parent project", rangeIncludes: ["Project"], domainIncludes: ["Task"], required: false, isArray: false },
411
+ { name: "dueDate", label: "Due Date", description: "Task due date", rangeIncludes: ["date"], domainIncludes: ["Task"], required: false, isArray: false }
412
+ ],
413
+ Document: [
414
+ { name: "content", label: "Content", description: "Document content", rangeIncludes: ["string"], domainIncludes: ["Document"], required: true, isArray: false },
415
+ { name: "format", label: "Format", description: "Content format", rangeIncludes: ["string"], domainIncludes: ["Document"], required: false, isArray: false },
416
+ { name: "author", label: "Author", description: "Document author", rangeIncludes: ["User"], domainIncludes: ["Document"], required: false, isArray: false },
417
+ { name: "tags", label: "Tags", description: "Document tags", rangeIncludes: ["string"], domainIncludes: ["Document"], required: false, isArray: true }
418
+ ],
419
+ Function: [
420
+ { name: "description", label: "Description", description: "Function description", rangeIncludes: ["string"], domainIncludes: ["Function"], required: false, isArray: false },
421
+ { name: "code", label: "Code", description: "Function code", rangeIncludes: ["string"], domainIncludes: ["Function"], required: true, isArray: false },
422
+ { name: "runtime", label: "Runtime", description: "Execution runtime", rangeIncludes: ["string"], domainIncludes: ["Function"], required: true, isArray: false },
423
+ { name: "triggers", label: "Triggers", description: "Event triggers", rangeIncludes: ["string"], domainIncludes: ["Function"], required: false, isArray: true }
424
+ ],
425
+ Workflow: [
426
+ { name: "description", label: "Description", description: "Workflow description", rangeIncludes: ["string"], domainIncludes: ["Workflow"], required: false, isArray: false },
427
+ { name: "steps", label: "Steps", description: "Workflow steps", rangeIncludes: ["object"], domainIncludes: ["Workflow"], required: true, isArray: true },
428
+ { name: "status", label: "Status", description: "Workflow status", rangeIncludes: ["string"], domainIncludes: ["Workflow"], required: true, isArray: false }
429
+ ],
430
+ Agent: [
431
+ { name: "description", label: "Description", description: "Agent description", rangeIncludes: ["string"], domainIncludes: ["Agent"], required: false, isArray: false },
432
+ { name: "model", label: "Model", description: "AI model", rangeIncludes: ["string"], domainIncludes: ["Agent"], required: true, isArray: false },
433
+ { name: "systemPrompt", label: "System Prompt", description: "Agent system prompt", rangeIncludes: ["string"], domainIncludes: ["Agent"], required: false, isArray: false },
434
+ { name: "tools", label: "Tools", description: "Available tools", rangeIncludes: ["string"], domainIncludes: ["Agent"], required: false, isArray: true }
435
+ ]
436
+ };
437
+ var MOCK_TYPES = Object.keys(mockProperties);
438
+ function generateMockSchema(typeName) {
439
+ const properties = mockProperties[typeName] || [];
440
+ return {
441
+ namespace: "default",
442
+ name: typeName,
443
+ id: `default/${typeName}`,
444
+ label: typeName,
445
+ description: `${typeName} entity type`,
446
+ parentTypes: ["Thing"],
447
+ properties,
448
+ subtypes: []
449
+ };
450
+ }
451
+ var firstNames = ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank", "Grace", "Henry", "Iris", "Jack"];
452
+ var lastNames = ["Smith", "Johnson", "Williams", "Brown", "Jones", "Garcia", "Miller", "Davis", "Rodriguez", "Martinez"];
453
+ var projectNames = ["Apollo", "Mercury", "Gemini", "Voyager", "Pioneer", "Horizon", "Nebula", "Cosmos", "Atlas", "Phoenix"];
454
+ var taskPrefixes = ["Implement", "Fix", "Update", "Review", "Design", "Test", "Deploy", "Document", "Refactor", "Optimize"];
455
+ var statuses = ["active", "pending", "completed", "archived"];
456
+ var priorities = ["low", "medium", "high", "critical"];
457
+ var roles = ["admin", "editor", "viewer", "developer"];
458
+ function randomItem(arr) {
459
+ return arr[Math.floor(Math.random() * arr.length)];
460
+ }
461
+ function randomDate(daysBack = 30) {
462
+ const date = /* @__PURE__ */ new Date();
463
+ date.setDate(date.getDate() - Math.floor(Math.random() * daysBack));
464
+ return date;
465
+ }
466
+ function generateMockUser(id) {
467
+ const firstName = randomItem(firstNames);
468
+ const lastName = randomItem(lastNames);
469
+ const name = `${firstName} ${lastName}`;
470
+ const now = /* @__PURE__ */ new Date();
471
+ const created = randomDate(60);
472
+ return {
473
+ ns: "default",
474
+ type: "User",
475
+ id: id || generateId("user"),
476
+ ts: now,
477
+ name,
478
+ createdAt: created,
479
+ updatedAt: now,
480
+ createdBy: "system",
481
+ data: {
482
+ "@type": "User",
483
+ email: `${firstName.toLowerCase()}.${lastName.toLowerCase()}@example.com`,
484
+ role: randomItem(roles),
485
+ avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${firstName}`,
486
+ status: randomItem(["active", "inactive"])
487
+ }
488
+ };
489
+ }
490
+ function generateMockProject(id) {
491
+ const name = `Project ${randomItem(projectNames)}`;
492
+ const now = /* @__PURE__ */ new Date();
493
+ const created = randomDate(90);
494
+ return {
495
+ ns: "default",
496
+ type: "Project",
497
+ id: id || generateId("proj"),
498
+ ts: now,
499
+ name,
500
+ createdAt: created,
501
+ updatedAt: now,
502
+ createdBy: "system",
503
+ data: {
504
+ "@type": "Project",
505
+ description: `A ${randomItem(["web", "mobile", "API", "data", "ML"])} project focused on ${randomItem(["performance", "scalability", "user experience", "automation", "analytics"])}`,
506
+ status: randomItem(statuses),
507
+ owner: `user_${Math.floor(Math.random() * 10)}`,
508
+ tags: [randomItem(["frontend", "backend", "fullstack"]), randomItem(["react", "node", "python", "go"])]
509
+ }
510
+ };
511
+ }
512
+ function generateMockTask(id) {
513
+ const action = randomItem(taskPrefixes);
514
+ const target = randomItem(["authentication", "dashboard", "API endpoint", "database schema", "user flow", "notification system", "search feature", "export functionality"]);
515
+ const name = `${action} ${target}`;
516
+ const now = /* @__PURE__ */ new Date();
517
+ const created = randomDate(14);
518
+ return {
519
+ ns: "default",
520
+ type: "Task",
521
+ id: id || generateId("task"),
522
+ ts: now,
523
+ name,
524
+ createdAt: created,
525
+ updatedAt: now,
526
+ createdBy: "system",
527
+ data: {
528
+ "@type": "Task",
529
+ description: `${action} the ${target} to improve ${randomItem(["performance", "reliability", "usability", "security"])}`,
530
+ status: randomItem(["todo", "in_progress", "review", "done"]),
531
+ priority: randomItem(priorities),
532
+ assignee: `user_${Math.floor(Math.random() * 10)}`,
533
+ dueDate: new Date(Date.now() + Math.random() * 14 * 24 * 60 * 60 * 1e3).toISOString()
534
+ }
535
+ };
536
+ }
537
+ function generateMockDocument(id) {
538
+ const docTypes = ["README", "API Documentation", "Architecture Guide", "User Manual", "Release Notes", "Meeting Notes", "Technical Spec", "Design Document"];
539
+ const name = randomItem(docTypes);
540
+ const now = /* @__PURE__ */ new Date();
541
+ const created = randomDate(30);
542
+ return {
543
+ ns: "default",
544
+ type: "Document",
545
+ id: id || generateId("doc"),
546
+ ts: now,
547
+ name,
548
+ createdAt: created,
549
+ updatedAt: now,
550
+ createdBy: "system",
551
+ data: {
552
+ "@type": "Document",
553
+ content: `# ${name}
554
+
555
+ This is a sample document with mock content.
556
+
557
+ ## Overview
558
+
559
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit.`,
560
+ format: "markdown",
561
+ author: `user_${Math.floor(Math.random() * 10)}`,
562
+ tags: [randomItem(["documentation", "guide", "reference"]), randomItem(["v1", "v2", "draft"])]
563
+ }
564
+ };
565
+ }
566
+ function generateMockFunction(id) {
567
+ const funcNames = ["processOrder", "sendNotification", "validateInput", "transformData", "generateReport", "syncData", "handleWebhook", "calculateMetrics"];
568
+ const name = randomItem(funcNames);
569
+ const now = /* @__PURE__ */ new Date();
570
+ const created = randomDate(45);
571
+ return {
572
+ ns: "default",
573
+ type: "Function",
574
+ id: id || generateId("fn"),
575
+ ts: now,
576
+ name,
577
+ createdAt: created,
578
+ updatedAt: now,
579
+ createdBy: "system",
580
+ data: {
581
+ "@type": "Function",
582
+ description: `Handles ${name.replace(/([A-Z])/g, " $1").toLowerCase().trim()} operations`,
583
+ code: `export default async function ${name}(ctx, args) {
584
+ // Implementation
585
+ return { success: true }
586
+ }`,
587
+ runtime: randomItem(["typescript", "javascript", "python"]),
588
+ triggers: [randomItem(["http", "schedule", "event", "queue"])]
589
+ }
590
+ };
591
+ }
592
+ function generateMockWorkflow(id) {
593
+ const workflowNames = ["Order Processing", "User Onboarding", "Content Approval", "Data Pipeline", "Release Deploy", "Support Ticket"];
594
+ const name = randomItem(workflowNames);
595
+ const now = /* @__PURE__ */ new Date();
596
+ const created = randomDate(60);
597
+ return {
598
+ ns: "default",
599
+ type: "Workflow",
600
+ id: id || generateId("wf"),
601
+ ts: now,
602
+ name,
603
+ createdAt: created,
604
+ updatedAt: now,
605
+ createdBy: "system",
606
+ data: {
607
+ "@type": "Workflow",
608
+ description: `Automated workflow for ${name.toLowerCase()}`,
609
+ steps: [
610
+ { id: "step1", name: "Initialize", type: "function" },
611
+ { id: "step2", name: "Process", type: "function" },
612
+ { id: "step3", name: "Notify", type: "notification" }
613
+ ],
614
+ status: randomItem(["active", "paused", "draft"])
615
+ }
616
+ };
617
+ }
618
+ function generateMockAgent(id) {
619
+ const agentNames = ["Code Assistant", "Data Analyst", "Support Bot", "Content Writer", "Research Agent", "QA Tester"];
620
+ const name = randomItem(agentNames);
621
+ const now = /* @__PURE__ */ new Date();
622
+ const created = randomDate(30);
623
+ return {
624
+ ns: "default",
625
+ type: "Agent",
626
+ id: id || generateId("agent"),
627
+ ts: now,
628
+ name,
629
+ createdAt: created,
630
+ updatedAt: now,
631
+ createdBy: "system",
632
+ data: {
633
+ "@type": "Agent",
634
+ description: `AI agent specialized in ${name.toLowerCase()} tasks`,
635
+ model: randomItem(["claude-3-opus", "claude-3-sonnet", "gpt-4", "gpt-4-turbo"]),
636
+ systemPrompt: `You are a helpful ${name.toLowerCase()} assistant.`,
637
+ tools: [randomItem(["search", "code", "browse", "analyze"])]
638
+ }
639
+ };
640
+ }
641
+ var generators = {
642
+ User: generateMockUser,
643
+ Project: generateMockProject,
644
+ Task: generateMockTask,
645
+ Document: generateMockDocument,
646
+ Function: generateMockFunction,
647
+ Workflow: generateMockWorkflow,
648
+ Agent: generateMockAgent
649
+ };
650
+ function generateMockThing(type, id) {
651
+ const generator = generators[type];
652
+ if (generator) {
653
+ return generator(id);
654
+ }
655
+ const now = /* @__PURE__ */ new Date();
656
+ return {
657
+ ns: "default",
658
+ type,
659
+ id: id || generateId(type.toLowerCase()),
660
+ ts: now,
661
+ name: `${type} ${Math.floor(Math.random() * 1e3)}`,
662
+ createdAt: randomDate(30),
663
+ updatedAt: now,
664
+ createdBy: "system",
665
+ data: {
666
+ "@type": type
667
+ }
668
+ };
669
+ }
670
+ function generateMockThings(type, count) {
671
+ return Array.from({ length: count }, () => generateMockThing(type));
672
+ }
673
+ function generateInitialMockData() {
674
+ return [
675
+ ...generateMockThings("User", 8),
676
+ ...generateMockThings("Project", 5),
677
+ ...generateMockThings("Task", 15),
678
+ ...generateMockThings("Document", 6),
679
+ ...generateMockThings("Function", 4),
680
+ ...generateMockThings("Workflow", 3),
681
+ ...generateMockThings("Agent", 3)
682
+ ];
683
+ }
684
+
685
+ // src/lib/mock-client.ts
686
+ function thingKey(ns, type, id) {
687
+ return `${ns}:${type}:${id}`;
688
+ }
689
+ async function delay(ms) {
690
+ if (ms > 0) {
691
+ await new Promise((resolve) => setTimeout(resolve, ms));
692
+ }
693
+ }
694
+ function createMockClient(options = {}) {
695
+ const { delay: delayMs = 100, verbose = false, initialData } = options;
696
+ const store = {
697
+ things: /* @__PURE__ */ new Map(),
698
+ deletedThings: /* @__PURE__ */ new Set()
699
+ };
700
+ const data = initialData ?? generateInitialMockData();
701
+ for (const thing of data) {
702
+ const key = thingKey(thing.ns, thing.type, thing.id);
703
+ store.things.set(key, thing);
704
+ }
705
+ if (verbose) {
706
+ console.log(`[MockClient] Initialized with ${store.things.size} things`);
707
+ }
708
+ function log(operation, ...args) {
709
+ if (verbose) {
710
+ console.log(`[MockClient] ${operation}`, ...args);
711
+ }
712
+ }
713
+ return {
714
+ /**
715
+ * Namespace operations
716
+ */
717
+ Namespace: {
718
+ async list(_params) {
719
+ await delay(delayMs);
720
+ log("Namespace.list");
721
+ const namespaces = /* @__PURE__ */ new Set();
722
+ for (const thing of store.things.values()) {
723
+ namespaces.add(thing.ns);
724
+ }
725
+ namespaces.add("default");
726
+ return Array.from(namespaces).map((ns) => ({
727
+ id: ns,
728
+ name: ns
729
+ }));
730
+ }
731
+ },
732
+ /**
733
+ * Schema operations
734
+ */
735
+ Schema: {
736
+ async discover(_params) {
737
+ await delay(delayMs);
738
+ log("Schema.discover");
739
+ const types = /* @__PURE__ */ new Set();
740
+ for (const thing of store.things.values()) {
741
+ types.add(thing.type);
742
+ }
743
+ for (const type of MOCK_TYPES) {
744
+ types.add(type);
745
+ }
746
+ const typeList = Array.from(types).sort();
747
+ return {
748
+ namespaces: ["default"],
749
+ types: typeList,
750
+ schemas: typeList
751
+ };
752
+ },
753
+ async get(params) {
754
+ await delay(delayMs);
755
+ log("Schema.get", params.type);
756
+ return generateMockSchema(params.type);
757
+ }
758
+ },
759
+ /**
760
+ * Thing operations
761
+ */
762
+ Thing: {
763
+ async types(params) {
764
+ await delay(delayMs);
765
+ log("Thing.types");
766
+ const types = /* @__PURE__ */ new Set();
767
+ for (const thing of store.things.values()) {
768
+ if (!params.ns || thing.ns === params.ns) {
769
+ types.add(thing.type);
770
+ }
771
+ }
772
+ for (const type of MOCK_TYPES) {
773
+ types.add(type);
774
+ }
775
+ return Array.from(types).sort().map((name) => ({
776
+ name,
777
+ ns: params.ns || "default"
778
+ }));
779
+ },
780
+ async list(params) {
781
+ await delay(delayMs);
782
+ log("Thing.list", params);
783
+ let things = Array.from(store.things.values());
784
+ if (params.ns) {
785
+ things = things.filter((t) => t.ns === params.ns);
786
+ }
787
+ if (params.type) {
788
+ things = things.filter((t) => t.type === params.type);
789
+ }
790
+ things = things.filter((t) => {
791
+ const key = thingKey(t.ns, t.type, t.id);
792
+ return !store.deletedThings.has(key);
793
+ });
794
+ things.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
795
+ const total = things.length;
796
+ const offset = params.offset || 0;
797
+ const limit = params.limit || 50;
798
+ things = things.slice(offset, offset + limit);
799
+ return { data: things, total };
800
+ },
801
+ async get(params) {
802
+ await delay(delayMs);
803
+ log("Thing.get", params);
804
+ const key = thingKey(params.ns || "default", params.type, params.id);
805
+ if (store.deletedThings.has(key)) {
806
+ return null;
807
+ }
808
+ return store.things.get(key) || null;
809
+ },
810
+ async create(params) {
811
+ await delay(delayMs);
812
+ log("Thing.create", params);
813
+ const ns = params.ns || "default";
814
+ const now = /* @__PURE__ */ new Date();
815
+ const baseThing = generateMockThing(params.type);
816
+ const thing = {
817
+ ...baseThing,
818
+ ns,
819
+ id: baseThing.id,
820
+ name: params.name || baseThing.name,
821
+ createdAt: now,
822
+ updatedAt: now,
823
+ ts: now,
824
+ data: {
825
+ "@type": params.type,
826
+ ...params.data
827
+ }
828
+ };
829
+ const key = thingKey(ns, params.type, thing.id);
830
+ store.things.set(key, thing);
831
+ return thing;
832
+ },
833
+ async update(params) {
834
+ await delay(delayMs);
835
+ log("Thing.update", params);
836
+ const ns = params.ns || "default";
837
+ const key = thingKey(ns, params.type, params.id);
838
+ const existing = store.things.get(key);
839
+ if (!existing || store.deletedThings.has(key)) {
840
+ throw new Error(`Thing not found: ${key}`);
841
+ }
842
+ const now = /* @__PURE__ */ new Date();
843
+ const updated = {
844
+ ...existing,
845
+ updatedAt: now,
846
+ ts: now,
847
+ data: {
848
+ ...existing.data,
849
+ ...params.data
850
+ }
851
+ };
852
+ store.things.set(key, updated);
853
+ return updated;
854
+ },
855
+ async delete(params) {
856
+ await delay(delayMs);
857
+ log("Thing.delete", params);
858
+ const ns = params.ns || "default";
859
+ const key = thingKey(ns, params.type, params.id);
860
+ if (params.hard) {
861
+ store.things.delete(key);
862
+ } else {
863
+ store.deletedThings.add(key);
864
+ }
865
+ return { success: true };
866
+ },
867
+ async versions(_params) {
868
+ await delay(delayMs);
869
+ log("Thing.versions", _params);
870
+ return [];
871
+ },
872
+ async stats(_params) {
873
+ await delay(delayMs);
874
+ log("Thing.stats", _params);
875
+ const byType = {};
876
+ let total = 0;
877
+ for (const thing of store.things.values()) {
878
+ const key = thingKey(thing.ns, thing.type, thing.id);
879
+ if (store.deletedThings.has(key)) continue;
880
+ if (_params.ns && thing.ns !== _params.ns) continue;
881
+ if (_params.type && thing.type !== _params.type) continue;
882
+ byType[thing.type] = (byType[thing.type] || 0) + 1;
883
+ total++;
884
+ }
885
+ return { total, byType };
886
+ }
887
+ },
888
+ /**
889
+ * SQL operations (mock implementation)
890
+ */
891
+ SQL: {
892
+ async execute(params) {
893
+ await delay(delayMs);
894
+ log("SQL.execute", params.query);
895
+ const query = params.query.toLowerCase().trim();
896
+ if (query.startsWith("select")) {
897
+ const match = query.match(/select\s+\*\s+from\s+(\w+)/i);
898
+ if (match) {
899
+ const type = match[1];
900
+ const things = Array.from(store.things.values()).filter(
901
+ (t) => t.type.toLowerCase() === type.toLowerCase()
902
+ );
903
+ const rows = things.map((t) => ({
904
+ id: t.id,
905
+ ns: t.ns,
906
+ type: t.type,
907
+ name: t.name,
908
+ createdAt: t.createdAt,
909
+ updatedAt: t.updatedAt,
910
+ data: JSON.stringify(t.data)
911
+ }));
912
+ return {
913
+ rows,
914
+ columns: [
915
+ { name: "id", type: "string" },
916
+ { name: "ns", type: "string" },
917
+ { name: "type", type: "string" },
918
+ { name: "name", type: "string" },
919
+ { name: "createdAt", type: "datetime" },
920
+ { name: "updatedAt", type: "datetime" },
921
+ { name: "data", type: "json" }
922
+ ],
923
+ rowsAffected: rows.length,
924
+ executionTimeMs: delayMs
925
+ };
926
+ }
927
+ }
928
+ return {
929
+ rows: [],
930
+ columns: [],
931
+ rowsAffected: 0,
932
+ executionTimeMs: delayMs
933
+ };
934
+ }
935
+ },
936
+ // Required for interface compatibility
937
+ dup: () => createMockClient(options),
938
+ onRpcBroken: (_callback) => {
939
+ },
940
+ [Symbol.dispose]: () => {
941
+ },
942
+ // Mock-specific methods for testing
943
+ _store: store,
944
+ _reset: () => {
945
+ store.things.clear();
946
+ store.deletedThings.clear();
947
+ const freshData = initialData ?? generateInitialMockData();
948
+ for (const thing of freshData) {
949
+ const key = thingKey(thing.ns, thing.type, thing.id);
950
+ store.things.set(key, thing);
951
+ }
952
+ }
953
+ };
954
+ }
955
+ function $MockContext(options) {
956
+ return createMockClient(options);
957
+ }
958
+
959
+ // src/lib/url-utils.ts
960
+ function deriveRpcUrl(url) {
961
+ let rpcUrl = url.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
962
+ rpcUrl = rpcUrl.replace(/\/(sync|rpc)$/, "");
963
+ rpcUrl = rpcUrl.replace(/\/$/, "");
964
+ return `${rpcUrl}/rpc`;
965
+ }
966
+
967
+ // src/lib/fetch-with-timeout.ts
968
+ var DEFAULT_REQUEST_TIMEOUT = 3e4;
969
+ async function fetchWithTimeout(url, options = {}) {
970
+ const { timeout = DEFAULT_REQUEST_TIMEOUT, signal: existingSignal, ...fetchOptions } = options;
971
+ const controller = new AbortController();
972
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
973
+ const existingAbortHandler = existingSignal ? () => controller.abort(existingSignal.reason) : null;
974
+ if (existingSignal) {
975
+ if (existingSignal.aborted) {
976
+ clearTimeout(timeoutId);
977
+ controller.abort(existingSignal.reason);
978
+ } else {
979
+ existingSignal.addEventListener("abort", existingAbortHandler);
980
+ }
981
+ }
982
+ try {
983
+ const response = await fetch(url, {
984
+ ...fetchOptions,
985
+ signal: controller.signal
986
+ });
987
+ return response;
988
+ } finally {
989
+ clearTimeout(timeoutId);
990
+ if (existingSignal && existingAbortHandler) {
991
+ existingSignal.removeEventListener("abort", existingAbortHandler);
992
+ }
993
+ }
994
+ }
995
+ function createFetchWithTimeout(defaultTimeout) {
996
+ return (url, options = {}) => fetchWithTimeout(url, { timeout: defaultTimeout, ...options });
997
+ }
998
+ function useHealthCheck(config) {
999
+ const [isConnected, setIsConnected] = useState(false);
1000
+ const [connectionError, setConnectionError] = useState();
1001
+ const [isChecking, setIsChecking] = useState(true);
1002
+ const { apiEndpoint, authToken, requestTimeout, healthCheckRetries = 3 } = config;
1003
+ const abortControllerRef = useRef(null);
1004
+ const performHealthCheck = useCallback(async () => {
1005
+ const response = await fetchWithTimeout(apiEndpoint, {
1006
+ method: "GET",
1007
+ headers: {
1008
+ "Content-Type": "application/json",
1009
+ ...authToken ? { Authorization: `Bearer ${authToken}` } : {}
1010
+ },
1011
+ timeout: requestTimeout ?? DEFAULT_REQUEST_TIMEOUT
1012
+ });
1013
+ if (!response.ok) {
1014
+ throw new Error(`Health check failed: ${response.status}`);
1015
+ }
1016
+ }, [apiEndpoint, authToken, requestTimeout]);
1017
+ const checkConnection = useCallback(async () => {
1018
+ setIsChecking(true);
1019
+ try {
1020
+ await retryWithBackoff(performHealthCheck, {
1021
+ maxRetries: healthCheckRetries,
1022
+ backoffMultiplier: 1e3
1023
+ });
1024
+ setIsConnected(true);
1025
+ setConnectionError(void 0);
1026
+ } catch (error) {
1027
+ setIsConnected(false);
1028
+ setConnectionError(error instanceof Error ? error : new Error("Connection failed"));
1029
+ } finally {
1030
+ setIsChecking(false);
1031
+ }
1032
+ }, [performHealthCheck, healthCheckRetries]);
1033
+ useEffect(() => {
1034
+ abortControllerRef.current = new AbortController();
1035
+ const { signal } = abortControllerRef.current;
1036
+ async function runCheck() {
1037
+ try {
1038
+ await retryWithBackoff(performHealthCheck, {
1039
+ maxRetries: healthCheckRetries,
1040
+ backoffMultiplier: 1e3,
1041
+ signal
1042
+ });
1043
+ if (!signal.aborted) {
1044
+ setIsConnected(true);
1045
+ setConnectionError(void 0);
1046
+ setIsChecking(false);
1047
+ }
1048
+ } catch (error) {
1049
+ if (!signal.aborted) {
1050
+ setIsConnected(false);
1051
+ setConnectionError(error instanceof Error ? error : new Error("Connection failed"));
1052
+ setIsChecking(false);
1053
+ }
1054
+ }
1055
+ }
1056
+ runCheck();
1057
+ return () => {
1058
+ abortControllerRef.current?.abort();
1059
+ };
1060
+ }, [performHealthCheck, healthCheckRetries]);
1061
+ return {
1062
+ isConnected,
1063
+ connectionError,
1064
+ checkConnection,
1065
+ isChecking
1066
+ };
1067
+ }
1068
+
1069
+ export { $CapnwebContext, $JsonRpcContext, $MockContext, DEFAULT_REQUEST_TIMEOUT, MOCK_TYPES, createCapnwebClient, createFetchWithTimeout, createJsonRpcClient, createMockClient, deriveRpcUrl, fetchWithTimeout, generateInitialMockData, generateMockSchema, generateMockThing, generateMockThings, useHealthCheck };
1070
+ //# sourceMappingURL=chunk-OVLO7UOH.js.map
1071
+ //# sourceMappingURL=chunk-OVLO7UOH.js.map