@altopelago/sansa 0.14.2 → 0.15.0-rc.2

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 (156) hide show
  1. package/CHANGELOG.md +118 -1
  2. package/README.md +96 -1
  3. package/conformance/README.md +8 -0
  4. package/conformance/aeonic-anchor-claims.json +133 -0
  5. package/conformance/aeonic-arithmetic-claims.json +60 -0
  6. package/conformance/aeonic-clock-claims.json +123 -0
  7. package/conformance/aeonic-comparison-claims.json +37 -0
  8. package/conformance/aeonic-datetime-claims.json +110 -0
  9. package/conformance/aeonic-rational-arithmetic-claims.json +72 -0
  10. package/conformance/aeonic-temporal-claims.json +105 -0
  11. package/conformance/cts-claims.json +17 -3
  12. package/conformance/results/aeonic-anchor-capacity.json +452 -0
  13. package/conformance/results/aeonic-anchor-snapshot-0.1.json +39 -0
  14. package/conformance/results/aeonic-arithmetic-snapshot-0.1.json +28 -0
  15. package/conformance/results/aeonic-clock-all-snapshot-0.1.json +49 -0
  16. package/conformance/results/aeonic-clock-arithmetic-snapshot-0.1.json +48 -0
  17. package/conformance/results/aeonic-clock-capacity.json +326 -0
  18. package/conformance/results/aeonic-clock-relations-snapshot-0.1.json +48 -0
  19. package/conformance/results/aeonic-comparison-snapshot-0.1.json +19 -0
  20. package/conformance/results/aeonic-datetime-all-snapshot-0.1.json +47 -0
  21. package/conformance/results/aeonic-datetime-arithmetic-snapshot-0.1.json +46 -0
  22. package/conformance/results/aeonic-datetime-capacity.json +302 -0
  23. package/conformance/results/aeonic-datetime-relations-snapshot-0.1.json +46 -0
  24. package/conformance/results/aeonic-rational-arithmetic-capacity.json +100 -0
  25. package/conformance/results/aeonic-rational-arithmetic-snapshot-0.2.json +30 -0
  26. package/conformance/results/aeonic-temporal-all-property-addressing-2026-11-16.json +39 -0
  27. package/conformance/results/aeonic-temporal-all-snapshot-0.1.json +39 -0
  28. package/conformance/results/aeonic-temporal-calendar-property-addressing-2026-11-16.json +38 -0
  29. package/conformance/results/aeonic-temporal-calendar-snapshot-0.1.json +38 -0
  30. package/conformance/results/aeonic-temporal-capacity-property-addressing-2026-11-16.json +136 -0
  31. package/conformance/results/aeonic-temporal-capacity.json +136 -0
  32. package/conformance/results/aeonic-temporal-relations-property-addressing-2026-11-16.json +38 -0
  33. package/conformance/results/aeonic-temporal-relations-snapshot-0.1.json +38 -0
  34. package/docs/aeonic-arithmetic.md +126 -0
  35. package/docs/aeonic-comparison.md +123 -0
  36. package/docs/aeonic-rational-arithmetic.md +167 -0
  37. package/docs/aeonic-temporal-civil-anchor.md +89 -0
  38. package/docs/aeonic-temporal-civil-clock.md +100 -0
  39. package/docs/aeonic-temporal-civil-date.md +124 -0
  40. package/docs/aeonic-temporal-civil-datetime.md +122 -0
  41. package/docs/api-contract.md +130 -3
  42. package/docs/capabilities.json +106 -2
  43. package/docs/child-identity-activation.md +93 -0
  44. package/docs/child-identity-candidate.md +60 -0
  45. package/docs/child-identity-tooling.md +31 -0
  46. package/docs/child-identity-workflows.md +102 -0
  47. package/docs/empty-keys-candidate.md +29 -0
  48. package/docs/migration-0.15.0.md +75 -0
  49. package/docs/property-addressing-implementation.md +118 -0
  50. package/docs/property-resolve-implementation.md +105 -0
  51. package/docs/property-selector-support.md +65 -0
  52. package/docs/property-selectors-api.d.ts +43 -0
  53. package/docs/property-selectors-api.pyi +27 -0
  54. package/docs/property-selectors-api.rs +48 -0
  55. package/docs/property-selectors-contract.md +168 -0
  56. package/docs/query-tool.md +32 -1
  57. package/docs/selector-cursor.md +45 -0
  58. package/docs/unicode-hardening.md +41 -0
  59. package/fixtures/address-v1.json +4 -3
  60. package/fixtures/child-identity-workflows/README.md +9 -0
  61. package/fixtures/child-identity-workflows/moved.aeon +10 -0
  62. package/fixtures/child-identity-workflows/original.aeon +10 -0
  63. package/fixtures/child-identity-workflows/reordered.aeon +10 -0
  64. package/fixtures/child-identity-workflows/replacement.aeon +10 -0
  65. package/fixtures/child-identity-workflows/workflows.json +89 -0
  66. package/fixtures/property-namespace-candidate-v1.json +336 -0
  67. package/fixtures/property-parser-candidate-v1.json +705 -0
  68. package/fixtures/property-query-candidate-v1.json +398 -0
  69. package/fixtures/property-resolve-candidate-v1.json +2702 -0
  70. package/fixtures/unicode-hardening-v1.json +401 -0
  71. package/package.json +30 -3
  72. package/scripts/calibrate-aeonic-anchor-capacity.py +294 -0
  73. package/scripts/calibrate-aeonic-clock-capacity.py +62 -0
  74. package/scripts/calibrate-aeonic-datetime-capacity.py +76 -0
  75. package/scripts/calibrate-aeonic-rational-capacity.py +85 -0
  76. package/scripts/calibrate-aeonic-temporal-capacity.py +95 -0
  77. package/scripts/cts-address.mjs +6 -2
  78. package/scripts/cts-aeonic-anchor.mjs +21 -0
  79. package/scripts/cts-aeonic-arithmetic-adapter.mjs +25 -0
  80. package/scripts/cts-aeonic-arithmetic.mjs +24 -0
  81. package/scripts/cts-aeonic-clock.mjs +24 -0
  82. package/scripts/cts-aeonic-comparison-adapter.mjs +30 -0
  83. package/scripts/cts-aeonic-comparison.mjs +25 -0
  84. package/scripts/cts-aeonic-datetime.mjs +24 -0
  85. package/scripts/cts-aeonic-rational-arithmetic-adapter.mjs +25 -0
  86. package/scripts/cts-aeonic-rational-arithmetic.mjs +24 -0
  87. package/scripts/cts-aeonic-temporal-civil-anchor-adapter.mjs +26 -0
  88. package/scripts/cts-aeonic-temporal-civil-clock-adapter.mjs +28 -0
  89. package/scripts/cts-aeonic-temporal-civil-date-adapter.mjs +28 -0
  90. package/scripts/cts-aeonic-temporal-civil-datetime-adapter.mjs +28 -0
  91. package/scripts/cts-aeonic-temporal.mjs +24 -0
  92. package/scripts/cts-instruction.mjs +4 -2
  93. package/scripts/cts-mutate.mjs +3 -2
  94. package/scripts/cts-resolve.mjs +17 -2
  95. package/scripts/playground.mjs +110 -0
  96. package/src/aeonic-arithmetic-binding.js +61 -0
  97. package/src/aeonic-arithmetic.d.ts +84 -0
  98. package/src/aeonic-arithmetic.js +276 -0
  99. package/src/aeonic-comparison.d.ts +86 -0
  100. package/src/aeonic-comparison.js +274 -0
  101. package/src/aeonic-convenience.d.ts +30 -0
  102. package/src/aeonic-convenience.js +45 -0
  103. package/src/aeonic-exact-number.js +34 -0
  104. package/src/aeonic-json.js +45 -0
  105. package/src/aeonic-rational-arithmetic.d.ts +86 -0
  106. package/src/aeonic-rational-arithmetic.js +417 -0
  107. package/src/aeonic-rational-json.js +51 -0
  108. package/src/aeonic-temporal-civil-anchor.d.ts +54 -0
  109. package/src/aeonic-temporal-civil-anchor.js +316 -0
  110. package/src/aeonic-temporal-civil-clock.d.ts +124 -0
  111. package/src/aeonic-temporal-civil-clock.js +388 -0
  112. package/src/aeonic-temporal-civil-date.d.ts +123 -0
  113. package/src/aeonic-temporal-civil-date.js +310 -0
  114. package/src/aeonic-temporal-civil-datetime.d.ts +138 -0
  115. package/src/aeonic-temporal-civil-datetime.js +501 -0
  116. package/src/index.d.ts +84 -1
  117. package/src/index.js +828 -183
  118. package/src/property-address.js +196 -0
  119. package/src/property-resolve.js +132 -0
  120. package/src/query-metadata.d.ts +16 -0
  121. package/src/query-metadata.js +25 -0
  122. package/src/selector-cursor.d.ts +19 -0
  123. package/src/selector-cursor.js +79 -0
  124. package/stress-tests/address/invalid.sansa-cases +0 -2
  125. package/stress-tests/address/valid.sansa-cases +3 -0
  126. package/tools/mutate-web/examples.mjs +1 -1
  127. package/tools/mutate-web/runtime.mjs +0 -2
  128. package/tools/playground/README.md +165 -0
  129. package/tools/playground/accessibility.js +91 -0
  130. package/tools/playground/aeon-highlight.js +77 -0
  131. package/tools/playground/aeon-source-composer.js +1077 -0
  132. package/tools/playground/anchor-examples.mjs +16 -0
  133. package/tools/playground/arithmetic-evaluator.mjs +28 -0
  134. package/tools/playground/arithmetic-model.mjs +187 -0
  135. package/tools/playground/arithmetic-worker.mjs +14 -0
  136. package/tools/playground/arithmetic.css +1 -0
  137. package/tools/playground/arithmetic.html +29 -0
  138. package/tools/playground/arithmetic.mjs +110 -0
  139. package/tools/playground/clock-examples.mjs +16 -0
  140. package/tools/playground/datetime-examples.mjs +22 -0
  141. package/tools/playground/examples.mjs +46 -0
  142. package/tools/playground/index.html +174 -0
  143. package/tools/playground/local.css +25 -0
  144. package/tools/playground/namespace.mjs +39 -0
  145. package/tools/playground/sansa-playground.js +1565 -0
  146. package/tools/playground/site.css +3914 -0
  147. package/tools/playground/temporal-examples.mjs +20 -0
  148. package/tools/playground/walkthrough.js +90 -0
  149. package/tools/playground/website-origin.json +16 -0
  150. package/tools/query-web/IDENTITY_SELECTORS.md +44 -0
  151. package/tools/query-web/app.js +4 -0
  152. package/tools/query-web/index.html +4 -0
  153. package/tools/query-web/runtime.mjs +70 -19
  154. package/tools/workflows/property-playground-assertions.mjs +33 -0
  155. package/tools/workflows/verify-child-identities.mjs +137 -0
  156. package/tools/workflows/verify-property-playground.mjs +48 -0
@@ -0,0 +1,1077 @@
1
+ function escapeHtml(value) {
2
+ return String(value ?? "")
3
+ .replaceAll("&", "&")
4
+ .replaceAll("<", "&lt;")
5
+ .replaceAll(">", "&gt;")
6
+ .replaceAll('"', "&quot;");
7
+ }
8
+
9
+ const sourceTypes = [
10
+ "StringLiteral",
11
+ "TrimtickStringLiteral",
12
+ "SymbolicLiteral",
13
+ "NumberLiteral",
14
+ "IntegerLiteral",
15
+ "FloatLiteral",
16
+ "BooleanLiteral",
17
+ "ToggleLiteral",
18
+ "NullLiteral",
19
+ "NaNLiteral",
20
+ "InfinityLiteral",
21
+ "ObjectNode",
22
+ "ListNode",
23
+ "TupleNode",
24
+ "NodeLiteral",
25
+ "HexLiteral",
26
+ "EncodingLiteral",
27
+ "RadixLiteral",
28
+ "SeparatorLiteral",
29
+ "DateLiteral",
30
+ "TimeLiteral",
31
+ "DateTimeLiteral"
32
+ ];
33
+
34
+ const reservedNullValues = ["none", "notSet", "notApplicable", "tombstone"];
35
+ const sourceCommentTypes = [
36
+ ["doc", "Doc"],
37
+ ["annotation", "Annotation"],
38
+ ["hint", "Hint"],
39
+ ["structure", "Structure"],
40
+ ["profile", "Profile"],
41
+ ["instructions", "Instructions"]
42
+ ];
43
+ const sourceCommentMarkers = {
44
+ doc: "#",
45
+ annotation: "@",
46
+ hint: "?",
47
+ structure: "{",
48
+ profile: "[",
49
+ instructions: "("
50
+ };
51
+ const sourceCommentTypeByMarker = Object.fromEntries(
52
+ Object.entries(sourceCommentMarkers).map(([type, marker]) => [marker, type])
53
+ );
54
+ const sourceTypeByValueType = new Map([
55
+ ["StringLiteral", "StringLiteral"],
56
+ ["TrimtickStringLiteral", "TrimtickStringLiteral"],
57
+ ["SymbolicLiteral", "SymbolicLiteral"],
58
+ ["NumberLiteral", "NumberLiteral"],
59
+ ["IntegerLiteral", "IntegerLiteral"],
60
+ ["FloatLiteral", "FloatLiteral"],
61
+ ["BooleanLiteral", "BooleanLiteral"],
62
+ ["ToggleLiteral", "ToggleLiteral"],
63
+ ["NullLiteral", "NullLiteral"],
64
+ ["NaNLiteral", "NaNLiteral"],
65
+ ["InfinityLiteral", "InfinityLiteral"],
66
+ ["ObjectNode", "ObjectNode"],
67
+ ["ListNode", "ListNode"],
68
+ ["TupleLiteral", "TupleNode"],
69
+ ["TupleNode", "TupleNode"],
70
+ ["NodeLiteral", "NodeLiteral"],
71
+ ["HexLiteral", "HexLiteral"],
72
+ ["EncodingLiteral", "EncodingLiteral"],
73
+ ["RadixLiteral", "RadixLiteral"],
74
+ ["SeparatorLiteral", "SeparatorLiteral"],
75
+ ["DateLiteral", "DateLiteral"],
76
+ ["TimeLiteral", "TimeLiteral"],
77
+ ["DateTimeLiteral", "DateTimeLiteral"],
78
+ ["WTCDateTimeLiteral", "DateTimeLiteral"]
79
+ ]);
80
+
81
+ function datatypeForSourceType(type) {
82
+ return {
83
+ StringLiteral: "string",
84
+ TrimtickStringLiteral: "trimtick",
85
+ SymbolicLiteral: "symbol",
86
+ NumberLiteral: "number",
87
+ IntegerLiteral: "integer",
88
+ FloatLiteral: "float",
89
+ BooleanLiteral: "boolean",
90
+ ToggleLiteral: "toggle",
91
+ NullLiteral: "null",
92
+ NaNLiteral: "nan",
93
+ InfinityLiteral: "infinity",
94
+ ObjectNode: "object",
95
+ ListNode: "list",
96
+ TupleNode: "tuple",
97
+ NodeLiteral: "node",
98
+ HexLiteral: "hex",
99
+ EncodingLiteral: "encoding",
100
+ RadixLiteral: "radix",
101
+ SeparatorLiteral: "sep",
102
+ DateLiteral: "date",
103
+ TimeLiteral: "time",
104
+ DateTimeLiteral: "datetime"
105
+ }[type] || "";
106
+ }
107
+
108
+ function datatypeBase(datatype) {
109
+ const text = String(datatype ?? "").trim();
110
+ const genericIndex = text.indexOf("<");
111
+ const bracketIndex = text.indexOf("[");
112
+ const endIndex = [genericIndex, bracketIndex]
113
+ .filter((index) => index >= 0)
114
+ .reduce((min, index) => Math.min(min, index), text.length);
115
+ return text.slice(0, endIndex);
116
+ }
117
+
118
+ function sourceTypeForDatatype(datatype) {
119
+ const base = datatypeBase(datatype);
120
+ if (!base) return null;
121
+ if (["n", "number"].includes(base)) return "NumberLiteral";
122
+ if (["int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64"].includes(base)) return "IntegerLiteral";
123
+ if (["float", "float32", "float64"].includes(base)) return "FloatLiteral";
124
+ if (base === "string") return "StringLiteral";
125
+ if (base === "trimtick" || base === "prose") return "TrimtickStringLiteral";
126
+ if (base === "symbol") return "SymbolicLiteral";
127
+ if (base === "boolean" || base === "bool") return "BooleanLiteral";
128
+ if (base === "toggle") return "ToggleLiteral";
129
+ if (base === "infinity") return "InfinityLiteral";
130
+ if (base === "nan") return "NaNLiteral";
131
+ if (base === "hex") return "HexLiteral";
132
+ if (["radix", "decimal", "radix2", "radix6", "radix8", "radix12", "radix16"].includes(base)) return "RadixLiteral";
133
+ if (["encoding", "base64", "embed", "inline"].includes(base)) return "EncodingLiteral";
134
+ if (base === "date") return "DateLiteral";
135
+ if (base === "time") return "TimeLiteral";
136
+ if (base === "datetime") return "DateTimeLiteral";
137
+ if (base === "wtc") return "WTCDateTimeLiteral";
138
+ if (base === "sep" || base === "kadot" || base === "separator") return "SeparatorLiteral";
139
+ if (base === "tuple" || base === "triple") return "TupleLiteral";
140
+ if (base === "list") return "ListNode";
141
+ if (["object", "obj", "envelope", "o"].includes(base)) return "ObjectNode";
142
+ if (base === "node") return "NodeLiteral";
143
+ if (base === "null") return "NullLiteral";
144
+ return null;
145
+ }
146
+
147
+ function sourceDefaultValue(type) {
148
+ return {
149
+ StringLiteral: "",
150
+ TrimtickStringLiteral: "",
151
+ SymbolicLiteral: "symbol",
152
+ NumberLiteral: "0",
153
+ IntegerLiteral: "0",
154
+ FloatLiteral: "0.0",
155
+ BooleanLiteral: "true",
156
+ ToggleLiteral: "on",
157
+ NullLiteral: "none",
158
+ NaNLiteral: "NaN",
159
+ InfinityLiteral: "Infinity",
160
+ ObjectNode: "",
161
+ ListNode: "",
162
+ TupleNode: "",
163
+ NodeLiteral: "node",
164
+ HexLiteral: "00",
165
+ EncodingLiteral: "",
166
+ RadixLiteral: "0",
167
+ SeparatorLiteral: " ",
168
+ DateLiteral: "2026-01-01",
169
+ TimeLiteral: "12:00:00",
170
+ DateTimeLiteral: "2026-01-01T12:00:00Z"
171
+ }[type] ?? "";
172
+ }
173
+
174
+ function valuePrefixForSourceType(type) {
175
+ return {
176
+ HexLiteral: "#",
177
+ RadixLiteral: "%",
178
+ SeparatorLiteral: "^",
179
+ SymbolicLiteral: "|...|",
180
+ NullLiteral: "!",
181
+ EncodingLiteral: "&"
182
+ }[type] ?? "";
183
+ }
184
+
185
+ function sourceTypeAllowsChildren(type) {
186
+ return type === "ObjectNode" || type === "ListNode" || type === "TupleNode" || type === "NodeLiteral";
187
+ }
188
+
189
+ function isPlainAeonKey(key) {
190
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(String(key ?? ""));
191
+ }
192
+
193
+ function parseQuotedPathKey(value) {
194
+ try {
195
+ return JSON.parse(`"${value}"`);
196
+ } catch {
197
+ return value;
198
+ }
199
+ }
200
+
201
+ function formatSourceMemberPath(key) {
202
+ return isPlainAeonKey(key) ? `.${key}` : `.[${JSON.stringify(String(key ?? ""))}]`;
203
+ }
204
+
205
+ function formatSourceAttributePath(key) {
206
+ return isPlainAeonKey(key) ? `.@.${key}` : `.@.[${JSON.stringify(String(key ?? ""))}]`;
207
+ }
208
+
209
+ function normalizeSourceRuntimePath(path) {
210
+ let output = "";
211
+ let bracketDepth = 0;
212
+ let inString = false;
213
+ let escaped = false;
214
+ for (let index = 0; index < String(path ?? "").length; index += 1) {
215
+ const char = path[index];
216
+ if (inString) {
217
+ output += char;
218
+ if (escaped) {
219
+ escaped = false;
220
+ } else if (char === "\\") {
221
+ escaped = true;
222
+ } else if (char === "\"") {
223
+ inString = false;
224
+ }
225
+ continue;
226
+ }
227
+ if (char === "\"") {
228
+ inString = true;
229
+ output += char;
230
+ continue;
231
+ }
232
+ if (char === "[") bracketDepth += 1;
233
+ if (char === "]") bracketDepth = Math.max(0, bracketDepth - 1);
234
+ if (char === "@" && bracketDepth === 0 && path[index + 1] !== ".") {
235
+ output += output.endsWith(".") ? "@." : ".@.";
236
+ continue;
237
+ }
238
+ output += char;
239
+ }
240
+ return output;
241
+ }
242
+
243
+ function sourceDisplayName(name, isAttribute = false) {
244
+ if (name.startsWith("//") || /^\[\d+\]$/.test(name)) return name;
245
+ if (isAttribute) {
246
+ const key = name.replace(/^@/, "");
247
+ return `@${isPlainAeonKey(key) ? key : JSON.stringify(key)}`;
248
+ }
249
+ return isPlainAeonKey(name) ? name : JSON.stringify(name);
250
+ }
251
+
252
+ function pathSegments(path) {
253
+ const segments = [];
254
+ const tokenRe = /\.([A-Za-z_][A-Za-z0-9_]*)|\["((?:\\.|[^"\\])*)"\]|\[(\d+)\]/g;
255
+ for (const match of String(path ?? "").matchAll(tokenRe)) {
256
+ if (match[1] !== undefined) {
257
+ segments.push(match[1]);
258
+ } else if (match[2] !== undefined) {
259
+ segments.push(parseQuotedPathKey(match[2]));
260
+ } else if (match[3] !== undefined) {
261
+ segments.push(Number.parseInt(match[3], 10));
262
+ }
263
+ }
264
+ return segments;
265
+ }
266
+
267
+ function sourceParentPath(path) {
268
+ const commentIndex = String(path).lastIndexOf("#comment");
269
+ if (commentIndex > -1) return path.slice(0, commentIndex);
270
+ const quotedSansaAttrMatch = String(path).match(/\.@\.\["((?:\\.|[^"\\])*)"\]$/);
271
+ if (quotedSansaAttrMatch) return path.slice(0, quotedSansaAttrMatch.index);
272
+ const plainSansaAttrMatch = String(path).match(/\.@\.([A-Za-z_][A-Za-z0-9_]*)$/);
273
+ if (plainSansaAttrMatch) return path.slice(0, plainSansaAttrMatch.index);
274
+ const indexMatch = String(path).match(/\[(\d+)\]$/);
275
+ if (indexMatch) return path.slice(0, indexMatch.index);
276
+ const quotedMemberMatch = String(path).match(/\.\["((?:\\.|[^"\\])*)"\]$/);
277
+ if (quotedMemberMatch) return quotedMemberMatch.index > 1 ? path.slice(0, quotedMemberMatch.index) : "";
278
+ const plainMemberMatch = String(path).match(/\.([A-Za-z_][A-Za-z0-9_]*)$/);
279
+ if (plainMemberMatch && plainMemberMatch.index > 0) return plainMemberMatch.index > 1 ? path.slice(0, plainMemberMatch.index) : "";
280
+ return "";
281
+ }
282
+
283
+ function sourcePathIsAttribute(path) {
284
+ return sourcePathName(path).startsWith("@");
285
+ }
286
+
287
+ function sourcePathIsComment(path) {
288
+ return sourcePathName(path).startsWith("//");
289
+ }
290
+
291
+ function sourcePathIsDescendant(path, parent) {
292
+ return path.startsWith(`${parent}.`) || path.startsWith(`${parent}[`) || path.startsWith(`${parent}#comment`);
293
+ }
294
+
295
+ function sourcePathName(path) {
296
+ const commentMatch = String(path).match(/#comment(\d+)$/);
297
+ if (commentMatch) return `//${commentMatch[1]}`;
298
+ const quotedSansaAttrMatch = String(path).match(/\.@\.\["((?:\\.|[^"\\])*)"\]$/);
299
+ if (quotedSansaAttrMatch) return `@${parseQuotedPathKey(quotedSansaAttrMatch[1])}`;
300
+ const sansaAttrMatch = String(path).match(/\.@\.([A-Za-z_][A-Za-z0-9_]*)$/);
301
+ if (sansaAttrMatch) return `@${sansaAttrMatch[1]}`;
302
+ const indexMatch = String(path).match(/\[(\d+)\]$/);
303
+ if (indexMatch) return `[${indexMatch[1]}]`;
304
+ const segments = pathSegments(path);
305
+ const last = segments.at(-1);
306
+ if (typeof last === "string") return last;
307
+ if (typeof last === "number") return `[${last}]`;
308
+ return String(path).replace(/^\$\.?/, "");
309
+ }
310
+
311
+ function joinSourcePath(parent, name) {
312
+ if (!parent) return `$${formatSourceMemberPath(name)}`;
313
+ if (/^\[\d+\]$/.test(name)) return `${parent}${name}`;
314
+ if (name.startsWith("@")) return `${parent}${formatSourceAttributePath(name.replace(/^@/, ""))}`;
315
+ if (name.startsWith("#comment")) return `${parent}${name}`;
316
+ return `${parent}${formatSourceMemberPath(name)}`;
317
+ }
318
+
319
+ function sourceDepth(path) {
320
+ return pathSegments(path).length + (sourcePathIsAttribute(path) || sourcePathIsComment(path) ? 1 : 0);
321
+ }
322
+
323
+ function datatypeName(datatype) {
324
+ if (typeof datatype === "string") return datatype;
325
+ return datatype?.name ?? "";
326
+ }
327
+
328
+ function formatEventPath(path) {
329
+ if (typeof path === "string") return path;
330
+ if (path && typeof path === "object" && typeof window.AeonFormatPath === "function") {
331
+ return window.AeonFormatPath(path);
332
+ }
333
+ if (path?.segments) {
334
+ let result = "";
335
+ for (const segment of path.segments) {
336
+ if (segment.type === "root") {
337
+ result = "$";
338
+ } else if (segment.type === "member") {
339
+ result += formatSourceMemberPath(segment.key);
340
+ } else if (segment.type === "index") {
341
+ result += `[${segment.index}]`;
342
+ }
343
+ }
344
+ return result || "$";
345
+ }
346
+ return String(path ?? "");
347
+ }
348
+
349
+ function sourceTypeForAeonValue(value) {
350
+ return sourceTypeByValueType.get(value?.valueType ?? value?.type) ?? "StringLiteral";
351
+ }
352
+
353
+ function sourceTypeForEvent(event) {
354
+ const value = event?.value ?? {};
355
+ return sourceTypeForDatatype(event?.datatype)
356
+ ?? sourceTypeByValueType.get(value.valueType ?? value.type ?? event?.valueType ?? event?.type)
357
+ ?? "StringLiteral";
358
+ }
359
+
360
+ function sourceUiValueForAeonValue(value, type) {
361
+ if (type === "StringLiteral" || type === "TrimtickStringLiteral") return value?.value ?? value?.raw ?? "";
362
+ if (type === "SymbolicLiteral") {
363
+ if (value?.value !== undefined) return String(value.value);
364
+ const raw = String(value?.raw ?? sourceDefaultValue(type));
365
+ return raw.startsWith("|") && raw.endsWith("|") ? raw.slice(1, -1) : raw;
366
+ }
367
+ if (type === "BooleanLiteral") return value?.value === false ? "false" : "true";
368
+ if (type === "NullLiteral") {
369
+ const raw = String(value?.raw ?? "");
370
+ const literalValue = String(value?.value ?? raw.replace(/^!/, "") ?? "none");
371
+ if (raw.startsWith('!"') || raw.startsWith("!'")) return `custom:${literalValue}`;
372
+ return reservedNullValues.includes(literalValue) ? literalValue : `custom:${literalValue}`;
373
+ }
374
+ if (type === "NaNLiteral") return String(value?.raw ?? value?.value ?? "NaN");
375
+ if (type === "InfinityLiteral") return String(value?.raw ?? value?.value ?? "Infinity");
376
+ if (type === "NodeLiteral") return value?.tag ?? "node";
377
+ if (type === "HexLiteral") return String(value?.raw ?? value?.value ?? sourceDefaultValue(type)).replace(/^#/, "");
378
+ if (type === "RadixLiteral") return String(value?.raw ?? value?.value ?? sourceDefaultValue(type)).replace(/^%/, "");
379
+ if (type === "EncodingLiteral") return String(value?.raw ?? value?.value ?? sourceDefaultValue(type)).replace(/^&/, "");
380
+ if (type === "SeparatorLiteral") return String(value?.raw ?? value?.value ?? sourceDefaultValue(type)).replace(/^\^/, "");
381
+ if (sourceTypeAllowsChildren(type)) return "";
382
+ return String(value?.raw ?? value?.value ?? sourceDefaultValue(type));
383
+ }
384
+
385
+ function sourceUiValueForEvent(event, type) {
386
+ return sourceUiValueForAeonValue(event?.value ?? event, type);
387
+ }
388
+
389
+ function attributeEntries(attributes) {
390
+ const output = [];
391
+ if (attributes instanceof Map) return Array.from(attributes.entries());
392
+ if (attributes && !Array.isArray(attributes) && typeof attributes === "object") return Object.entries(attributes);
393
+ for (const attribute of attributes ?? []) {
394
+ const entries = attribute?.entries instanceof Map
395
+ ? attribute.entries
396
+ : new Map(Object.entries(attribute?.entries ?? {}));
397
+ for (const entry of entries) output.push(entry);
398
+ }
399
+ return output;
400
+ }
401
+
402
+ function aeonAttributeSource(value) {
403
+ return value?.attributes ?? value?.annotations ?? [];
404
+ }
405
+
406
+ function addSourceAttributeRows(attributes, ownerPath, rows, seen) {
407
+ for (const [key, entry] of attributeEntries(attributes)) {
408
+ const path = joinSourcePath(ownerPath, `@${key}`);
409
+ if (seen.has(path)) continue;
410
+ const type = sourceTypeForDatatype(entry?.datatype) ?? sourceTypeForAeonValue(entry?.value);
411
+ rows.push({
412
+ path,
413
+ type,
414
+ datatype: datatypeName(entry?.datatype) || "",
415
+ identity: entry?.structuralId ?? entry?.identity,
416
+ value: sourceUiValueForAeonValue(entry?.value, type),
417
+ open: true
418
+ });
419
+ seen.add(path);
420
+ addSourceAttributeRows(aeonAttributeSource(entry), path, rows, seen);
421
+ addSourceAttributeRowsFromValue(entry?.value, path, rows, seen);
422
+ }
423
+ }
424
+
425
+ function addSourceAttributeRowsFromValue(value, path, rows, seen) {
426
+ addSourceAttributeRows(aeonAttributeSource(value), path, rows, seen);
427
+ if (value?.type === "ObjectNode") {
428
+ for (const binding of value.bindings ?? []) {
429
+ const child = joinSourcePath(path, binding.key);
430
+ addSourceAttributeRows(aeonAttributeSource(binding), child, rows, seen);
431
+ addSourceAttributeRowsFromValue(binding.value, child, rows, seen);
432
+ }
433
+ }
434
+ if (value?.type === "ListNode" || value?.type === "TupleNode") {
435
+ for (const [index, element] of (value.elements ?? []).entries()) {
436
+ addSourceAttributeRowsFromValue(element, `${path}[${index}]`, rows, seen);
437
+ }
438
+ }
439
+ if (value?.type === "NodeLiteral") {
440
+ for (const [index, child] of (value.children ?? []).entries()) {
441
+ addSourceAttributeRowsFromValue(child, `${path}[${index}]`, rows, seen);
442
+ }
443
+ }
444
+ }
445
+
446
+ function sourceRowsFromValue(value, path = "$.value", rows = []) {
447
+ const type = value === null ? "NullLiteral"
448
+ : Array.isArray(value) ? "ListNode"
449
+ : value && typeof value === "object" ? "ObjectNode"
450
+ : typeof value === "boolean" ? "BooleanLiteral"
451
+ : typeof value === "number" ? Number.isInteger(value) ? "IntegerLiteral" : "FloatLiteral"
452
+ : "StringLiteral";
453
+ rows.push({
454
+ path,
455
+ type,
456
+ datatype: "",
457
+ value: sourceTypeAllowsChildren(type) ? "" : String(value ?? sourceDefaultValue(type)),
458
+ open: true
459
+ });
460
+ if (Array.isArray(value)) {
461
+ value.forEach((child, index) => sourceRowsFromValue(child, `${path}[${index}]`, rows));
462
+ } else if (value && typeof value === "object") {
463
+ Object.entries(value).forEach(([key, child]) => sourceRowsFromValue(child, joinSourcePath(path, key), rows));
464
+ }
465
+ return rows;
466
+ }
467
+
468
+ function sourceRowsFromRuntimeResult(result) {
469
+ const events = Array.isArray(result?.aes) ? result.aes : Array.isArray(result?.events) ? result.events : [];
470
+ const rows = [];
471
+ const seen = new Set();
472
+ for (const event of events) {
473
+ const path = normalizeSourceRuntimePath(formatEventPath(event.path));
474
+ if (!path || path === "$" || path.includes("[*]") || path.startsWith('$.["aeon:') || seen.has(path)) continue;
475
+ const type = sourceTypeForEvent(event);
476
+ rows.push({
477
+ path,
478
+ type,
479
+ datatype: event.datatype ?? "",
480
+ identity: event.structuralId ?? event.identity,
481
+ value: sourceUiValueForEvent(event, type),
482
+ open: true
483
+ });
484
+ seen.add(path);
485
+ addSourceAttributeRows(aeonAttributeSource(event), path, rows, seen);
486
+ addSourceAttributeRowsFromValue(event.value, path, rows, seen);
487
+ }
488
+ if (rows.length > 0) return rows;
489
+ const document = result?.document;
490
+ const root = document && typeof document === "object" && "payload" in document ? document.payload : document;
491
+ if (!root || typeof root !== "object") return sourceRowsFromValue(root ?? "", "$.value");
492
+ return Object.entries(root).flatMap(([key, value]) => sourceRowsFromValue(value, `$.${key}`));
493
+ }
494
+
495
+ function parseStandaloneSemanticComments(text) {
496
+ const commentsByPath = new Map();
497
+ const pending = [];
498
+ const stack = [];
499
+ const lines = String(text ?? "").split(/\r?\n/);
500
+ for (const line of lines) {
501
+ const standalone = line.match(/^\s*\/\/([#@?{\[(])\s?(.*)$/);
502
+ if (standalone) {
503
+ pending.push({ type: sourceCommentTypeByMarker[standalone[1]] ?? "doc", value: standalone[2] ?? "" });
504
+ continue;
505
+ }
506
+ if (/\/\/[#@?{\[(]/.test(line)) continue;
507
+ const binding = line.match(/^(\s*)([A-Za-z_][A-Za-z0-9_]*|"([^"\\]|\\.)*"|'([^'\\]|\\.)*')\s*(?:@\{[^}]*\}\s*)?(?::[^=]+)?=/);
508
+ if (!binding) continue;
509
+ const indent = binding[1].length;
510
+ while (stack.length > 0 && stack.at(-1).indent >= indent) stack.pop();
511
+ const rawKey = binding[2];
512
+ let key = rawKey;
513
+ if (rawKey.startsWith('"') || rawKey.startsWith("'")) {
514
+ try {
515
+ key = JSON.parse(rawKey.startsWith("'") ? `"${rawKey.slice(1, -1).replaceAll('"', '\\"')}"` : rawKey);
516
+ } catch {
517
+ key = rawKey.slice(1, -1);
518
+ }
519
+ }
520
+ const parent = stack.at(-1)?.path ?? "";
521
+ const path = joinSourcePath(parent, key);
522
+ if (pending.length > 0) {
523
+ commentsByPath.set(path, [...(commentsByPath.get(path) ?? []), ...pending.splice(0)]);
524
+ }
525
+ if (line.includes("{")) stack.push({ indent, path });
526
+ }
527
+ return commentsByPath;
528
+ }
529
+
530
+ function addStandaloneCommentRows(text, rows) {
531
+ const commentsByPath = parseStandaloneSemanticComments(text);
532
+ const seen = new Set(rows.map((row) => row.path));
533
+ for (const [ownerPath, comments] of commentsByPath) {
534
+ if (!rows.some((row) => row.path === ownerPath)) continue;
535
+ let index = 1;
536
+ for (const comment of comments) {
537
+ while (seen.has(joinSourcePath(ownerPath, `#comment${index}`))) index += 1;
538
+ const path = joinSourcePath(ownerPath, `#comment${index}`);
539
+ rows.push({ path, kind: "comment", commentType: comment.type, value: comment.value, open: true });
540
+ seen.add(path);
541
+ index += 1;
542
+ }
543
+ }
544
+ }
545
+
546
+ function preservedHeaderSource(text) {
547
+ const lines = String(text ?? "").split(/\r?\n/);
548
+ const output = [];
549
+ for (let index = 0; index < lines.length; index += 1) {
550
+ const line = lines[index];
551
+ if (/^\s*aeon\s*:\s*header\s*=/.test(line)) {
552
+ output.push(line);
553
+ let depth = (line.match(/\{/g) ?? []).length - (line.match(/\}/g) ?? []).length;
554
+ while (depth > 0 && index + 1 < lines.length) {
555
+ index += 1;
556
+ output.push(lines[index]);
557
+ depth += (lines[index].match(/\{/g) ?? []).length - (lines[index].match(/\}/g) ?? []).length;
558
+ }
559
+ continue;
560
+ }
561
+ if (/^\s*aeon\s*:\s*[A-Za-z_][A-Za-z0-9_]*\s*=/.test(line)) output.push(line);
562
+ }
563
+ return output.join("\n").trim();
564
+ }
565
+
566
+ function orderedSourceRows(rows) {
567
+ const byPath = new Map(rows.map((row) => [row.path, row]));
568
+ const orderedChildren = (parentPath) => rows
569
+ .map((row, index) => ({ row, index }))
570
+ .filter(({ row }) => sourceParentPath(row.path) === parentPath)
571
+ .sort((left, right) => {
572
+ const leftComment = sourcePathIsComment(left.row.path);
573
+ const rightComment = sourcePathIsComment(right.row.path);
574
+ if (leftComment !== rightComment) return leftComment ? -1 : 1;
575
+ const leftAttr = sourcePathIsAttribute(left.row.path);
576
+ const rightAttr = sourcePathIsAttribute(right.row.path);
577
+ if (leftAttr !== rightAttr) return leftAttr ? -1 : 1;
578
+ return left.index - right.index;
579
+ })
580
+ .map(({ row }) => row);
581
+ const output = [];
582
+ const visit = (row) => {
583
+ output.push(row);
584
+ orderedChildren(row.path).forEach(visit);
585
+ };
586
+ rows.filter((row) => !byPath.has(sourceParentPath(row.path))).forEach(visit);
587
+ return output;
588
+ }
589
+
590
+ function visibleSourceRows(rows) {
591
+ return orderedSourceRows(rows).filter((row) => {
592
+ let parent = sourceParentPath(row.path);
593
+ while (parent) {
594
+ const parentRow = rows.find((candidate) => candidate.path === parent);
595
+ if (parentRow && parentRow.open === false) return false;
596
+ parent = sourceParentPath(parent);
597
+ }
598
+ return true;
599
+ });
600
+ }
601
+
602
+ function aeonKey(key) {
603
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) ? key : JSON.stringify(key);
604
+ }
605
+
606
+ function trimtickValue(value, depth) {
607
+ const indent = " ".repeat(depth);
608
+ const contentIndent = " ".repeat(depth + 1);
609
+ const lines = String(value ?? "").split(/\r?\n/);
610
+ const body = lines.map((line) => `${contentIndent}${line}`).join("\n");
611
+ return `>\`\n${body}\n${indent}\``;
612
+ }
613
+
614
+ function aeonScalarValue(row) {
615
+ const value = String(row.value ?? sourceDefaultValue(row.type));
616
+ if (row.type === "StringLiteral") return JSON.stringify(value);
617
+ if (row.type === "TrimtickStringLiteral") return `>\`\n${value}\n\``;
618
+ if (row.type === "SymbolicLiteral") {
619
+ const payload = value || sourceDefaultValue(row.type);
620
+ return `|${JSON.stringify(payload).slice(1, -1).replaceAll("|", "\\|")}|`;
621
+ }
622
+ if (row.type === "BooleanLiteral") return value === "false" ? "false" : "true";
623
+ if (row.type === "ToggleLiteral") return ["off", "yes", "no"].includes(value) ? value : "on";
624
+ if (row.type === "NullLiteral") {
625
+ if (value.startsWith("custom:")) return `!${JSON.stringify(value.slice("custom:".length))}`;
626
+ if (reservedNullValues.includes(value)) return `!${value}`;
627
+ return value ? `!${JSON.stringify(value)}` : "!none";
628
+ }
629
+ if (row.type === "NaNLiteral") return value === "-NaN" ? "-NaN" : "NaN";
630
+ if (row.type === "InfinityLiteral") return value === "-Infinity" ? "-Infinity" : "Infinity";
631
+ if (row.type === "EncodingLiteral") return value.startsWith("&") ? value : `&${value}`;
632
+ if (row.type === "SeparatorLiteral") return value.startsWith("^") ? value : `^${value || " "}`;
633
+ if (row.type === "HexLiteral") return value.startsWith("#") ? value : `#${value || "00"}`;
634
+ if (row.type === "RadixLiteral") return value.startsWith("%") ? value : `%${value || "0"}`;
635
+ if (row.type === "ObjectNode") return "{}";
636
+ if (row.type === "ListNode") return "[]";
637
+ if (row.type === "TupleNode") return "()";
638
+ if (row.type === "NodeLiteral") return `<${aeonKey(value || "node")}()>`;
639
+ return value || sourceDefaultValue(row.type);
640
+ }
641
+
642
+ function mountAeonSourceComposer(options) {
643
+ const shell = options.shell;
644
+ const source = options.source;
645
+ const modal = shell.querySelector("[data-source-builder-modal]");
646
+ const tree = shell.querySelector("[data-source-builder-tree]");
647
+ const detail = shell.querySelector("[data-source-builder-detail]");
648
+ const closeButtons = shell.querySelectorAll("[data-source-builder-close]");
649
+ const openButton = shell.querySelector("[data-source-builder-open]");
650
+ const reloadButton = shell.querySelector("[data-source-builder-reload]");
651
+ const applyButton = shell.querySelector("[data-source-builder-apply]");
652
+ const addPeerButton = shell.querySelector("[data-source-builder-add-peer]");
653
+ const addChildButton = shell.querySelector("[data-source-builder-add-child]");
654
+ const addAttributeButton = shell.querySelector("[data-source-builder-add-attribute]");
655
+ const addCommentButton = shell.querySelector("[data-source-builder-add-comment]");
656
+ const removeButton = shell.querySelector("[data-source-builder-remove]");
657
+ if (!source || !modal || !tree || !detail) return null;
658
+
659
+ const state = { rows: [], selectedPath: null };
660
+ const runtimeReady = options.runtimeReady ?? import("@aeon/runtime");
661
+ const getMode = options.getMode ?? (() => "transport");
662
+ const runtimeConfig = options.runtimeConfig ?? ((text) => ({
663
+ text,
664
+ options: { mode: "loose", datatypePolicy: "reserved_only", includeAnnotations: true, output: "map" }
665
+ }));
666
+ const onError = options.onError ?? (() => {});
667
+ const onApply = options.onApply ?? (() => {});
668
+
669
+ const sourceChildren = (path, rows = state.rows) => rows.filter((row) => sourceParentPath(row.path) === path);
670
+ const sourceValueChildren = (path, rows = state.rows) => sourceChildren(path, rows).filter((row) => !sourcePathIsAttribute(row.path) && !sourcePathIsComment(row.path));
671
+ const sourceTypeOptionsForRow = (row, rows) => {
672
+ if (sourceValueChildren(row.path, rows).length === 0) return sourceTypes;
673
+ if (row.type === "ListNode" || row.type === "TupleNode") return ["ListNode", "TupleNode"];
674
+ return [row.type];
675
+ };
676
+
677
+ function sourceIdentity(row) {
678
+ return row.identity ? String.fromCharCode(92) + row.identity + String.fromCharCode(92) : "";
679
+ }
680
+
681
+ function renderSourceBuilderAttributes(row, rows) {
682
+ const attrs = sourceChildren(row.path, rows).filter((child) => sourcePathIsAttribute(child.path));
683
+ if (attrs.length === 0) return "";
684
+ const values = attrs.map((attr) => {
685
+ const key = sourcePathName(attr.path).replace(/^@/, "");
686
+ const datatype = attr.datatype ? `:${attr.datatype}` : "";
687
+ return `${aeonKey(key)}${sourceIdentity(attr)}${datatype} = ${renderSourceBuilderValue(attr, rows)}`;
688
+ });
689
+ return ` @{${values.join(", ")}}`;
690
+ }
691
+
692
+ function renderSourceBuilderComments(row, rows, depth = 0) {
693
+ return sourceChildren(row.path, rows)
694
+ .filter((child) => sourcePathIsComment(child.path))
695
+ .map((comment) => {
696
+ const marker = sourceCommentMarkers[comment.commentType ?? "doc"] ?? "#";
697
+ return `${" ".repeat(depth)}//${marker} ${String(comment.value ?? "").replace(/\r?\n/g, " ")}`;
698
+ })
699
+ .join("\n");
700
+ }
701
+
702
+ function renderSourceBuilderValue(row, rows, depth = 0) {
703
+ const children = sourceValueChildren(row.path, rows);
704
+ if (row.type === "TrimtickStringLiteral") return trimtickValue(row.value, depth);
705
+ if (row.type === "ListNode" || row.type === "TupleNode") {
706
+ const open = row.type === "TupleNode" ? "(" : "[";
707
+ const close = row.type === "TupleNode" ? ")" : "]";
708
+ if (children.length === 0) return `${open}${close}`;
709
+ const values = children.map((child) => `${" ".repeat(depth + 1)}${sourceIdentity(child)}${child.identity ? " = " : ""}${renderSourceBuilderValue(child, rows, depth + 1)}`);
710
+ return `${open}\n${values.join(",\n")}\n${" ".repeat(depth)}${close}`;
711
+ }
712
+ if (row.type === "ObjectNode") {
713
+ if (children.length === 0) return "{}";
714
+ const values = children.map((child) => renderSourceBuilderBinding(child, rows, depth + 1));
715
+ return `{\n${values.join("\n")}\n${" ".repeat(depth)}}`;
716
+ }
717
+ if (row.type === "NodeLiteral") {
718
+ if (children.length === 0) return aeonScalarValue(row);
719
+ const values = children.map((child) => `${" ".repeat(depth + 1)}${sourceIdentity(child)}${child.identity ? " = " : ""}${renderSourceBuilderValue(child, rows, depth + 1)}`);
720
+ return `<${aeonKey(row.value || "node")}(\n${values.join("\n")}\n${" ".repeat(depth)})>`;
721
+ }
722
+ return aeonScalarValue(row);
723
+ }
724
+
725
+ function renderSourceBuilderBinding(row, rows, depth = 0) {
726
+ const name = sourcePathName(row.path);
727
+ const datatype = row.datatype ? `:${row.datatype}` : "";
728
+ const attrs = renderSourceBuilderAttributes(row, rows);
729
+ const comments = renderSourceBuilderComments(row, rows, depth);
730
+ const binding = `${" ".repeat(depth)}${aeonKey(name)}${sourceIdentity(row)}${attrs}${datatype} = ${renderSourceBuilderValue(row, rows, depth)}`;
731
+ return [comments, binding].filter(Boolean).join("\n");
732
+ }
733
+
734
+ function render() {
735
+ const rows = state.rows;
736
+ if (!state.selectedPath || !rows.some((row) => row.path === state.selectedPath)) {
737
+ state.selectedPath = rows[0]?.path ?? null;
738
+ }
739
+ tree.innerHTML = visibleSourceRows(rows).map((row) => {
740
+ const selected = row.path === state.selectedPath;
741
+ const hasChildren = sourceValueChildren(row.path, rows).length > 0;
742
+ const name = sourcePathName(row.path);
743
+ const isAttribute = sourcePathIsAttribute(row.path);
744
+ const isComment = sourcePathIsComment(row.path);
745
+ const displayName = isComment ? `//${sourceCommentMarkers[row.commentType ?? "doc"]} ${row.value ?? ""}` : sourceDisplayName(name, isAttribute);
746
+ return `
747
+ <button class="source-builder-tree-item${selected ? " is-selected" : ""}${isAttribute ? " is-attribute" : ""}${isComment ? " is-comment" : ""}" type="button" data-source-builder-path="${escapeHtml(row.path)}" style="--source-depth:${Math.max(0, sourceDepth(row.path) - 1)}">
748
+ <span class="source-builder-twist">${isAttribute ? "" : hasChildren ? (row.open === false ? "+" : "-") : ""}</span>
749
+ <span class="source-builder-name">${escapeHtml(displayName)}</span>
750
+ <span class="source-builder-type">${isComment ? escapeHtml(row.commentType ?? "doc") : escapeHtml(row.datatype || datatypeForSourceType(row.type))}</span>
751
+ </button>`;
752
+ }).join("");
753
+
754
+ const selected = rows.find((row) => row.path === state.selectedPath);
755
+ if (!selected) {
756
+ if (removeButton) {
757
+ removeButton.disabled = true;
758
+ removeButton.textContent = "Remove binding";
759
+ }
760
+ detail.innerHTML = "<p class=\"source-builder-empty\">No binding selected.</p>";
761
+ return;
762
+ }
763
+ if (selected.kind === "comment") {
764
+ if (addChildButton) addChildButton.disabled = true;
765
+ if (addAttributeButton) addAttributeButton.disabled = true;
766
+ if (addCommentButton) addCommentButton.disabled = true;
767
+ if (removeButton) {
768
+ removeButton.disabled = false;
769
+ removeButton.textContent = "Remove comment";
770
+ }
771
+ detail.innerHTML = `
772
+ <label>
773
+ <span>Comment type</span>
774
+ <select name="commentType">
775
+ ${sourceCommentTypes.map(([value, label]) => `<option value="${value}"${value === selected.commentType ? " selected" : ""}>${label}</option>`).join("")}
776
+ </select>
777
+ </label>
778
+ <label class="source-builder-value-field">
779
+ <span>Value</span>
780
+ <textarea name="value">${escapeHtml(selected.value)}</textarea>
781
+ </label>
782
+ `;
783
+ return;
784
+ }
785
+ const hasChildren = sourceValueChildren(selected.path, rows).length > 0;
786
+ const valueDisabled = selected.type !== "NodeLiteral" && (sourceTypeAllowsChildren(selected.type) || hasChildren) ? " disabled" : "";
787
+ const valueLabel = selected.type === "NodeLiteral" ? "Tag" : "Value";
788
+ const valuePrefix = valuePrefixForSourceType(selected.type);
789
+ const typeOptions = sourceTypeOptionsForRow(selected, rows);
790
+ const isAttribute = sourcePathIsAttribute(selected.path);
791
+ const nullValue = String(selected.value ?? "none");
792
+ const nullMode = nullValue.startsWith("custom:") ? "custom" : nullValue;
793
+ if (addChildButton) addChildButton.disabled = isAttribute || !sourceTypeAllowsChildren(selected.type);
794
+ if (addAttributeButton) addAttributeButton.disabled = isAttribute;
795
+ if (addCommentButton) addCommentButton.disabled = isAttribute;
796
+ if (removeButton) {
797
+ removeButton.disabled = false;
798
+ removeButton.textContent = "Remove binding";
799
+ }
800
+ detail.innerHTML = `
801
+ <label>
802
+ <span>Key</span>
803
+ <input name="name" type="text" value="${escapeHtml(sourcePathName(selected.path).replace(/^@/, "").replace(/^\[|\]$/g, ""))}" ${/^\[\d+\]$/.test(sourcePathName(selected.path)) && !isAttribute ? "disabled" : ""} />
804
+ </label>
805
+ <label>
806
+ <span>Type</span>
807
+ <select name="type">
808
+ ${typeOptions.map((type) => `<option value="${type}"${type === selected.type ? " selected" : ""}>${type}</option>`).join("")}
809
+ </select>
810
+ </label>
811
+ <label>
812
+ <span>Datatype</span>
813
+ <input name="datatype" type="text" value="${escapeHtml(selected.datatype ?? datatypeForSourceType(selected.type))}" />
814
+ </label>
815
+ ${selected.type === "NullLiteral" ? `
816
+ <label>
817
+ <span>Value !</span>
818
+ <select name="nullMode">
819
+ ${[...reservedNullValues, "custom"].map((value) => `<option value="${value}"${value === nullMode ? " selected" : ""}>${value}</option>`).join("")}
820
+ </select>
821
+ </label>
822
+ <label class="source-builder-value-field${nullMode === "custom" ? "" : " is-hidden"}">
823
+ <span>Custom null</span>
824
+ <input name="value" type="text" value="${escapeHtml(nullValue.startsWith("custom:") ? nullValue.slice("custom:".length) : "")}" />
825
+ </label>
826
+ ` : selected.type === "BooleanLiteral" ? `
827
+ <label>
828
+ <span>Value</span>
829
+ <select name="value"${valueDisabled}>
830
+ ${["true", "false"].map((value) => `<option value="${value}"${value === String(selected.value ?? "true") ? " selected" : ""}>${value}</option>`).join("")}
831
+ </select>
832
+ </label>
833
+ ` : selected.type === "ToggleLiteral" ? `
834
+ <label>
835
+ <span>Value</span>
836
+ <select name="value"${valueDisabled}>
837
+ ${["yes", "no", "on", "off"].map((value) => `<option value="${value}"${value === String(selected.value ?? "on") ? " selected" : ""}>${value}</option>`).join("")}
838
+ </select>
839
+ </label>
840
+ ` : selected.type === "InfinityLiteral" ? `
841
+ <label>
842
+ <span>Value</span>
843
+ <select name="value"${valueDisabled}>
844
+ ${["Infinity", "-Infinity"].map((value) => `<option value="${value}"${value === String(selected.value ?? "Infinity") ? " selected" : ""}>${value}</option>`).join("")}
845
+ </select>
846
+ </label>
847
+ ` : selected.type === "NaNLiteral" ? `
848
+ <label>
849
+ <span>Value</span>
850
+ <select name="value"${valueDisabled}>
851
+ ${["NaN", "-NaN"].map((value) => `<option value="${value}"${value === String(selected.value ?? "NaN") ? " selected" : ""}>${value}</option>`).join("")}
852
+ </select>
853
+ </label>
854
+ ` : `
855
+ <label class="source-builder-value-field">
856
+ <span>${valuePrefix ? `${valueLabel} ${valuePrefix}` : valueLabel}</span>
857
+ <textarea name="value"${valueDisabled}>${escapeHtml(selected.value)}</textarea>
858
+ </label>
859
+ `}
860
+ `;
861
+ }
862
+
863
+ async function seedRows() {
864
+ const runtime = await runtimeReady;
865
+ const runRuntime = runtime.runRuntime;
866
+ const mode = getMode();
867
+ const normal = runtimeConfig(source.value, mode, false);
868
+ let result = runRuntime(normal.text, normal.options);
869
+ let rows = sourceRowsFromRuntimeResult(result);
870
+ if (mode !== "transport" && (result.meta?.errors?.length ?? 0) > 0) {
871
+ const relaxed = runtimeConfig(source.value, mode, true);
872
+ const relaxedResult = runRuntime(relaxed.text, relaxed.options);
873
+ const relaxedRows = sourceRowsFromRuntimeResult(relaxedResult);
874
+ if (relaxedRows.length > 0) {
875
+ result = relaxedResult;
876
+ rows = relaxedRows;
877
+ }
878
+ }
879
+ state.rows = rows;
880
+ addStandaloneCommentRows(source.value, state.rows);
881
+ if (mode !== "transport") {
882
+ for (const row of state.rows) {
883
+ if (row.kind !== "comment" && !row.datatype) row.datatype = datatypeForSourceType(row.type);
884
+ }
885
+ }
886
+ state.selectedPath = state.rows[0]?.path ?? null;
887
+ }
888
+
889
+ async function open(trigger = openButton) {
890
+ await seedRows();
891
+ render();
892
+ window.AeonAccessibility?.openModal(modal, trigger);
893
+ }
894
+
895
+ function close() {
896
+ window.AeonAccessibility?.closeModal(modal);
897
+ }
898
+
899
+ function syncDetail() {
900
+ if (!state.selectedPath) return;
901
+ const row = state.rows.find((candidate) => candidate.path === state.selectedPath);
902
+ if (!row) return;
903
+ const data = new FormData(detail);
904
+ if (row.kind === "comment") {
905
+ row.commentType = String(data.get("commentType") || "doc");
906
+ row.value = String(data.get("value") ?? "");
907
+ return;
908
+ }
909
+ const previousPath = row.path;
910
+ const previousType = row.type;
911
+ const previousDatatype = row.datatype;
912
+ const type = String(data.get("type") || row.type);
913
+ const name = String(data.get("name") || sourcePathName(row.path)).trim();
914
+ const parent = sourceParentPath(row.path);
915
+ const isAttribute = sourcePathIsAttribute(row.path);
916
+ const defaultPreviousDatatype = datatypeForSourceType(previousType);
917
+ const defaultNextDatatype = datatypeForSourceType(type);
918
+ const previousDatatypeWasReservedForType = sourceTypeForDatatype(previousDatatype) === previousType;
919
+ row.type = type;
920
+ row.datatype = previousType === type
921
+ ? String(data.get("datatype") ?? "")
922
+ : previousDatatype === defaultPreviousDatatype || previousDatatypeWasReservedForType ? defaultNextDatatype : String(data.get("datatype") || "");
923
+ if (type === "NullLiteral") {
924
+ const nullMode = String(data.get("nullMode") || "none");
925
+ row.value = nullMode === "custom" ? `custom:${String(data.get("value") ?? "")}` : nullMode;
926
+ } else {
927
+ row.value = previousType === type ? String(data.get("value") ?? sourceDefaultValue(type)) : sourceDefaultValue(type);
928
+ }
929
+ const children = sourceValueChildren(row.path);
930
+ const allowedTypes = previousType === "ListNode" || previousType === "TupleNode" ? ["ListNode", "TupleNode"] : [previousType];
931
+ if (children.length > 0 && !allowedTypes.includes(type)) {
932
+ row.type = previousType;
933
+ row.datatype = datatypeForSourceType(row.type);
934
+ }
935
+ if (name && (!/^\[\d+\]$/.test(sourcePathName(row.path)) || isAttribute)) {
936
+ const nextPath = joinSourcePath(parent, isAttribute ? `@${name.replace(/^@/, "")}` : name);
937
+ if (nextPath !== previousPath && !state.rows.some((candidate) => candidate.path === nextPath)) {
938
+ for (const candidate of state.rows) {
939
+ if (candidate.path === previousPath || sourcePathIsDescendant(candidate.path, previousPath)) {
940
+ candidate.path = `${nextPath}${candidate.path.slice(previousPath.length)}`;
941
+ }
942
+ }
943
+ state.selectedPath = nextPath;
944
+ }
945
+ }
946
+ }
947
+
948
+ function addRow(kind) {
949
+ syncDetail();
950
+ const rows = state.rows;
951
+ const selected = rows.find((row) => row.path === state.selectedPath) ?? rows[0];
952
+ const selectedIsAttribute = sourcePathIsAttribute(selected?.path ?? "");
953
+ const selectedIsComment = sourcePathIsComment(selected?.path ?? "");
954
+ const base = kind === "attribute" && selected && !selectedIsAttribute
955
+ ? selected.path
956
+ : kind === "comment" && selected && !selectedIsAttribute && !selectedIsComment
957
+ ? selected.path
958
+ : kind === "child" && selected && !selectedIsAttribute && sourceTypeAllowsChildren(selected.type)
959
+ ? selected.path
960
+ : sourceParentPath(selected?.path ?? "");
961
+ const parent = rows.find((row) => row.path === base);
962
+ const childIndex = sourceValueChildren(base, rows).length;
963
+ const attrNames = new Set(sourceChildren(base, rows).filter((row) => sourcePathIsAttribute(row.path)).map((row) => sourcePathName(row.path)));
964
+ const commentNames = new Set(sourceChildren(base, rows).filter((row) => sourcePathIsComment(row.path)).map((row) => sourcePathName(row.path)));
965
+ let attrIndex = attrNames.size + 1;
966
+ while (attrNames.has(`@attr${attrIndex}`)) attrIndex += 1;
967
+ let commentIndex = commentNames.size + 1;
968
+ while (commentNames.has(`//${commentIndex}`)) commentIndex += 1;
969
+ const name = kind === "comment"
970
+ ? `#comment${commentIndex}`
971
+ : kind === "attribute"
972
+ ? `@attr${attrIndex}`
973
+ : parent?.type === "ListNode" || parent?.type === "TupleNode" || parent?.type === "NodeLiteral" ? `[${childIndex}]` : `field${childIndex + 1}`;
974
+ const path = joinSourcePath(base, name);
975
+ rows.push({
976
+ path,
977
+ ...(kind === "comment" ? { kind: "comment", commentType: "doc" } : {}),
978
+ type: "StringLiteral",
979
+ datatype: getMode() === "transport" || kind === "comment" ? "" : "string",
980
+ value: kind === "comment" ? "Comment" : "",
981
+ open: true
982
+ });
983
+ if (parent) parent.open = true;
984
+ state.selectedPath = path;
985
+ render();
986
+ }
987
+
988
+ function removeRow() {
989
+ const path = state.selectedPath;
990
+ if (!path) return;
991
+ const visibleBeforeRemove = visibleSourceRows(state.rows);
992
+ const removedIndex = visibleBeforeRemove.findIndex((row) => row.path === path);
993
+ const nextSelectedPath = removedIndex > 0
994
+ ? visibleBeforeRemove[removedIndex - 1]?.path
995
+ : visibleBeforeRemove.find((row, index) => index > removedIndex && !sourcePathIsDescendant(row.path, path))?.path;
996
+ state.rows = state.rows.filter((row) => row.path !== path && !sourcePathIsDescendant(row.path, path));
997
+ state.selectedPath = nextSelectedPath && state.rows.some((row) => row.path === nextSelectedPath)
998
+ ? nextSelectedPath
999
+ : state.rows[0]?.path ?? null;
1000
+ render();
1001
+ }
1002
+
1003
+ function buildSource() {
1004
+ syncDetail();
1005
+ const rows = orderedSourceRows(state.rows);
1006
+ const header = preservedHeaderSource(source.value);
1007
+ const body = rows
1008
+ .filter((row) => !sourceParentPath(row.path) && !sourcePathIsAttribute(row.path) && !sourcePathIsComment(row.path))
1009
+ .map((row) => renderSourceBuilderBinding(row, rows))
1010
+ .join("\n");
1011
+ return [header, body].filter(Boolean).join("\n");
1012
+ }
1013
+
1014
+ openButton?.addEventListener("click", () => open().catch((error) => onError(error)));
1015
+ reloadButton?.addEventListener("click", () => seedRows().then(render).catch((error) => onError(error)));
1016
+ applyButton?.addEventListener("click", () => {
1017
+ source.value = buildSource();
1018
+ source.dispatchEvent(new Event("input", { bubbles: true }));
1019
+ close();
1020
+ onApply(source.value);
1021
+ });
1022
+ addPeerButton?.addEventListener("click", () => addRow("peer"));
1023
+ addChildButton?.addEventListener("click", () => addRow("child"));
1024
+ addAttributeButton?.addEventListener("click", () => addRow("attribute"));
1025
+ addCommentButton?.addEventListener("click", () => addRow("comment"));
1026
+ removeButton?.addEventListener("click", removeRow);
1027
+ closeButtons.forEach((button) => button.addEventListener("click", close));
1028
+
1029
+ tree.addEventListener("click", (event) => {
1030
+ const item = event.target.closest("[data-source-builder-path]");
1031
+ if (!item) return;
1032
+ syncDetail();
1033
+ const path = item.dataset.sourceBuilderPath;
1034
+ state.selectedPath = path;
1035
+ if (event.target.closest(".source-builder-twist")) {
1036
+ const row = state.rows.find((candidate) => candidate.path === path);
1037
+ if (row && sourceValueChildren(row.path).length > 0) row.open = row.open === false;
1038
+ }
1039
+ render();
1040
+ });
1041
+
1042
+ detail.addEventListener("input", (event) => {
1043
+ if (event.target?.name === "type") return;
1044
+ syncDetail();
1045
+ if (event.target?.name === "commentType" || state.rows.find((row) => row.path === state.selectedPath)?.kind === "comment") {
1046
+ render();
1047
+ detail.querySelector(`[name="${event.target?.name}"]`)?.focus();
1048
+ }
1049
+ });
1050
+ detail.addEventListener("change", (event) => {
1051
+ if (event.target?.name === "commentType") {
1052
+ syncDetail();
1053
+ render();
1054
+ detail.querySelector('[name="commentType"]')?.focus();
1055
+ return;
1056
+ }
1057
+ if (event.target?.name === "nullMode") {
1058
+ syncDetail();
1059
+ render();
1060
+ detail.querySelector('[name="nullMode"]')?.focus();
1061
+ return;
1062
+ }
1063
+ if (event.target?.name === "type") {
1064
+ syncDetail();
1065
+ render();
1066
+ }
1067
+ });
1068
+
1069
+ const keydown = (event) => {
1070
+ if (event.key === "Escape" && !modal.hidden) close();
1071
+ };
1072
+ document.addEventListener("keydown", keydown);
1073
+
1074
+ return { open, close, destroy: () => document.removeEventListener("keydown", keydown) };
1075
+ }
1076
+
1077
+ window.AeonSourceComposer = { mount: mountAeonSourceComposer };