@almadar/core 10.129.0 → 11.0.1

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 (135) hide show
  1. package/dist/behavior-package.d.ts +49 -11
  2. package/dist/behavior-package.js +1 -1
  3. package/dist/{orbital-CkFdDS9f.d.ts → builders-BdgbY7Th.d.ts} +5828 -6917
  4. package/dist/builders.d.ts +6 -6
  5. package/dist/builders.js +7 -6
  6. package/dist/{bus-CcbB__oo.d.ts → bus-C0hFDNFR.d.ts} +262 -354
  7. package/dist/chunk-347APWFM.js +286 -0
  8. package/dist/chunk-347APWFM.js.map +1 -0
  9. package/dist/chunk-5WQ3U7NJ.js +2363 -0
  10. package/dist/chunk-5WQ3U7NJ.js.map +1 -0
  11. package/dist/chunk-5YTPYMPZ.js +99 -0
  12. package/dist/chunk-5YTPYMPZ.js.map +1 -0
  13. package/dist/chunk-66Q5VX2F.js +3810 -0
  14. package/dist/chunk-66Q5VX2F.js.map +1 -0
  15. package/dist/chunk-7GHJU5WI.js +39 -0
  16. package/dist/chunk-7GHJU5WI.js.map +1 -0
  17. package/dist/chunk-B4MNHGBP.js +8 -0
  18. package/dist/chunk-B4MNHGBP.js.map +1 -0
  19. package/dist/chunk-E4T2MQAV.js +24 -0
  20. package/dist/chunk-E4T2MQAV.js.map +1 -0
  21. package/dist/chunk-ENOCKYGA.js +412 -0
  22. package/dist/chunk-ENOCKYGA.js.map +1 -0
  23. package/dist/chunk-FGT5OS2Y.js +918 -0
  24. package/dist/chunk-FGT5OS2Y.js.map +1 -0
  25. package/dist/chunk-GF7KCLNR.js +3284 -0
  26. package/dist/chunk-GF7KCLNR.js.map +1 -0
  27. package/dist/chunk-PNGFWLHD.js +1567 -0
  28. package/dist/chunk-PNGFWLHD.js.map +1 -0
  29. package/dist/{chunk-X4SC7FGF.js → chunk-RGACZEYC.js} +99 -96
  30. package/dist/chunk-RGACZEYC.js.map +1 -0
  31. package/dist/{chunk-RYPVOI6H.js → chunk-SNZYN7UA.js} +2541 -433
  32. package/dist/{chunk-RYPVOI6H.js.map → chunk-SNZYN7UA.js.map} +1 -1
  33. package/dist/{chunk-KDMV222Q.js → chunk-TDNQT3M3.js} +304 -373
  34. package/dist/chunk-TDNQT3M3.js.map +1 -0
  35. package/dist/chunk-VG7BRFUD.js +152 -0
  36. package/dist/chunk-VG7BRFUD.js.map +1 -0
  37. package/dist/chunk-Z7BI7DE7.js +1293 -0
  38. package/dist/chunk-Z7BI7DE7.js.map +1 -0
  39. package/dist/{domain-Dz3jP-UM.d.ts → domain-Cpmja5ak.d.ts} +55 -55
  40. package/dist/{effect-CiEVLsZz.d.ts → effect-DZaXwSAz.d.ts} +283 -453
  41. package/dist/{effect-result-Bebwu9yT.d.ts → effect-result-1HpXgeBc.d.ts} +656 -851
  42. package/dist/{expression-D0Fs0riG.d.ts → expression-DirYKz-f.d.ts} +5 -13
  43. package/dist/factory/index.d.ts +7 -144
  44. package/dist/factory/index.js +8 -8
  45. package/dist/factory-runtime/index.d.ts +7 -6
  46. package/dist/factory-runtime/index.js +527 -8
  47. package/dist/factory-runtime/index.js.map +1 -1
  48. package/dist/fixtures.d.ts +9 -11
  49. package/dist/fixtures.js +12 -8
  50. package/dist/fixtures.js.map +1 -1
  51. package/dist/i18n/index.d.ts +15 -19
  52. package/dist/i18n/index.js +2 -1
  53. package/dist/{index-BC-Jycqj.d.ts → index-D7SxwNdv.d.ts} +34 -734
  54. package/dist/index.d.ts +92 -247
  55. package/dist/index.js +322 -986
  56. package/dist/index.js.map +1 -1
  57. package/dist/kernel-wire.d.ts +3 -3
  58. package/dist/kernel-wire.js +3 -79
  59. package/dist/kernel-wire.js.map +1 -1
  60. package/dist/language/constructs.json +22 -2
  61. package/dist/language/program-types.json +203 -22
  62. package/dist/language/protocols.json +46 -0
  63. package/dist/language/ui-vocabulary.json +1697 -0
  64. package/dist/language/validation-codes.json +1222 -1212
  65. package/dist/language/vocabulary.json +44 -8
  66. package/dist/language-data.d.ts +7 -4
  67. package/dist/language-data.js +20 -14
  68. package/dist/language-data.js.map +1 -1
  69. package/dist/patterns/component-mapping.json +11 -1
  70. package/dist/patterns/definitions.d.ts +2 -2
  71. package/dist/patterns/definitions.js +1 -1
  72. package/dist/patterns/event-contracts.json +1 -15
  73. package/dist/patterns/game-font-families.json +13 -0
  74. package/dist/patterns/index.d.ts +24 -120
  75. package/dist/patterns/index.js +3 -3
  76. package/dist/patterns/pattern-tile-geometry.json +1065 -0
  77. package/dist/patterns/patterns-registry.json +2539 -431
  78. package/dist/patterns/registry.json +2539 -431
  79. package/dist/trait-sRjIivFq.d.ts +3519 -0
  80. package/dist/types/index.d.ts +9 -10
  81. package/dist/types/index.js +11 -5
  82. package/dist/{types-DGwrltUF.d.ts → types-C6_yPMpn.d.ts} +3 -3
  83. package/fixtures/events-wire/client-effects-by-trait/response.json +0 -18
  84. package/fixtures/events-wire/client-effects-provenance/response.json +0 -18
  85. package/fixtures/events-wire/effect-results-every-kind/response.json +2 -27
  86. package/fixtures/events-wire/navigate-1/response.json +8 -5
  87. package/fixtures/events-wire/navigate-2/response.json +11 -8
  88. package/fixtures/events-wire/navigate-3/response.json +14 -11
  89. package/fixtures/events-wire/navigate-back/response.json +7 -4
  90. package/fixtures/events-wire/render-ui-3/response.json +12 -9
  91. package/fixtures/events-wire/render-ui-clear/response.json +0 -7
  92. package/fixtures/events-wire/sse-stream/response.json +0 -20
  93. package/fixtures/events-wire/sse-stream/stream.json +0 -20
  94. package/fixtures/events-wire/stateless-traits/response.json +14 -5
  95. package/fixtures/kernel-wire/golden/basic-entity.json +1687 -0
  96. package/fixtures/kernel-wire/golden/entity-rerender.json +743 -0
  97. package/fixtures/kernel-wire/golden/rollback.json +793 -0
  98. package/fixtures/kernel-wire/golden/tick-counter.json +1538 -0
  99. package/fixtures/kernel-wire/golden/two-orbital-chore.json +847 -0
  100. package/fixtures/kernel-wire/golden/two-orbital-task.json +457 -0
  101. package/fixtures/kernel-wire/played-step.json +136 -0
  102. package/fixtures/kernel-wire/scripts/basic-entity.json +28 -0
  103. package/fixtures/kernel-wire/scripts/entity-rerender.json +13 -0
  104. package/fixtures/kernel-wire/scripts/rollback.json +53 -0
  105. package/fixtures/kernel-wire/scripts/tick-counter.json +26 -0
  106. package/fixtures/kernel-wire/scripts/two-orbital-chore.json +9 -0
  107. package/fixtures/kernel-wire/scripts/two-orbital-task.json +9 -0
  108. package/package.json +28 -19
  109. package/dist/builders-DmZE5By0.d.ts +0 -2663
  110. package/dist/chunk-45I2O4SJ.js +0 -4646
  111. package/dist/chunk-45I2O4SJ.js.map +0 -1
  112. package/dist/chunk-6LR43Z5E.js +0 -3061
  113. package/dist/chunk-6LR43Z5E.js.map +0 -1
  114. package/dist/chunk-GIUA3NUJ.js +0 -809
  115. package/dist/chunk-GIUA3NUJ.js.map +0 -1
  116. package/dist/chunk-GTY53NS5.js +0 -1908
  117. package/dist/chunk-GTY53NS5.js.map +0 -1
  118. package/dist/chunk-JOHDVS6J.js +0 -1614
  119. package/dist/chunk-JOHDVS6J.js.map +0 -1
  120. package/dist/chunk-KDMV222Q.js.map +0 -1
  121. package/dist/chunk-QRHJUS3D.js +0 -23
  122. package/dist/chunk-QRHJUS3D.js.map +0 -1
  123. package/dist/chunk-QUOTJULD.js +0 -4009
  124. package/dist/chunk-QUOTJULD.js.map +0 -1
  125. package/dist/chunk-V5VNGRVU.js +0 -66
  126. package/dist/chunk-V5VNGRVU.js.map +0 -1
  127. package/dist/chunk-X4SC7FGF.js.map +0 -1
  128. package/dist/entityAccess-BPSz1i2n.d.ts +0 -80
  129. package/dist/mock/index.d.ts +0 -153
  130. package/dist/mock/index.js +0 -190
  131. package/dist/mock/index.js.map +0 -1
  132. package/dist/schema-T5RT5s6H.d.ts +0 -282
  133. package/dist/state-machine/index.d.ts +0 -359
  134. package/dist/state-machine/index.js +0 -3
  135. package/dist/state-machine/index.js.map +0 -1
@@ -0,0 +1,1567 @@
1
+ import { SuggestedGuardSchema, DesignPreferencesSchema, DomainContextSchema, ThemeRefSchema, CustomPatternMapSchema, DesignTokensSchema, ThemeDefinitionSchema } from './chunk-M4S2B5VJ.js';
2
+ import { FieldProjectionSchema, EffectSchema, EntityFieldSchema, TypeVariableSchema, PatternObjectSchema, EntitySchema, EntityPersistenceSchema } from './chunk-FGT5OS2Y.js';
3
+ import { SExprSchema, ExpressionSchema, SExprListSchema } from './chunk-347APWFM.js';
4
+ import { EventIdSchema, PageIdSchema, TraitIdSchema, OrbitalIdSchema, EntityIdSchema, IdentityLedgerSchema } from './chunk-VG7BRFUD.js';
5
+ import { z } from 'zod';
6
+
7
+ function unionOsGrants(a, b) {
8
+ const list = (x, y) => [.../* @__PURE__ */ new Set([...x ?? [], ...y ?? []])];
9
+ const keyed = (x, y, key, items, make) => {
10
+ const out2 = /* @__PURE__ */ new Map();
11
+ for (const grant of [...x ?? [], ...y ?? []]) {
12
+ const seen = out2.get(key(grant));
13
+ out2.set(key(grant), seen === void 0 ? grant : make(seen, list(items(seen), items(grant))));
14
+ }
15
+ return [...out2.values()];
16
+ };
17
+ const out = {};
18
+ const fs = keyed(a?.fs, b?.fs, (g) => g.glob, (g) => g.modes, (g, modes) => ({ ...g, modes }));
19
+ const net = keyed(a?.net, b?.net, (g) => g.target, (g) => g.kinds, (g, kinds) => ({ ...g, kinds }));
20
+ if (fs.length > 0) out.fs = fs;
21
+ if (net.length > 0) out.net = net;
22
+ const dev = keyed(a?.dev, b?.dev, (g) => g.target, (g) => g.kinds, (g, kinds) => ({ ...g, kinds }));
23
+ if (dev.length > 0) out.dev = dev;
24
+ const kv = {};
25
+ for (const store of [...Object.keys(a?.kv ?? {}), ...Object.keys(b?.kv ?? {})]) {
26
+ kv[store] = list(a?.kv?.[store], b?.kv?.[store]);
27
+ }
28
+ if (Object.keys(kv).length > 0) out.kv = kv;
29
+ const anchored = {};
30
+ const distinct = (x, y) => {
31
+ const out2 = /* @__PURE__ */ new Map();
32
+ for (const g of [...x ?? [], ...y ?? []]) out2.set(JSON.stringify(g), g);
33
+ return [...out2.values()];
34
+ };
35
+ const anchoredFs = distinct(a?.anchored?.fs, b?.anchored?.fs);
36
+ const anchoredExec = distinct(a?.anchored?.exec, b?.anchored?.exec);
37
+ const anchoredNet = distinct(a?.anchored?.net, b?.anchored?.net);
38
+ if (anchoredFs.length > 0) anchored.fs = anchoredFs;
39
+ if (anchoredExec.length > 0) anchored.exec = anchoredExec;
40
+ if (anchoredNet.length > 0) anchored.net = anchoredNet;
41
+ if (Object.keys(anchored).length > 0) out.anchored = anchored;
42
+ const exec = list(a?.exec, b?.exec);
43
+ const env = list(a?.env, b?.env);
44
+ const stdio = list(a?.stdio, b?.stdio);
45
+ const sys = list(a?.sys, b?.sys);
46
+ const desktop = list(a?.desktop, b?.desktop);
47
+ if (exec.length > 0) out.exec = exec;
48
+ if (env.length > 0) out.env = env;
49
+ if (stdio.length > 0) out.stdio = stdio;
50
+ if (sys.length > 0) out.sys = sys;
51
+ if (desktop.length > 0) out.desktop = desktop;
52
+ return out;
53
+ }
54
+ var OsGrantsSchema = z.custom((v) => typeof v === "object" && v !== null && !Array.isArray(v));
55
+ var DeploymentSchema = z.record(z.string(), z.array(z.string()));
56
+ var SKELETON_VARIANTS = ["header", "table", "list", "grid", "detail", "stats", "form", "card", "text"];
57
+ var SkeletonVariantSchema = z.enum(SKELETON_VARIANTS);
58
+ var SkeletonShapeSchema = z.object({
59
+ variant: SkeletonVariantSchema,
60
+ rows: z.number().int().positive().optional(),
61
+ columns: z.number().int().positive().optional(),
62
+ fields: z.number().int().positive().optional()
63
+ });
64
+ var SkeletonSpecSchema = z.union([SkeletonVariantSchema, z.literal("none"), SkeletonShapeSchema]);
65
+ var SkeletonNodeSchema = z.lazy(
66
+ () => z.union([z.object({ shape: SkeletonShapeSchema }), z.object({ stack: z.array(SkeletonNodeSchema) })])
67
+ );
68
+ var AwaitRenderSchema = z.object({
69
+ trait: z.string(),
70
+ slot: z.string(),
71
+ skeleton: SkeletonNodeSchema
72
+ });
73
+ var StateSchema = z.object({
74
+ name: z.string().min(1, "State name is required"),
75
+ isInitial: z.boolean().optional(),
76
+ isTerminal: z.boolean().optional(),
77
+ isFinal: z.boolean().optional(),
78
+ description: z.string().optional(),
79
+ onEntry: z.array(z.string()).optional(),
80
+ onExit: z.array(z.string()).optional(),
81
+ holds: SExprSchema.optional()
82
+ });
83
+ var PayloadTypeWhenSchema = z.object({
84
+ knob: z.string().min(1),
85
+ equals: z.string().min(1),
86
+ type: z.string().min(1)
87
+ });
88
+ function payloadTypeContainer(type) {
89
+ if (type === "array") return { kind: "array", element: "" };
90
+ if (type === "object") return { kind: "object" };
91
+ if (type.startsWith("Map<") && type.endsWith(">")) {
92
+ const inner = type.slice(4, -1);
93
+ const comma = inner.indexOf(",");
94
+ if (comma > 0 && comma < inner.length - 1) {
95
+ return { kind: "map", key: inner.slice(0, comma).trim(), value: inner.slice(comma + 1).trim() };
96
+ }
97
+ }
98
+ if (type.length > 2 && type.startsWith("[") && type.endsWith("]")) {
99
+ return { kind: "array", element: type.slice(1, -1) };
100
+ }
101
+ return { kind: "opaque" };
102
+ }
103
+ var payloadFieldShape = {
104
+ type: z.string().min(1),
105
+ required: z.boolean().optional(),
106
+ nullable: z.boolean().optional(),
107
+ description: z.string().optional(),
108
+ additionalProperties: z.lazy(() => PayloadFieldDescriptorSchema).optional(),
109
+ values: z.array(z.string()).optional(),
110
+ properties: z.lazy(() => z.array(PayloadFieldSchema)).optional(),
111
+ typeWhen: z.array(PayloadTypeWhenSchema).optional(),
112
+ entity: z.string().min(1).optional(),
113
+ projectedFrom: FieldProjectionSchema.optional(),
114
+ items: z.lazy(() => PayloadFieldDescriptorSchema).optional()
115
+ };
116
+ var PayloadFieldDescriptorSchema = z.object({
117
+ name: z.string(),
118
+ ...payloadFieldShape
119
+ });
120
+ var PayloadFieldSchema = z.object({
121
+ name: z.string().min(1),
122
+ ...payloadFieldShape
123
+ });
124
+ var InboundVerificationSchema = z.object({
125
+ header: z.string().min(1),
126
+ credential: z.string().min(1)
127
+ });
128
+ var InboundDeclarationSchema = z.object({
129
+ name: z.string().min(1),
130
+ answers: z.string().min(1),
131
+ verifies: InboundVerificationSchema.optional()
132
+ });
133
+ var EventSchema = z.object({
134
+ key: z.string().min(1, "Event key is required"),
135
+ id: EventIdSchema.optional(),
136
+ name: z.string().min(1, "Event name is required"),
137
+ description: z.string().optional(),
138
+ synonyms: z.string().optional(),
139
+ tier: z.string().optional(),
140
+ payloadSchema: z.array(PayloadFieldSchema).optional(),
141
+ payloadEntity: z.string().optional(),
142
+ input: z.boolean().optional(),
143
+ listened: z.boolean().optional(),
144
+ inbound: InboundDeclarationSchema.optional(),
145
+ classification: z.enum(["domain", "system"]).optional(),
146
+ semanticRole: z.string().optional()
147
+ });
148
+ var GuardSchema = z.object({
149
+ name: z.string().min(1, "Guard name is required"),
150
+ expression: ExpressionSchema,
151
+ description: z.string().optional()
152
+ });
153
+ var TransitionSchema = z.object({
154
+ from: z.string().min(1, "Transition source state is required"),
155
+ to: z.string().min(1, "Transition target state is required"),
156
+ event: z.string().min(1, "Transition event is required"),
157
+ eventId: EventIdSchema.optional(),
158
+ guard: ExpressionSchema.nullish(),
159
+ effects: z.array(EffectSchema).optional(),
160
+ ensures: SExprListSchema.optional(),
161
+ description: z.string().nullish(),
162
+ awaitRender: z.array(AwaitRenderSchema).optional()
163
+ });
164
+ var StateMachineSchema = z.object({
165
+ states: z.array(StateSchema).min(1, "At least one state is required"),
166
+ events: z.array(EventSchema),
167
+ transitions: z.array(TransitionSchema),
168
+ guards: z.array(GuardSchema).optional()
169
+ });
170
+ function isCircuitEvent(event) {
171
+ return !event.startsWith("_");
172
+ }
173
+ var TraitConfigValueSchema = z.lazy(
174
+ () => z.union([
175
+ z.string(),
176
+ z.number(),
177
+ z.boolean(),
178
+ z.null(),
179
+ z.array(TraitConfigValueSchema),
180
+ z.record(z.string(), TraitConfigValueSchema)
181
+ ])
182
+ );
183
+ var TraitConfigSchema = z.record(z.string(), TraitConfigValueSchema);
184
+ function isCallSiteConfigDeclaration(entry) {
185
+ return typeof entry === "object" && entry !== null && !Array.isArray(entry) && "type" in entry && typeof entry.type === "string" && "default" in entry;
186
+ }
187
+ function isConfigRedeclaration(entry) {
188
+ if (!isCallSiteConfigDeclaration(entry)) return false;
189
+ if (entry.wired === true) return false;
190
+ return entry.type !== "unknown" || entry.label !== void 0 || entry.description !== void 0 || entry.synonyms !== void 0 || entry.tier !== void 0;
191
+ }
192
+ var CONFIG_DECLARATION_META_KEYS = ["label", "description", "tier", "synonyms", "values"];
193
+ function isConfigFieldSchema(entry) {
194
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return false;
195
+ if (!("type" in entry) || typeof entry.type !== "string") return false;
196
+ return "default" in entry || CONFIG_DECLARATION_META_KEYS.some((k) => k in entry);
197
+ }
198
+ function normalizeCallSiteConfigToValues(config) {
199
+ if (config === void 0) {
200
+ return void 0;
201
+ }
202
+ const out = {};
203
+ let hasAny = false;
204
+ for (const [key, entry] of Object.entries(config)) {
205
+ const value = isConfigFieldSchema(entry) ? entry.default : entry;
206
+ if (value !== void 0) {
207
+ out[key] = value;
208
+ hasAny = true;
209
+ }
210
+ }
211
+ return hasAny ? out : void 0;
212
+ }
213
+ function mergeCallSiteConfigOverrides(base, overrides) {
214
+ const next = {};
215
+ for (const [k, entry] of Object.entries(base)) {
216
+ next[k] = isConfigFieldSchema(entry) ? entry : { type: "unknown", default: entry };
217
+ }
218
+ for (const [k, v] of Object.entries(overrides)) {
219
+ if (isCallSiteConfigDeclaration(v)) {
220
+ next[k] = v;
221
+ continue;
222
+ }
223
+ const existing = base[k];
224
+ next[k] = existing !== void 0 && isConfigFieldSchema(existing) ? { ...existing, default: v } : { type: "unknown", default: v };
225
+ }
226
+ return next;
227
+ }
228
+ var REFERENCE_CONFIG_TYPES = ["entity", "trait", "event"];
229
+ function isReferenceConfigType(type) {
230
+ return REFERENCE_CONFIG_TYPES.includes(type);
231
+ }
232
+ var SECRET_CONFIG_TYPES = ["secret"];
233
+ function isSecretConfigType(type) {
234
+ return SECRET_CONFIG_TYPES.includes(type);
235
+ }
236
+ function maskSecretConfigValues(config, values) {
237
+ const masked = {};
238
+ for (const [key, value] of Object.entries(values)) {
239
+ const decl = config[key];
240
+ if (decl !== void 0 && isSecretConfigType(decl.type) && typeof value === "string" && value.length > 0) {
241
+ masked[key] = value.length > 4 ? `\u2022\u2022\u2022\u2022${value.slice(-4)}` : "\u2022\u2022\u2022\u2022";
242
+ } else {
243
+ masked[key] = value;
244
+ }
245
+ }
246
+ return masked;
247
+ }
248
+ function canonicalizeUnboundTraitOverride(fieldType, value) {
249
+ return fieldType === "trait" && value === "none" ? null : value;
250
+ }
251
+ function overrideDeclaredKnobs(declared, overrides) {
252
+ const out = { ...declared };
253
+ for (const key of Object.keys(overrides)) {
254
+ const field = declared[key];
255
+ if (field === void 0) {
256
+ throw new Error(
257
+ `overrideDeclaredKnobs: config override "${key}" is not a declared knob (ORB_O_CONFIG_UNKNOWN_KEY). Declared: ${Object.keys(declared).join(", ") || "(none)"}`
258
+ );
259
+ }
260
+ out[key] = { ...field, default: canonicalizeUnboundTraitOverride(field.type, overrides[key]) };
261
+ }
262
+ return out;
263
+ }
264
+ var ConfigFieldItemsDeclarationSchema = z.lazy(
265
+ () => z.object({
266
+ nullable: z.boolean().optional(),
267
+ additionalProperties: EntityFieldSchema.optional(),
268
+ type: z.string().optional(),
269
+ properties: z.record(z.string(), TraitEntityFieldSchema).optional(),
270
+ items: ConfigFieldItemsDeclarationSchema.optional(),
271
+ values: z.array(z.string()).optional()
272
+ })
273
+ );
274
+ var ConfigFieldDeclarationSchema = z.object({
275
+ nullable: z.boolean().optional(),
276
+ additionalProperties: EntityFieldSchema.optional(),
277
+ type: z.string(),
278
+ default: TraitConfigValueSchema.optional(),
279
+ refId: z.string().optional(),
280
+ required: z.boolean().optional(),
281
+ label: z.string().optional(),
282
+ description: z.string().optional(),
283
+ tier: z.string().optional(),
284
+ values: z.array(z.string()).optional(),
285
+ synonyms: z.string().optional(),
286
+ items: ConfigFieldItemsDeclarationSchema.optional(),
287
+ properties: z.lazy(() => z.record(z.string(), TraitEntityFieldSchema)).optional(),
288
+ forwardedFrom: z.string().optional(),
289
+ nestedForwardedFrom: z.array(z.string()).optional(),
290
+ payloadFor: z.string().optional(),
291
+ projectedFrom: FieldProjectionSchema.optional(),
292
+ record: z.string().optional(),
293
+ wired: z.boolean().optional()
294
+ });
295
+ var DeclaredTraitConfigSchema = z.record(
296
+ z.string(),
297
+ ConfigFieldDeclarationSchema
298
+ );
299
+ var TRAIT_FIELD_TYPES = [
300
+ "string",
301
+ "number",
302
+ "boolean",
303
+ "date",
304
+ "array",
305
+ "object",
306
+ "timestamp",
307
+ "datetime",
308
+ "instant",
309
+ "enum",
310
+ "email",
311
+ "url",
312
+ "phone",
313
+ "uuid",
314
+ "image",
315
+ "bytes",
316
+ "trait",
317
+ "slot",
318
+ "pattern",
319
+ "node",
320
+ "event",
321
+ "EventAddress",
322
+ "CallKey",
323
+ "SExpr",
324
+ "union",
325
+ "tuple",
326
+ "field"
327
+ ];
328
+ var TraitEntityFieldSchema = z.object({
329
+ nullable: z.boolean().optional(),
330
+ additionalProperties: EntityFieldSchema.optional(),
331
+ name: z.string().min(1),
332
+ type: z.union([z.enum(TRAIT_FIELD_TYPES), TypeVariableSchema]),
333
+ required: z.boolean().optional(),
334
+ default: TraitConfigValueSchema.optional(),
335
+ values: z.array(z.string()).optional(),
336
+ items: ConfigFieldItemsDeclarationSchema.optional(),
337
+ properties: z.lazy(() => z.record(z.string(), TraitEntityFieldSchema)).optional(),
338
+ record: z.string().optional()
339
+ });
340
+ var TraitDataEntitySchema = z.object({
341
+ name: z.string().min(1),
342
+ collection: z.string().optional(),
343
+ fields: z.array(TraitEntityFieldSchema).min(1),
344
+ timestamps: z.boolean().optional(),
345
+ description: z.string().optional(),
346
+ runtime: z.boolean().optional(),
347
+ singleton: z.boolean().optional(),
348
+ pages: z.array(z.string()).optional()
349
+ });
350
+ var DURATION_INTERVAL = /^\d+(ms|s|m|h|d)$/;
351
+ var CRON_INTERVAL = /^\S+(\s+\S+){4}$/;
352
+ var TickIntervalSchema = z.union([
353
+ z.literal("frame"),
354
+ z.number().positive(),
355
+ z.string().refine((v) => DURATION_INTERVAL.test(v) || CRON_INTERVAL.test(v), {
356
+ message: 'interval must be "frame", a positive number of milliseconds, a duration ("500ms"/"5s"/"1m"/"1h"/"1d"), or a 5-field cron expression ("0 9 * * *")'
357
+ })
358
+ ]);
359
+ var TraitTickSchema = z.object({
360
+ name: z.string().min(1),
361
+ description: z.string().optional(),
362
+ priority: z.number().optional(),
363
+ interval: TickIntervalSchema,
364
+ appliesTo: z.array(z.string()).optional(),
365
+ runsInBackground: z.boolean().optional(),
366
+ whileVisible: z.boolean().optional(),
367
+ pages: z.array(z.string()).optional(),
368
+ pageIds: z.array(PageIdSchema).optional(),
369
+ guard: ExpressionSchema.optional(),
370
+ effects: z.array(EffectSchema).min(1),
371
+ emits: z.array(z.string()).optional(),
372
+ emitIds: z.array(EventIdSchema).optional()
373
+ });
374
+ var EventScopeSchema = z.enum(["internal", "external"]);
375
+ var EventPayloadTypeMemberSchema = PayloadFieldDescriptorSchema;
376
+ var EventPayloadFieldSchema = PayloadFieldSchema;
377
+ var CONFIG_REF_EVENT_PATTERN = /^@config\.[A-Za-z_][A-Za-z0-9_]*$/;
378
+ function configRefEventKnob(event) {
379
+ return CONFIG_REF_EVENT_PATTERN.test(event) ? event.slice("@config.".length) : void 0;
380
+ }
381
+ function resolveConfigRefEventName(event, declaredConfig, effectiveConfig) {
382
+ const knob = configRefEventKnob(event);
383
+ if (knob === void 0) return { ok: false, error: "unknown-knob" };
384
+ const field = declaredConfig?.[knob];
385
+ if (field === void 0) return { ok: false, error: "unknown-knob" };
386
+ if (field.type !== "string" && field.type !== "event") return { ok: false, error: "not-string" };
387
+ if (field.default === void 0) return { ok: false, error: "no-default" };
388
+ const value = effectiveConfig[knob];
389
+ if (typeof value !== "string") return { ok: false, error: "not-string" };
390
+ return { ok: true, value };
391
+ }
392
+ var TraitEventContractSchema = z.object({
393
+ /**
394
+ * Event name. Mirrors the Rust validator's `is_valid_event_identifier`:
395
+ * starts with a letter, then any letters / digits / underscores. Both
396
+ * UPPER_SNAKE_CASE and PascalCase shapes are valid identifiers in the
397
+ * post-Phase 2.5 nominal-event type system (events declared via
398
+ * `type X = Event<T>`). A pre-resolution `@config.<knob>` reference
399
+ * (Option B) is also legal — inline/resolve substitutes it with the
400
+ * knob's effective literal before codegen/runtime consume it.
401
+ */
402
+ event: z.string().min(1).regex(
403
+ /^([A-Za-z][A-Za-z0-9_]*|@config\.[A-Za-z_][A-Za-z0-9_]*)$/,
404
+ "Event name must start with a letter and contain only letters, digits, and underscores, or be a `@config.<knob>` reference"
405
+ ),
406
+ eventId: EventIdSchema.optional(),
407
+ description: z.string().optional(),
408
+ synonyms: z.string().optional(),
409
+ tier: z.string().optional(),
410
+ definerKnob: z.string().optional(),
411
+ scopeOverridden: z.boolean().optional(),
412
+ payloadSchema: z.array(EventPayloadFieldSchema).optional(),
413
+ payloadEntity: z.string().optional(),
414
+ scope: EventScopeSchema.optional()
415
+ });
416
+ var ListenSourceSchema = z.union([
417
+ z.object({ kind: z.literal("any") }),
418
+ z.object({
419
+ kind: z.literal("trait"),
420
+ trait: z.string().min(1),
421
+ traitId: TraitIdSchema.optional()
422
+ }),
423
+ z.object({
424
+ kind: z.literal("orbital"),
425
+ orbital: z.string().min(1),
426
+ trait: z.string().min(1),
427
+ orbitalId: OrbitalIdSchema.optional(),
428
+ traitId: TraitIdSchema.optional()
429
+ })
430
+ ]);
431
+ function splitEventAddress(raw) {
432
+ const parts = raw.split(".");
433
+ if (parts.length <= 1) return { event: raw };
434
+ if (parts.length === 2) {
435
+ const [src, event] = parts;
436
+ return src === "*" ? { event, source: { kind: "any" } } : { event, source: { kind: "trait", trait: src } };
437
+ }
438
+ const n = parts.length;
439
+ return {
440
+ event: parts[n - 1],
441
+ source: { kind: "orbital", orbital: parts.slice(0, n - 2).join("."), trait: parts[n - 2] }
442
+ };
443
+ }
444
+ function joinEventAddress(event, source) {
445
+ if (source === void 0) return event;
446
+ switch (source.kind) {
447
+ case "any":
448
+ return `*.${event}`;
449
+ case "trait":
450
+ return `${source.trait}.${event}`;
451
+ case "orbital":
452
+ return `${source.orbital}.${source.trait}.${event}`;
453
+ }
454
+ }
455
+ var TraitEventListenerSchema = z.object({
456
+ event: z.string().min(1),
457
+ eventId: EventIdSchema.optional(),
458
+ triggers: z.string().min(1),
459
+ triggersId: EventIdSchema.optional(),
460
+ description: z.string().optional(),
461
+ synonyms: z.string().optional(),
462
+ tier: z.string().optional(),
463
+ guard: ExpressionSchema.optional(),
464
+ scope: EventScopeSchema.optional(),
465
+ payloadMapping: z.record(z.string(), SExprSchema).optional(),
466
+ key: SExprSchema.optional(),
467
+ source: ListenSourceSchema.optional()
468
+ });
469
+ var RequiredFieldSchema = z.object({
470
+ name: z.string().min(1),
471
+ type: z.union([z.enum(TRAIT_FIELD_TYPES), TypeVariableSchema]),
472
+ description: z.string().optional()
473
+ });
474
+ var TraitReferenceObjectSchema = z.object({
475
+ ref: z.string().min(1),
476
+ refId: TraitIdSchema.optional(),
477
+ // V4 local declaration id (see the interface doc) — declared so the
478
+ // strip-mode zod gate carries it through instead of dropping it.
479
+ id: TraitIdSchema.optional(),
480
+ // Phase 1.2: optional registry path disambiguator, pairs with `ref`.
481
+ from: z.string().optional(),
482
+ linkedEntity: z.string().optional(),
483
+ linkedEntityId: EntityIdSchema.optional(),
484
+ name: z.string().optional(),
485
+ events: z.record(
486
+ z.string().min(1, "events key (atom event name) must be non-empty"),
487
+ z.string().min(1, "events value (caller event name) must be non-empty")
488
+ ).optional(),
489
+ eventIds: z.record(z.string().min(1), EventIdSchema).optional(),
490
+ _resolved: z.lazy(() => TraitSchema).optional(),
491
+ // 3-II type-parameter arguments (see `TraitReference.typeArgs`).
492
+ typeArgs: z.record(
493
+ z.string().min(1, "typeArgs key (declared param name) must be non-empty"),
494
+ z.string().min(1, "typeArgs value (type name) must be non-empty")
495
+ ).optional(),
496
+ fields: z.record(
497
+ z.string().min(1, "fields key (canonical field name) must be non-empty"),
498
+ z.string().min(1, "fields value (consumer field name) must be non-empty")
499
+ ).optional(),
500
+ // Each value is either a plain wiring value (TraitConfigValue) or an
501
+ // annotated ConfigFieldDeclaration. Declaration form is tried first
502
+ // (it's more specific — has a `"type"` string key); plain values fall
503
+ // through to the recursive TraitConfigValue union.
504
+ config: z.record(z.string(), z.union([ConfigFieldDeclarationSchema, TraitConfigValueSchema])).optional(),
505
+ appliesTo: z.array(z.string()).optional(),
506
+ // Phase F.7: caller-supplied listen entries are already-resolved
507
+ // structured definitions (see `TraitReference.listens`).
508
+ listens: z.array(TraitEventListenerSchema).optional(),
509
+ emitsScope: z.enum(["internal", "external"]).optional(),
510
+ // Phase F.8: per-transition effects override. The keys are event
511
+ // names (the transition triggers AFTER renames); values are SExpr
512
+ // effect tuples.
513
+ effects: z.record(
514
+ z.string().min(1, "effects override key (event name) must be non-empty"),
515
+ z.array(SExprSchema)
516
+ ).optional()
517
+ });
518
+ var TraitReferenceSchema = TraitReferenceObjectSchema.refine(
519
+ (ref) => {
520
+ if (!ref.events) return true;
521
+ for (const [from, to] of Object.entries(ref.events)) {
522
+ if (from.length === 0 || to.length === 0) return false;
523
+ }
524
+ return true;
525
+ },
526
+ {
527
+ message: 'TraitReference "events" entries must have non-empty atom and caller event names',
528
+ path: ["events"]
529
+ }
530
+ );
531
+ var TraitUIBindingSchema = z.record(
532
+ z.string(),
533
+ z.object({
534
+ presentation: z.enum(["modal", "drawer", "popover", "inline", "confirm-dialog"]),
535
+ content: z.union([PatternObjectSchema, z.array(PatternObjectSchema)]),
536
+ props: z.object({
537
+ size: z.enum(["sm", "md", "lg", "xl", "full"]).optional(),
538
+ position: z.enum(["left", "right", "top", "bottom", "center"]).optional(),
539
+ title: z.string().optional(),
540
+ closable: z.boolean().optional(),
541
+ width: z.string().optional(),
542
+ showProgress: z.boolean().optional(),
543
+ step: z.number().optional(),
544
+ totalSteps: z.number().optional()
545
+ }).optional()
546
+ })
547
+ );
548
+ var EntityFieldContractSchema = z.object({
549
+ requires: z.array(z.string()),
550
+ provides: z.array(z.string())
551
+ });
552
+ var EffectSiteSchema = z.enum(["transition", "tick"]);
553
+ var EffectUseSchema = z.object({
554
+ kind: z.string(),
555
+ resource: z.string().optional(),
556
+ resolved: z.boolean().optional(),
557
+ site: EffectSiteSchema.optional()
558
+ });
559
+ var EffectRowSchema = z.array(EffectUseSchema);
560
+ var DispatchModeSchema = z.enum(["persistedAwaited", "hybridClientOnly", "runtimeOptimistic"]);
561
+ var TraitDispatchModeSchema = z.enum(["client", "optimistic", "server"]);
562
+ var SourceDeclarationMetadataSchema = z.object({
563
+ traitId: z.string().min(1),
564
+ fingerprint: z.string().min(1)
565
+ });
566
+ var SourceBehaviorMetadataSchema = z.object({
567
+ behavior: z.string().min(1),
568
+ alias: z.string().min(1),
569
+ originalName: z.string().min(1)
570
+ });
571
+ var TraitTypeParamDefSchema = z.object({
572
+ name: z.string().min(1),
573
+ kind: z.string().min(1),
574
+ default: z.string().optional()
575
+ });
576
+ var TraitSchema = z.object({
577
+ id: TraitIdSchema.optional(),
578
+ name: z.string().min(1),
579
+ description: z.string().optional(),
580
+ description_visual_prompt: z.string().optional(),
581
+ entityRebindable: z.boolean().optional(),
582
+ entityContract: EntityFieldContractSchema.optional(),
583
+ effectRow: EffectRowSchema.optional(),
584
+ entityBindingDescription: z.string().optional(),
585
+ entityBindingSynonyms: z.string().optional(),
586
+ dispatch: TraitDispatchModeSchema.optional(),
587
+ linkedEntity: z.string().optional(),
588
+ linkedEntityId: EntityIdSchema.optional(),
589
+ entityRefIds: z.record(z.string().min(1), EntityIdSchema).optional(),
590
+ traitEmbedIds: z.record(z.string().min(1), TraitIdSchema).optional(),
591
+ requiredFields: z.array(RequiredFieldSchema).optional(),
592
+ dataEntities: z.array(TraitDataEntitySchema).optional(),
593
+ stateMachine: StateMachineSchema.optional(),
594
+ initialEffects: z.array(EffectSchema).optional(),
595
+ ticks: z.array(TraitTickSchema).optional(),
596
+ emits: z.array(TraitEventContractSchema).optional(),
597
+ listens: z.array(TraitEventListenerSchema).optional(),
598
+ /** Call-site rename map (`events { ACTION: CONFIRM_VOID }`) — mirrors `Trait.events`. */
599
+ events: z.record(z.string().min(1), z.string().min(1)).optional(),
600
+ ui: TraitUIBindingSchema.optional(),
601
+ config: DeclaredTraitConfigSchema.optional(),
602
+ sourceBehavior: SourceBehaviorMetadataSchema.optional(),
603
+ sourceDeclaration: SourceDeclarationMetadataSchema.optional(),
604
+ sourceEntityDefinition: EntitySchema.optional(),
605
+ typeParams: z.array(TraitTypeParamDefSchema).optional()
606
+ });
607
+ var TraitRefSchema = z.union([
608
+ z.string().min(1),
609
+ TraitReferenceSchema,
610
+ TraitSchema
611
+ // Allow inline trait definitions
612
+ ]);
613
+ function isInlineTrait(traitRef) {
614
+ return typeof traitRef === "object" && "name" in traitRef && !("ref" in traitRef);
615
+ }
616
+ function getTraitName(traitRef) {
617
+ if (typeof traitRef === "string") {
618
+ return traitRef;
619
+ }
620
+ if (isInlineTrait(traitRef)) {
621
+ return traitRef.name;
622
+ }
623
+ return traitRef.ref;
624
+ }
625
+ function getTraitConfig(traitRef) {
626
+ if (typeof traitRef === "string") {
627
+ return void 0;
628
+ }
629
+ if (isInlineTrait(traitRef)) {
630
+ return void 0;
631
+ }
632
+ return traitRef.config;
633
+ }
634
+ function normalizeTraitRef(traitRef) {
635
+ if (typeof traitRef === "string") {
636
+ return { ref: traitRef };
637
+ }
638
+ if (isInlineTrait(traitRef)) {
639
+ return { ref: traitRef.name };
640
+ }
641
+ return traitRef;
642
+ }
643
+ var OrbitalTraitRefSchema = TraitRefSchema;
644
+ var ViewTypeSchema = z.enum([
645
+ "list",
646
+ "detail",
647
+ "create",
648
+ "edit",
649
+ "dashboard",
650
+ "custom"
651
+ ]);
652
+ var PageTraitRefSchema = z.object({
653
+ ref: z.string().min(1, "Trait ref is required"),
654
+ refId: TraitIdSchema.optional(),
655
+ linkedEntity: z.string().optional(),
656
+ linkedEntityId: EntityIdSchema.optional(),
657
+ config: TraitConfigSchema.optional()
658
+ });
659
+ var PageAccessSchema = z.enum(["public", "authenticated"]);
660
+ var PageIndexingSchema = z.enum(["index", "noindex"]);
661
+ var PageMetaSchema = z.union([
662
+ z.string(),
663
+ z.tuple([z.literal("i18n/t"), z.string().min(1)])
664
+ ]);
665
+ function resolvePageMeta(meta, lookup) {
666
+ if (meta === void 0) return void 0;
667
+ return typeof meta === "string" ? meta : lookup(meta[1]);
668
+ }
669
+ var PageModifiersSchema = z.object({
670
+ access: PageAccessSchema.optional(),
671
+ indexing: PageIndexingSchema.optional(),
672
+ title: PageMetaSchema.optional(),
673
+ description: PageMetaSchema.optional(),
674
+ translationOf: z.string().min(1).optional(),
675
+ label: z.string().optional(),
676
+ icon: z.string().optional(),
677
+ roles: z.array(z.string().min(1)).min(1).optional()
678
+ }).strict();
679
+ var OrbitalPageStrictSchema = z.object({
680
+ id: PageIdSchema.optional(),
681
+ name: z.string().min(1, "Page name is required"),
682
+ path: z.string().min(1, "Page path is required").startsWith("/", "Path must start with /"),
683
+ primaryEntity: z.string().min(1, "Primary entity is required"),
684
+ traits: z.array(PageTraitRefSchema).min(1, "Page must have at least one trait"),
685
+ title: PageMetaSchema.optional(),
686
+ description: PageMetaSchema.optional(),
687
+ access: PageAccessSchema.optional(),
688
+ indexing: PageIndexingSchema.optional(),
689
+ sourcePage: z.string().min(1).optional(),
690
+ translationOf: z.string().min(1).optional(),
691
+ icon: z.string().optional(),
692
+ label: z.string().optional(),
693
+ roles: z.array(z.string().min(1)).min(1).optional()
694
+ }).strict();
695
+ var OrbitalPageSchema = z.object({
696
+ id: PageIdSchema.optional(),
697
+ name: z.string().min(1, "Page name is required"),
698
+ path: z.string(),
699
+ protocol: z.string().min(1).optional(),
700
+ address: SExprSchema.optional(),
701
+ viewType: ViewTypeSchema.optional(),
702
+ title: PageMetaSchema.optional(),
703
+ description: PageMetaSchema.optional(),
704
+ access: PageAccessSchema.optional(),
705
+ indexing: PageIndexingSchema.optional(),
706
+ sourcePage: z.string().min(1).optional(),
707
+ translationOf: z.string().min(1).optional(),
708
+ primaryEntity: z.string().optional(),
709
+ traits: z.array(PageTraitRefSchema).optional(),
710
+ isInitial: z.boolean().optional(),
711
+ isNotFound: z.boolean().optional(),
712
+ icon: z.string().optional(),
713
+ label: z.string().optional(),
714
+ roles: z.array(z.string().min(1)).min(1).optional()
715
+ }).strict().superRefine((page, ctx) => {
716
+ if (page.protocol !== void 0) {
717
+ if (page.path !== "") ctx.addIssue({ code: "custom", path: ["path"], message: "A protocol page has an empty path; its address says where it is reached" });
718
+ return;
719
+ }
720
+ if (page.address !== void 0) ctx.addIssue({ code: "custom", path: ["address"], message: "A route page takes no address; its path is its address" });
721
+ if (page.path.length === 0) ctx.addIssue({ code: "custom", path: ["path"], message: "Page path is required" });
722
+ else if (!page.path.startsWith("/")) ctx.addIssue({ code: "custom", path: ["path"], message: "Path must start with /" });
723
+ });
724
+ var PageSchema = OrbitalPageSchema;
725
+ var ProtocolSideSchema = z.enum(["client", "server", "process", "start"]);
726
+ var ProtocolSpecSchema = z.object({
727
+ name: z.string().min(1),
728
+ address: z.array(z.object({ name: z.string().min(1), ty: z.string().min(1), required: z.boolean() }).strict()).optional(),
729
+ viewer: z.boolean(),
730
+ grant: z.string().min(1).optional(),
731
+ side: ProtocolSideSchema
732
+ }).strict();
733
+ var ROUTE_PROTOCOL = "route";
734
+ function isRoutePage(page) {
735
+ return page.protocol === void 0;
736
+ }
737
+ function protocolName(page) {
738
+ return page.protocol ?? ROUTE_PROTOCOL;
739
+ }
740
+ var SERVICE_TYPES = ["rest", "socket", "mcp"];
741
+ var ServiceTypeSchema = z.enum(SERVICE_TYPES);
742
+ var RestAuthConfigSchema = z.object({
743
+ type: z.enum(["api-key", "bearer", "basic", "oauth2"]),
744
+ keyName: z.string().optional(),
745
+ location: z.enum(["query", "header"]).optional(),
746
+ secretEnv: z.string().optional()
747
+ });
748
+ var RestServiceDefSchema = z.object({
749
+ name: z.string().min(1, "Service name is required"),
750
+ type: z.literal("rest"),
751
+ description: z.string().optional(),
752
+ baseUrl: z.string().url("Base URL must be a valid URL"),
753
+ headers: z.record(z.string(), z.string()).optional(),
754
+ auth: RestAuthConfigSchema.optional(),
755
+ timeout: z.number().positive().optional()
756
+ });
757
+ var SocketEventsSchema = z.object({
758
+ inbound: z.array(z.string()),
759
+ outbound: z.array(z.string())
760
+ });
761
+ var SocketServiceDefSchema = z.object({
762
+ name: z.string().min(1, "Service name is required"),
763
+ type: z.literal("socket"),
764
+ description: z.string().optional(),
765
+ url: z.string().url("WebSocket URL must be valid"),
766
+ events: SocketEventsSchema,
767
+ reconnect: z.object({
768
+ enabled: z.boolean(),
769
+ maxAttempts: z.number().positive().optional(),
770
+ delayMs: z.number().positive().optional()
771
+ }).optional()
772
+ });
773
+ var McpServiceDefSchema = z.object({
774
+ name: z.string().min(1, "Service name is required"),
775
+ type: z.literal("mcp"),
776
+ description: z.string().optional(),
777
+ serverPath: z.string().min(1, "Server path is required"),
778
+ capabilities: z.array(z.string()).min(1, "At least one capability is required"),
779
+ env: z.record(z.string(), z.string()).optional()
780
+ });
781
+ var ServiceDefinitionSchema = z.discriminatedUnion("type", [
782
+ RestServiceDefSchema,
783
+ SocketServiceDefSchema,
784
+ McpServiceDefSchema
785
+ ]);
786
+ function isServiceReference(service) {
787
+ return typeof service === "string";
788
+ }
789
+ function isServiceReferenceObject(service) {
790
+ return typeof service === "object" && service !== null && "ref" in service && !("type" in service);
791
+ }
792
+ var ServiceRefStringSchema = z.string().regex(
793
+ /^[A-Z][a-zA-Z0-9]*\.services\.[a-zA-Z][a-zA-Z0-9]*$/,
794
+ 'Service reference must be in format "Alias.services.ServiceName" (e.g., "Weather.services.openweather")'
795
+ );
796
+ var ServiceRefObjectSchema = z.object({
797
+ ref: ServiceRefStringSchema,
798
+ description: z.string().optional(),
799
+ baseUrl: z.string().url("baseUrl override must be a valid URL").optional(),
800
+ headers: z.record(z.string(), z.string()).optional(),
801
+ url: z.string().url("url override must be a valid URL").optional(),
802
+ serverPath: z.string().optional()
803
+ });
804
+ var ServiceRefSchema = z.union([
805
+ ServiceDefinitionSchema,
806
+ ServiceRefObjectSchema,
807
+ ServiceRefStringSchema
808
+ ]);
809
+ function parseServiceRef(ref) {
810
+ const match = ref.match(
811
+ /^([A-Z][a-zA-Z0-9]*)\.services\.([a-zA-Z][a-zA-Z0-9]*)$/
812
+ );
813
+ if (!match) return null;
814
+ return { alias: match[1], serviceName: match[2] };
815
+ }
816
+ function isRestService(service) {
817
+ return service.type === "rest";
818
+ }
819
+ function isSocketService(service) {
820
+ return service.type === "socket";
821
+ }
822
+ function isMcpService(service) {
823
+ return service.type === "mcp";
824
+ }
825
+ function getServiceNames(services) {
826
+ return services.map((s) => s.name);
827
+ }
828
+ function findService(services, name) {
829
+ return services.find((s) => s.name.toLowerCase() === name.toLowerCase());
830
+ }
831
+ function hasService(services, name) {
832
+ return services.some((s) => s.name.toLowerCase() === name.toLowerCase());
833
+ }
834
+ function credentialStorageKey(identity) {
835
+ if (typeof identity.name !== "string" || identity.principal !== void 0 && typeof identity.principal !== "string") {
836
+ throw new Error("credential identity requires string name and principal");
837
+ }
838
+ return JSON.stringify([identity.principal ?? null, identity.name]);
839
+ }
840
+ function resolveCredentialStatusIdentity(selection, principal) {
841
+ if (selection !== null && typeof selection === "object" && !Array.isArray(selection)) {
842
+ const keys = Reflect.ownKeys(selection);
843
+ if (keys.length !== 2 || !keys.includes("credential") || !keys.includes("scope") || !("credential" in selection) || !("scope" in selection)) {
844
+ throw new Error("credential-status: expected { credential, scope: app | user }");
845
+ }
846
+ const { credential, scope } = selection;
847
+ if (typeof credential !== "string" || scope !== "app" && scope !== "user") {
848
+ throw new Error("credential-status: expected { credential, scope: app | user }");
849
+ }
850
+ if (scope === "app") return { name: credential };
851
+ if (principal === void 0) throw new Error("credential-status: nobody is signed in");
852
+ return { name: credential, principal };
853
+ }
854
+ if (principal === void 0) throw new Error("credential-status: nobody is signed in");
855
+ if (typeof selection !== "string") throw new Error("credential-status: the credential must be a secret knob's name");
856
+ return { name: selection, principal };
857
+ }
858
+ function credentialStatusConnected(value, principal) {
859
+ return value !== void 0 && (principal !== void 0 || value !== "");
860
+ }
861
+ var UseDeclarationSchema = z.object({
862
+ from: z.string().min(1, "Import source is required"),
863
+ as: z.string().min(1, "Alias is required").regex(
864
+ /^[A-Z][a-zA-Z0-9]*$/,
865
+ 'Alias must be PascalCase (e.g., "Health", "GameCore")'
866
+ ),
867
+ config: DeclaredTraitConfigSchema.optional(),
868
+ lazy: z.boolean().optional()
869
+ });
870
+ var LazyTraitSchema = z.object({
871
+ name: z.string().min(1),
872
+ dispatchMode: DispatchModeSchema,
873
+ listens: z.array(TraitEventListenerSchema).optional(),
874
+ backgroundTicks: z.boolean().optional()
875
+ });
876
+ var LazyPageSchema = z.object({
877
+ path: z.string().min(1),
878
+ orbital: z.string().min(1),
879
+ orbRef: z.string().min(1),
880
+ links: z.array(z.string()).optional(),
881
+ protocol: z.string().optional(),
882
+ after: z.string().optional(),
883
+ places: z.array(z.string()).optional(),
884
+ traits: z.array(LazyTraitSchema).optional()
885
+ });
886
+ function expectedEntityName(decl) {
887
+ switch (decl.kind) {
888
+ case "entity":
889
+ return decl.name;
890
+ case "identity":
891
+ return decl.name;
892
+ case "event":
893
+ case "page":
894
+ case "state":
895
+ case "transition":
896
+ case "config":
897
+ return void 0;
898
+ }
899
+ }
900
+ var ExpectDeclarationSchema = z.discriminatedUnion("kind", [
901
+ z.object({
902
+ strict: z.boolean().optional(),
903
+ kind: z.literal("identity"),
904
+ name: z.string().optional(),
905
+ shape: z.array(EntityFieldSchema).optional()
906
+ }),
907
+ z.object({
908
+ strict: z.boolean().optional(),
909
+ kind: z.literal("entity"),
910
+ name: z.string().min(1, "Expected entity name is required"),
911
+ shape: z.array(EntityFieldSchema).optional(),
912
+ persistence: EntityPersistenceSchema.optional(),
913
+ shared: z.boolean().optional(),
914
+ browser: z.boolean().optional(),
915
+ read_policy: SExprSchema.optional(),
916
+ create_policy: SExprSchema.optional(),
917
+ update_policy: SExprSchema.optional(),
918
+ delete_policy: SExprSchema.optional(),
919
+ access_waivers: z.object({
920
+ read: z.string().optional(),
921
+ create: z.string().optional(),
922
+ update: z.string().optional(),
923
+ delete: z.string().optional()
924
+ }).optional(),
925
+ invariants: z.array(SExprSchema).optional()
926
+ }),
927
+ z.object({
928
+ strict: z.boolean().optional(),
929
+ kind: z.literal("event"),
930
+ traitName: z.string().min(1, "Expected event trait name is required"),
931
+ event: z.string().min(1, "Expected event name is required"),
932
+ payload: z.array(EventPayloadFieldSchema).optional()
933
+ }),
934
+ z.object({
935
+ strict: z.boolean().optional(),
936
+ kind: z.literal("page"),
937
+ path: z.string().min(1, "Expected page path is required"),
938
+ traits: z.array(z.string().min(1)).optional()
939
+ }),
940
+ z.object({
941
+ strict: z.boolean().optional(),
942
+ kind: z.literal("state"),
943
+ traitName: z.string().min(1, "Expected state trait name is required"),
944
+ state: z.string().min(1, "Expected state name is required"),
945
+ holds: SExprSchema.optional()
946
+ }),
947
+ z.object({
948
+ strict: z.boolean().optional(),
949
+ kind: z.literal("transition"),
950
+ traitName: z.string().min(1, "Expected transition trait name is required"),
951
+ from: z.string().min(1),
952
+ event: z.string().min(1),
953
+ to: z.string().min(1),
954
+ ensures: SExprListSchema.optional()
955
+ }),
956
+ z.object({
957
+ strict: z.boolean().optional(),
958
+ kind: z.literal("config"),
959
+ name: z.string().min(1, "Expected config knob name is required"),
960
+ knob: ConfigFieldDeclarationSchema
961
+ })
962
+ ]);
963
+ var ExpectationDiagnosticSchema = z.object({
964
+ kind: z.enum(["unknown-orbital", "identity-field-not-declared", "entity-field-not-declared", "event-source-unknown"]),
965
+ orbital: z.string(),
966
+ entity: z.string().optional(),
967
+ field: z.string().optional()
968
+ }).strict();
969
+ var OrganismExpectationsSchema = z.record(
970
+ z.string(),
971
+ z.object({ expectations: z.array(ExpectDeclarationSchema), diagnostics: z.array(ExpectationDiagnosticSchema) }).strict()
972
+ );
973
+ function isEntityReference(entity) {
974
+ return typeof entity === "string";
975
+ }
976
+ function isEntityCall(entity) {
977
+ return typeof entity === "object" && entity !== null && "extends" in entity;
978
+ }
979
+ function isEntityReferenceAny(entity) {
980
+ return isEntityReference(entity) || isEntityCall(entity);
981
+ }
982
+ var EntityRefStringSchema = z.string().regex(
983
+ /^[A-Z][a-zA-Z0-9]*(\.orbitals\.[A-Z][a-zA-Z0-9]*)?\.entity$/,
984
+ 'Entity reference must be in format "Alias.entity" (e.g., "Goblin.entity") or "Alias.orbitals.Name.entity"'
985
+ );
986
+ var EntityCallSchema = z.object({
987
+ extends: z.string().regex(
988
+ /^[A-Z][a-zA-Z0-9]*\.entity$/,
989
+ 'EntityCall "extends" must be in format "Alias.entity"'
990
+ ),
991
+ name: z.string().optional(),
992
+ fields: z.array(EntityFieldSchema).optional(),
993
+ persistence: EntityPersistenceSchema.optional(),
994
+ collection: z.string().optional()
995
+ }).refine(
996
+ (call) => {
997
+ if (!call.fields) return true;
998
+ const seen = /* @__PURE__ */ new Set();
999
+ for (const field of call.fields) {
1000
+ if (field.name === void 0) continue;
1001
+ if (seen.has(field.name)) return false;
1002
+ seen.add(field.name);
1003
+ }
1004
+ return true;
1005
+ },
1006
+ {
1007
+ message: 'EntityCall "fields" override list must not contain duplicate field names',
1008
+ path: ["fields"]
1009
+ }
1010
+ );
1011
+ var EntityRefSchema = z.union([
1012
+ EntitySchema,
1013
+ EntityRefStringSchema,
1014
+ EntityCallSchema
1015
+ ]);
1016
+ function isPageReferenceString(page) {
1017
+ return typeof page === "string";
1018
+ }
1019
+ function isPageReferenceObject(page) {
1020
+ return typeof page === "object" && "ref" in page && !("name" in page);
1021
+ }
1022
+ function isPageReference(page) {
1023
+ return isPageReferenceString(page) || isPageReferenceObject(page);
1024
+ }
1025
+ var PageRefStringSchema = z.string().regex(
1026
+ /^[A-Z][a-zA-Z0-9]*\.pages\.[A-Z][a-zA-Z0-9]*$/,
1027
+ 'Page reference must be in format "Alias.pages.PageName" (e.g., "User.pages.Profile")'
1028
+ );
1029
+ var PageRefObjectSchema = z.object({
1030
+ ref: PageRefStringSchema,
1031
+ refId: PageIdSchema.optional(),
1032
+ // Phase 1.2: optional registry path disambiguator, pairs with `ref`.
1033
+ from: z.string().optional(),
1034
+ path: z.string().startsWith("/").optional(),
1035
+ linkedEntity: z.string().optional(),
1036
+ linkedEntityId: EntityIdSchema.optional(),
1037
+ traits: z.array(TraitRefSchema).optional(),
1038
+ traitRefIds: z.array(TraitIdSchema).optional(),
1039
+ access: PageAccessSchema.optional(),
1040
+ indexing: PageIndexingSchema.optional(),
1041
+ title: PageMetaSchema.optional(),
1042
+ description: PageMetaSchema.optional(),
1043
+ translationOf: z.string().min(1).optional(),
1044
+ label: z.string().optional(),
1045
+ icon: z.string().optional(),
1046
+ roles: z.array(z.string().min(1)).min(1).optional()
1047
+ });
1048
+ var PageRefSchema = z.union([
1049
+ PageSchema,
1050
+ PageRefStringSchema,
1051
+ PageRefObjectSchema
1052
+ ]);
1053
+ var OrbitalRefStringSchema = z.string().regex(
1054
+ /^[A-Z][a-zA-Z0-9]*\.orbitals\.[A-Z][a-zA-Z0-9]*$/,
1055
+ 'Orbital reference must be "Alias.orbitals.OrbitalName"'
1056
+ );
1057
+ var OrbitalRefObjectSchema = z.object({
1058
+ ref: OrbitalRefStringSchema,
1059
+ refId: OrbitalIdSchema.optional(),
1060
+ entity: z.string().optional(),
1061
+ fields: z.record(z.string(), z.string()).optional(),
1062
+ pages: z.record(z.string(), z.string()).optional(),
1063
+ pageModifiers: z.record(z.string(), PageModifiersSchema).optional(),
1064
+ omit: z.array(z.string()).optional(),
1065
+ only: z.array(z.string()).optional(),
1066
+ config: DeclaredTraitConfigSchema.optional(),
1067
+ events: z.record(z.string(), z.string()).optional(),
1068
+ roles: z.record(z.string(), z.array(z.string())).optional(),
1069
+ entities: z.record(z.string(), z.string()).optional(),
1070
+ mounts: z.record(z.string(), z.array(z.string())).optional(),
1071
+ extend: z.array(EntityFieldSchema).optional(),
1072
+ mock: z.record(z.string(), z.string()).optional(),
1073
+ retype: z.array(EntityFieldSchema).optional(),
1074
+ persistence: EntityPersistenceSchema.optional(),
1075
+ collection: z.string().optional(),
1076
+ shared: z.boolean().optional(),
1077
+ identity: z.boolean().optional(),
1078
+ browser: z.boolean().optional(),
1079
+ traits: z.record(
1080
+ z.string(),
1081
+ z.object({
1082
+ linkedEntity: z.string().optional(),
1083
+ config: DeclaredTraitConfigSchema.optional(),
1084
+ events: z.record(z.string(), z.string()).optional(),
1085
+ fields: z.record(z.string(), z.string()).optional(),
1086
+ listens: z.array(TraitEventListenerSchema).optional(),
1087
+ emitsScope: EventScopeSchema.optional(),
1088
+ dispatch: TraitDispatchModeSchema.optional()
1089
+ })
1090
+ ).optional(),
1091
+ listens: z.array(TraitEventListenerSchema.extend({ trait: z.string() })).optional()
1092
+ });
1093
+ function parseOrbitalRef(ref) {
1094
+ const match = ref.match(/^([A-Z][a-zA-Z0-9]*)\.orbitals\.([A-Z][a-zA-Z0-9]*)$/);
1095
+ if (!match) return null;
1096
+ return { alias: match[1], orbitalName: match[2] };
1097
+ }
1098
+ z.string().regex(
1099
+ /^([A-Z][a-zA-Z0-9]*\.traits\.)?[A-Z][a-zA-Z0-9]*$/,
1100
+ 'Trait reference must be "TraitName" or "Alias.traits.TraitName"'
1101
+ );
1102
+ function isImportedTraitRef(ref) {
1103
+ return /^[A-Z][a-zA-Z0-9]*\.traits\.[A-Z][a-zA-Z0-9]*$/.test(ref);
1104
+ }
1105
+ function parseImportedTraitRef(ref) {
1106
+ const match = ref.match(/^([A-Z][a-zA-Z0-9]*)\.traits\.([A-Z][a-zA-Z0-9]*)$/);
1107
+ if (!match) return null;
1108
+ return { alias: match[1], traitName: match[2] };
1109
+ }
1110
+ function parseEntityRef(ref) {
1111
+ const match = ref.match(/^([A-Z][a-zA-Z0-9]*)\.entity$/);
1112
+ if (!match) return null;
1113
+ return { alias: match[1] };
1114
+ }
1115
+ function parsePageRef(ref) {
1116
+ const match = ref.match(/^([A-Z][a-zA-Z0-9]*)\.pages\.([A-Z][a-zA-Z0-9]*)$/);
1117
+ if (!match) return null;
1118
+ return { alias: match[1], pageName: match[2] };
1119
+ }
1120
+ var EventListenerSchema = z.object({
1121
+ event: z.string().min(1),
1122
+ triggers: z.string().min(1),
1123
+ guard: z.string().optional()
1124
+ });
1125
+ var EventSourceSchema = z.object({
1126
+ trait: z.string().min(1),
1127
+ transition: z.string().optional(),
1128
+ tick: z.string().optional()
1129
+ });
1130
+ var ComputedEventContractSchema = z.object({
1131
+ event: z.string().min(1),
1132
+ originalEvent: z.string().min(1),
1133
+ source: EventSourceSchema,
1134
+ description: z.string().optional(),
1135
+ payload: z.array(EventPayloadFieldSchema).optional()
1136
+ });
1137
+ var ComputedEventListenerSchema = z.object({
1138
+ event: z.string().min(1),
1139
+ source: EventSourceSchema,
1140
+ triggers: z.string().min(1),
1141
+ guard: ExpressionSchema.optional(),
1142
+ payloadMapping: z.record(z.string(), SExprSchema).optional()
1143
+ });
1144
+ var TypeAliasMembersSchema = z.union([
1145
+ z.array(EventPayloadFieldSchema),
1146
+ z.tuple([EventPayloadTypeMemberSchema.refine((field) => field.name === "", "An unnamed alias member requires an empty name")])
1147
+ ]);
1148
+ var OrbitalDefinitionSchema = z.object({
1149
+ id: OrbitalIdSchema.optional(),
1150
+ name: z.string().min(1, "Orbital name is required"),
1151
+ description: z.string().optional(),
1152
+ visual_prompt: z.string().optional(),
1153
+ // Import system
1154
+ uses: z.array(UseDeclarationSchema).optional(),
1155
+ // Consumer-side requirement declarations (`.lolo` `expects ...`)
1156
+ expects: z.array(ExpectDeclarationSchema).optional(),
1157
+ spec: z.boolean().optional(),
1158
+ // Theme & Services
1159
+ theme: ThemeRefSchema.optional(),
1160
+ services: z.array(ServiceRefSchema).optional(),
1161
+ // Components (inline or reference)
1162
+ entity: EntityRefSchema,
1163
+ // Mirrors the `OrbitalDefinition.auxiliaryEntities` type field — WAS
1164
+ // undeclared here, so `OrbitalSchemaSchema.safeParse` (every load through
1165
+ // `external-loader.ts`) silently stripped it on every externally-loaded
1166
+ // orbital (zod drops unrecognized keys by default), while a schema parsed
1167
+ // directly via `JSON.parse` kept it. Found via the entity-field auto-merge
1168
+ // rebind-target fallback landing on the wrong entity for any RECURSIVELY
1169
+ // loaded `uses` file (`packages/almadar-runtime/src/resolver/
1170
+ // reference-resolver.ts`'s `mergeImportedEntityFieldsIntoOrbital`).
1171
+ auxiliaryEntities: z.array(EntityRefSchema).optional(),
1172
+ traits: z.array(TraitRefSchema),
1173
+ // A reference-form orbital's pages come from its upstream until inline.
1174
+ pages: z.array(PageRefSchema).default([]),
1175
+ // Event interface (trait-centric model) - computed by resolver
1176
+ emits: z.array(ComputedEventContractSchema).optional(),
1177
+ listens: z.array(ComputedEventListenerSchema).optional(),
1178
+ // Filter for exposed events (trait-centric model)
1179
+ exposes: z.array(z.string()).optional(),
1180
+ osGrants: OsGrantsSchema.optional(),
1181
+ // This orbital's own declared knobs (§4.5)
1182
+ config: DeclaredTraitConfigSchema.optional(),
1183
+ // Transient — set by lowering, cleared by inline/resolve
1184
+ reference: OrbitalRefObjectSchema.optional(),
1185
+ // Context fields - persisted throughout orbital lifecycle
1186
+ domainContext: DomainContextSchema.optional(),
1187
+ design: DesignPreferencesSchema.optional(),
1188
+ suggestedGuards: z.array(SuggestedGuardSchema).optional(),
1189
+ types: z.record(z.string(), TypeAliasMembersSchema).optional()
1190
+ }).superRefine((orbital, ctx) => {
1191
+ if (orbital.spec === true) return;
1192
+ const entities = [[orbital.entity, ["entity"]], ...(orbital.auxiliaryEntities ?? []).map((e, i) => [e, ["auxiliaryEntities", i]])];
1193
+ for (const [entity, path] of entities) {
1194
+ if (!isEntityReferenceAny(entity) && entity.fields.length === 0) {
1195
+ ctx.addIssue({ code: "too_small", minimum: 1, origin: "array", inclusive: true, path: [...path, "fields"], message: "At least one field is required" });
1196
+ }
1197
+ }
1198
+ });
1199
+ var OrbitalSchema = OrbitalDefinitionSchema;
1200
+ function unwrapTraitRef(traitRef) {
1201
+ if (typeof traitRef === "string" || isInlineTrait(traitRef) || traitRef._resolved === void 0) {
1202
+ return { trait: traitRef };
1203
+ }
1204
+ return traitRef.config === void 0 ? { trait: traitRef._resolved } : { trait: traitRef._resolved, config: traitRef.config };
1205
+ }
1206
+ function inlineTraitRefs(orbitals) {
1207
+ return orbitals.map((orbital) => ({
1208
+ ...orbital,
1209
+ traits: orbital.traits.map((traitRef) => {
1210
+ const { trait, config } = unwrapTraitRef(traitRef);
1211
+ if (config === void 0 || typeof trait === "string" || !isInlineTrait(trait)) return trait;
1212
+ return { ...trait, config: mergeCallSiteConfigOverrides(trait.config ?? {}, config) };
1213
+ })
1214
+ }));
1215
+ }
1216
+ function isOrbitalDefinition(orbital) {
1217
+ return "entity" in orbital;
1218
+ }
1219
+ var OrbitalUnitSchema = OrbitalSchema;
1220
+ var ProtocolSideSchema2 = z.enum(["client", "server", "process", "start"]);
1221
+ var ProtocolGrantSchema = z.enum(["net-listen", "stdio"]);
1222
+ var ProtocolAddressFieldSchema = z.strictObject({
1223
+ name: z.string().min(1),
1224
+ type: z.string().min(1),
1225
+ required: z.boolean()
1226
+ });
1227
+ var ProtocolSpecSchema2 = z.strictObject({
1228
+ name: z.string().min(1),
1229
+ address: z.array(ProtocolAddressFieldSchema).nullable(),
1230
+ viewer: z.boolean(),
1231
+ grant: ProtocolGrantSchema.nullable(),
1232
+ side: ProtocolSideSchema2
1233
+ });
1234
+
1235
+ // src/types/schema.ts
1236
+ var HOST_SIGN_IN_ROUTE = "/login";
1237
+ function isHostSignInRoute(path) {
1238
+ return path.replace(/\/+$/, "") === HOST_SIGN_IN_ROUTE;
1239
+ }
1240
+ var SiteMetaSchema = z.object({
1241
+ origin: z.string().url().optional(),
1242
+ icon: z.string().min(1).optional(),
1243
+ name: z.string().min(1).optional(),
1244
+ signIn: z.string().startsWith("/").optional()
1245
+ }).strict();
1246
+ var ConfigProvenanceRecordSchema = z.object({
1247
+ trait: z.string(),
1248
+ patternPath: z.string().optional(),
1249
+ prop: z.string(),
1250
+ knob: z.string()
1251
+ });
1252
+ var SchemaMetadataSchema = z.object({
1253
+ version: z.number().optional(),
1254
+ createdAt: z.number().optional(),
1255
+ source: z.string().optional(),
1256
+ updatedAt: z.number().optional(),
1257
+ configProvenance: z.record(z.string(), z.array(ConfigProvenanceRecordSchema)).optional(),
1258
+ messageSources: z.record(z.string(), z.string()).optional(),
1259
+ operatorSites: z.record(z.string(), z.enum(["client", "server", "any"])).optional(),
1260
+ dispatchFacts: z.object({ busExcluded: z.array(z.string()), targetOptions: z.array(z.string()) }).optional(),
1261
+ protocols: z.array(ProtocolSpecSchema2).optional()
1262
+ });
1263
+ var OrbitalSchemaSchema = z.object({
1264
+ types: z.record(z.string(), TypeAliasMembersSchema).optional(),
1265
+ typeContractVersion: z.literal(1).optional(),
1266
+ resolved: z.object({ orb: z.string(), typeContractVersion: z.literal(2) }).optional(),
1267
+ name: z.string().min(1, "Schema name is required"),
1268
+ description: z.string().optional(),
1269
+ theme: ThemeRefSchema.optional(),
1270
+ themes: z.array(z.string().min(1)).optional(),
1271
+ themeDefinitions: z.array(ThemeDefinitionSchema).optional(),
1272
+ summary: z.string().optional(),
1273
+ version: z.string().optional(),
1274
+ domainContext: DomainContextSchema.optional(),
1275
+ design: DesignPreferencesSchema.optional(),
1276
+ designTokens: DesignTokensSchema,
1277
+ customPatterns: CustomPatternMapSchema,
1278
+ orbitals: z.array(OrbitalSchema).min(1, "At least one orbital is required"),
1279
+ locales: z.array(z.string().min(1)).optional(),
1280
+ messages: z.record(z.string(), z.record(z.string(), z.string())).optional(),
1281
+ publicDir: z.string().min(1).optional(),
1282
+ store: z.string().min(1).optional(),
1283
+ egress: z.array(z.string().min(1)).optional(),
1284
+ osGrants: OsGrantsSchema.optional(),
1285
+ deployment: DeploymentSchema.optional(),
1286
+ inbound: z.array(z.string().min(1)).optional(),
1287
+ site: SiteMetaSchema.optional(),
1288
+ lazyPages: z.array(LazyPageSchema).optional(),
1289
+ services: z.array(ServiceDefinitionSchema).optional(),
1290
+ config: DeclaredTraitConfigSchema.optional(),
1291
+ _metadata: SchemaMetadataSchema.optional(),
1292
+ // V4 identity — optional/dual-carry until the Phase-7 flip. Present on
1293
+ // id-carrying `.orb` files so `parseOrbitalSchema` preserves them instead
1294
+ // of stripping unknown keys.
1295
+ schemaVersion: z.number().optional(),
1296
+ ledger: IdentityLedgerSchema.optional()
1297
+ });
1298
+ function parseOrbitalSchema(data) {
1299
+ return OrbitalSchemaSchema.parse(data);
1300
+ }
1301
+ function safeParseOrbitalSchema(data) {
1302
+ return OrbitalSchemaSchema.safeParse(data);
1303
+ }
1304
+ var TRAITS_SEGMENT = ".traits.";
1305
+ var ORBITALS_SEGMENT = ".orbitals.";
1306
+ var PASCAL = /^[A-Z][A-Za-z0-9]*$/;
1307
+ var SPECIFIER = /^(?:[a-z0-9][a-z0-9-]*(?:\/behaviors)?|\.(?:\/[A-Za-z0-9_-]+)+)\/[A-Za-z0-9][A-Za-z0-9_-]*$/;
1308
+ function splitLiteral(raw, segment) {
1309
+ const at = raw.lastIndexOf(segment);
1310
+ if (at <= 0) return void 0;
1311
+ const behavior = raw.slice(0, at);
1312
+ const name = raw.slice(at + segment.length);
1313
+ if (!SPECIFIER.test(behavior) || !PASCAL.test(name)) return void 0;
1314
+ return { behavior, name };
1315
+ }
1316
+ function parseTraitValueLiteral(raw) {
1317
+ const parts = splitLiteral(raw, TRAITS_SEGMENT);
1318
+ return parts === void 0 ? void 0 : { behavior: parts.behavior, trait: parts.name };
1319
+ }
1320
+ function parseOrbitalValueLiteral(raw) {
1321
+ const parts = splitLiteral(raw, ORBITALS_SEGMENT);
1322
+ return parts === void 0 ? void 0 : { behavior: parts.behavior, orbital: parts.name };
1323
+ }
1324
+ function parseBehaviorValueLiteral(raw) {
1325
+ return parseTraitValueLiteral(raw) ?? parseOrbitalValueLiteral(raw);
1326
+ }
1327
+ function formatTraitValueLiteral(value) {
1328
+ return `${value.behavior}${TRAITS_SEGMENT}${value.trait}`;
1329
+ }
1330
+ function formatOrbitalValueLiteral(value) {
1331
+ return `${value.behavior}${ORBITALS_SEGMENT}${value.orbital}`;
1332
+ }
1333
+ function formatBehaviorValueLiteral(value) {
1334
+ return isOrbitalValueShape(value) ? formatOrbitalValueLiteral(value) : formatTraitValueLiteral(value);
1335
+ }
1336
+ var TraitOverridesSchema = TraitReferenceObjectSchema.pick({
1337
+ config: true,
1338
+ events: true,
1339
+ fields: true,
1340
+ listens: true,
1341
+ emitsScope: true,
1342
+ linkedEntity: true
1343
+ }).strict();
1344
+ var TraitValueSchema = TraitOverridesSchema.extend({
1345
+ behavior: z.string().regex(SPECIFIER),
1346
+ trait: z.string().regex(PASCAL)
1347
+ }).strict();
1348
+ var OrbitalValueUseSchema = z.object({ from: z.string(), as: z.string().regex(PASCAL) }).strict();
1349
+ var OrbitalValueSiblingSchema = z.object({
1350
+ name: z.string().regex(PASCAL),
1351
+ ref: z.string(),
1352
+ linkedEntity: z.string().optional(),
1353
+ config: z.record(z.string(), TraitConfigValueSchema).optional()
1354
+ }).strict();
1355
+ var OrbitalOverridesSchema = OrbitalRefObjectSchema.omit({ ref: true, refId: true, config: true, traits: true }).extend({
1356
+ name: z.string().regex(PASCAL).optional(),
1357
+ app: z.record(z.string(), TraitConfigValueSchema).optional(),
1358
+ config: z.record(z.string(), TraitConfigValueSchema).optional(),
1359
+ traits: z.record(z.string(), TraitOverridesSchema).optional(),
1360
+ uses: z.array(OrbitalValueUseSchema).optional(),
1361
+ siblings: z.array(OrbitalValueSiblingSchema).optional()
1362
+ }).strict();
1363
+ var OrbitalValueSchema = OrbitalOverridesSchema.extend({
1364
+ behavior: z.string().regex(SPECIFIER),
1365
+ orbital: z.string().regex(PASCAL)
1366
+ }).strict();
1367
+ var BehaviorValueSchema = z.union([TraitValueSchema, OrbitalValueSchema]);
1368
+ function mergeTraitOverrides(base, overrides) {
1369
+ const merged = { ...base };
1370
+ if (overrides.config !== void 0) merged.config = { ...base.config, ...overrides.config };
1371
+ if (overrides.events !== void 0) merged.events = { ...base.events, ...overrides.events };
1372
+ if (overrides.fields !== void 0) merged.fields = { ...base.fields, ...overrides.fields };
1373
+ if (overrides.listens !== void 0) merged.listens = overrides.listens;
1374
+ if (overrides.emitsScope !== void 0) merged.emitsScope = overrides.emitsScope;
1375
+ if (overrides.linkedEntity !== void 0) merged.linkedEntity = overrides.linkedEntity;
1376
+ return merged;
1377
+ }
1378
+ function applyTraitOverrides(value, overrides) {
1379
+ return { ...mergeTraitOverrides(value, overrides), behavior: value.behavior, trait: value.trait };
1380
+ }
1381
+ function mergeFieldsByName(base, next) {
1382
+ const out = [...base ?? []];
1383
+ for (const field of next) {
1384
+ const at = field.name === void 0 ? -1 : out.findIndex((f) => f.name === field.name);
1385
+ if (at >= 0) out[at] = field;
1386
+ else out.push(field);
1387
+ }
1388
+ return out;
1389
+ }
1390
+ function applyOrbitalOverrides(value, overrides) {
1391
+ const merged = { ...value, ...overrides, behavior: value.behavior, orbital: value.orbital };
1392
+ if (overrides.app !== void 0) merged.app = { ...value.app, ...overrides.app };
1393
+ if (overrides.config !== void 0) merged.config = { ...value.config, ...overrides.config };
1394
+ if (overrides.events !== void 0) merged.events = { ...value.events, ...overrides.events };
1395
+ if (overrides.fields !== void 0) merged.fields = { ...value.fields, ...overrides.fields };
1396
+ if (overrides.pages !== void 0) merged.pages = { ...value.pages, ...overrides.pages };
1397
+ if (overrides.pageModifiers !== void 0) merged.pageModifiers = { ...value.pageModifiers, ...overrides.pageModifiers };
1398
+ if (overrides.roles !== void 0) merged.roles = { ...value.roles, ...overrides.roles };
1399
+ if (overrides.entities !== void 0) merged.entities = { ...value.entities, ...overrides.entities };
1400
+ if (overrides.mounts !== void 0) merged.mounts = { ...value.mounts, ...overrides.mounts };
1401
+ if (overrides.mock !== void 0) merged.mock = { ...value.mock, ...overrides.mock };
1402
+ if (overrides.extend !== void 0) merged.extend = mergeFieldsByName(value.extend, overrides.extend);
1403
+ if (overrides.retype !== void 0) merged.retype = mergeFieldsByName(value.retype, overrides.retype);
1404
+ if (overrides.uses !== void 0) {
1405
+ const byAlias = new Map((value.uses ?? []).map((u) => [u.as, u]));
1406
+ for (const use of overrides.uses) byAlias.set(use.as, use);
1407
+ merged.uses = [...byAlias.values()];
1408
+ }
1409
+ if (overrides.siblings !== void 0) {
1410
+ const byName = new Map((value.siblings ?? []).map((t) => [t.name, t]));
1411
+ for (const sibling of overrides.siblings) {
1412
+ const prior = byName.get(sibling.name);
1413
+ byName.set(sibling.name, { ...prior, ...sibling, ...prior?.config !== void 0 || sibling.config !== void 0 ? { config: { ...prior?.config, ...sibling.config } } : {} });
1414
+ }
1415
+ merged.siblings = [...byName.values()];
1416
+ }
1417
+ if (overrides.traits !== void 0) {
1418
+ const traits = { ...value.traits };
1419
+ for (const [name, entry] of Object.entries(overrides.traits)) {
1420
+ traits[name] = mergeTraitOverrides(traits[name] ?? {}, entry);
1421
+ }
1422
+ merged.traits = traits;
1423
+ }
1424
+ return merged;
1425
+ }
1426
+ function applyBehaviorOverrides(value, overrides) {
1427
+ if (isOrbitalValueShape(value)) return applyOrbitalOverrides(value, OrbitalOverridesSchema.parse(overrides));
1428
+ return applyTraitOverrides(value, TraitOverridesSchema.parse(overrides));
1429
+ }
1430
+ function isTraitValue(value) {
1431
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1432
+ if (!("behavior" in value) || !("trait" in value)) return false;
1433
+ const { behavior, trait } = value;
1434
+ return typeof behavior === "string" && SPECIFIER.test(behavior) && typeof trait === "string" && PASCAL.test(trait);
1435
+ }
1436
+ function isOrbitalValue(value) {
1437
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1438
+ if (!("behavior" in value) || !("orbital" in value)) return false;
1439
+ const { behavior, orbital } = value;
1440
+ return typeof behavior === "string" && SPECIFIER.test(behavior) && typeof orbital === "string" && PASCAL.test(orbital);
1441
+ }
1442
+ function behaviorRef(specifier) {
1443
+ if (!SPECIFIER.test(specifier)) {
1444
+ throw new Error(`behavior/ref: "${specifier}" is not a behavior specifier (<prefix>/<name>, std/behaviors/<name> or ./<dir>/<name>)`);
1445
+ }
1446
+ return { behavior: specifier };
1447
+ }
1448
+ function isBehaviorRefValue(value) {
1449
+ return BehaviorRefSchema.safeParse(value).success;
1450
+ }
1451
+ function isOrbitalValueShape(value) {
1452
+ return "orbital" in value;
1453
+ }
1454
+ var EXPOSURES = ["app", "experience", "palette", "both", "internal"];
1455
+ var VectorSchema = z.array(z.number());
1456
+ var CatalogScopeSchema = z.object({
1457
+ paths: z.array(z.string().min(1)).min(1),
1458
+ exposure: z.array(z.enum(EXPOSURES)).optional()
1459
+ }).strict();
1460
+ var BehaviorRefSchema = z.object({ behavior: z.string().regex(SPECIFIER) }).strict();
1461
+ var CatalogEntrySchema = z.object({
1462
+ /** `<prefix>/<name>`. */
1463
+ behavior: z.string(),
1464
+ package: z.string(),
1465
+ topic: z.string(),
1466
+ level: z.enum(["atom", "molecule", "organism"]),
1467
+ exposure: z.enum(EXPOSURES).optional(),
1468
+ /** The `@almadar/ui` pattern the behavior is the factory of (`;; @pattern`); absent when it is not one. */
1469
+ pattern: z.string().optional(),
1470
+ description: z.string(),
1471
+ capabilities: z.array(z.string()),
1472
+ /** The behavior's traits as ready-to-bind values; absent in a listing asked for without traits (`traits: false`). */
1473
+ traits: z.array(TraitValueSchema).optional(),
1474
+ /** The behavior as a value (`.lolo` type `behavior`), ready to store. */
1475
+ value: BehaviorRefSchema,
1476
+ /** Shipped embedding vectors, keyed by facet (`description`, `capabilities`). */
1477
+ vectors: z.record(z.string(), VectorSchema),
1478
+ /** The embedding model the vectors were stamped with. */
1479
+ model: z.string()
1480
+ }).strict();
1481
+ var TraitKnobSchema = z.object({
1482
+ key: z.string(),
1483
+ type: z.string(),
1484
+ default: TraitConfigValueSchema.optional(),
1485
+ label: z.string().optional(),
1486
+ description: z.string().optional(),
1487
+ tier: z.string().optional(),
1488
+ vector: VectorSchema.optional()
1489
+ }).strict();
1490
+ var TraitEventsSchema = z.object({
1491
+ emits: z.array(z.string()),
1492
+ listens: z.array(z.string()),
1493
+ transitions: z.array(z.string()),
1494
+ domain: z.array(z.string()).optional()
1495
+ }).strict();
1496
+ var TraitMachineObject = z.object({
1497
+ linkedEntity: z.string().optional(),
1498
+ stateMachine: StateMachineSchema
1499
+ }).strict();
1500
+ var TraitMachineSchema = TraitMachineObject;
1501
+ var TraitSourceSchema = z.object({
1502
+ text: z.string(),
1503
+ transitions: z.array(z.object({ index: z.number().int(), start: z.number().int(), end: z.number().int() }).strict())
1504
+ }).strict();
1505
+ var TraitDescriptionObject = z.object({
1506
+ value: TraitValueSchema,
1507
+ knobs: z.array(TraitKnobSchema),
1508
+ events: TraitEventsSchema,
1509
+ machine: TraitMachineSchema.optional(),
1510
+ source: TraitSourceSchema.optional(),
1511
+ model: z.string()
1512
+ }).strict();
1513
+ var TraitDescriptionSchema = TraitDescriptionObject;
1514
+ var DescribeTargetSchema = z.union([TraitValueSchema, OrbitalValueSchema, BehaviorRefSchema]);
1515
+ var KnobFieldSchema = z.lazy(
1516
+ () => z.object({
1517
+ name: z.string(),
1518
+ type: z.string(),
1519
+ required: z.boolean().optional(),
1520
+ values: z.array(z.string()).optional(),
1521
+ properties: z.array(KnobFieldSchema).optional(),
1522
+ default: TraitConfigValueSchema.optional(),
1523
+ label: z.string().optional(),
1524
+ description: z.string().optional(),
1525
+ synonyms: z.string().optional(),
1526
+ tier: z.string().optional(),
1527
+ forwardedFrom: z.string().optional()
1528
+ }).strict()
1529
+ );
1530
+ var OrbitalDescriptionSchema = z.object({
1531
+ value: OrbitalValueSchema,
1532
+ config: DeclaredTraitConfigSchema,
1533
+ knobs: z.array(KnobFieldSchema),
1534
+ entity: z.object({ name: z.string(), fields: z.array(EntityFieldSchema), identity: z.boolean().optional(), persistence: EntityPersistenceSchema.optional() }).strict().optional(),
1535
+ /** Entities a sibling orbital owns that this one references: what an import of it maps through `entities {}`. */
1536
+ borrows: z.array(z.string()),
1537
+ /** What the orbital needs from its siblings at runtime, derived by `orb` (identity, entities, pages, events). */
1538
+ expects: z.array(ExpectDeclarationSchema),
1539
+ traits: z.array(z.object({
1540
+ trait: z.string(),
1541
+ config: DeclaredTraitConfigSchema,
1542
+ knobs: z.array(KnobFieldSchema),
1543
+ events: TraitEventsSchema,
1544
+ /** Declared `-> @rebindable`: the trait may be bound to another record. */
1545
+ rebindable: z.boolean().optional(),
1546
+ /** The upstream trait this one composes (`trait X = Alias.traits.Y`), as written; absent for a trait the behavior defines itself. */
1547
+ ref: z.string().optional(),
1548
+ /** The trait's declared `@capabilities` tags. */
1549
+ capabilities: z.array(z.string()).optional()
1550
+ }).strict()),
1551
+ /** Each page with the traits it mounts: what the behavior declares as standing on its own. */
1552
+ pages: z.array(z.object({ name: z.string(), path: z.string(), traits: z.array(z.string()).optional(), label: z.string().optional(), icon: z.string().optional() }).strict()),
1553
+ /** Controls the orbital leaves for an embedding organism (`emitsScope external`) that nothing in it handles: an importer must route each. */
1554
+ forwards: z.array(z.object({ trait: z.string(), event: z.string(), via: z.array(z.string()) }).strict()).optional()
1555
+ }).strict();
1556
+ var BehaviorDescriptionSchema = z.object({
1557
+ behavior: z.string(),
1558
+ config: DeclaredTraitConfigSchema,
1559
+ knobs: z.array(KnobFieldSchema),
1560
+ orbitals: z.array(OrbitalDescriptionSchema),
1561
+ /** The behaviors this one imports (`uses … from`): what it already contains. */
1562
+ uses: z.array(z.string()).optional()
1563
+ }).strict();
1564
+
1565
+ export { AwaitRenderSchema, BehaviorDescriptionSchema, BehaviorRefSchema, BehaviorValueSchema, CONFIG_REF_EVENT_PATTERN, CatalogEntrySchema, CatalogScopeSchema, ComputedEventContractSchema, ComputedEventListenerSchema, ConfigFieldDeclarationSchema, ConfigProvenanceRecordSchema, DeclaredTraitConfigSchema, DeploymentSchema, DescribeTargetSchema, DispatchModeSchema, EntityCallSchema, EntityFieldContractSchema, EntityRefSchema, EntityRefStringSchema, EventListenerSchema, EventPayloadFieldSchema, EventSchema, EventScopeSchema, EventSourceSchema, ExpectDeclarationSchema, ExpectationDiagnosticSchema, GuardSchema, HOST_SIGN_IN_ROUTE, InboundVerificationSchema, KnobFieldSchema, LazyPageSchema, LazyTraitSchema, ListenSourceSchema, McpServiceDefSchema, OrbitalDefinitionSchema, OrbitalDescriptionSchema, OrbitalOverridesSchema, OrbitalPageSchema, OrbitalPageStrictSchema, OrbitalRefObjectSchema, OrbitalRefStringSchema, OrbitalSchema, OrbitalSchemaSchema, OrbitalTraitRefSchema, OrbitalUnitSchema, OrbitalValueSchema, OrbitalValueSiblingSchema, OrbitalValueUseSchema, OrganismExpectationsSchema, OsGrantsSchema, PageAccessSchema, PageIndexingSchema, PageMetaSchema, PageModifiersSchema, PageRefObjectSchema, PageRefSchema, PageRefStringSchema, PageSchema, PageTraitRefSchema, PayloadFieldSchema, PayloadTypeWhenSchema, ProtocolSideSchema, ProtocolSpecSchema, REFERENCE_CONFIG_TYPES, ROUTE_PROTOCOL, RequiredFieldSchema, RestAuthConfigSchema, RestServiceDefSchema, SECRET_CONFIG_TYPES, SERVICE_TYPES, SKELETON_VARIANTS, SchemaMetadataSchema, ServiceDefinitionSchema, ServiceRefObjectSchema, ServiceRefSchema, ServiceRefStringSchema, ServiceTypeSchema, SiteMetaSchema, SkeletonNodeSchema, SkeletonShapeSchema, SkeletonSpecSchema, SkeletonVariantSchema, SocketEventsSchema, SocketServiceDefSchema, SourceDeclarationMetadataSchema, StateMachineSchema, StateSchema, TickIntervalSchema, TraitConfigSchema, TraitConfigValueSchema, TraitDataEntitySchema, TraitDescriptionSchema, TraitDispatchModeSchema, TraitEntityFieldSchema, TraitEventContractSchema, TraitEventListenerSchema, TraitEventsSchema, TraitKnobSchema, TraitMachineSchema, TraitOverridesSchema, TraitRefSchema, TraitReferenceSchema, TraitSchema, TraitSourceSchema, TraitTickSchema, TraitUIBindingSchema, TraitValueSchema, TransitionSchema, UseDeclarationSchema, ViewTypeSchema, applyBehaviorOverrides, applyOrbitalOverrides, applyTraitOverrides, behaviorRef, configRefEventKnob, credentialStatusConnected, credentialStorageKey, expectedEntityName, findService, formatBehaviorValueLiteral, formatOrbitalValueLiteral, formatTraitValueLiteral, getServiceNames, getTraitConfig, getTraitName, hasService, inlineTraitRefs, isBehaviorRefValue, isCallSiteConfigDeclaration, isCircuitEvent, isConfigFieldSchema, isConfigRedeclaration, isEntityCall, isEntityReference, isEntityReferenceAny, isHostSignInRoute, isImportedTraitRef, isInlineTrait, isMcpService, isOrbitalDefinition, isOrbitalValue, isPageReference, isPageReferenceObject, isPageReferenceString, isReferenceConfigType, isRestService, isRoutePage, isSecretConfigType, isServiceReference, isServiceReferenceObject, isSocketService, isTraitValue, joinEventAddress, maskSecretConfigValues, mergeCallSiteConfigOverrides, normalizeCallSiteConfigToValues, normalizeTraitRef, overrideDeclaredKnobs, parseBehaviorValueLiteral, parseEntityRef, parseImportedTraitRef, parseOrbitalRef, parseOrbitalSchema, parseOrbitalValueLiteral, parsePageRef, parseServiceRef, parseTraitValueLiteral, payloadTypeContainer, protocolName, resolveConfigRefEventName, resolveCredentialStatusIdentity, resolvePageMeta, safeParseOrbitalSchema, splitEventAddress, unionOsGrants, unwrapTraitRef };
1566
+ //# sourceMappingURL=chunk-PNGFWLHD.js.map
1567
+ //# sourceMappingURL=chunk-PNGFWLHD.js.map