@niscorp/loom 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/DESIGN.md +253 -0
  2. package/LICENSE +202 -0
  3. package/README.md +101 -0
  4. package/dist/chunk-A3UOFGL4.js +29 -0
  5. package/dist/chunk-A3UOFGL4.js.map +1 -0
  6. package/dist/chunk-D743DI5J.js +17 -0
  7. package/dist/chunk-D743DI5J.js.map +1 -0
  8. package/dist/chunk-DWQWPBBV.js +63 -0
  9. package/dist/chunk-DWQWPBBV.js.map +1 -0
  10. package/dist/chunk-LWY5TG7M.js +208 -0
  11. package/dist/chunk-LWY5TG7M.js.map +1 -0
  12. package/dist/chunk-MIRMQPUE.js +132 -0
  13. package/dist/chunk-MIRMQPUE.js.map +1 -0
  14. package/dist/chunk-PTXRAWJX.js +58 -0
  15. package/dist/chunk-PTXRAWJX.js.map +1 -0
  16. package/dist/chunk-TV4U22MY.js +176 -0
  17. package/dist/chunk-TV4U22MY.js.map +1 -0
  18. package/dist/chunk-X7PCPONB.js +380 -0
  19. package/dist/chunk-X7PCPONB.js.map +1 -0
  20. package/dist/chunk-XTY7XO5C.js +61 -0
  21. package/dist/chunk-XTY7XO5C.js.map +1 -0
  22. package/dist/index.cjs +630 -0
  23. package/dist/index.cjs.map +1 -0
  24. package/dist/index.d.cts +40 -0
  25. package/dist/index.d.ts +40 -0
  26. package/dist/index.js +6 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/loom-editor-CQ_GI4IA.d.cts +27 -0
  29. package/dist/loom-editor-D5SBQ4_F.d.ts +27 -0
  30. package/dist/plugins/nova/index.cjs +81 -0
  31. package/dist/plugins/nova/index.cjs.map +1 -0
  32. package/dist/plugins/nova/index.d.cts +14 -0
  33. package/dist/plugins/nova/index.d.ts +14 -0
  34. package/dist/plugins/nova/index.js +5 -0
  35. package/dist/plugins/nova/index.js.map +1 -0
  36. package/dist/plugins/nova/react/index.cjs +107 -0
  37. package/dist/plugins/nova/react/index.cjs.map +1 -0
  38. package/dist/plugins/nova/react/index.d.cts +17 -0
  39. package/dist/plugins/nova/react/index.d.ts +17 -0
  40. package/dist/plugins/nova/react/index.js +36 -0
  41. package/dist/plugins/nova/react/index.js.map +1 -0
  42. package/dist/plugins/prism/index.cjs +48 -0
  43. package/dist/plugins/prism/index.cjs.map +1 -0
  44. package/dist/plugins/prism/index.d.cts +18 -0
  45. package/dist/plugins/prism/index.d.ts +18 -0
  46. package/dist/plugins/prism/index.js +4 -0
  47. package/dist/plugins/prism/index.js.map +1 -0
  48. package/dist/plugins/prism/react/index.cjs +744 -0
  49. package/dist/plugins/prism/react/index.cjs.map +1 -0
  50. package/dist/plugins/prism/react/index.d.cts +12 -0
  51. package/dist/plugins/prism/react/index.d.ts +12 -0
  52. package/dist/plugins/prism/react/index.js +419 -0
  53. package/dist/plugins/prism/react/index.js.map +1 -0
  54. package/dist/plugins/vex/index.cjs +67 -0
  55. package/dist/plugins/vex/index.cjs.map +1 -0
  56. package/dist/plugins/vex/index.d.cts +25 -0
  57. package/dist/plugins/vex/index.d.ts +25 -0
  58. package/dist/plugins/vex/index.js +4 -0
  59. package/dist/plugins/vex/index.js.map +1 -0
  60. package/dist/plugins/vex/react/index.cjs +432 -0
  61. package/dist/plugins/vex/react/index.cjs.map +1 -0
  62. package/dist/plugins/vex/react/index.d.cts +13 -0
  63. package/dist/plugins/vex/react/index.d.ts +13 -0
  64. package/dist/plugins/vex/react/index.js +296 -0
  65. package/dist/plugins/vex/react/index.js.map +1 -0
  66. package/dist/react/index.cjs +1076 -0
  67. package/dist/react/index.cjs.map +1 -0
  68. package/dist/react/index.d.cts +82 -0
  69. package/dist/react/index.d.ts +82 -0
  70. package/dist/react/index.js +120 -0
  71. package/dist/react/index.js.map +1 -0
  72. package/dist/schema--OhtatTX.d.cts +10 -0
  73. package/dist/schema--OhtatTX.d.ts +10 -0
  74. package/dist/types-BonjN3CB.d.cts +144 -0
  75. package/dist/types-BonjN3CB.d.ts +144 -0
  76. package/package.json +144 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,630 @@
1
+ 'use strict';
2
+
3
+ var zod = require('zod');
4
+ var nova = require('@niscorp/nova');
5
+
6
+ // src/compile/parse.ts
7
+ var defOf = (schema) => schema.def;
8
+ var INTEGER_FORMAT = "safeint";
9
+ var stringFormat = (schema) => {
10
+ const def = defOf(schema);
11
+ if (def.format !== void 0) return def.format;
12
+ for (const check of def.checks ?? []) {
13
+ if (check.def?.format !== void 0) return check.def.format;
14
+ }
15
+ return void 0;
16
+ };
17
+ var isInteger = (schema) => {
18
+ const def = defOf(schema);
19
+ if (def.format === INTEGER_FORMAT) return true;
20
+ return (def.checks ?? []).some((check) => check.def?.format === INTEGER_FORMAT);
21
+ };
22
+ var enumOptions = (schema) => Object.values(defOf(schema).entries ?? {}).map((value) => ({ value, label: String(value) }));
23
+ var objectFields = (schema, walk) => Object.entries(defOf(schema).shape ?? {}).map(([key, value]) => ({
24
+ key,
25
+ // A property is optional when the schema accepts `undefined` for it
26
+ // (covers `.optional()` and `.default()`) — asked of Zod, not inferred.
27
+ required: !value.safeParse(void 0).success,
28
+ field: parseField(value, walk)
29
+ }));
30
+ var branchKeys = (branch) => Object.keys(defOf(branch).shape ?? {});
31
+ var JSON_TYPES = /* @__PURE__ */ new Set(["string", "number", "boolean", "object", "array", "null"]);
32
+ var jsonType = (branch) => {
33
+ const type = defOf(branch).type;
34
+ return JSON_TYPES.has(type) ? type : void 0;
35
+ };
36
+ var distinguish = (branch, siblings, tag) => {
37
+ if (tag !== void 0) {
38
+ const literal2 = (defOf(branch).shape ?? {})[tag];
39
+ return { kind: "tag", key: tag, value: literal2 !== void 0 ? defOf(literal2).values?.[0] : void 0 };
40
+ }
41
+ const elsewhere = new Set(siblings.flatMap(branchKeys));
42
+ const key = branchKeys(branch).find((k) => !elsewhere.has(k));
43
+ if (key !== void 0) return { kind: "key", key };
44
+ const type = jsonType(branch);
45
+ if (type !== void 0 && siblings.every((s) => jsonType(s) !== type)) return { kind: "type", type };
46
+ return void 0;
47
+ };
48
+ var patternLabel = (pattern) => pattern.kind === "tag" ? String(pattern.value) : pattern.kind === "key" ? pattern.key : pattern.kind === "type" ? pattern.type : "other";
49
+ var flattenBranches = (branches, seen = /* @__PURE__ */ new Set()) => branches.flatMap((branch) => {
50
+ const { core } = unwrap(branch);
51
+ const def = defOf(core);
52
+ if (def.type !== "union" || seen.has(def)) return [branch];
53
+ return flattenBranches(def.options ?? [], new Set(seen).add(def));
54
+ });
55
+ var branchField = (branch, walk, tag) => tag === void 0 ? parseField(branch, walk) : { kind: "object", fields: objectFields(branch, walk).filter((f) => f.key !== tag) };
56
+ var parseByType = {
57
+ string: (schema) => {
58
+ const format = stringFormat(schema);
59
+ return format !== void 0 ? { kind: "string", format } : { kind: "string" };
60
+ },
61
+ number: (schema) => isInteger(schema) ? { kind: "number", integer: true } : { kind: "number" },
62
+ boolean: () => ({ kind: "boolean" }),
63
+ enum: (schema) => ({ kind: "enum", options: enumOptions(schema) }),
64
+ object: (schema, walk) => {
65
+ const def = defOf(schema);
66
+ walk.stack.add(def);
67
+ const fields = objectFields(schema, walk);
68
+ walk.stack.delete(def);
69
+ return walk.targets.has(def) ? { kind: "object", fields, recursive: true } : { kind: "object", fields };
70
+ },
71
+ array: (schema, walk) => {
72
+ const element = defOf(schema).element;
73
+ return { kind: "array", item: element !== void 0 ? parseField(element, walk) : { kind: "unknown" } };
74
+ },
75
+ tuple: (schema, walk) => ({ kind: "tuple", items: (defOf(schema).items ?? []).map((item) => parseField(item, walk)) }),
76
+ union: (schema, walk) => {
77
+ const branches = [...new Set(flattenBranches(defOf(schema).options ?? []))];
78
+ const tag = defOf(schema).discriminator;
79
+ const patterns = branches.map((b) => distinguish(b, branches.filter((x) => x !== b), tag));
80
+ const open = patterns.reduce((acc, p, i) => p === void 0 ? [...acc, i] : acc, []);
81
+ if (branches.length === 0 || open.length > 1) return { kind: "unknown" };
82
+ if (open.length === 1) patterns[open[0]] = { kind: "fallback" };
83
+ const def = defOf(schema);
84
+ walk.stack.add(def);
85
+ const variants = branches.map((branch, i) => ({
86
+ label: readMeta(branch).title ?? patternLabel(patterns[i]),
87
+ field: branchField(branch, walk, tag),
88
+ pattern: patterns[i]
89
+ }));
90
+ walk.stack.delete(def);
91
+ return walk.targets.has(def) ? { kind: "union", variants, recursive: true } : { kind: "union", variants };
92
+ }
93
+ };
94
+ var unknownField = () => ({ kind: "unknown" });
95
+ var WRAPPERS = /* @__PURE__ */ new Set(["optional", "nullable", "default", "readonly"]);
96
+ var lazyResolved = /* @__PURE__ */ new WeakMap();
97
+ var resolveLazy = (lazy) => {
98
+ const def = defOf(lazy);
99
+ const cached = lazyResolved.get(def);
100
+ if (cached !== void 0) return cached;
101
+ const resolved = def.getter?.();
102
+ if (resolved !== void 0) lazyResolved.set(def, resolved);
103
+ return resolved;
104
+ };
105
+ var unwrap = (schema) => {
106
+ let core = schema;
107
+ let fallback;
108
+ let def = defOf(core);
109
+ while (WRAPPERS.has(def.type) || def.type === "lazy") {
110
+ const inner = def.type === "lazy" ? resolveLazy(core) : def.innerType;
111
+ if (inner === void 0) break;
112
+ if ("defaultValue" in def) fallback = def.defaultValue;
113
+ core = inner;
114
+ def = defOf(core);
115
+ }
116
+ return fallback !== void 0 ? { core, default: fallback } : { core };
117
+ };
118
+ var readMeta = (schema) => {
119
+ const meta = {};
120
+ const title = schema.meta()?.title;
121
+ if (typeof title === "string") meta.title = title;
122
+ if (schema.description !== void 0) meta.description = schema.description;
123
+ return meta;
124
+ };
125
+ var parseField = (schema, walk) => {
126
+ const { core, default: fallback } = unwrap(schema);
127
+ if (walk.stack.has(defOf(core))) {
128
+ walk.targets.add(defOf(core));
129
+ return { kind: "self" };
130
+ }
131
+ const body = (parseByType[defOf(core).type] ?? unknownField)(core, walk);
132
+ const meta = { ...readMeta(core), ...readMeta(schema) };
133
+ return { ...body, ...meta, ...fallback !== void 0 ? { default: fallback } : {} };
134
+ };
135
+ var parse = (schema) => parseField(schema, { stack: /* @__PURE__ */ new Set(), targets: /* @__PURE__ */ new Set() });
136
+ var EMPTY = {
137
+ string: () => "",
138
+ number: () => 0,
139
+ boolean: () => false,
140
+ // No neutral in-domain value: "no selection" is absence (undefined), which
141
+ // an optional enum accepts and a required one flags — unlike null, which a
142
+ // Zod enum rejects outright. Defaults drop undefined, so no stray key.
143
+ enum: () => void 0,
144
+ array: () => [],
145
+ // Each slot built from its own field; a fixed-length list, so no growth.
146
+ tuple: (field, options) => field.kind === "tuple" ? field.items.map((item) => buildDocument(item, options)) : [],
147
+ // A recursion point has no value of its own; the array holding it defaults to [].
148
+ self: () => void 0,
149
+ unknown: () => null,
150
+ object: (field, options) => {
151
+ if (field.kind !== "object") return {};
152
+ const includeOptional = options.includeOptional ?? true;
153
+ const document = {};
154
+ for (const child2 of field.fields) {
155
+ if (!child2.required && !includeOptional) continue;
156
+ const value = buildDocument(child2.field, options);
157
+ if (value !== void 0) document[child2.key] = value;
158
+ }
159
+ return document;
160
+ },
161
+ // An empty union defaults to its first variant (tag + branch defaults).
162
+ union: (field) => {
163
+ if (field.kind !== "union") return {};
164
+ const first = field.variants[0];
165
+ return first === void 0 ? {} : variantDefaults(first);
166
+ }
167
+ };
168
+ var buildDocument = (field, options) => {
169
+ if (field.default !== void 0) return field.default;
170
+ return (options.empty?.[field.kind] ?? EMPTY[field.kind])(field, options);
171
+ };
172
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
173
+ var variantDefaults = (variant) => {
174
+ const defaults = buildDocument(variant.field, {});
175
+ if (variant.pattern.kind !== "tag") return defaults;
176
+ return { [variant.pattern.key]: variant.pattern.value, ...isRecord(defaults) ? defaults : {} };
177
+ };
178
+
179
+ // src/compile/roles.ts
180
+ var Roles = {
181
+ // Layout primitives — arrange other nodes.
182
+ box: "loom:box",
183
+ // a flexible cell that grows to fill its row (an array item's editor)
184
+ group: "loom:group",
185
+ array: "loom:array",
186
+ arrayItem: "loom:array-item",
187
+ variant: "loom:variant",
188
+ // One branch of a variant — shows itself only when it's the active branch
189
+ // (the widget matches the value to a branch in JS and tells it through context).
190
+ branch: "loom:branch",
191
+ // Field wrapper — label, description, error, and required marker around one control.
192
+ field: "loom:field",
193
+ // Controls — edit a value; emit `ui:model`.
194
+ text: "loom:text",
195
+ number: "loom:number",
196
+ checkbox: "loom:checkbox",
197
+ select: "loom:select",
198
+ raw: "loom:raw",
199
+ // List actions — model writes to the bound array (no triggers). `append` adds
200
+ // a default element to the list it binds. `rowMenu` is the per-row actions menu
201
+ // (move / remove, and wrap / unwrap when the list's items are a recursive union
202
+ // with container variants); it reads `$items` and `$index` and writes the new
203
+ // array. Both work at any depth, since the bound path resolves per render.
204
+ append: "loom:append",
205
+ rowMenu: "loom:row-menu"
206
+ };
207
+
208
+ // src/compile/to-nova.ts
209
+ var ERROR_NAMESPACE = "_errors";
210
+ var ITEM = "item";
211
+ var INDEX = "$index";
212
+ var ITEM_EXPR = `$${ITEM}`;
213
+ var LIST_EXPR = "$items";
214
+ var ROOT = { expr: "$", path: "" };
215
+ var child = (loc, key) => ({
216
+ expr: `${loc.expr}.${key}`,
217
+ path: loc.path === "" ? key : `${loc.path}.${key}`
218
+ });
219
+ var itemLoc = (loc) => ({ expr: ITEM_EXPR, path: loc.path === "" ? "*" : `${loc.path}.*` });
220
+ var TEMPLATE_ROOT = { expr: ITEM_EXPR, path: "" };
221
+ var errorBinding = (expr) => expr.startsWith("$.") ? `$.${ERROR_NAMESPACE}.${expr.slice(2)}` : void 0;
222
+ var withProps = (node, props) => Object.keys(props).length > 0 ? { ...node, props } : node;
223
+ var control = (role, expr, props = {}) => withProps({ component: role, model: expr }, props);
224
+ var literal = (data) => data === void 0 ? void 0 : JSON.stringify(data);
225
+ var wrapField = (loc, prop, ctx) => {
226
+ const error = errorBinding(loc.expr);
227
+ return {
228
+ component: Roles.field,
229
+ props: {
230
+ label: prop.field.title ?? prop.key,
231
+ required: prop.required,
232
+ ...error !== void 0 ? { error } : {},
233
+ ...prop.field.description !== void 0 ? { description: prop.field.description } : {}
234
+ },
235
+ children: buildLayout(prop.field, loc, ctx)
236
+ };
237
+ };
238
+ var titleProps = (field) => field.title !== void 0 ? { title: field.title } : {};
239
+ var withTitle = (node, field) => withProps(node, titleProps(field));
240
+ var stringBuild = (field, loc) => control(Roles.text, loc.expr, field.format !== void 0 ? { format: field.format } : {});
241
+ var numberBuild = (field, loc) => control(Roles.number, loc.expr, field.integer ? { integer: true } : {});
242
+ var booleanBuild = (_field, loc) => control(Roles.checkbox, loc.expr);
243
+ var enumBuild = (field, loc) => control(Roles.select, loc.expr, { options: field.options });
244
+ var unknownBuild = (_field, loc) => control(Roles.raw, loc.expr);
245
+ var buildGroup = (field, loc, ctx) => withTitle(
246
+ {
247
+ component: Roles.group,
248
+ children: field.fields.map((prop) => wrapField(child(loc, prop.key), prop, ctx))
249
+ },
250
+ field
251
+ );
252
+ var objectBuild = (field, loc, ctx) => {
253
+ if (field.recursive !== true) return buildGroup(field, loc, ctx);
254
+ const name = ctx.name();
255
+ ctx.templates.push({ name, defaultChild: buildDocument(field, ctx.options), containers: [] });
256
+ ctx.register(name, buildGroup(field, TEMPLATE_ROOT, ctx));
257
+ const inline = buildGroup(field, loc, ctx);
258
+ ctx.templates.pop();
259
+ return inline;
260
+ };
261
+ var tupleBuild = (field, loc, ctx) => withTitle(
262
+ {
263
+ component: Roles.group,
264
+ children: field.items.map(
265
+ (item, index) => wrapField(child(loc, String(index)), { key: String(index + 1), required: true, field: item }, ctx)
266
+ )
267
+ },
268
+ field
269
+ );
270
+ var selfBuild = (_field, loc, ctx) => {
271
+ const template = ctx.templates[ctx.templates.length - 1];
272
+ if (template !== void 0 && loc.expr === ITEM_EXPR) return { ref: template.name };
273
+ return control(Roles.raw, loc.expr);
274
+ };
275
+ var defaultItem = (field, ctx) => field.item.kind === "self" ? ctx.templates[ctx.templates.length - 1]?.defaultChild : buildDocument(field.item, ctx.options);
276
+ var childrenKey = (field) => {
277
+ if (field.kind !== "object") return void 0;
278
+ return field.fields.find((f) => f.field.kind === "array" && f.field.item.kind === "self")?.key;
279
+ };
280
+ var containersOf = (variants) => variants.flatMap((variant) => {
281
+ const key = childrenKey(variant.field);
282
+ return key === void 0 ? [] : [{ label: variant.label, pattern: variant.pattern, defaults: variantDefaults(variant), key }];
283
+ });
284
+ var arrayBuild = (field, loc, ctx) => {
285
+ const containers = field.item.kind === "self" ? ctx.templates[ctx.templates.length - 1]?.containers ?? [] : [];
286
+ const itemRow = {
287
+ component: Roles.arrayItem,
288
+ children: [
289
+ { component: Roles.box, children: buildLayout(field.item, itemLoc(loc), ctx) },
290
+ // the editor cell — grows
291
+ {
292
+ component: Roles.rowMenu,
293
+ model: LIST_EXPR,
294
+ props: { index: INDEX, ...containers.length > 0 ? { containers: literal(containers) } : {} }
295
+ }
296
+ ]
297
+ };
298
+ return withTitle(
299
+ {
300
+ component: Roles.array,
301
+ children: [
302
+ { for: loc.expr, as: ITEM, do: itemRow },
303
+ { component: Roles.append, model: loc.expr, props: { label: "Add", child: literal(defaultItem(field, ctx)) } }
304
+ ]
305
+ },
306
+ field
307
+ );
308
+ };
309
+ var buildVariant = (field, loc, ctx) => withProps(
310
+ {
311
+ component: Roles.variant,
312
+ model: loc.expr,
313
+ // Each branch editor in its own `branch` wrapper, indexed; the widget shows
314
+ // only the one whose index it matched. (Nova hands a component its children
315
+ // as one tree, so the branches need to be individually addressable.) A
316
+ // branch edits the same value, so it shares the union's loc.
317
+ children: field.variants.map((variant, index) => ({
318
+ component: Roles.branch,
319
+ props: { index },
320
+ children: buildLayout(variant.field, loc, ctx)
321
+ }))
322
+ },
323
+ {
324
+ // `childrenKey` lets the chooser carry children when switching between two
325
+ // container variants (and warn before dropping them otherwise). Encoded as
326
+ // a literal: the patterns and defaults carry `$`-bearing data Nova must not
327
+ // resolve.
328
+ branches: literal(
329
+ field.variants.map((variant) => ({
330
+ label: variant.label,
331
+ pattern: variant.pattern,
332
+ defaults: variantDefaults(variant),
333
+ ...childrenKey(variant.field) !== void 0 ? { childrenKey: childrenKey(variant.field) } : {}
334
+ }))
335
+ ),
336
+ ...titleProps(field)
337
+ }
338
+ );
339
+ var variantBuild = (field, loc, ctx) => {
340
+ if (field.recursive !== true) return buildVariant(field, loc, ctx);
341
+ const name = ctx.name();
342
+ const first = field.variants[0];
343
+ ctx.templates.push({ name, defaultChild: first !== void 0 ? variantDefaults(first) : {}, containers: containersOf(field.variants) });
344
+ ctx.register(name, buildVariant(field, TEMPLATE_ROOT, ctx));
345
+ const inline = buildVariant(field, loc, ctx);
346
+ ctx.templates.pop();
347
+ return inline;
348
+ };
349
+ var buildLayout = (field, loc, ctx) => {
350
+ const role = ctx.widgetRole(field, loc.path);
351
+ if (role !== void 0) return control(role, loc.expr);
352
+ switch (field.kind) {
353
+ case "string":
354
+ return stringBuild(field, loc);
355
+ case "number":
356
+ return numberBuild(field, loc);
357
+ case "boolean":
358
+ return booleanBuild(field, loc);
359
+ case "enum":
360
+ return enumBuild(field, loc);
361
+ case "object":
362
+ return objectBuild(field, loc, ctx);
363
+ case "array":
364
+ return arrayBuild(field, loc, ctx);
365
+ case "tuple":
366
+ return tupleBuild(field, loc, ctx);
367
+ case "union":
368
+ return variantBuild(field, loc, ctx);
369
+ case "self":
370
+ return selfBuild(field, loc, ctx);
371
+ case "unknown":
372
+ return unknownBuild(field, loc);
373
+ }
374
+ };
375
+ var toNova = (ir, options = {}) => {
376
+ const layouts = {};
377
+ let counter = 0;
378
+ const matchers = options.widgets ?? [];
379
+ const ctx = {
380
+ register: (name, node) => {
381
+ layouts[name] = node;
382
+ },
383
+ templates: [],
384
+ name: () => `loom:tree:${counter++}`,
385
+ // Match on where the field sits (its structural path) plus its facts.
386
+ widgetRole: (field, path) => matchers.find(
387
+ (matcher) => matcher.match({ kind: field.kind, path, title: field.title, description: field.description })
388
+ )?.role,
389
+ options
390
+ };
391
+ const rootLoc = options.rootKey !== void 0 ? { expr: `$.${options.rootKey}`, path: "" } : ROOT;
392
+ const layout = buildLayout(ir, rootLoc, ctx);
393
+ const value = options.value ?? buildDocument(ir, options);
394
+ const document = options.rootKey !== void 0 ? { [options.rootKey]: value } : value;
395
+ if (!isRecord(document)) {
396
+ throw new Error("loom.toNova: the root document must be an object (or use rootKey).");
397
+ }
398
+ const action = {
399
+ id: options.id ?? "loom-form",
400
+ data: document,
401
+ layout
402
+ };
403
+ return { action, layouts };
404
+ };
405
+
406
+ // src/validate.ts
407
+ var setPath = (root, path, message) => {
408
+ let node = root;
409
+ for (let i = 0; i < path.length - 1; i += 1) {
410
+ const key = String(path[i]);
411
+ const next = node[key];
412
+ node = typeof next === "object" && next !== null ? next : node[key] = {};
413
+ }
414
+ const leaf = String(path[path.length - 1]);
415
+ if (!(leaf in node)) node[leaf] = message;
416
+ };
417
+ var errorTree = (issues) => {
418
+ const tree = {};
419
+ for (const issue of issues) {
420
+ if (issue.path.length > 0) setPath(tree, issue.path, issue.message);
421
+ }
422
+ return tree;
423
+ };
424
+ var stripErrors = (data) => {
425
+ const { [ERROR_NAMESPACE]: _omit, ...document } = data;
426
+ return document;
427
+ };
428
+ var attachValidation = (shell, instanceId, schema, onDocument) => {
429
+ const runtime = shell.getRuntime(instanceId);
430
+ if (runtime === void 0) return () => {
431
+ };
432
+ let lastDocument = "";
433
+ const handle = (data) => {
434
+ const document = stripErrors(data);
435
+ const fingerprint = JSON.stringify(document);
436
+ if (fingerprint === lastDocument) return;
437
+ lastDocument = fingerprint;
438
+ const result = schema.safeParse(document);
439
+ const errors = result.success ? {} : errorTree(result.error.issues);
440
+ runtime.setData({ ...document, [ERROR_NAMESPACE]: errors });
441
+ onDocument?.(document);
442
+ };
443
+ return shell.onDataChange((change) => {
444
+ if (change.instanceId === instanceId) handle(change.data);
445
+ });
446
+ };
447
+
448
+ // src/editor/default.layout.ts
449
+ var LOOM_COLUMN = "loom:column";
450
+ var slot = (canvasId) => ({ component: "CanvasSlot", props: { canvasId } });
451
+ var titleOf = (formId) => {
452
+ const name = formId.replace(/^form:/, "");
453
+ return name.charAt(0).toUpperCase() + name.slice(1);
454
+ };
455
+ var formPanel = (formId) => ({
456
+ component: "Box",
457
+ props: { border: true, radius: 8, padding: 16 },
458
+ children: [{ component: "loom:group", props: { title: titleOf(formId) }, children: [slot(formId)] }]
459
+ });
460
+ var column = (grow, min, children) => ({
461
+ component: LOOM_COLUMN,
462
+ props: { grow, min },
463
+ children: [{ component: "Stack", props: { direction: "column", gap: 16 }, children }]
464
+ });
465
+ var defaultCanvasLayout = (formIds, viewIds) => ({
466
+ component: "Stack",
467
+ props: { direction: "row", gap: 16, align: "start" },
468
+ children: [
469
+ ...formIds.length > 0 ? [column(2, 420, formIds.map(formPanel))] : [],
470
+ ...viewIds.length > 0 ? [column(1, 340, viewIds.map(slot))] : []
471
+ ]
472
+ });
473
+
474
+ // src/editor/view.ts
475
+ var mountView = (editor, action, read) => {
476
+ const { shell } = editor;
477
+ shell.registerAction(action);
478
+ shell.addCanvas({ id: action.id, initial: action.id });
479
+ const instance = shell.getCanvasState(action.id).active?.id;
480
+ if (instance === void 0) return;
481
+ const sync = () => {
482
+ shell.getRuntime(instance)?.setData(read(editor));
483
+ };
484
+ editor.on("change", sync);
485
+ sync();
486
+ };
487
+
488
+ // src/editor/editor.ts
489
+ var formCanvas = (document) => `form:${document}`;
490
+ var ROOT_KEY = "$root";
491
+ var needsWrap = (document) => parse(document).kind !== "object";
492
+ var stripErrors2 = (data) => {
493
+ const { [ERROR_NAMESPACE]: _omit, ...document } = data;
494
+ return document;
495
+ };
496
+ var createLoomEditor = (config) => {
497
+ const plugins = /* @__PURE__ */ new Map();
498
+ const listeners = { change: /* @__PURE__ */ new Set(), open: /* @__PURE__ */ new Set() };
499
+ const emit = (event) => listeners[event].forEach((handler) => handler());
500
+ const store = nova.createLayoutStore();
501
+ const shell = nova.createShell({
502
+ canvases: [],
503
+ registry: config.registry,
504
+ actions: {},
505
+ layoutStore: store
506
+ });
507
+ let active;
508
+ let formInstances = {};
509
+ let wrappedDocs = /* @__PURE__ */ new Set();
510
+ let formCanvasIds = [];
511
+ let documents = {};
512
+ let validations = {};
513
+ let detach = [];
514
+ const refresh = () => {
515
+ const nextDocs = {};
516
+ const nextProblems = {};
517
+ for (const [name, instanceId] of Object.entries(formInstances)) {
518
+ const data = shell.getRuntime(instanceId)?.getData() ?? {};
519
+ const document = stripErrors2(data);
520
+ const problems = data[ERROR_NAMESPACE] ?? {};
521
+ if (wrappedDocs.has(name)) {
522
+ nextDocs[name] = document[ROOT_KEY];
523
+ nextProblems[name] = problems[ROOT_KEY] ?? {};
524
+ } else {
525
+ nextDocs[name] = document;
526
+ nextProblems[name] = problems;
527
+ }
528
+ }
529
+ documents = nextDocs;
530
+ validations = nextProblems;
531
+ };
532
+ const clearForms = () => {
533
+ detach.forEach((off) => off());
534
+ detach = [];
535
+ for (const canvasId of formCanvasIds) shell.removeCanvas(canvasId);
536
+ formCanvasIds = [];
537
+ formInstances = {};
538
+ wrappedDocs = /* @__PURE__ */ new Set();
539
+ };
540
+ const open = (artifact) => {
541
+ const plugin = plugins.get(artifact.type);
542
+ if (plugin === void 0) throw new Error(`loom editor: no plugin '${artifact.type}'`);
543
+ clearForms();
544
+ active = plugin;
545
+ for (const [name, document] of Object.entries(plugin.documents)) {
546
+ const canvasId = formCanvas(name);
547
+ let action;
548
+ if (typeof document === "function") {
549
+ const value = artifact.documents?.[name];
550
+ action = { id: canvasId, data: isRecord(value) ? value : {}, layout: document(value) };
551
+ } else {
552
+ const ir = parse(document);
553
+ const wrap = needsWrap(document);
554
+ if (wrap) wrappedDocs.add(name);
555
+ const value = artifact.documents?.[name] ?? buildDocument(ir, {});
556
+ const built = toNova(ir, {
557
+ id: canvasId,
558
+ ...wrap ? { rootKey: ROOT_KEY } : {},
559
+ ...isRecord(value) ? { value } : {},
560
+ widgets: plugin.widgets ?? []
561
+ });
562
+ for (const [id, node] of Object.entries(built.layouts)) store.set(id, node);
563
+ action = built.action;
564
+ }
565
+ shell.registerAction(action);
566
+ shell.addCanvas({ id: canvasId, initial: action.id });
567
+ formCanvasIds.push(canvasId);
568
+ const instanceId = shell.getCanvasState(canvasId).active?.id;
569
+ if (instanceId !== void 0) formInstances[name] = instanceId;
570
+ }
571
+ for (const [name, instanceId] of Object.entries(formInstances)) {
572
+ const document = plugin.documents[name];
573
+ if (typeof document !== "function" && document !== void 0) {
574
+ const schema = wrappedDocs.has(name) ? zod.z.object({ [ROOT_KEY]: document }) : document;
575
+ detach.push(attachValidation(shell, instanceId, schema));
576
+ }
577
+ }
578
+ detach.push(
579
+ shell.onDataChange((change) => {
580
+ if (!Object.values(formInstances).includes(change.instanceId)) return;
581
+ refresh();
582
+ emit("change");
583
+ })
584
+ );
585
+ const viewIds = Object.keys(shell.getState().canvases).filter((id) => !formCanvasIds.includes(id)).sort((a, b) => Number(a.startsWith("loom:")) - Number(b.startsWith("loom:")));
586
+ shell.setCanvasLayout(defaultCanvasLayout(formCanvasIds, viewIds));
587
+ refresh();
588
+ emit("open");
589
+ emit("change");
590
+ };
591
+ const editor = {
592
+ get shell() {
593
+ return shell;
594
+ },
595
+ get plugin() {
596
+ return active;
597
+ },
598
+ get documents() {
599
+ return documents;
600
+ },
601
+ get validations() {
602
+ return validations;
603
+ },
604
+ loadPlugin: (plugin) => {
605
+ plugins.set(plugin.name, plugin);
606
+ plugin.mount?.(editor);
607
+ },
608
+ open,
609
+ on: (event, handler) => {
610
+ listeners[event].add(handler);
611
+ return () => listeners[event].delete(handler);
612
+ },
613
+ dispose: () => {
614
+ detach.forEach((off) => off());
615
+ detach = [];
616
+ shell.dispose();
617
+ }
618
+ };
619
+ return editor;
620
+ };
621
+
622
+ exports.ERROR_NAMESPACE = ERROR_NAMESPACE;
623
+ exports.Roles = Roles;
624
+ exports.attachValidation = attachValidation;
625
+ exports.createLoomEditor = createLoomEditor;
626
+ exports.mountView = mountView;
627
+ exports.parse = parse;
628
+ exports.toNova = toNova;
629
+ //# sourceMappingURL=index.cjs.map
630
+ //# sourceMappingURL=index.cjs.map