@elementumai/edk 0.9.15 → 0.9.16

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 (86) hide show
  1. package/dist-sdk/pull/util.d.ts +0 -15
  2. package/dist-sdk/pull/util.js +44 -5
  3. package/dist-sdk/src/engine/build/context.d.ts +2 -2
  4. package/dist-sdk/src/engine/progress.d.ts +4 -0
  5. package/dist-sdk/src/engine/progress.js +16 -4
  6. package/dist-sdk/src/engine/pull/context.d.ts +5 -0
  7. package/dist-sdk/src/engine/pull/ref-only.d.ts +4 -0
  8. package/dist-sdk/src/engine/pull/ref-only.js +11 -0
  9. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +1 -1
  10. package/dist-sdk/src/entities/access-policy/from-tf.js +47 -12
  11. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +5 -3
  12. package/dist-sdk/src/entities/access-policy/to-tf.js +23 -1
  13. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +27 -2
  14. package/dist-sdk/src/entities/agent/from-tf.d.ts +1 -0
  15. package/dist-sdk/src/entities/agent/from-tf.js +18 -3
  16. package/dist-sdk/src/entities/agent/to-tf.js +14 -0
  17. package/dist-sdk/src/entities/agent/tools.d.ts +79 -2
  18. package/dist-sdk/src/entities/agent/tools.js +2 -1
  19. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +11 -0
  20. package/dist-sdk/src/entities/agent-tool/from-tf.js +45 -3
  21. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +7 -0
  22. package/dist-sdk/src/entities/agent-tool/to-tf.js +72 -20
  23. package/dist-sdk/src/entities/app/module.js +8 -0
  24. package/dist-sdk/src/entities/app/to-tf.js +1 -0
  25. package/dist-sdk/src/entities/automation/build.d.ts +12 -5
  26. package/dist-sdk/src/entities/automation/build.js +30 -11
  27. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +4 -0
  28. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +108 -23
  29. package/dist-sdk/src/entities/automation/from-tf.d.ts +73 -5
  30. package/dist-sdk/src/entities/automation/from-tf.js +255 -30
  31. package/dist-sdk/src/entities/automation/index.d.ts +2 -1
  32. package/dist-sdk/src/entities/automation/index.js +2 -1
  33. package/dist-sdk/src/entities/automation/module.js +6 -7
  34. package/dist-sdk/src/entities/automation/output-field-types.d.ts +5 -0
  35. package/dist-sdk/src/entities/automation/output-field-types.js +12 -0
  36. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +20 -0
  37. package/dist-sdk/src/entities/automation/output-key-wire-name.js +22 -0
  38. package/dist-sdk/src/entities/automation/script-code.js +13 -4
  39. package/dist-sdk/src/entities/automation/tasks.d.ts +41 -5
  40. package/dist-sdk/src/entities/automation/tasks.js +31 -9
  41. package/dist-sdk/src/entities/automation/to-tf.d.ts +0 -2
  42. package/dist-sdk/src/entities/automation/to-tf.js +85 -36
  43. package/dist-sdk/src/entities/automation/triggers.d.ts +5 -2
  44. package/dist-sdk/src/entities/automation/types.d.ts +2 -0
  45. package/dist-sdk/src/entities/automation/types.js +5 -0
  46. package/dist-sdk/src/entities/automation/workflow-output.d.ts +35 -0
  47. package/dist-sdk/src/entities/automation/workflow-output.js +53 -0
  48. package/dist-sdk/src/entities/dashboard/from-tf.js +1 -1
  49. package/dist-sdk/src/entities/dashboard/to-tf.js +1 -0
  50. package/dist-sdk/src/entities/element/build.d.ts +11 -8
  51. package/dist-sdk/src/entities/element/build.js +14 -5
  52. package/dist-sdk/src/entities/element/locals.d.ts +2 -2
  53. package/dist-sdk/src/entities/element/locals.js +6 -2
  54. package/dist-sdk/src/entities/element/system-fields.d.ts +4 -0
  55. package/dist-sdk/src/entities/element/system-fields.js +12 -0
  56. package/dist-sdk/src/entities/element/to-tf.js +1 -0
  57. package/dist-sdk/src/entities/field/from-tf.js +47 -1
  58. package/dist-sdk/src/entities/relationship/from-tf.js +2 -2
  59. package/dist-sdk/src/entities/relationship/to-tf.js +1 -0
  60. package/dist-sdk/src/entities/search-table/from-tf.js +6 -6
  61. package/dist-sdk/src/entities/search-table/module.js +2 -2
  62. package/dist-sdk/src/entities/search-table/types.d.ts +1 -0
  63. package/dist-sdk/src/entities/search-table/types.js +1 -0
  64. package/dist-sdk/src/entities/shared/filters/ast.d.ts +2 -0
  65. package/dist-sdk/src/entities/shared/filters/index.d.ts +12 -2
  66. package/dist-sdk/src/entities/shared/filters/index.js +17 -1
  67. package/dist-sdk/src/entities/shared/filters/print.js +25 -11
  68. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +1 -1
  69. package/dist-sdk/src/entities/shared/filters/tf-codec.js +39 -7
  70. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +18 -2
  71. package/dist-sdk/src/entities/skill/module.js +9 -0
  72. package/dist-sdk/src/entities/skill/to-tf.js +18 -0
  73. package/dist-sdk/src/entities/skill/tools.d.ts +18 -4
  74. package/dist-sdk/src/entities/skill/tools.js +1 -1
  75. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +12 -0
  76. package/dist-sdk/src/entities/skill-tool/from-tf.js +58 -3
  77. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +6 -0
  78. package/dist-sdk/src/entities/skill-tool/to-tf.js +78 -43
  79. package/dist-sdk/src/entities/view/from-tf.js +30 -9
  80. package/dist-sdk/src/entities/view/to-tf.js +18 -10
  81. package/dist-sdk/src/entities/widget/from-tf.js +1 -1
  82. package/dist-sdk/src/entities/widget/to-tf.js +1 -0
  83. package/dist-sdk/src/graph/index.d.ts +13 -0
  84. package/dist-sdk/src/graph/index.js +5 -0
  85. package/dist-sdk/src/graph/types.d.ts +10 -0
  86. package/package.json +2 -1
@@ -15,3 +15,8 @@ export declare function outputFieldTypesFromScriptSchema(schema: unknown): Map<s
15
15
  multiple: boolean;
16
16
  kind: string;
17
17
  }> | undefined;
18
+ /**
19
+ * A nested result path belongs to its declared top-level object even when the
20
+ * current schema projection does not yet model that object's item properties.
21
+ */
22
+ export declare function scriptOutputReferenceIsDeclared(outputTypes: ReadonlyMap<string, unknown> | undefined, name: string): boolean;
@@ -55,3 +55,15 @@ export function outputFieldTypesFromScriptSchema(schema) {
55
55
  }
56
56
  return out.size > 0 ? out : undefined;
57
57
  }
58
+ /**
59
+ * A nested result path belongs to its declared top-level object even when the
60
+ * current schema projection does not yet model that object's item properties.
61
+ */
62
+ export function scriptOutputReferenceIsDeclared(outputTypes, name) {
63
+ if (outputTypes?.has(name) === true)
64
+ return true;
65
+ if (!name.startsWith("result."))
66
+ return false;
67
+ const root = `result.${name.slice("result.".length).split(".")[0]}`;
68
+ return outputTypes?.has(root) === true;
69
+ }
@@ -16,6 +16,26 @@
16
16
  * either side can never introduce a cycle.
17
17
  */
18
18
  export declare const OUTPUT_KEY_WIRE_NAME: Readonly<Record<string, string>>;
19
+ /**
20
+ * Compares a raw wire segment against an {@link OUTPUT_KEY_WIRE_NAME} value.
21
+ * The Title-Case wire name above is confirmed against each task's own
22
+ * `refs` map (a stable, schema-derived attribute), but a `taskReference.name`
23
+ * embedded in a filter/formula envelope is a SEPARATE serialization the
24
+ * platform lowercases (live-confirmed on conciergeforfield, sanofi/us: the
25
+ * same aiTransform task's `refs` map has `Response`, but every
26
+ * `taskReference.name` pointing at it says `response`). A case-sensitive
27
+ * compare silently missed the envelope form and fell through to the raw
28
+ * segment, printing an unmapped `.response`/`.refs["response"]` accessor
29
+ * that doesn't exist ("Invalid index" on every plan).
30
+ *
31
+ * Accepts the exact wire key OR that key fully lowercased - not a full
32
+ * case-fold on both sides. `documentModel`'s wire key is already `"text"`,
33
+ * and a file-reader task's schema can declare its own field named `Text`
34
+ * (an arbitrary user-chosen schema name, not this table's business) -
35
+ * folding both sides to lowercase would alias that unrelated `Text` field
36
+ * onto `.output` too and rebuild it as `refs["text"]`.
37
+ */
38
+ export declare function matchesOutputWireKey(segment: string, wireKey: string): boolean;
19
39
  /**
20
40
  * apiRequest task outputs in authoring use camelCase segments (`statusCode`,
21
41
  * `file.content`, …) but the provider refs map uses display labels — confirmed
@@ -21,6 +21,28 @@ export const OUTPUT_KEY_WIRE_NAME = {
21
21
  aiClassify: "Response",
22
22
  documentModel: "text",
23
23
  };
24
+ /**
25
+ * Compares a raw wire segment against an {@link OUTPUT_KEY_WIRE_NAME} value.
26
+ * The Title-Case wire name above is confirmed against each task's own
27
+ * `refs` map (a stable, schema-derived attribute), but a `taskReference.name`
28
+ * embedded in a filter/formula envelope is a SEPARATE serialization the
29
+ * platform lowercases (live-confirmed on conciergeforfield, sanofi/us: the
30
+ * same aiTransform task's `refs` map has `Response`, but every
31
+ * `taskReference.name` pointing at it says `response`). A case-sensitive
32
+ * compare silently missed the envelope form and fell through to the raw
33
+ * segment, printing an unmapped `.response`/`.refs["response"]` accessor
34
+ * that doesn't exist ("Invalid index" on every plan).
35
+ *
36
+ * Accepts the exact wire key OR that key fully lowercased - not a full
37
+ * case-fold on both sides. `documentModel`'s wire key is already `"text"`,
38
+ * and a file-reader task's schema can declare its own field named `Text`
39
+ * (an arbitrary user-chosen schema name, not this table's business) -
40
+ * folding both sides to lowercase would alias that unrelated `Text` field
41
+ * onto `.output` too and rebuild it as `refs["text"]`.
42
+ */
43
+ export function matchesOutputWireKey(segment, wireKey) {
44
+ return segment === wireKey || segment === wireKey.toLowerCase();
45
+ }
24
46
  /**
25
47
  * apiRequest task outputs in authoring use camelCase segments (`statusCode`,
26
48
  * `file.content`, …) but the provider refs map uses display labels — confirmed
@@ -157,7 +157,7 @@ export function stripTsIgnoreLines(code) {
157
157
  .join("\n");
158
158
  }
159
159
  function finishBody(rawBody, rawParams, fullSrc) {
160
- const body = dedent(stripTsIgnoreLines(rawBody).replace(/^\n+/, "").replace(/\s+$/, ""));
160
+ const body = dedent(stripTsIgnoreLines(rawBody).replace(/^\n+/, "").replace(/\n[ \t]*$/, ""));
161
161
  const params = collectParamNames(rawParams);
162
162
  const unknown = freeIdentifiers(body, params);
163
163
  if (unknown.length > 0) {
@@ -513,12 +513,21 @@ function splitTopLevelExpressions(value) {
513
513
  parts.push(value.slice(start).trim());
514
514
  return parts.filter((part) => part.length > 0);
515
515
  }
516
- /** Strip the common leading indentation (the flush-left fixed point survives ei's heredoc round trip). */
516
+ /**
517
+ * Strip the common leading indentation (the flush-left fixed point survives
518
+ * ei's heredoc round trip). A blank line is sliced the same as any other
519
+ * line, not force-replaced with "" - the printer (annotateScriptLines) pads
520
+ * a blank line's own original content (e.g. accidental trailing whitespace
521
+ * an editor left in the deployed script - live-confirmed on
522
+ * conciergeforfield, sanofi/us) with the SAME indent every real line gets,
523
+ * specifically so this slice lands back on that original content instead
524
+ * of discarding it.
525
+ */
517
526
  function dedent(body) {
518
527
  const lines = body.split("\n");
519
528
  const indents = lines.filter((l) => l.trim() !== "").map((l) => /^\s*/.exec(l)[0].length);
520
529
  const min = indents.length > 0 ? Math.min(...indents) : 0;
521
- return lines.map((l) => (l.trim() === "" ? "" : l.slice(min))).join("\n");
530
+ return lines.map((l) => l.slice(min)).join("\n");
522
531
  }
523
532
  /**
524
533
  * AST-based free-identifier scan using the real TypeScript compiler parser.
@@ -1274,7 +1283,7 @@ function scanExecuteScriptBodies(src) {
1274
1283
  if (name !== undefined) {
1275
1284
  const body = extractCodeBody(call.args[1]);
1276
1285
  if (body !== undefined) {
1277
- result.set(name, dedent(stripTsIgnoreLines(body).replace(/^\n+/, "").replace(/\s+$/, "")));
1286
+ result.set(name, dedent(stripTsIgnoreLines(body).replace(/^\n+/, "").replace(/\n[ \t]*$/, "")));
1278
1287
  }
1279
1288
  }
1280
1289
  }
@@ -236,6 +236,8 @@ export type ScriptOutputScalarType = "text" | "string" | "integer" | "number" |
236
236
  export type ScriptOutputType = ScriptOutputScalarType | {
237
237
  readonly type: "array";
238
238
  readonly items: ScriptOutputType;
239
+ /** Name stored on the array's item schema node, distinct from the array property's own name. */
240
+ readonly itemName?: string;
239
241
  } | {
240
242
  readonly type: "object";
241
243
  readonly properties?: ScriptOutputProperties;
@@ -283,6 +285,36 @@ type ExecuteScriptOutput<O extends ScriptOutputs | undefined> = {
283
285
  readonly [K in keyof ScriptOutputPropertiesOf<O>]: ExecuteScriptFieldValue<Extract<ScriptOutputPropertiesOf<O>[K], ScriptOutputType>>;
284
286
  } : Record<string, unknown>;
285
287
  };
288
+ /**
289
+ * One field an executeScript list-valued input exposes to the script, and
290
+ * what to call it there. `alias` is the script-facing property name
291
+ * (`item.<alias>` inside the script body); `field` is the platform field
292
+ * read from each item of the referenced list.
293
+ */
294
+ export interface ExecuteScriptFieldMapping {
295
+ readonly alias: string;
296
+ /**
297
+ * `UnsafePlatformId` is a pull-fidelity fallback for a mapping export
298
+ * couldn't resolve to a portable field reference - preserved as-is rather
299
+ * than dropped, mirroring the same escape hatch used for a field
300
+ * assignment export can't reconstruct.
301
+ */
302
+ readonly field: FieldRef | UnsafePlatformId;
303
+ }
304
+ declare const EXECUTE_SCRIPT_LIST_INPUT_MARKER: "__edkExecuteScriptListInput";
305
+ /** @internal — used by build.ts's fluent `.executeScript()` typing; not part of the public surface. */
306
+ export interface ExecuteScriptListInputToken {
307
+ readonly [EXECUTE_SCRIPT_LIST_INPUT_MARKER]: true;
308
+ readonly value: ValueOrRef<unknown>;
309
+ readonly fields: readonly ExecuteScriptFieldMapping[];
310
+ }
311
+ /**
312
+ * Wrap a list-valued executeScript input (e.g. a prior task's `.records`)
313
+ * with the field mappings the script can read off each item - which fields,
314
+ * and under what alias. Only meaningful for a list-shaped input; a scalar
315
+ * input has no per-item fields to map.
316
+ */
317
+ export declare function withFieldMappings(value: ValueOrRef<unknown>, fields: readonly ExecuteScriptFieldMapping[]): ExecuteScriptListInputToken;
286
318
  export interface ExecuteScriptOptions<O extends ScriptOutputs | undefined = undefined> {
287
319
  /**
288
320
  * A FUNCTION whose body ships as the platform script (v3):
@@ -300,7 +332,11 @@ export interface ExecuteScriptOptions<O extends ScriptOutputs | undefined = unde
300
332
  * print this form).
301
333
  */
302
334
  readonly code: ScriptCodeFn<Record<string, unknown>, Record<string, unknown>> | ScriptFile;
303
- readonly inputs?: Record<string, ValueOrRef<unknown>>;
335
+ /**
336
+ * A list-valued input can carry {@link withFieldMappings} to declare which
337
+ * fields of each list item the script can read, and under what alias.
338
+ */
339
+ readonly inputs?: Record<string, ValueOrRef<unknown> | ExecuteScriptListInputToken>;
304
340
  /**
305
341
  * Output schema: property name → `"text" | "integer" | "number" |
306
342
  * "decimal" | "boolean" | "object"`, or `{ name, properties }` when the
@@ -637,8 +673,8 @@ export type CalculationExpression = string | Ref<unknown> | Expr<ExprType, ExprC
637
673
  /** Relationship rows included when a calculation traverses related records. */
638
674
  export interface CalculationValueOptions<Expression extends CalculationExpression = CalculationExpression> {
639
675
  readonly expression: Expression;
640
- /** Server-assigned entry id, retained when updating pulled source. */
641
- readonly id?: string;
676
+ /** Platform-managed; calculation entry IDs cannot be authored. */
677
+ readonly id?: never;
642
678
  /** Override the task-level record context for this value. */
643
679
  readonly record?: ValueOrRef<string>;
644
680
  /** Override the task-level relationship inclusion for this value. */
@@ -647,8 +683,8 @@ export interface CalculationValueOptions<Expression extends CalculationExpressio
647
683
  export type CalculationValueInput = CalculationExpression | CalculationValueOptions;
648
684
  export type CalculationValues = Readonly<Record<string, CalculationValueInput>>;
649
685
  export interface CalculationEntry<Name extends string = string, Expression extends CalculationExpression = CalculationExpression> {
650
- /** Server-assigned entry id — omit when authoring a new calculation; include when updating an existing one (mirrors {@link VariableDecl.id}). */
651
- readonly id?: string;
686
+ /** Platform-managed; calculation entry IDs cannot be authored. */
687
+ readonly id?: never;
652
688
  readonly name: Name;
653
689
  /**
654
690
  * Prefer a typed calc expression. Raw strings and refs remain supported for
@@ -209,7 +209,12 @@ function outputSchemaNode(name, type) {
209
209
  }
210
210
  }
211
211
  if (type.type === "array") {
212
- return { array: { ...(name === undefined ? {} : { name }), item: outputSchemaNode(undefined, type.items) } };
212
+ return {
213
+ array: {
214
+ ...(name === undefined ? {} : { name }),
215
+ item: outputSchemaNode(type.itemName, type.items),
216
+ },
217
+ };
213
218
  }
214
219
  const properties = type.properties === undefined
215
220
  ? undefined
@@ -227,6 +232,19 @@ function outputSchema(outputs) {
227
232
  const properties = Object.entries(declared).map(([name, type]) => outputSchemaNode(name, type));
228
233
  return { object: { ...(rootName !== undefined ? { name: rootName } : {}), properties } };
229
234
  }
235
+ const EXECUTE_SCRIPT_LIST_INPUT_MARKER = "__edkExecuteScriptListInput";
236
+ /**
237
+ * Wrap a list-valued executeScript input (e.g. a prior task's `.records`)
238
+ * with the field mappings the script can read off each item - which fields,
239
+ * and under what alias. Only meaningful for a list-shaped input; a scalar
240
+ * input has no per-item fields to map.
241
+ */
242
+ export function withFieldMappings(value, fields) {
243
+ return { [EXECUTE_SCRIPT_LIST_INPUT_MARKER]: true, value, fields };
244
+ }
245
+ function isExecuteScriptListInputToken(value) {
246
+ return typeof value === "object" && value !== null && value[EXECUTE_SCRIPT_LIST_INPUT_MARKER] === true;
247
+ }
230
248
  /**
231
249
  * Build the executeScript `ActionDef` from an ALREADY-RESOLVED body string.
232
250
  * Shared by the public `executeScript()` factory below (which resolves the
@@ -237,10 +255,16 @@ function outputSchema(outputs) {
237
255
  * so the body is computed exactly once, not re-derived by each layer.
238
256
  */
239
257
  export function executeScriptActionDefWithBody(body, opts) {
240
- const inputs = Object.entries(opts.inputs ?? {}).map(([name, value]) => ({
241
- name,
242
- value: serializeValueOrRef(value),
243
- }));
258
+ const inputs = Object.entries(opts.inputs ?? {}).map(([name, entry]) => {
259
+ if (isExecuteScriptListInputToken(entry)) {
260
+ return {
261
+ name,
262
+ value: serializeValueOrRef(entry.value),
263
+ field_mappings: entry.fields.map((f) => ({ alias: f.alias, field_id: f.field })),
264
+ };
265
+ }
266
+ return { name, value: serializeValueOrRef(entry) };
267
+ });
244
268
  return {
245
269
  key: "executeScript",
246
270
  config: {
@@ -617,7 +641,6 @@ function normalizeCalculationOptions(opts) {
617
641
  return Object.entries(opts.values).map(([name, value]) => {
618
642
  const advanced = typeof value === "object" && value !== null && "expression" in value;
619
643
  return {
620
- ...(advanced && value.id !== undefined ? { id: value.id } : {}),
621
644
  name,
622
645
  expression: advanced ? value.expression : value,
623
646
  ...(advanced && value.record !== undefined
@@ -653,8 +676,8 @@ export function calculation(opts) {
653
676
  // `outputType`/`multiple`/`referencedFields`) this used to mirror. Sending
654
677
  // the GET shape back on create/update 500s server-side with no
655
678
  // field-level error, because it isn't what the write mutation's input type
656
- // actually accepts. `id` is server-assigned and simply omitted from the
657
- // entry when authoring new (mirrors {@link VariableDecl.id}).
679
+ // actually accepts. Calculation entry IDs are server-assigned state and
680
+ // are intentionally absent from the public authoring API.
658
681
  const calculations = [];
659
682
  for (const c of entries) {
660
683
  const rawCalculationReference = isExpr(c.expression)
@@ -705,7 +728,6 @@ export function calculation(opts) {
705
728
  },
706
729
  };
707
730
  calculations.push({
708
- ...(c.id !== undefined ? { id: c.id } : {}),
709
731
  name: c.name,
710
732
  recordId: c.record !== undefined ? serializeValueOrRef(c.record) : null,
711
733
  calculationReference: wireCalculationReference,
@@ -33,8 +33,6 @@ export interface AutomationToTfContext {
33
33
  readonly serviceAccounts?: Readonly<Record<string, AppServiceAccount>>;
34
34
  /** App-local automations whose publish resource will be emitted in this build. */
35
35
  readonly activeAutomationRefNames?: ReadonlySet<string>;
36
- /** Display names for app-local authored automations, keyed by source refName. */
37
- readonly automationNamesByRefName?: ReadonlyMap<string, string>;
38
36
  /**
39
37
  * Every app/element stream root discovered in this same build, keyed by
40
38
  * `workspaceAspectKey` — lets a cross-aspect token (an app/element ref, or
@@ -10,7 +10,7 @@ import { resolveForeignRef } from "../shared/foreign-ref.js";
10
10
  import { filterToTf as serializeFilterToTf } from "../shared/filters/tf-codec.js";
11
11
  import { referenceValueTypeForField } from "../shared/filters/index.js";
12
12
  import { API_TASK_REF_AUTHORING_NAMES, API_TASK_REF_WIRE_NAMES } from "./output-key-wire-name.js";
13
- import { outputFieldTypesFromScriptSchema } from "./output-field-types.js";
13
+ import { outputFieldTypesFromScriptSchema, scriptOutputReferenceIsDeclared } from "./output-field-types.js";
14
14
  import { CONNECTOR_ORG_BAG } from "../org/connector.js";
15
15
  import { FILE_READER_SUB_TYPE_BY_RESOURCE, FILE_READER_SUB_TYPE_BY_TYPE_KEY } from "../file-reader/types.js";
16
16
  import { UNRESOLVED_FIELD_MARKER } from "../shared/ref.js";
@@ -443,9 +443,9 @@ function automationTargetToTf(value, ctx, dataBlocks) {
443
443
  if (managedOwnerLabel !== undefined) {
444
444
  const managedLabel = scopedLabel(managedOwnerLabel, tsLabelToTfLabel(value.refName));
445
445
  const targetOwner = ctx.workspaceAspects?.get(workspaceAspectKey(ownerKind, isOwn ? ctx.appRefName : value.parent ?? ""));
446
- const targetActiveNames = targetOwner?.activeAutomationNamesByRefName;
447
- const isActive = targetActiveNames !== undefined
448
- ? targetActiveNames.has(value.refName)
446
+ const targetActiveRefs = targetOwner?.activeAutomationRefNames;
447
+ const isActive = targetActiveRefs !== undefined
448
+ ? targetActiveRefs.has(value.refName)
449
449
  : isOwn && ctx.activeAutomationRefNames?.has(value.refName) === true;
450
450
  // The on-demand trigger resource exposes the parameter ids from the
451
451
  // mutable draft workflow. Once an ACTIVE target is published, however,
@@ -454,12 +454,6 @@ function automationTargetToTf(value, ctx, dataBlocks) {
454
454
  // ids describe that same current revision. Draft/inactive targets retain
455
455
  // the direct resource references below because they have no publish edge.
456
456
  if (isActive) {
457
- const lookupName = targetActiveNames?.get(value.refName) ??
458
- (isOwn ? ctx.automationNamesByRefName?.get(value.refName) : undefined) ??
459
- value.name;
460
- if (lookupName === undefined || lookupName === "") {
461
- throw new EntityTfError(`managed ACTIVE automation ref "${value.refName}" has no lookup name`);
462
- }
463
457
  // Data block addresses are module-global even though EDK emits one
464
458
  // file per automation. Scope the lookup to this caller so two callers
465
459
  // of the same target cannot declare a duplicate data address.
@@ -470,7 +464,7 @@ function automationTargetToTf(value, ctx, dataBlocks) {
470
464
  label: currentBindingLabel,
471
465
  attrs: {
472
466
  app_id: expr.resourceAttr(ownerKind === "element" ? "elementum_element" : "elementum_app", managedOwnerLabel, ["id"]),
473
- name: lookupName,
467
+ id: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, managedLabel, ["id"]),
474
468
  depends_on: [expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, managedLabel)],
475
469
  },
476
470
  });
@@ -971,7 +965,18 @@ function calculationFormulaRefToParts(value, refs) {
971
965
  return calculationTaskMustache(value.taskReference.taskRefKey, value.taskReference.name, refs);
972
966
  }
973
967
  if (isObject(value.variableReference) && typeof value.variableReference.id === "string") {
974
- return [`variable.${value.variableReference.id}`];
968
+ // `value.variableReference.id` is the client-side id `stampAndCollectVariableIds`
969
+ // just minted for this build's own `elementum_variable_task` create entry, not the
970
+ // variable's real (deploy-time-assigned) platform id - baking it in as a literal
971
+ // here always mismatches live state on the very next plan. Interpolate the live
972
+ // resource's `variable_id` instead, the same fix already applied to workflow_publish
973
+ // outputs and task input values referencing the same variable.
974
+ const target = refs.variableById.get(value.variableReference.id);
975
+ if (target === undefined) {
976
+ refs.owner.diagnostics.push(`automation unresolved variable ref ${JSON.stringify(value.variableReference.id)} preserved as a literal calculation reference`);
977
+ return [`variable.${value.variableReference.id}`];
978
+ }
979
+ return ["variable.", expr.resourceAttr(target.type, target.label, ["variable_id"])];
975
980
  }
976
981
  if (isObject(value.templateReference))
977
982
  return calculationTemplateToParts(value.templateReference, refs);
@@ -1124,8 +1129,8 @@ const TS_TRIGGER_REF_TO_WIRE = {
1124
1129
  // ("record.createdBy.email") never reaches this flat lookup table (see
1125
1130
  // from-tf.ts's matching comment) — this table is for genuine trigger-level
1126
1131
  // pseudo-fields only, keyed by the DIRECT ts accessor name, not a dotted
1127
- // record path. The audit-email casing exception lives in
1128
- // AUDIT_FIELD_EMAIL_WIRE_NAME, next to the code that actually builds it.
1132
+ // record path. Record-path refs are handled below from app fields and
1133
+ // suffix mappings.
1129
1134
  slackThreadId: "Slack Thread ID",
1130
1135
  slackChannelId: "Slack Channel ID",
1131
1136
  messageAuthorEmail: "Message Author Email",
@@ -1162,13 +1167,6 @@ const FIELD_REF_SUFFIX_TO_WIRE = {
1162
1167
  "employee.manager.email": " Manager Email",
1163
1168
  "employee.manager.name": " Manager Name",
1164
1169
  };
1165
- // Confirmed live on demoapptwo: the "...Email"/"...Manager Email" audit refs
1166
- // lowercase "by", unlike every other audit-field ref suffix. Only these two
1167
- // keys/suffixes are overridden; closedBy is not confirmed and is left alone.
1168
- const AUDIT_FIELD_EMAIL_WIRE_NAME = {
1169
- createdBy: "Created by",
1170
- updatedBy: "Updated by",
1171
- };
1172
1170
  const PROVIDER_FIXED_SYSTEM_FIELD_KEYS = new Set([
1173
1171
  "stage",
1174
1172
  "createdAt",
@@ -1224,18 +1222,13 @@ function wireRefName(name, ctx) {
1224
1222
  if (wireSuffix === undefined) {
1225
1223
  throw new EntityTfError(`automation reference "${name}" has unsupported record-field path "${suffix}"`);
1226
1224
  }
1227
- // Build must reproduce the live refs[] key's exact casing because the
1228
- // Terraform map lookup is case-sensitive. The current provider emits
1229
- // compound audit refs with the system field's display casing intact
1230
- // (for example "Created By ID") — EXCEPT the "...Email"/"...Manager
1231
- // Email" audit refs, which lowercase "by" (confirmed live on
1232
- // demoapptwo: "Created by Email", "Updated by Manager Email"). Only
1233
- // override those two confirmed suffixes; every other suffix (and every
1234
- // other system field) keeps the field's own display casing.
1235
- const auditEmailName = systemFieldKey !== undefined && (wireSuffix === " Email" || wireSuffix === " Manager Email")
1236
- ? AUDIT_FIELD_EMAIL_WIRE_NAME[systemFieldKey]
1237
- : undefined;
1238
- return `${auditEmailName ?? fieldName}${wireSuffix}`;
1225
+ // Email audit refs have historically varied in the capitalization of
1226
+ // "by" between organizations. The provider exposes both spellings as
1227
+ // aliases, so author the established lowercase wire name consistently.
1228
+ const refName = `${fieldName}${wireSuffix}`;
1229
+ return /^(Created|Updated) By (?:Manager )?Email$/.test(refName)
1230
+ ? refName.replace(/ By(?= (?:Manager )?Email$)/, " by")
1231
+ : refName;
1239
1232
  }
1240
1233
  // A webhook trigger's body/headers refs (ctx.trigger.body["X"]) can only
1241
1234
  // type-check against DeepRefs<WebhookTriggerOutput>, so parts[0] being
@@ -1690,6 +1683,18 @@ function valueToTf(value, refs) {
1690
1683
  return value.map((item) => valueToTf(item, refs));
1691
1684
  if (!isObject(value))
1692
1685
  throw new EntityTfError(`unsupported automation value ${String(value)}`);
1686
+ if (typeof value.__edkUnresolvedForEachItem === "string") {
1687
+ // Printed by print-automation.ts for a forEachItemRef pointing at a
1688
+ // sibling or non-nearest-ancestor loop - EDK has no authoring primitive
1689
+ // for "another loop's current item". Fail the build loudly instead of
1690
+ // silently reinterpreting this as a task-output reference: `ctx.actions`
1691
+ // would have turned ANY property-access shape into a real, but WRONG,
1692
+ // task ref (review feedback on PR #1097, cursor[bot]).
1693
+ const path = Array.isArray(value.path) ? value.path.join(".") : "";
1694
+ throw new EntityTfError(`unresolved forEach item reference to "${value.__edkUnresolvedForEachItem}"${path ? `.${path}` : ""}: ` +
1695
+ `EDK cannot express a reference to another loop's current item - re-express this by hand ` +
1696
+ `(e.g. restructure the loops, or pass the value through a variable) before this automation can build`);
1697
+ }
1693
1698
  if (value.__unsafe === "platformId" && typeof value.value === "string") {
1694
1699
  refs.owner.diagnostics.push(`automation raw UUID fallback ${JSON.stringify(value.value)} is source-org-only and non-portable`);
1695
1700
  return value.value;
@@ -1896,6 +1901,24 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1896
1901
  },
1897
1902
  });
1898
1903
  }
1904
+ const isUndeclaredScriptOutput = task.type === TASK_RESOURCES.executeScript &&
1905
+ wireName.startsWith("result.") &&
1906
+ !scriptOutputReferenceIsDeclared(task.outputFieldTypes, wireName);
1907
+ if (isUndeclaredScriptOutput) {
1908
+ // A pulled live workflow can retain this dangling envelope even
1909
+ // though the provider cannot expose it through `refs`. Pull rejects
1910
+ // multiple/DECIMAL variants, so the scalar envelope is lossless.
1911
+ refs.owner.diagnostics.push(`automation switch preserves reference to ${JSON.stringify(wireName)} on execute-script task ` +
1912
+ `${JSON.stringify(value.taskRefKey)} even though that task does not declare the output`);
1913
+ return expr.jsonencode({
1914
+ fieldType: (realType ?? "TEXT").toUpperCase(),
1915
+ multiple: false,
1916
+ taskReference: {
1917
+ name: wireName,
1918
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
1919
+ },
1920
+ });
1921
+ }
1899
1922
  return expr.resourceAttr(task.type, task.label, ["refs", { index: wireName }]);
1900
1923
  }
1901
1924
  return expr.template([
@@ -2022,6 +2045,8 @@ function triggerRecordFieldPath(reference) {
2022
2045
  return { fieldKey: path[1], suffix: path.slice(2).join(".") };
2023
2046
  }
2024
2047
  function fieldFromFilterLeftValue(value, refs) {
2048
+ if (isObject(value) && value.type === "FIELD")
2049
+ return token(value.value ?? value.field);
2025
2050
  if (!isObject(value) || !isObject(value.value) || value.value.type?.toString().toUpperCase() !== "TRIGGER") {
2026
2051
  return undefined;
2027
2052
  }
@@ -2302,7 +2327,6 @@ function configAttrs(kind, config, refs) {
2302
2327
  }
2303
2328
  }
2304
2329
  return {
2305
- ...(typeof item.id === "string" ? { id: item.id } : {}),
2306
2330
  variable_name: item.name,
2307
2331
  formula: calculationFormulaToTf(reference.templateReference, refs),
2308
2332
  ...(includeType !== "AUTO" ? { include_type: includeType } : {}),
@@ -2558,7 +2582,6 @@ export function automationToTf(entity, ctx) {
2558
2582
  workspaceAspects: ctx.workspaceAspects,
2559
2583
  diagnostics: ctx.diagnostics ?? [],
2560
2584
  activeAutomationRefNames: ctx.activeAutomationRefNames,
2561
- automationNamesByRefName: ctx.automationNamesByRefName,
2562
2585
  };
2563
2586
  if (entity.kind !== "automation")
2564
2587
  throw new EntityTfError(`automationToTf expects kind "automation"; got "${entity.kind}"`);
@@ -2917,6 +2940,15 @@ export function automationToTf(entity, ctx) {
2917
2940
  if (children.length === 0)
2918
2941
  throw new EntityTfError(`${wireType} task "${refKey}" must have branches`);
2919
2942
  const usedLabels = new Map();
2943
+ // Separate from usedLabels above: that map rejects two branches
2944
+ // sharing the same RAW display label/no-label, but a genuinely
2945
+ // unlabeled branch's fixed "case" fallback and an EXPLICIT label
2946
+ // like "Case" have different raw labels ("" vs "Case") yet
2947
+ // sanitize to the identical tf suffix ("case") - a real address
2948
+ // collision usedLabels never catches. Live-confirmed shape
2949
+ // (review feedback, PR #1100, cursor[bot]): unlabeled sibling next
2950
+ // to a branch explicitly labeled "Case".
2951
+ const usedSuffixes = new Map();
2920
2952
  for (const [index, child] of children.entries()) {
2921
2953
  const isDefault = wireType === "switch" && (child.isDefault === true || child.label === null);
2922
2954
  const displayLabel = isDefault
@@ -2929,6 +2961,13 @@ export function automationToTf(entity, ctx) {
2929
2961
  : `${wireType} task "${refKey}" reuses label ${JSON.stringify(displayLabel)} on cases ${prior} and ${index + 1}`);
2930
2962
  }
2931
2963
  usedLabels.set(displayLabel, index + 1);
2964
+ const fallbackLabel = isDefault ? "default" : "case";
2965
+ const suffix = sanitizeName(child.label ?? child.defaultLabel ?? fallbackLabel);
2966
+ const priorSuffix = usedSuffixes.get(suffix);
2967
+ if (priorSuffix !== undefined) {
2968
+ throw new EntityTfError(`${wireType} task "${refKey}" cases ${priorSuffix} and ${index + 1} both sanitize to the terraform label suffix ${JSON.stringify(suffix)}; give each branch/case a distinct label`);
2969
+ }
2970
+ usedSuffixes.set(suffix, index + 1);
2932
2971
  }
2933
2972
  let previous;
2934
2973
  for (const [index, child] of children.entries()) {
@@ -2937,7 +2976,17 @@ export function automationToTf(entity, ctx) {
2937
2976
  // ei's own resource label follows the branch's real display text
2938
2977
  // (a default branch renamed "Default Path" exports as
2939
2978
  // "..._default_path", not a hardcoded "..._default") - confirmed live.
2940
- const fallbackLabel = isDefault ? "default" : `branch_${index + 1}`;
2979
+ // A genuinely unlabeled non-default branch/case exports with the
2980
+ // fixed literal suffix "case" (no index) regardless of wireType or
2981
+ // position - live-confirmed on conciergeforfield (sanofi/us): both
2982
+ // an unlabeled elementum_fork_join_branch and an unlabeled
2983
+ // elementum_switch_case exported as "..._case". The prior
2984
+ // "branch_${index+1}" fallback never matched this, so every
2985
+ // rebuild relabeled the resource and planned a destroy+create for
2986
+ // an otherwise-unchanged branch. usedSuffixes above already
2987
+ // rejects the fixed "case" suffix colliding with an explicitly
2988
+ // labeled sibling that sanitizes to the same thing.
2989
+ const fallbackLabel = isDefault ? "default" : "case";
2941
2990
  const branchLabel = `${tfLabel}_${sanitizeName(child.label ?? child.defaultLabel ?? fallbackLabel)}`;
2942
2991
  const branchAttrs = {
2943
2992
  [wireType === "switch" ? "switch_task" : "fork_join_task"]: address,
@@ -219,8 +219,11 @@ export interface SlackMessageTriggerOutput {
219
219
  export declare function slackMessage(): TriggerChain<SlackMessageTriggerOutput>;
220
220
  export interface SurveyResponseCreateTriggerOptions {
221
221
  readonly app: AppOrElementRef;
222
- /** Raw survey template id until surveys are catalog-modeled. */
223
- readonly survey: string;
222
+ /**
223
+ * Survey template id until survey templates are catalog-modeled. The
224
+ * explicit wrapper marks this platform-owned value as non-portable.
225
+ */
226
+ readonly survey: UnsafePlatformId;
224
227
  }
225
228
  export type SurveyResponseCreateTriggerOutput = Record<string, unknown>;
226
229
  /** Fires when a response is created for the selected survey template. */
@@ -77,3 +77,5 @@ export declare const AUTOMATION_TASK_TYPE_SET: ReadonlySet<string>;
77
77
  */
78
78
  export declare const ALL_AUTOMATION_TASK_TYPE_SET: ReadonlySet<string>;
79
79
  export declare const AUTOMATION_BRANCH_TYPE_SET: ReadonlySet<string>;
80
+ /** Whether an exported address belongs to an automation composite. */
81
+ export declare function isAutomationResourceAddress(address: string): boolean;
@@ -131,3 +131,8 @@ export const AUTOMATION_TASK_TYPE_SET = new Set(AUTOMATION_TASK_TYPES);
131
131
  */
132
132
  export const ALL_AUTOMATION_TASK_TYPE_SET = new Set(TASK_SUB_TYPES.map((t) => t.resourceType));
133
133
  export const AUTOMATION_BRANCH_TYPE_SET = new Set(AUTOMATION_BRANCH_TYPES);
134
+ /** Whether an exported address belongs to an automation composite. */
135
+ export function isAutomationResourceAddress(address) {
136
+ const separator = address.indexOf(".");
137
+ return separator > 0 && ALL_AUTOMATION_RESOURCE_TYPES.includes(address.slice(0, separator));
138
+ }
@@ -0,0 +1,35 @@
1
+ import type { Ref } from "../shared/ref.js";
2
+ /** Product-shaped output types an automation may publish for downstream use. */
3
+ export declare const workflowOutputType: {
4
+ readonly text: "text";
5
+ readonly number: "number";
6
+ readonly decimal: "decimal";
7
+ readonly boolean: "boolean";
8
+ readonly date: "date";
9
+ readonly datetime: "datetime";
10
+ readonly json: "json";
11
+ readonly object: "object";
12
+ readonly record: "record";
13
+ readonly tableRecord: "tableRecord";
14
+ };
15
+ export type WorkflowOutputType = (typeof workflowOutputType)[keyof typeof workflowOutputType];
16
+ export interface WorkflowOutputDeclaration<Value extends Ref<unknown> = Ref<unknown>, Type extends WorkflowOutputType = WorkflowOutputType, Multiple extends boolean = boolean> {
17
+ /** @internal */
18
+ readonly __kind: "workflowOutput";
19
+ readonly value: Value;
20
+ readonly type: Type;
21
+ readonly multiple: Multiple;
22
+ }
23
+ /**
24
+ * Explicitly type one published automation output when its reference alone
25
+ * cannot reproduce the metadata stored by the platform. The value must be a
26
+ * task or trigger reference; variable and template references do not carry
27
+ * this metadata in the workflow HCL contract.
28
+ */
29
+ export declare function workflowOutput<const Value extends Ref<unknown>, const Type extends WorkflowOutputType, const Multiple extends boolean>(value: Value, options: {
30
+ readonly type: Type;
31
+ readonly multiple: Multiple;
32
+ }): WorkflowOutputDeclaration<Value, Type, Multiple>;
33
+ export declare function isWorkflowOutputDeclaration(value: unknown): value is WorkflowOutputDeclaration;
34
+ export declare function workflowOutputFieldType(type: WorkflowOutputType): string;
35
+ export declare function workflowOutputTypeFromFieldType(fieldType: string): WorkflowOutputType | undefined;