@elementumai/edk 0.10.1 → 0.10.3

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 (125) hide show
  1. package/README.md +7 -7
  2. package/dist-sdk/src/catalog/org.d.ts +7 -5
  3. package/dist-sdk/src/catalog/org.js +14 -9
  4. package/dist-sdk/src/catalog/token.js +4 -0
  5. package/dist-sdk/src/core/types/app.d.ts +22 -0
  6. package/dist-sdk/src/engine/build/context.d.ts +8 -0
  7. package/dist-sdk/src/engine/build/source-context.d.ts +3 -4
  8. package/dist-sdk/src/engine/coverage-gaps.d.ts +2 -0
  9. package/dist-sdk/src/engine/coverage-gaps.js +3 -0
  10. package/dist-sdk/src/engine/ei/state.d.ts +48 -0
  11. package/dist-sdk/src/engine/ei/state.js +91 -0
  12. package/dist-sdk/src/engine/pull/authored-address.d.ts +100 -0
  13. package/dist-sdk/src/engine/pull/authored-address.js +360 -0
  14. package/dist-sdk/src/engine/pull/context.d.ts +59 -0
  15. package/dist-sdk/src/engine/tf/expr.d.ts +7 -0
  16. package/dist-sdk/src/engine/tf/expr.js +62 -18
  17. package/dist-sdk/src/engine/tf/index.d.ts +1 -1
  18. package/dist-sdk/src/engine/tf/index.js +1 -1
  19. package/dist-sdk/src/engine/tf/labels.d.ts +10 -2
  20. package/dist-sdk/src/engine/tf/labels.js +15 -2
  21. package/dist-sdk/src/engine/tf/parse.js +19 -6
  22. package/dist-sdk/src/engine/workspace/backend.d.ts +34 -0
  23. package/dist-sdk/src/engine/workspace/backend.js +104 -0
  24. package/dist-sdk/src/engine/workspace/generated-file.d.ts +3 -0
  25. package/dist-sdk/src/engine/workspace/generated-file.js +6 -0
  26. package/dist-sdk/src/engine/workspace/loader.js +2 -2
  27. package/dist-sdk/src/entities/agent-tool/to-tf.js +1 -1
  28. package/dist-sdk/src/entities/app/build.d.ts +36 -4
  29. package/dist-sdk/src/entities/app/build.js +67 -4
  30. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +12 -0
  31. package/dist-sdk/src/entities/app/from-tf.js +13 -9
  32. package/dist-sdk/src/entities/app/module.js +3 -1
  33. package/dist-sdk/src/entities/app/stage-keys.d.ts +82 -0
  34. package/dist-sdk/src/entities/app/stage-keys.js +160 -0
  35. package/dist-sdk/src/entities/app/to-tf.js +21 -21
  36. package/dist-sdk/src/entities/approval-chain/from-tf.d.ts +9 -1
  37. package/dist-sdk/src/entities/approval-chain/from-tf.js +31 -3
  38. package/dist-sdk/src/entities/approval-chain/module.js +12 -4
  39. package/dist-sdk/src/entities/approval-chain/to-tf.d.ts +1 -0
  40. package/dist-sdk/src/entities/approval-chain/to-tf.js +6 -1
  41. package/dist-sdk/src/entities/automation/build.d.ts +2 -0
  42. package/dist-sdk/src/entities/automation/build.js +25 -17
  43. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +3 -0
  44. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +5 -3
  45. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +127 -31
  46. package/dist-sdk/src/entities/automation/from-tf.d.ts +28 -6
  47. package/dist-sdk/src/entities/automation/from-tf.js +172 -27
  48. package/dist-sdk/src/entities/automation/module.js +123 -37
  49. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +21 -0
  50. package/dist-sdk/src/entities/automation/output-key-wire-name.js +38 -0
  51. package/dist-sdk/src/entities/automation/to-tf.d.ts +3 -1
  52. package/dist-sdk/src/entities/automation/to-tf.js +191 -33
  53. package/dist-sdk/src/entities/automation/triggers.d.ts +2 -0
  54. package/dist-sdk/src/entities/automation/triggers.js +1 -0
  55. package/dist-sdk/src/entities/chart/from-tf.d.ts +6 -0
  56. package/dist-sdk/src/entities/chart/from-tf.js +9 -1
  57. package/dist-sdk/src/entities/dashboard/from-tf.js +51 -4
  58. package/dist-sdk/src/entities/dynamic-layout/from-tf.d.ts +3 -0
  59. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +48 -4
  60. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +2 -0
  61. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +7 -2
  62. package/dist-sdk/src/entities/element/build.js +1 -1
  63. package/dist-sdk/src/entities/element/from-tf.d.ts +12 -6
  64. package/dist-sdk/src/entities/element/from-tf.js +23 -7
  65. package/dist-sdk/src/entities/element/module.js +5 -3
  66. package/dist-sdk/src/entities/element/to-tf.d.ts +3 -2
  67. package/dist-sdk/src/entities/element/to-tf.js +36 -25
  68. package/dist-sdk/src/entities/field/allow-list.d.ts +18 -0
  69. package/dist-sdk/src/entities/field/allow-list.js +42 -0
  70. package/dist-sdk/src/entities/field/build.d.ts +38 -3
  71. package/dist-sdk/src/entities/field/build.js +7 -2
  72. package/dist-sdk/src/entities/field/from-tf.js +252 -76
  73. package/dist-sdk/src/entities/field/module.d.ts +6 -0
  74. package/dist-sdk/src/entities/field/module.js +24 -2
  75. package/dist-sdk/src/entities/field/options.d.ts +2 -0
  76. package/dist-sdk/src/entities/field/order.d.ts +25 -0
  77. package/dist-sdk/src/entities/field/order.js +74 -0
  78. package/dist-sdk/src/entities/field/to-tf.d.ts +6 -0
  79. package/dist-sdk/src/entities/field/to-tf.js +87 -0
  80. package/dist-sdk/src/entities/field/types.d.ts +5 -0
  81. package/dist-sdk/src/entities/field/types.js +8 -0
  82. package/dist-sdk/src/entities/relationship/build.d.ts +3 -3
  83. package/dist-sdk/src/entities/relationship/from-tf.js +4 -2
  84. package/dist-sdk/src/entities/relationship/to-tf.js +3 -1
  85. package/dist-sdk/src/entities/service-account/workspace-owner.d.ts +8 -3
  86. package/dist-sdk/src/entities/service-account/workspace-owner.js +12 -4
  87. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +5 -0
  88. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +13 -0
  89. package/dist-sdk/src/entities/shared/filters/ast.d.ts +7 -0
  90. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +1 -1
  91. package/dist-sdk/src/entities/skill/to-tf.js +19 -14
  92. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +2 -0
  93. package/dist-sdk/src/entities/skill-tool/from-tf.js +3 -0
  94. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +6 -1
  95. package/dist-sdk/src/entities/skill-tool/to-tf.js +6 -1
  96. package/dist-sdk/src/entities/task/build.js +1 -1
  97. package/dist-sdk/src/entities/task/module.js +2 -1
  98. package/dist-sdk/src/entities/task/to-tf.js +4 -0
  99. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.d.ts +11 -0
  100. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.js +13 -38
  101. package/dist-sdk/src/entities/view/custom-view-validate.d.ts +29 -0
  102. package/dist-sdk/src/entities/view/custom-view-validate.js +292 -0
  103. package/dist-sdk/src/entities/view/from-tf.d.ts +2 -0
  104. package/dist-sdk/src/entities/view/from-tf.js +40 -6
  105. package/dist-sdk/src/entities/view/module.js +4 -1
  106. package/dist-sdk/src/entities/view/to-tf.d.ts +6 -0
  107. package/dist-sdk/src/entities/view/to-tf.js +25 -9
  108. package/dist-sdk/src/entities/view/types.d.ts +6 -0
  109. package/dist-sdk/src/entities/view/types.js +6 -0
  110. package/dist-sdk/src/entities/visual-flow/from-tf.d.ts +2 -1
  111. package/dist-sdk/src/entities/visual-flow/from-tf.js +11 -2
  112. package/dist-sdk/src/entities/visual-flow/module.js +15 -5
  113. package/dist-sdk/src/entities/visual-flow/to-tf.d.ts +2 -0
  114. package/dist-sdk/src/entities/visual-flow/to-tf.js +1 -1
  115. package/dist-sdk/src/entities/widget/build.d.ts +8 -1
  116. package/dist-sdk/src/entities/widget/from-tf.js +12 -6
  117. package/dist-sdk/src/entities/widget/to-tf.d.ts +1 -0
  118. package/dist-sdk/src/entities/widget/to-tf.js +16 -0
  119. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +8 -2
  120. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  121. package/dist-sdk/src/graph/index.d.ts +9 -2
  122. package/dist-sdk/src/graph/index.js +4 -0
  123. package/dist-sdk/src/graph/modules.js +2 -1
  124. package/dist-sdk/src/graph/types.d.ts +72 -3
  125. package/package.json +2 -17
@@ -0,0 +1,360 @@
1
+ import { sanitizeName, tsLabelToTfLabel } from "../tf/labels.js";
2
+ import { isTfExpr } from "../tf/model.js";
3
+ /** The platform id an import id ends with (`<parent>/<id>` and `<a>:<id>` forms included). */
4
+ export function canonicalImportId(importId) {
5
+ const last = importId.split(/[:/]/).at(-1);
6
+ return last === undefined || last === "" ? importId : last;
7
+ }
8
+ function typedIdentity(type, id) {
9
+ return `${type}\u0000${canonicalImportId(id)}`;
10
+ }
11
+ function addressType(address) {
12
+ const dot = address.indexOf(".");
13
+ return dot === -1 ? undefined : address.slice(0, dot);
14
+ }
15
+ /**
16
+ * Index managed state by resource type and canonical platform identity.
17
+ *
18
+ * Type is part of the key because composite resources can expose two provider
19
+ * resource types backed by the same platform object and ID.
20
+ */
21
+ export function authoredAddressesById(resources) {
22
+ const addresses = new Map();
23
+ const ambiguous = new Set();
24
+ for (const resource of resources) {
25
+ if (resource.mode !== "managed" ||
26
+ typeof resource.type !== "string" ||
27
+ typeof resource.name !== "string") {
28
+ continue;
29
+ }
30
+ const address = `${resource.type}.${resource.name}`;
31
+ for (const instance of resource.instances ?? []) {
32
+ const id = instance.attributes?.id;
33
+ if (typeof id !== "string" || id === "")
34
+ continue;
35
+ const identity = typedIdentity(resource.type, id);
36
+ if (ambiguous.has(identity))
37
+ continue;
38
+ const prior = addresses.get(identity);
39
+ if (prior !== undefined && prior !== address) {
40
+ addresses.delete(identity);
41
+ ambiguous.add(identity);
42
+ continue;
43
+ }
44
+ addresses.set(identity, address);
45
+ }
46
+ }
47
+ return addresses;
48
+ }
49
+ /**
50
+ * Every managed type + canonical id state holds, including one bound at two
51
+ * addresses (which `authoredAddressesById` drops). An identity in this set is
52
+ * never treated as new to the workspace.
53
+ */
54
+ export function managedStateIdentities(resources) {
55
+ const identities = new Set();
56
+ for (const resource of resources) {
57
+ if (resource.mode !== "managed" || typeof resource.type !== "string")
58
+ continue;
59
+ for (const instance of resource.instances ?? []) {
60
+ const id = instance.attributes?.id;
61
+ if (typeof id === "string" && id !== "")
62
+ identities.add(typedIdentity(resource.type, id));
63
+ }
64
+ }
65
+ return identities;
66
+ }
67
+ const AUTHORED_FIELD_RE = /(?:^|[\s,{])([A-Za-z_$][\w$]*)\s*:\s*([a-z][A-Za-z0-9]*)Field\(\s*\{([^{}]*?)\bname:\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')/g;
68
+ /**
69
+ * Field bag keys an authored app/element source declares, with the display
70
+ * name and constructor that identify the platform field on a stateless pull
71
+ * (#1579). Only the literal `name:` form is recognized; anything else is
72
+ * simply not matched and keeps its export label.
73
+ */
74
+ export function authoredSourceFields(source) {
75
+ const out = [];
76
+ for (const match of source.matchAll(AUTHORED_FIELD_RE)) {
77
+ const raw = match[4] ?? match[5];
78
+ if (raw === undefined)
79
+ continue;
80
+ // Escapes in display names are rare; keep the escaped character literally.
81
+ const name = raw.replace(/\\(.)/g, "$1");
82
+ out.push({ key: match[1], ctor: match[2], name });
83
+ }
84
+ return out;
85
+ }
86
+ /**
87
+ * Stateless fallback for {@link authoredAddressesById}: bind each exported
88
+ * field to the address its authored bag key builds, when exactly one authored
89
+ * field shares its resource type and display name. State stays authoritative:
90
+ * identities already in `stateById` are left alone.
91
+ */
92
+ export function authoredAddressesFromSource(doc, importIds, fields, stateById, resourceTypeForCtor) {
93
+ const byId = new Map();
94
+ const matched = new Set();
95
+ const stateBound = new Set();
96
+ for (const block of doc.blocks) {
97
+ if (block.kind !== "resource" || block.type === undefined || block.label === undefined)
98
+ continue;
99
+ const name = block.attrs["name"];
100
+ if (typeof name !== "string")
101
+ continue;
102
+ const candidates = fields.filter((f) => resourceTypeForCtor(f.ctor) === block.type && f.name === name);
103
+ if (candidates.length !== 1)
104
+ continue;
105
+ const field = candidates[0];
106
+ const id = importIds.get(`${block.type}.${block.label}`);
107
+ if (id === undefined)
108
+ continue;
109
+ const identity = typedIdentity(block.type, id);
110
+ if (stateById.has(identity)) {
111
+ stateBound.add(field);
112
+ continue;
113
+ }
114
+ const suffix = sanitizeName(name);
115
+ if (suffix === "" || !block.label.endsWith(suffix))
116
+ continue;
117
+ const target = `${block.label.slice(0, block.label.length - suffix.length)}${tsLabelToTfLabel(field.key)}`;
118
+ matched.add(field);
119
+ if (target !== block.label)
120
+ byId.set(identity, `${block.type}.${target}`);
121
+ }
122
+ const unmatched = fields.filter((f) => !matched.has(f) && !stateBound.has(f));
123
+ return { byId, unmatched };
124
+ }
125
+ /**
126
+ * Unmatched authored fields whose key other hand-written files still
127
+ * reference as `.<key>`; those references break after the pull (#1579).
128
+ */
129
+ export function staleAuthoredFieldReferences(unmatched, otherSources) {
130
+ return unmatched.filter((field) => {
131
+ const ref = new RegExp(`\\.${field.key.replace(/\$/g, "\\$")}\\b`);
132
+ return otherSources.some((text) => ref.test(text));
133
+ });
134
+ }
135
+ /**
136
+ * Join export addresses to the addresses state already binds, by platform id.
137
+ *
138
+ * ei numbers same-named resources `_1`, `_2` in its export order, so a label
139
+ * can change hands between pulls (#1658). An authored target the export gives
140
+ * to another identity is still taken back when that occupant moves to its own
141
+ * authored address, or when the occupant is new to state and the label the
142
+ * moving identity left is free: the occupant takes that label instead (a swap).
143
+ * An occupant counts as new only when `inState` (every managed identity state
144
+ * holds) is given and doesn't contain it. Anything else stays at its export
145
+ * address and is reported.
146
+ */
147
+ function resolveAuthoredAddresses(importIds, authoredById, inState) {
148
+ const claimsByTarget = new Map();
149
+ for (const [from, id] of importIds) {
150
+ const type = addressType(from);
151
+ if (type === undefined)
152
+ continue;
153
+ const to = authoredById.get(typedIdentity(type, id));
154
+ if (to === undefined || to === from)
155
+ continue;
156
+ const claims = claimsByTarget.get(to);
157
+ if (claims === undefined)
158
+ claimsByTarget.set(to, [from]);
159
+ else
160
+ claims.push(from);
161
+ }
162
+ const ambiguities = [];
163
+ const pending = new Map();
164
+ for (const [authoredTarget, from] of claimsByTarget) {
165
+ if (from.length > 1)
166
+ ambiguities.push({ authoredTarget, from });
167
+ else
168
+ pending.set(from[0], authoredTarget);
169
+ }
170
+ const authoredAddresses = new Set(authoredById.values());
171
+ const accepted = new Map();
172
+ const acceptedTargets = new Set();
173
+ const aliases = [];
174
+ const accept = (from, to) => {
175
+ accepted.set(from, to);
176
+ acceptedTargets.add(to);
177
+ aliases.push({ from, to });
178
+ };
179
+ // A move whose target is held by another moving identity waits for that move.
180
+ for (let progressed = true; progressed && pending.size > 0;) {
181
+ progressed = false;
182
+ for (const [from, to] of pending) {
183
+ const occupiedById = importIds.get(to);
184
+ const sourceId = importIds.get(from);
185
+ const free = occupiedById === undefined || canonicalImportId(occupiedById) === canonicalImportId(sourceId);
186
+ const occupant = occupiedById === undefined ? undefined : typedIdentity(addressType(to), occupiedById);
187
+ const occupantNew = occupant !== undefined && inState !== undefined && !inState.has(occupant) && !authoredById.has(occupant);
188
+ const vacatedFree = !authoredAddresses.has(from) && !claimsByTarget.has(from) && !acceptedTargets.has(from);
189
+ if (free || accepted.has(to)) {
190
+ accept(from, to);
191
+ }
192
+ else if (pending.get(to) === from) {
193
+ // Two managed identities whose labels traded places.
194
+ accept(from, to);
195
+ accept(to, from);
196
+ pending.delete(to);
197
+ }
198
+ else if (occupantNew && vacatedFree) {
199
+ accept(from, to);
200
+ accept(to, from);
201
+ }
202
+ else {
203
+ continue;
204
+ }
205
+ pending.delete(from);
206
+ progressed = true;
207
+ }
208
+ }
209
+ const conflicts = [...pending].map(([from, authoredTarget]) => ({
210
+ from,
211
+ authoredTarget,
212
+ occupiedById: importIds.get(authoredTarget) ?? "",
213
+ }));
214
+ return { aliases, ambiguities, conflicts };
215
+ }
216
+ /**
217
+ * Resolve export addresses to addresses already bound in authored state.
218
+ *
219
+ * A first-pull resource has no state binding and keeps its export address.
220
+ * Ambiguous many-to-one aliases are omitted rather than merging resources.
221
+ */
222
+ export function authoredAddressAliases(importIds, authoredById, inState) {
223
+ return resolveAuthoredAddresses(importIds, authoredById, inState).aliases;
224
+ }
225
+ /**
226
+ * Two export addresses claiming one authored target cannot be joined
227
+ * without guessing. Report them the same way occupancy conflicts are.
228
+ */
229
+ export function authoredAddressAmbiguities(importIds, authoredById, inState) {
230
+ return resolveAuthoredAddresses(importIds, authoredById, inState).ambiguities;
231
+ }
232
+ /**
233
+ * Collapse authored (export → state) and extract (post-relabel → rebuild)
234
+ * aliases into a single export → final hop. Extract aliases name the
235
+ * already-relabelled address as `from`; adoption still keys import ids by
236
+ * the pre-relabel export address.
237
+ */
238
+ export function composeAdoptionAddressAliases(authoredAliases, extractAliases) {
239
+ const exportFromByAuthored = new Map();
240
+ for (const { from, to } of authoredAliases) {
241
+ if (from !== to)
242
+ exportFromByAuthored.set(to, from);
243
+ }
244
+ const composed = [];
245
+ const consumedExportFrom = new Set();
246
+ for (const { from, to } of extractAliases) {
247
+ const exportFrom = exportFromByAuthored.get(from) ?? from;
248
+ consumedExportFrom.add(exportFrom);
249
+ if (exportFrom !== to)
250
+ composed.push({ from: exportFrom, to });
251
+ }
252
+ for (const alias of authoredAliases) {
253
+ if (alias.from === alias.to || consumedExportFrom.has(alias.from))
254
+ continue;
255
+ composed.push(alias);
256
+ }
257
+ return composed;
258
+ }
259
+ /**
260
+ * State can be stale enough, or same-named labels can shift far enough, that
261
+ * an identity's authored address stays held by a different identity even
262
+ * after resolution. Such a rename is unsafe; report it while leaving both
263
+ * resources at their export addresses.
264
+ */
265
+ export function authoredAddressConflicts(importIds, authoredById, inState) {
266
+ return resolveAuthoredAddresses(importIds, authoredById, inState).conflicts;
267
+ }
268
+ const CALCULATION_LOCAL_PREFIXES = [
269
+ "edk_calculation_type_",
270
+ "edk_calculation_outputs_",
271
+ "edk_variable_id_",
272
+ "edk_variable_ids_",
273
+ "edk_unsupported_bindings_",
274
+ ];
275
+ function labelSuffixRewrites(labels) {
276
+ return [...labels.entries()]
277
+ .map(([key, to]) => ({ from: key.slice(key.indexOf("\u0000") + 1), to }))
278
+ .sort((a, b) => b.from.length - a.from.length);
279
+ }
280
+ function rewriteCalculationLocalName(name, rewrites) {
281
+ for (const { from, to } of rewrites) {
282
+ for (const prefix of CALCULATION_LOCAL_PREFIXES) {
283
+ if (name === `${prefix}${from}`)
284
+ return `${prefix}${to}`;
285
+ }
286
+ }
287
+ return name;
288
+ }
289
+ function relabelValue(value, labels, localRewrites) {
290
+ if (Array.isArray(value))
291
+ return value.map((item) => relabelValue(item, labels, localRewrites));
292
+ if (value === null || typeof value !== "object")
293
+ return value;
294
+ if (isTfExpr(value)) {
295
+ switch (value.$expr) {
296
+ case "resource-attr": {
297
+ const label = labels.get(`${value.type}\u0000${value.label}`);
298
+ return label === undefined ? value : { ...value, label };
299
+ }
300
+ case "local": {
301
+ const name = rewriteCalculationLocalName(value.name, localRewrites);
302
+ return name === value.name ? value : { ...value, name };
303
+ }
304
+ case "jsonencode":
305
+ return { ...value, value: relabelValue(value.value, labels, localRewrites) };
306
+ case "template":
307
+ return {
308
+ ...value,
309
+ parts: value.parts.map((part) => typeof part === "string" ? part : relabelValue(part, labels, localRewrites)),
310
+ };
311
+ case "for-object":
312
+ return {
313
+ ...value,
314
+ collection: relabelValue(value.collection, labels, localRewrites),
315
+ key: relabelValue(value.key, labels, localRewrites),
316
+ value: relabelValue(value.value, labels, localRewrites),
317
+ };
318
+ default:
319
+ // data-attr is a lookup, not an address authored by this workspace.
320
+ return value;
321
+ }
322
+ }
323
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, relabelValue(child, labels, localRewrites)]));
324
+ }
325
+ /**
326
+ * Relabel resource blocks and all managed references before extraction so
327
+ * printers recover the workspace's existing bag keys and own-file names.
328
+ */
329
+ export function relabelDocument(doc, aliases) {
330
+ if (aliases.length === 0)
331
+ return doc;
332
+ const labels = new Map();
333
+ for (const { from, to } of aliases) {
334
+ const fromDot = from.indexOf(".");
335
+ const toDot = to.indexOf(".");
336
+ if (fromDot === -1 || toDot === -1)
337
+ continue;
338
+ labels.set(`${from.slice(0, fromDot)}\u0000${from.slice(fromDot + 1)}`, to.slice(toDot + 1));
339
+ }
340
+ if (labels.size === 0)
341
+ return doc;
342
+ const localRewrites = labelSuffixRewrites(labels);
343
+ return {
344
+ ...doc,
345
+ blocks: doc.blocks.map((block) => {
346
+ const rewrittenAttrs = relabelValue(block.attrs, labels, localRewrites);
347
+ const attrs = block.kind === "locals"
348
+ ? Object.fromEntries(Object.entries(rewrittenAttrs).map(([key, child]) => [
349
+ rewriteCalculationLocalName(key, localRewrites),
350
+ child,
351
+ ]))
352
+ : rewrittenAttrs;
353
+ if (block.kind !== "resource" || block.type === undefined || block.label === undefined) {
354
+ return { ...block, attrs };
355
+ }
356
+ const label = labels.get(`${block.type}\u0000${block.label}`);
357
+ return label === undefined ? { ...block, attrs } : { ...block, label, attrs };
358
+ }),
359
+ };
360
+ }
@@ -1,9 +1,14 @@
1
1
  import { type TfValue } from "../tf/index.js";
2
+ import type { EntityKindId } from "../../graph/index.js";
2
3
  /** A `data-attr` reference recorded on a data block in the same stream. */
3
4
  export interface DataRef {
4
5
  readonly resourceType: string;
5
6
  readonly tfLabel: string;
6
7
  }
8
+ export interface ServiceAccountIdentity {
9
+ readonly name: string;
10
+ readonly appRefName: string;
11
+ }
7
12
  /** A managed resource recovered from the same export stream by its import id. */
8
13
  export interface ImportedResourceRef {
9
14
  readonly type: string;
@@ -97,6 +102,11 @@ export interface FromTfContext {
97
102
  * which one a reference means (edk#1412).
98
103
  */
99
104
  readonly groupKeysByName?: ReadonlyMap<string, string>;
105
+ /**
106
+ * Service account id → its name and owning app's catalog key, from state.
107
+ * ei writes a service account owned by another app as a bare id.
108
+ */
109
+ readonly serviceAccountsById?: ReadonlyMap<string, ServiceAccountIdentity>;
100
110
  /**
101
111
  * Foreign app/element display names this stream saw referenced (currently:
102
112
  * a RELATION field's `related_object_id` as a `data.elementum_app`/
@@ -140,6 +150,14 @@ export interface FromTfContext {
140
150
  * `field/from-tf.ts`'s `implemented` check for the motivating case.
141
151
  */
142
152
  readonly skipped: string[];
153
+ /**
154
+ * The subset of `skipped` that no authored source can ever manage (e.g. a
155
+ * layout on a stage with no handle of its own, #1136). If an earlier pull
156
+ * already adopted them, adoption releases them from state so the next
157
+ * apply does not destroy the live resources. Undefined for a caller that
158
+ * does not wire it up.
159
+ */
160
+ readonly releaseIfManaged?: string[];
143
161
  /**
144
162
  * Authoring blockers: live configuration that authored source cannot
145
163
  * reproduce, where printing what pull CAN reconstruct would make the next
@@ -150,6 +168,47 @@ export interface FromTfContext {
150
168
  * author it may proceed. Report through {@link reportAuthoringBlocker}.
151
169
  */
152
170
  readonly authoringBlockers?: AuthoringBlocker[];
171
+ /**
172
+ * Root-extracted resources that only round-trip together with an own-file
173
+ * resource extracted later (a dashboard chart widget and its chart,
174
+ * #1731). Once own-file extraction is done, stream-root checks each one.
175
+ * When the build will not emit it (its `requires` was skipped and no
176
+ * authored file for it is kept, is missing from the export, or never named
177
+ * a resource this pull extracts), `prune` removes it from the root, and it
178
+ * is skipped and released, so the next plan never destroys it. Undefined
179
+ * for a caller that does not wire it up.
180
+ */
181
+ readonly requiresExtracted?: ExtractRequirement[];
182
+ }
183
+ /** See {@link FromTfContext.requiresExtracted}. */
184
+ export interface ExtractRequirement {
185
+ /** Address (`type.label`) of the dependent resource. */
186
+ readonly address: string;
187
+ /**
188
+ * What it cannot be authored without: the address of an own-file resource
189
+ * in this stream, or, for an `unresolved` reference, how the export named it.
190
+ */
191
+ readonly requires: string;
192
+ /**
193
+ * The reference is not a managed resource this pull extracts (a raw id or a
194
+ * data source). The dependent is never written to source, so it is always
195
+ * skipped and released (#1731 SF2).
196
+ */
197
+ readonly unresolved?: true;
198
+ /**
199
+ * The own-file `requires` is printed as. When pull skips it but keeps that
200
+ * authored file, build still emits both, so the dependent stays (#1731 SF3).
201
+ */
202
+ readonly requiresOwnFile?: {
203
+ readonly kind: EntityKindId;
204
+ readonly refName: string;
205
+ };
206
+ /** The stream root without the dependent resource. */
207
+ readonly prune: (root: {
208
+ readonly refName: string;
209
+ }) => {
210
+ readonly refName: string;
211
+ };
153
212
  }
154
213
  /**
155
214
  * Live configuration authored source cannot reproduce unchanged. Only its
@@ -25,5 +25,12 @@ export interface ExpressionParseOptions {
25
25
  readonly allowVariables?: boolean;
26
26
  }
27
27
  export declare function parseStringValue(raw: string, options?: ExpressionParseOptions): string | TfExpr;
28
+ /**
29
+ * Index just past the quoted template opening at `openQuote`, or undefined
30
+ * when it doesn't close. A long chain of unclosed holes in invalid HCL can
31
+ * overflow the scanner's recursion; that is also "doesn't close", so the
32
+ * caller falls back and the HCL parser reports the syntax error.
33
+ */
34
+ export declare function quotedTemplateEnd(s: string, openQuote: number): number | undefined;
28
35
  /** Parse the inside of a ${...} interpolation. */
29
36
  export declare function parseExpression(src: string, options?: ExpressionParseOptions): TfExpr;
@@ -20,7 +20,9 @@ export class TfExprError extends Error {
20
20
  }
21
21
  }
22
22
  export function parseStringValue(raw, options = {}) {
23
- const parts = splitTemplate(raw, options);
23
+ return templateValue(splitTemplate(raw, options, decodeTemplateEscapes));
24
+ }
25
+ function templateValue(parts) {
24
26
  if (parts.length === 1 && typeof parts[0] === "string") {
25
27
  return parts[0]; // plain string, already decoded
26
28
  }
@@ -30,10 +32,12 @@ export function parseStringValue(raw, options = {}) {
30
32
  return expr.template(parts);
31
33
  }
32
34
  /**
33
- * Split a raw template string into alternating literal text (decoded) and
34
- * parsed expressions. "$${" is an escape, not an interpolation start.
35
+ * Split a raw template string into alternating literal text (decoded by
36
+ * `decodeLiteral`) and parsed expressions. "$${" is an escape, not an
37
+ * interpolation start. Holes are parsed from their raw source, so a quoted
38
+ * key inside one decodes its own escapes.
35
39
  */
36
- function splitTemplate(raw, options) {
40
+ function splitTemplate(raw, options, decodeLiteral) {
37
41
  const parts = [];
38
42
  let literal = "";
39
43
  let i = 0;
@@ -46,7 +50,7 @@ function splitTemplate(raw, options) {
46
50
  if (raw.startsWith("${", i)) {
47
51
  const end = findInterpolationEnd(raw, i + 2);
48
52
  if (literal !== "") {
49
- parts.push(decodeTemplateEscapes(literal));
53
+ parts.push(decodeLiteral(literal));
50
54
  literal = "";
51
55
  }
52
56
  parts.push(parseExpression(raw.slice(i + 2, end), options));
@@ -60,7 +64,7 @@ function splitTemplate(raw, options) {
60
64
  i++;
61
65
  }
62
66
  if (literal !== "" || parts.length === 0) {
63
- parts.push(decodeTemplateEscapes(literal));
67
+ parts.push(decodeLiteral(literal));
64
68
  }
65
69
  return parts;
66
70
  }
@@ -85,6 +89,12 @@ function findInterpolationEnd(raw, start) {
85
89
  }
86
90
  throw new TfExprError("unterminated ${ interpolation", raw);
87
91
  }
92
+ /**
93
+ * Index just past the quoted string opening at `openQuote`. A ${...} hole is
94
+ * skipped whole: HCL lets an interpolation hold its own quoted strings
95
+ * (`"variable|${x.variables["0"].id}"`), and those quotes don't end the
96
+ * template (#1542). "$${" is an escape, not a hole.
97
+ */
88
98
  function skipQuotedString(s, openQuote) {
89
99
  let i = openQuote + 1;
90
100
  while (i < s.length) {
@@ -92,20 +102,51 @@ function skipQuotedString(s, openQuote) {
92
102
  i += 2;
93
103
  continue;
94
104
  }
105
+ if (s.startsWith("$${", i)) {
106
+ i += 3;
107
+ continue;
108
+ }
109
+ if (s.startsWith("${", i)) {
110
+ i = findInterpolationEnd(s, i + 2) + 1;
111
+ continue;
112
+ }
95
113
  if (s[i] === '"')
96
114
  return i + 1;
97
115
  i++;
98
116
  }
99
117
  throw new TfExprError("unterminated string literal", s);
100
118
  }
101
- function hasLiveInterpolation(rawInner) {
102
- for (let i = 0; i < rawInner.length; i++) {
103
- if (rawInner.startsWith("$${", i) || rawInner.startsWith("%%{", i)) {
119
+ /**
120
+ * Index just past the quoted template opening at `openQuote`, or undefined
121
+ * when it doesn't close. A long chain of unclosed holes in invalid HCL can
122
+ * overflow the scanner's recursion; that is also "doesn't close", so the
123
+ * caller falls back and the HCL parser reports the syntax error.
124
+ */
125
+ export function quotedTemplateEnd(s, openQuote) {
126
+ try {
127
+ return skipQuotedString(s, openQuote);
128
+ }
129
+ catch (error) {
130
+ if (error instanceof TfExprError || error instanceof RangeError)
131
+ return undefined;
132
+ throw error;
133
+ }
134
+ }
135
+ /** Whether the quoted string opening at `openQuote` holds a live ${ or %{ before it closes. */
136
+ function opensLiveHole(s, openQuote) {
137
+ for (let i = openQuote + 1; i < s.length; i++) {
138
+ if (s[i] === "\\") {
139
+ i++;
140
+ continue;
141
+ }
142
+ if (s.startsWith("$${", i) || s.startsWith("%%{", i)) {
104
143
  i += 2;
105
144
  continue;
106
145
  }
107
- if (rawInner.startsWith("${", i) || rawInner.startsWith("%{", i))
146
+ if (s.startsWith("${", i) || s.startsWith("%{", i))
108
147
  return true;
148
+ if (s[i] === '"')
149
+ return false;
109
150
  }
110
151
  return false;
111
152
  }
@@ -314,13 +355,15 @@ class Parser {
314
355
  */
315
356
  parseQuotedValue() {
316
357
  const start = this.pos;
358
+ if (!opensLiveHole(this.src, this.pos))
359
+ return this.parseQuotedString();
317
360
  const end = skipQuotedString(this.src, this.pos);
318
361
  const rawInner = this.src.slice(this.pos + 1, end - 1);
319
- if (!hasLiveInterpolation(rawInner))
320
- return this.parseQuotedString();
321
362
  this.pos = end;
322
363
  try {
323
- return parseStringValue(decodeStringEscapes(rawInner, this.src), this.options);
364
+ // String escapes decode in literal text only; a hole's quoted keys
365
+ // decode their own when the hole is parsed.
366
+ return templateValue(splitTemplate(rawInner, this.options, (literal) => decodeTemplateEscapes(decodeStringEscapes(literal, this.src))));
324
367
  }
325
368
  catch (error) {
326
369
  this.pos = start;
@@ -331,16 +374,17 @@ class Parser {
331
374
  if (this.peek() !== '"') {
332
375
  throw new TfExprError(`expected string at "${this.rest().slice(0, 20)}"`, this.src);
333
376
  }
334
- const end = skipQuotedString(this.src, this.pos);
335
- const rawInner = this.src.slice(this.pos + 1, end - 1);
336
- this.pos = end;
337
377
  // Live interpolations in keys and indexes (a dynamic index key, a
338
378
  // computed object key) are OUTSIDE the closed grammar — silently
339
379
  // literalizing them would change semantics while the structural
340
- // round-trip stayed green. Loud instead.
341
- if (hasLiveInterpolation(rawInner)) {
380
+ // round-trip stayed green. Loud instead, and before skipping the
381
+ // string, so an unclosed hole still gets this message.
382
+ if (opensLiveHole(this.src, this.pos)) {
342
383
  throw new TfExprError("interpolation inside an expression string is outside the supported grammar", this.src);
343
384
  }
385
+ const end = skipQuotedString(this.src, this.pos);
386
+ const rawInner = this.src.slice(this.pos + 1, end - 1);
387
+ this.pos = end;
344
388
  // Every string crossing the parse boundary follows the same rule:
345
389
  // standard escapes decode, then template escapes decode (render is the
346
390
  // exact inverse via quoteHclString).
@@ -9,4 +9,4 @@ export { decodeTemplateEscapes, encodeTemplateEscapes, quoteHclString } from "./
9
9
  export { parseExpression, parseStringValue, TfExprError } from "./expr.js";
10
10
  export { assertNoUnsafeIntegers, inspectBackendHcl, parseHcl, parseHclDocuments, TfParseError, type BackendHclInspection, } from "./parse.js";
11
11
  export { renderBlock, renderDocument } from "./render.js";
12
- export { appResourceLabelPrefix, appScopedResourceLabel, bareChildResourceLabel, childPartFromScopedLabel, elementResourceLabelPrefix, elementScopedResourceLabel, isCanonicalTsLabel, isTfLabel, isUuid, ownerFromScopedChildLabel, sanitizeName, scopedLabelToBagKey, scopedResourceLabel, snakeSlug, splitCamelCase, stableIdSuffix, tfLabelToTsLabel, tsLabelToTfLabel, taskResourceLabelPrefix, type ChildResourceScope, type FieldOwnerScope, } from "./labels.js";
12
+ export { appResourceLabelPrefix, appScopedResourceLabel, bareChildResourceLabel, childPartFromScopedLabel, elementResourceLabelPrefix, elementScopedResourceLabel, isCanonicalTsLabel, isTfLabel, isUuid, ownerFromScopedChildLabel, sanitizeName, scopedLabelToBagKey, scopedResourceLabel, snakeSlug, splitCamelCase, stageHandleTfLabel, stableIdSuffix, tfLabelToTsLabel, tsLabelToTfLabel, taskResourceLabelPrefix, type ChildResourceScope, type FieldOwnerScope, } from "./labels.js";
@@ -8,4 +8,4 @@ export { decodeTemplateEscapes, encodeTemplateEscapes, quoteHclString } from "./
8
8
  export { parseExpression, parseStringValue, TfExprError } from "./expr.js";
9
9
  export { assertNoUnsafeIntegers, inspectBackendHcl, parseHcl, parseHclDocuments, TfParseError, } from "./parse.js";
10
10
  export { renderBlock, renderDocument } from "./render.js";
11
- export { appResourceLabelPrefix, appScopedResourceLabel, bareChildResourceLabel, childPartFromScopedLabel, elementResourceLabelPrefix, elementScopedResourceLabel, isCanonicalTsLabel, isTfLabel, isUuid, ownerFromScopedChildLabel, sanitizeName, scopedLabelToBagKey, scopedResourceLabel, snakeSlug, splitCamelCase, stableIdSuffix, tfLabelToTsLabel, tsLabelToTfLabel, taskResourceLabelPrefix, } from "./labels.js";
11
+ export { appResourceLabelPrefix, appScopedResourceLabel, bareChildResourceLabel, childPartFromScopedLabel, elementResourceLabelPrefix, elementScopedResourceLabel, isCanonicalTsLabel, isTfLabel, isUuid, ownerFromScopedChildLabel, sanitizeName, scopedLabelToBagKey, scopedResourceLabel, snakeSlug, splitCamelCase, stageHandleTfLabel, stableIdSuffix, tfLabelToTsLabel, tsLabelToTfLabel, taskResourceLabelPrefix, } from "./labels.js";
@@ -29,6 +29,15 @@ export declare function isCanonicalTsLabel(tsLabel: string): boolean;
29
29
  * stage-key shape) and the field bag-key fallback when `__refName` is absent.
30
30
  */
31
31
  export declare function snakeSlug(s: string): string;
32
+ /**
33
+ * The Terraform-label handle for a `stage_ids_by_key` index (#1136). An index
34
+ * that is already a tf label is its own handle. An imported key that keeps
35
+ * punctuation (`"enrichment_&_validation"`, `"pre-approval"`) maps to
36
+ * `snakeSlug(key)`, which is also the slug of the stage name build derives,
37
+ * so build can map the handle back to the real key. Returns `undefined` when
38
+ * no tf-label handle exists (for example a key whose slug starts with a digit).
39
+ */
40
+ export declare function stageHandleTfLabel(key: string): string | undefined;
32
41
  /** Faithful port of ei's SanitizeName: platform name → HCL identifier. */
33
42
  export declare function sanitizeName(name: string): string;
34
43
  /** True when `value` has the shape of a platform id (not a validity check — just the wire shape). */
@@ -70,8 +79,7 @@ export declare function appScopedResourceLabel(appTfLabel: string, childPart: st
70
79
  * re-pulled — the old extractor never stripped the namespace, so it left prefixed bag keys
71
80
  * (e.g. `ticketsActive`) that now over-double when rebuilt. A field FRESHLY re-extracted with
72
81
  * `childPartFromScopedLabel`'s current (also-fixed) stripping round-trips to the exact same
73
- * address ei already uses — see `__tests__/tf/labels.test.ts`'s "element-prefixed child labels
74
- * round-trip" block. Re-pull an existing element (`elementum pull element <ns>`) before your
82
+ * address ei already uses. Re-pull an existing element (`elementum pull element <ns>`) before your
75
83
  * next build/plan if it predates this fix; adoption's rename guard (board item 225,
76
84
  * `docs/design/rename-label-identity.md`) moves any address that does shift with a `moved` block.
77
85
  */