@elementumai/edk 0.13.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +6 -2
  2. package/dist-sdk/src/catalog/factories.js +8 -2
  3. package/dist-sdk/src/catalog/types.d.ts +5 -0
  4. package/dist-sdk/src/engine/coverage-gaps.d.ts +2 -0
  5. package/dist-sdk/src/engine/coverage-gaps.js +4 -0
  6. package/dist-sdk/src/engine/ei/run.d.ts +8 -0
  7. package/dist-sdk/src/engine/ei/run.js +46 -7
  8. package/dist-sdk/src/engine/pull/context.d.ts +24 -0
  9. package/dist-sdk/src/engine/pull/stream-root.d.ts +11 -0
  10. package/dist-sdk/src/engine/pull/stream-root.js +22 -6
  11. package/dist-sdk/src/engine/workspace/authoring-layout.js +16 -2
  12. package/dist-sdk/src/entities/access-policy/from-tf.js +4 -7
  13. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +2 -1
  14. package/dist-sdk/src/entities/agent/from-tf.d.ts +2 -0
  15. package/dist-sdk/src/entities/agent/from-tf.js +28 -1
  16. package/dist-sdk/src/entities/agent/module.js +1 -0
  17. package/dist-sdk/src/entities/agent/to-tf.d.ts +3 -1
  18. package/dist-sdk/src/entities/agent/to-tf.js +21 -3
  19. package/dist-sdk/src/entities/app/from-tf.d.ts +1 -0
  20. package/dist-sdk/src/entities/app/from-tf.js +6 -23
  21. package/dist-sdk/src/entities/app/module.js +2 -0
  22. package/dist-sdk/src/entities/approval-chain/from-tf.js +2 -2
  23. package/dist-sdk/src/entities/automation/build.d.ts +10 -1
  24. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +1 -0
  25. package/dist-sdk/src/entities/automation/from-tf.js +72 -11
  26. package/dist-sdk/src/entities/automation/index.d.ts +1 -1
  27. package/dist-sdk/src/entities/automation/module.js +12 -0
  28. package/dist-sdk/src/entities/automation/system-ref-name.d.ts +23 -3
  29. package/dist-sdk/src/entities/automation/system-ref-name.js +86 -4
  30. package/dist-sdk/src/entities/automation/to-tf.d.ts +5 -1
  31. package/dist-sdk/src/entities/automation/to-tf.js +227 -27
  32. package/dist-sdk/src/entities/dashboard/from-tf.d.ts +3 -1
  33. package/dist-sdk/src/entities/dashboard/from-tf.js +42 -2
  34. package/dist-sdk/src/entities/dashboard/to-tf.js +9 -1
  35. package/dist-sdk/src/entities/dashboard-widget-order/module.d.ts +10 -0
  36. package/dist-sdk/src/entities/dashboard-widget-order/module.js +25 -0
  37. package/dist-sdk/src/entities/dashboard-widget-order/order.d.ts +31 -0
  38. package/dist-sdk/src/entities/dashboard-widget-order/order.js +102 -0
  39. package/dist-sdk/src/entities/element/from-tf.d.ts +1 -0
  40. package/dist-sdk/src/entities/element/from-tf.js +5 -21
  41. package/dist-sdk/src/entities/element/module.js +2 -0
  42. package/dist-sdk/src/entities/field/from-tf.d.ts +25 -2
  43. package/dist-sdk/src/entities/field/from-tf.js +119 -14
  44. package/dist-sdk/src/entities/relationship/from-tf.js +2 -2
  45. package/dist-sdk/src/entities/role/build.d.ts +3 -4
  46. package/dist-sdk/src/entities/search-table/build.d.ts +9 -3
  47. package/dist-sdk/src/entities/search-table/build.js +4 -4
  48. package/dist-sdk/src/entities/search-table/printer.js +3 -1
  49. package/dist-sdk/src/entities/search-table/to-tf.js +20 -2
  50. package/dist-sdk/src/entities/shared/context.d.ts +14 -1
  51. package/dist-sdk/src/entities/shared/filters/index.d.ts +24 -13
  52. package/dist-sdk/src/entities/shared/filters/index.js +12 -1
  53. package/dist-sdk/src/entities/shared/filters/print.d.ts +2 -0
  54. package/dist-sdk/src/entities/shared/filters/print.js +15 -6
  55. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +4 -0
  56. package/dist-sdk/src/entities/shared/filters/tf-codec.js +16 -0
  57. package/dist-sdk/src/entities/shared/filters/types.d.ts +4 -0
  58. package/dist-sdk/src/entities/shared/tool-field-ref.d.ts +1 -1
  59. package/dist-sdk/src/entities/shared/tool-field-ref.js +2 -5
  60. package/dist-sdk/src/entities/task/from-tf.js +3 -3
  61. package/dist-sdk/src/entities/view/custom-view-validate.d.ts +6 -4
  62. package/dist-sdk/src/entities/view/custom-view-validate.js +36 -18
  63. package/dist-sdk/src/entities/view/from-tf.js +9 -0
  64. package/dist-sdk/src/entities/view/to-tf.js +66 -47
  65. package/dist-sdk/src/entities/visual-flow/module.js +52 -1
  66. package/dist-sdk/src/entities/widget/from-tf.js +6 -6
  67. package/dist-sdk/src/graph/index.d.ts +4 -0
  68. package/dist-sdk/src/graph/index.js +1 -0
  69. package/dist-sdk/src/graph/modules.js +2 -0
  70. package/dist-sdk/src/graph/types.d.ts +36 -1
  71. package/package.json +2 -2
@@ -289,6 +289,182 @@ function onlyEntry(value, subject) {
289
289
  }
290
290
  return entries[0];
291
291
  }
292
+ /**
293
+ * Record fields whose value is an object the platform writes into a field only
294
+ * by id (edk#2283, edk#2284). Its run-time converter takes a user id or email,
295
+ * a group id or name, or an option id or label. A whole user, group or option
296
+ * object fails the run, and a Multi-Select has no reference to its option ids.
297
+ */
298
+ const OBJECT_VALUED_FIELD_KINDS = {
299
+ elementum_user_field: "user",
300
+ elementum_group_field: "group",
301
+ elementum_dropdown_field: "Dropdown",
302
+ elementum_multiselect_field: "Multi-Select",
303
+ };
304
+ const OBJECT_VALUED_TARGET_FIELD_TYPES = new Set([
305
+ "USER", "USER_ID", "GROUP", "GROUP_ID", "PICKLIST", "PICKLIST_ID", "MULTI_PICKLIST", "MULTI_PICKLIST_ID",
306
+ ]);
307
+ /** The same kinds by catalog field type, for an owner known only from its generated catalog. */
308
+ const OBJECT_VALUED_CATALOG_FIELD_KINDS = {
309
+ USER: "user",
310
+ USER_ID: "user",
311
+ GROUP: "group",
312
+ GROUP_ID: "group",
313
+ PICKLIST: "Dropdown",
314
+ MULTI_PICKLIST: "Multi-Select",
315
+ };
316
+ /** System fields whose value is such an object. They have no field resource to read the type from. */
317
+ const OBJECT_VALUED_SYSTEM_FIELD_KINDS = {
318
+ createdBy: "user",
319
+ updatedBy: "user",
320
+ closedBy: "user",
321
+ status: "Dropdown",
322
+ stage: "Dropdown",
323
+ };
324
+ /**
325
+ * Fails a user, group, Dropdown or Multi-Select field assignment that reads a
326
+ * found or trigger record's whole user, group or option object, or any part
327
+ * of a Multi-Select. Build and plan pass those and the run fails. Pull keeps
328
+ * printing the live shape and only warns, as for a record-id field mapping.
329
+ */
330
+ function assertRecordFieldValueIsWritable(reference, fieldToken, refs) {
331
+ const problem = recordFieldValueProblem(reference, fieldToken, refs);
332
+ if (problem === undefined)
333
+ return;
334
+ const { message, finding } = problem;
335
+ if (currentValidationMode() === "pull") {
336
+ // Pull prints the live shape and warns. Build writes the finding into the
337
+ // compiled file, so the pull's revision record keeps it as one the
338
+ // platform already runs (#2283).
339
+ refs.owner.advisoriesWhileRecorded?.push({ finding, advisory: message, error: message });
340
+ recordValidations([{
341
+ severity: "warning",
342
+ address: `${AUTOMATION_RESOURCE_TYPE}.${refs.owner.automationTfLabel}`,
343
+ name: refs.owner.automationTfLabel,
344
+ ownerKind: "automation",
345
+ message,
346
+ }]);
347
+ return;
348
+ }
349
+ // An automation the platform already runs this way stays plannable while
350
+ // its revision record lists this exact finding from a pull or apply. Build
351
+ // decides that (it holds the record) and fails any finding the record
352
+ // doesn't list. Without the list there is no record to match, so fail.
353
+ if (!refs.owner.pulledLive || refs.owner.advisoriesWhileRecorded === undefined)
354
+ throw new EntityTfError(message);
355
+ refs.owner.advisoriesWhileRecorded.push({
356
+ finding,
357
+ advisory: `automation ${refs.owner.automationTfLabel}: ${message}`,
358
+ error: `${message} applied-automation-revisions.json doesn't record this assignment from a pull or apply of this automation ` +
359
+ "(it is new, or the record predates EDK recording these), so build stops it. If the platform already runs it, " +
360
+ "pull the app or element again to record it.",
361
+ });
362
+ }
363
+ function recordFieldValueProblem(reference, fieldToken, refs) {
364
+ if (fieldToken?.fieldType === undefined || !OBJECT_VALUED_TARGET_FIELD_TYPES.has(fieldToken.fieldType))
365
+ return undefined;
366
+ const source = recordFieldSource(reference, refs);
367
+ if (source === undefined)
368
+ return undefined;
369
+ // An authored owner's field resources decide the kind. An owner known only
370
+ // from its generated catalog has none, so its catalog field types decide.
371
+ const address = source.addresses?.get(source.fieldKey);
372
+ const sourceType = address === undefined ? undefined : address.slice(0, address.indexOf("."));
373
+ const catalogTypes = source.addresses === undefined && source.ownerRefName !== undefined
374
+ ? fieldNamesForAppRefName(refs.owner.catalogFieldTypesByAppRefName, source.ownerRefName)
375
+ : undefined;
376
+ const catalogType = catalogTypes?.get(source.fieldKey);
377
+ const kind = sourceType !== undefined ? OBJECT_VALUED_FIELD_KINDS[sourceType]
378
+ : catalogType !== undefined ? OBJECT_VALUED_CATALOG_FIELD_KINDS[catalogType]
379
+ : source.addresses !== undefined || catalogTypes !== undefined ? OBJECT_VALUED_SYSTEM_FIELD_KINDS[source.fieldKey]
380
+ : undefined;
381
+ const multiSelect = kind === "Multi-Select";
382
+ if (kind === undefined)
383
+ return undefined;
384
+ const target = fieldToken.name ?? fieldToken.refName;
385
+ // What the revision record keeps: the target field key and the source path as authored.
386
+ const finding = `${fieldToken.refName ?? target} <- ${source.path}`;
387
+ if (multiSelect) {
388
+ return { finding, message: `field "${target}" is set from ${source.path}, a Multi-Select. The platform has no reference to a Multi-Select's option ids, ` +
389
+ `so the run fails with "Unable to validate". Build a JSON list of the option ids (or, for another Multi-Select field, the labels) ` +
390
+ "in an executeScript, store it with setVariable, and set the field from that variable." };
391
+ }
392
+ if (source.rest.length > 0)
393
+ return undefined;
394
+ if (kind === "Dropdown") {
395
+ return { finding, message: `field "${target}" is set from ${source.path}, a whole Dropdown option. The platform writes a Dropdown only from an option id or label, ` +
396
+ `so the run fails. Set it from ${source.path}.id when it is the same field, or ${source.path}.label for another Dropdown, ` +
397
+ "since option ids belong to one field." };
398
+ }
399
+ return { finding, message: `field "${target}" is set from ${source.path}, a whole ${kind} object. The platform writes a ${kind} into a field only by id, ` +
400
+ `so the run fails. Set it from ${source.path}.id instead.` };
401
+ }
402
+ /**
403
+ * The record field a task, trigger, on-demand record parameter or record
404
+ * loop item reference reads, with the field addresses of the record's owner.
405
+ */
406
+ function recordFieldSource(reference, refs) {
407
+ if (!isObject(reference))
408
+ return undefined;
409
+ const taskOwner = (taskRefKey) => {
410
+ const owner = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey] ?? refs.tasks.get(taskRefKey)?.recordTarget?.refName;
411
+ if (owner === undefined)
412
+ return { addresses: undefined };
413
+ if (owner === refs.owner.appRefName)
414
+ return { addresses: refs.owner.fieldAddresses };
415
+ return { addresses: fieldNamesForAppRefName(refs.owner.fieldAddressesByAppRefName, owner), ownerRefName: owner };
416
+ };
417
+ if (isObject(reference.taskReference) && typeof reference.taskReference.taskRefKey === "string" && typeof reference.taskReference.name === "string") {
418
+ const [head, fieldKey, ...rest] = normalizeIndexedRecordsFieldPath(reference.taskReference.name).split(".");
419
+ if (head !== "record" || fieldKey === undefined)
420
+ return undefined;
421
+ const taskRefKey = reference.taskReference.taskRefKey;
422
+ return {
423
+ path: `ctx.actions${sourceKeyAccessor(taskRefKey)}.${reference.taskReference.name.replace(/^records\.(\d+)\./, "records[$1].")}`,
424
+ fieldKey,
425
+ rest,
426
+ ...taskOwner(taskRefKey),
427
+ };
428
+ }
429
+ if (isObject(reference.triggerReference) && typeof reference.triggerReference.name === "string") {
430
+ const name = reference.triggerReference.name;
431
+ const [head, fieldKey, ...rest] = name.split(".");
432
+ if (head === "record" && fieldKey !== undefined) {
433
+ return { path: `ctx.trigger.${name}`, fieldKey, rest, addresses: refs.owner.fieldAddresses };
434
+ }
435
+ const param = onDemandRecordFieldPath(name, refs);
436
+ if (param === undefined)
437
+ return undefined;
438
+ return {
439
+ path: `ctx.trigger${sourceKeyAccessor(param.paramName)}.${name.slice(param.paramName.length + 1)}`,
440
+ fieldKey: param.fieldKey,
441
+ rest: param.suffix === "" ? [] : param.suffix.split("."),
442
+ ...(param.isOwner
443
+ ? { addresses: refs.owner.fieldAddresses }
444
+ : { addresses: fieldNamesForAppRefName(refs.owner.fieldAddressesByAppRefName, param.target.refName), ownerRefName: param.target.refName }),
445
+ };
446
+ }
447
+ if (isObject(reference.forEachReference) && typeof reference.forEachReference.forEachTaskRefKey === "string" && typeof reference.forEachReference.name === "string") {
448
+ const loop = reference.forEachReference.forEachTaskRefKey;
449
+ const sourceTask = refs.recordItemForEachSourceByRefKey.get(loop);
450
+ if (sourceTask === undefined)
451
+ return undefined;
452
+ const [fieldKey, ...rest] = reference.forEachReference.name.split(".");
453
+ if (fieldKey === undefined || fieldKey === "")
454
+ return undefined;
455
+ return {
456
+ path: `ctx.loops${sourceKeyAccessor(loop)}.item.${reference.forEachReference.name}`,
457
+ fieldKey,
458
+ rest,
459
+ ...taskOwner(sourceTask),
460
+ };
461
+ }
462
+ return undefined;
463
+ }
464
+ /** `.key`, or `["key"]` for a task or loop key that isn't an identifier, as pulled source writes it. */
465
+ function sourceKeyAccessor(key) {
466
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
467
+ }
292
468
  /**
293
469
  * Tasks whose refs carry every field of the record they search (edk#2280)
294
470
  * or create (edk#2406), including system fields via object_fields /
@@ -1734,12 +1910,29 @@ const RECORD_COLLECTION_TASK_WIRE_TYPES = new Set([
1734
1910
  const TS_FOR_EACH_GENERIC_SEGMENT_TO_WIRE = {
1735
1911
  iteration: "Iteration",
1736
1912
  };
1913
+ /**
1914
+ * A forEach item's loop metadata (`ctx.item.metadata.<name>`, every
1915
+ * collection kind) is not an item field. Filters spell it
1916
+ * `for_each.<id>.metadata.<name>`; the loop's refs map keys it by display
1917
+ * name (live availableReferences, #2922).
1918
+ */
1919
+ const FOR_EACH_LOOP_METADATA_TO_WIRE = {
1920
+ "metadata.first": "Is First Item",
1921
+ "metadata.last": "Is Last Item",
1922
+ "metadata.iteration": "Iteration",
1923
+ "metadata.size": "Total Size",
1924
+ };
1925
+ function isForEachLoopMetadata(name) {
1926
+ return Object.hasOwn(FOR_EACH_LOOP_METADATA_TO_WIRE, name);
1927
+ }
1737
1928
  function forEachWireRefName(name, ctx, isRecordCollection) {
1738
1929
  // A recordSearch collection's whole item and branded record identity both
1739
1930
  // point at the loop's ASPECT_RECORD_ID reference. Live provider state
1740
1931
  // exposes that reference under "Record"; "ID" is a distinct TEXT handle.
1741
1932
  if (name === "item" || name === "recordId")
1742
1933
  return "Record";
1934
+ if (isForEachLoopMetadata(name))
1935
+ return FOR_EACH_LOOP_METADATA_TO_WIRE[name];
1743
1936
  // Record fields are keyed by their platform display names, not their typed
1744
1937
  // catalog handles. Reuse the same field/suffix mapping as trigger record
1745
1938
  // paths.
@@ -1992,8 +2185,8 @@ function assertLiteralFitsFieldType(value, field) {
1992
2185
  return;
1993
2186
  const fieldType = field.fieldType;
1994
2187
  const accepts = {
1995
- USER: { test: (text) => UUID_PATTERN.test(text), expected: "a user id, or a user reference such as ctx.trigger.record.<userField>" },
1996
- GROUP: { test: (text) => UUID_PATTERN.test(text), expected: "a group id, or a group reference" },
2188
+ USER: { test: (text) => UUID_PATTERN.test(text), expected: "a user id, or a user id reference such as ctx.trigger.record.<userField>.id" },
2189
+ GROUP: { test: (text) => UUID_PATTERN.test(text), expected: "a group id, or a group id reference such as ctx.trigger.record.<groupField>.id" },
1997
2190
  DATE: { test: (text) => ISO_DATE_PATTERN.test(text) && !Number.isNaN(Date.parse(text)), expected: "an ISO date (YYYY-MM-DD) or a date reference" },
1998
2191
  DATETIME: {
1999
2192
  test: (text) => ISO_DATETIME_PATTERN.test(text) && !Number.isNaN(Date.parse(text)),
@@ -2094,8 +2287,8 @@ function workflowPublishOutputValueToTf(value, refs) {
2094
2287
  return valueToTf(value, refs);
2095
2288
  }
2096
2289
  /**
2097
- * A `createRecord` task's own output record's field, embedded as a LIVE
2098
- * field resource `.id` reference instead of a resolved display name.
2290
+ * A field of the record a `createRecord` task made, in any app or element,
2291
+ * embedded as a LIVE field `.id` reference instead of a resolved display name.
2099
2292
  * Confirmed live (demoapptwo, #1066): the platform stores this specific
2100
2293
  * reference shape as `"record.<field-platform-id>.<suffix>"` — the SAME raw
2101
2294
  * form the unresolved-field escape hatch above already reproduces for a
@@ -2110,26 +2303,23 @@ function workflowPublishOutputValueToTf(value, refs) {
2110
2303
  * pattern as `taskId`/`variableReference.name` just below), so this stays
2111
2304
  * correct even across a field id change, unlike a literal string would.
2112
2305
  *
2113
- * Scoped to createRecord and to the SAME app as the automation owner — the
2114
- * only case confirmed live. A cross-app createRecord output, or a
2115
- * recordSearch/findRelatedRecords field access on an EXISTING (not
2116
- * just-created) record, is left on the existing display-name path until
2117
- * confirmed either way; returning `undefined` here falls through to it.
2306
+ * The suffix is optional and the field may be a system field of the created
2307
+ * record's own app or element: Under Armour's `TOOL_Create_Engagement_Record`
2308
+ * output `.record.id`, on a record of the Engagements element, exports as
2309
+ * `record.<Engagements ID field id>` (edk#2924). The field id resolves like a
2310
+ * filter value's found-record field (`foundRecordFieldReferenceName`): the
2311
+ * target's custom field resource, its `<owner>_<key>_field_id` system-field
2312
+ * local, or a `data.elementum_field` lookup for an app/element outside this
2313
+ * build. A field it can't resolve returns `undefined` and keeps the
2314
+ * display-name path. recordSearch/findRelatedRecords field access on an
2315
+ * EXISTING (not just-created) record isn't confirmed for outputs and stays
2316
+ * on that path too.
2118
2317
  */
2119
- function createRecordOwnFieldRefTfValue(target, name, refs) {
2318
+ function createRecordFieldRefTfValue(target, name, taskRefKey, refs) {
2120
2319
  if (target?.type !== "elementum_create_record_task")
2121
2320
  return undefined;
2122
- const match = /^record\.([^.]+)\.(.+)$/.exec(name);
2123
- if (match === null)
2124
- return undefined;
2125
- const [, fieldKey, suffix] = match;
2126
- const fieldType = refs.owner.fieldMetadata.get(fieldKey)?.fieldType;
2127
- if (fieldType === undefined)
2128
- return undefined;
2129
- const fieldId = fieldRefToTfValue(fieldType, fieldKey, refs.owner.appTfLabel, refs.owner.parentScope, refs.owner.fieldAddresses);
2130
- if (fieldId === undefined)
2131
- return undefined;
2132
- return expr.template(["record.", fieldId, `.${suffix}`]);
2321
+ const parts = foundRecordFieldReferenceName(target.type, name, taskRefKey, refs);
2322
+ return parts === undefined ? undefined : expr.template(parts);
2133
2323
  }
2134
2324
  /**
2135
2325
  * The canonical reference envelope for a workflow-OUTPUT task reference —
@@ -2140,7 +2330,7 @@ function createRecordOwnFieldRefTfValue(target, name, refs) {
2140
2330
  * against that name (edk#835), so EDK emits it directly instead of the refs-map
2141
2331
  * display label. The exceptions keep their existing resolution, since they
2142
2332
  * reference FIELDS / declared values by EDK-owned names, not the mobius
2143
- * display-label drift class: a task's own record field (`record.<field>`),
2333
+ * display-label drift class: a field of the task's record (`record.<field>`),
2144
2334
  * aiAgent (platform-nested via {@link aiAgentPlatformRefName}), and file-reader
2145
2335
  * (arbitrary schema field names). `fieldType`/`multiple` come from the generated
2146
2336
  * service_tasks contract (via {@link publishOutputType}). Returns undefined when
@@ -2157,16 +2347,16 @@ function taskReferenceEnvelope(value, refs) {
2157
2347
  const canonicalName = taskRef.name;
2158
2348
  const isFileReaderTask = target.type === "elementum_ai_file_read_task" || target.type === "elementum_file_reader_task";
2159
2349
  const isAiAgentTask = target.type === "elementum_ai_agent_task";
2160
- // A task's OWN just-created/found record FIELD (`record.<field>`) is not a
2350
+ // A field of the task's created/found record (`record.<field>`) is not a
2161
2351
  // task-output name — it resolves by the field's own id/display name. No
2162
2352
  // canonical output is ever spelled `record.<field>` (the contract has
2163
2353
  // record/records/recordId), so that dotted prefix uniquely marks it.
2164
- const isOwnRecordFieldRef = canonicalName.startsWith("record.");
2165
- const ownRecordFieldRef = createRecordOwnFieldRefTfValue(target, canonicalName, refs);
2166
- const platformRefName = ownRecordFieldRef
2354
+ const isRecordFieldRef = canonicalName.startsWith("record.");
2355
+ const createdRecordFieldRef = createRecordFieldRefTfValue(target, canonicalName, taskRef.taskRefKey, refs);
2356
+ const platformRefName = createdRecordFieldRef
2167
2357
  ?? (isFileReaderTask
2168
2358
  ? canonicalName
2169
- : isOwnRecordFieldRef
2359
+ : isRecordFieldRef
2170
2360
  ? taskWireRefName(canonicalName, taskRef.taskRefKey, refs)
2171
2361
  : isAiAgentTask
2172
2362
  ? aiAgentPlatformRefName(canonicalName)
@@ -3171,6 +3361,11 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
3171
3361
  const name = value.name === "recordId" ? "item" : value.name === "item" ? "" : value.name;
3172
3362
  return expr.template(["for_each.", expr.resourceAttr(task.type, task.label, ["id"]), `.${name}`]);
3173
3363
  }
3364
+ // The loop's own metadata is not a field of the iterated records:
3365
+ // export spells it `for_each.<id>.metadata.<name>` (#2922).
3366
+ if (isForEachLoopMetadata(value.name)) {
3367
+ return expr.template(["for_each.", expr.resourceAttr(task.type, task.label, ["id"]), `.${value.name}`]);
3368
+ }
3174
3369
  // Filter export uses a compact field-ID path, not inner.refs (the
3175
3370
  // script-input spelling) or the TypeScript property name. Resolve
3176
3371
  // the collection's actual owner and preserve that export dialect.
@@ -3498,6 +3693,8 @@ function filterToTf(value, refs) {
3498
3693
  return serializeFilterToTf(value, {
3499
3694
  ...(refs.allowUnknownPicklistOptions === true && { keepUnresolvedOptions: true }),
3500
3695
  field: (field) => valueToTf(field, refs),
3696
+ // `userRef(email)` compares as the user's id, through the same user lookup a task value uses (#2891).
3697
+ user: (email) => valueToTf({ __kind: "user", email }, refs),
3501
3698
  fieldFromLeftValue: (left) => fieldFromFilterLeftValue(left, refs),
3502
3699
  reference: (reference, role, realType, operator) => filterReferenceToTf(reference, refs, role ?? "value", realType, operator),
3503
3700
  referenceRealType: (reference, role, authored) => {
@@ -4014,6 +4211,7 @@ function configAttrs(kind, config, refs) {
4014
4211
  ? picklistAssignmentValueToTf(staticValue, fieldToken, refs)
4015
4212
  : undefined;
4016
4213
  let reference = field.valueReference;
4214
+ assertRecordFieldValueIsWritable(reference, fieldToken, refs);
4017
4215
  if (typeof reference === "string") {
4018
4216
  reference = normalizeTriggerRecordIdEnvelopeString(reference, refs);
4019
4217
  }
@@ -4251,6 +4449,8 @@ export function automationToTf(entity, ctx) {
4251
4449
  activeAutomationRefNames: ctx.activeAutomationRefNames,
4252
4450
  ...(ctx.elementsWithoutAuditFields !== undefined ? { elementsWithoutAuditFields: ctx.elementsWithoutAuditFields } : {}),
4253
4451
  ...(ctx.fieldAddressesByAppRefName !== undefined ? { fieldAddressesByAppRefName: ctx.fieldAddressesByAppRefName } : {}),
4452
+ ...(ctx.catalogFieldTypesByAppRefName !== undefined ? { catalogFieldTypesByAppRefName: ctx.catalogFieldTypesByAppRefName } : {}),
4453
+ ...(ctx.advisoriesWhileRecorded !== undefined ? { advisoriesWhileRecorded: ctx.advisoriesWhileRecorded } : {}),
4254
4454
  ...(ctx.authoredAspectKeys !== undefined ? { authoredAspectKeys: ctx.authoredAspectKeys } : {}),
4255
4455
  recordLacksAuditFields: ctx.parentScope === "element" && ctx.ownerAuditFields !== true,
4256
4456
  };
@@ -19,4 +19,6 @@ export interface DashboardOwner {
19
19
  readonly fieldKeysByName?: ReadonlyMap<string, string | null>;
20
20
  readonly unextractedFieldIds?: Set<string>;
21
21
  }
22
- export declare function dashboardsFromTf(blocks: readonly TfBlock[], widgetBlocks: readonly TfBlock[], owner: DashboardOwner, ctx: FromTfContext): NormalizedDashboard[];
22
+ export declare function dashboardsFromTf(blocks: readonly TfBlock[], widgetBlocks: readonly TfBlock[], owner: DashboardOwner, ctx: FromTfContext,
23
+ /** `elementum_dashboard_widget_order` blocks; each orders its dashboard's widgets. */
24
+ orderBlocks?: readonly TfBlock[]): NormalizedDashboard[];
@@ -5,6 +5,7 @@ import { filterFromTf } from "../access-policy/from-tf.js";
5
5
  import { filterOwnerForAspect } from "../relationship/from-tf.js";
6
6
  import { filterWireToTf } from "../shared/filters/tf-codec.js";
7
7
  import { DASHBOARD_WIDGET_RESOURCE_TYPE } from "../dashboard-widget/module.js";
8
+ import { DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE, KNOWN_DASHBOARD_WIDGET_ORDER_ATTRS, dashboardWidgetOrderFor, inDashboardWidgetOrder } from "../dashboard-widget-order/order.js";
8
9
  import { DASHBOARD_RESOURCE_TYPE } from "./module.js";
9
10
  import { CHART_RESOURCE_TYPE } from "../chart/types.js";
10
11
  import { chartRefNameFromTfLabel } from "../chart/from-tf.js";
@@ -12,7 +13,9 @@ import { dashboardWidgetSize } from "./build.js";
12
13
  import { resolveDataAspectTarget } from "../shared/aspect-target-from-tf.js";
13
14
  import { managedViewSortFromTf } from "../view/from-tf.js";
14
15
  const KNOWN_DASHBOARD_ATTRS = new Set(["name", "owner_id", "owner_type", "favorite", "tags"]);
15
- export function dashboardsFromTf(blocks, widgetBlocks, owner, ctx) {
16
+ export function dashboardsFromTf(blocks, widgetBlocks, owner, ctx,
17
+ /** `elementum_dashboard_widget_order` blocks; each orders its dashboard's widgets. */
18
+ orderBlocks = []) {
16
19
  const dashboards = [];
17
20
  for (const block of blocks) {
18
21
  const label = block.label;
@@ -32,7 +35,21 @@ export function dashboardsFromTf(blocks, widgetBlocks, owner, ctx) {
32
35
  }
33
36
  const tags = stringList(block.attrs, "tags", where, ctx);
34
37
  const key = scopedLabelToBagKey(owner.ownerTfLabel, label, owner.scope);
35
- const widgets = dashboardWidgetsFromTf(widgetBlocks.filter((widget) => resourceRefLabel(widget.attrs["dashboard_id"], DASHBOARD_RESOURCE_TYPE) === label), label, key, owner, ctx);
38
+ const order = dashboardWidgetOrderFor(orderBlocks, DASHBOARD_RESOURCE_TYPE, label);
39
+ if (order !== undefined) {
40
+ const orderWhere = `${DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE}.${order.label ?? "?"}`;
41
+ reportUnknownAttrs(order.attrs, KNOWN_DASHBOARD_WIDGET_ORDER_ATTRS, orderWhere, "dashboardsFromTf", ctx);
42
+ if (resourceRefLabel(order.attrs["owner_id"], owner.type) !== owner.label) {
43
+ ctx.diagnostics.push(`${orderWhere}: owner_id does not reference ${owner.type}.${owner.label}; widgets keep the export's order`);
44
+ }
45
+ }
46
+ const ownedWidgets = widgetBlocks.filter((widget) => resourceRefLabel(widget.attrs["dashboard_id"], DASHBOARD_RESOURCE_TYPE) === label);
47
+ const orderedWidgets = order !== undefined && resourceRefLabel(order.attrs["owner_id"], owner.type) === owner.label
48
+ ? inDashboardWidgetOrder(ownedWidgets, order)
49
+ : ownedWidgets;
50
+ const widgets = dashboardWidgetsFromTf(orderedWidgets, label, key, owner, ctx);
51
+ if (order !== undefined)
52
+ requireEveryWidget(order, ownedWidgets, widgets, label, ctx);
36
53
  dashboards.push({
37
54
  key,
38
55
  name: optionalString(block.attrs, "name", where, ctx) ?? "",
@@ -122,6 +139,29 @@ function dashboardWidgetsFromTf(blocks, dashboardLabel, dashboardKey, owner, ctx
122
139
  }];
123
140
  });
124
141
  }
142
+ /**
143
+ * The order's import lists every chart and records widget of the dashboard,
144
+ * but build lists only the widgets source holds. A widget this pull leaves out
145
+ * would therefore plan a reorder no source edit asked for, so the order is
146
+ * skipped and released with it. It runs after the widgets' own requirements,
147
+ * so a chart widget skipped for its chart takes the order along. The next
148
+ * plan imports the order for the widgets source holds (the kind's
149
+ * stateAdoption), so it plans no change.
150
+ */
151
+ function requireEveryWidget(order, widgetBlocks, written, dashboardLabel, ctx) {
152
+ if (ctx.requiresExtracted === undefined)
153
+ return;
154
+ const address = `${DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE}.${order.label ?? ""}`;
155
+ const writtenKeys = new Set(written.map((widget) => widget.key));
156
+ for (const block of widgetBlocks) {
157
+ const label = block.label ?? "";
158
+ const key = tfLabelToTsLabel(label.startsWith(`${dashboardLabel}_`) ? label.slice(dashboardLabel.length + 1) : label);
159
+ const requires = `${DASHBOARD_WIDGET_RESOURCE_TYPE}.${label}`;
160
+ ctx.requiresExtracted.push(writtenKeys.has(key)
161
+ ? { address, requires, prune: (root) => root }
162
+ : { address, requires, unresolved: true, prune: (root) => root });
163
+ }
164
+ }
125
165
  /**
126
166
  * The filter ranges over the target's records, so its fields may belong to
127
167
  * the target rather than to the dashboard's owner. A raw field id decodes
@@ -3,6 +3,7 @@ import { workspaceAspectKey } from "../../engine/build/context.js";
3
3
  import { filterToTf } from "../access-policy/to-tf.js";
4
4
  import { filterTfToWire } from "../shared/filters/tf-codec.js";
5
5
  import { DASHBOARD_WIDGET_RESOURCE_TYPE } from "../dashboard-widget/module.js";
6
+ import { dashboardWidgetOrderToTf } from "../dashboard-widget-order/order.js";
6
7
  import { targetFilterFieldResolver } from "../relationship/to-tf.js";
7
8
  import { resolveForeignRef } from "../shared/foreign-ref.js";
8
9
  import { DASHBOARD_RESOURCE_TYPE } from "./module.js";
@@ -30,6 +31,8 @@ export function dashboardsToTf(dashboards, opts) {
30
31
  label: dashboardLabel,
31
32
  attrs,
32
33
  });
34
+ // The widgets bag's key order is the dashboard's widget order.
35
+ const widgetLabels = [];
33
36
  for (const [widgetKey, widget] of Object.entries(dashboard.widgets ?? {})) {
34
37
  const where = `dashboards.${key}.widgets.${widgetKey}`;
35
38
  if (!isCanonicalTsLabel(widgetKey)) {
@@ -92,8 +95,13 @@ export function dashboardsToTf(dashboards, opts) {
92
95
  opts.diagnostics.push(`${where}: unsupported widget type; dropped`);
93
96
  continue;
94
97
  }
95
- blocks.push({ kind: "resource", type: DASHBOARD_WIDGET_RESOURCE_TYPE, label: scopedResourceLabel(opts.ownerTfLabel, tsLabelToTfLabel(`${key}_${widgetKey}`), opts.scope), attrs: widgetAttrs });
98
+ const widgetLabel = scopedResourceLabel(opts.ownerTfLabel, tsLabelToTfLabel(`${key}_${widgetKey}`), opts.scope);
99
+ widgetLabels.push(widgetLabel);
100
+ blocks.push({ kind: "resource", type: DASHBOARD_WIDGET_RESOURCE_TYPE, label: widgetLabel, attrs: widgetAttrs });
96
101
  }
102
+ const order = dashboardWidgetOrderToTf(dashboardLabel, opts.ownerId, expr.resourceAttr(DASHBOARD_RESOURCE_TYPE, dashboardLabel, ["id"]), widgetLabels);
103
+ if (order !== undefined)
104
+ blocks.push(order);
97
105
  }
98
106
  return blocks;
99
107
  }
@@ -0,0 +1,10 @@
1
+ import { type EntityKindModule } from "../../graph/types.js";
2
+ import { DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE } from "./order.js";
3
+ export { DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE };
4
+ /**
5
+ * `elementum_dashboard_widget_order` orders one dashboard's widgets. Build
6
+ * emits it from the authored `widgets` key order; pull prints widgets in its
7
+ * order. It has no authoring of its own: the bag order is the order. Its
8
+ * import id is `<owner id>:<dashboard id>`.
9
+ */
10
+ export declare const dashboardWidgetOrderModule: EntityKindModule;
@@ -0,0 +1,25 @@
1
+ import { NO_CANVAS, NO_CATALOG, NO_DATA, NO_LIFECYCLE } from "../../graph/types.js";
2
+ import { DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE, dashboardWidgetOrderStateAdoption } from "./order.js";
3
+ export { DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE };
4
+ /**
5
+ * `elementum_dashboard_widget_order` orders one dashboard's widgets. Build
6
+ * emits it from the authored `widgets` key order; pull prints widgets in its
7
+ * order. It has no authoring of its own: the bag order is the order. Its
8
+ * import id is `<owner id>:<dashboard id>`.
9
+ */
10
+ export const dashboardWidgetOrderModule = {
11
+ kind: "dashboard-widget-order",
12
+ stream: { role: "streamMember" },
13
+ authoring: { unit: "inline", bag: "widgets" },
14
+ parents: [{ parent: "dashboard", child: "dashboard-widget-order" }],
15
+ resource: { shape: "single", resourceType: DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE, adoptable: true },
16
+ data: NO_DATA,
17
+ lifecycle: NO_LIFECYCLE,
18
+ canvas: NO_CANVAS,
19
+ catalog: NO_CATALOG,
20
+ stateAdoption: dashboardWidgetOrderStateAdoption,
21
+ // Build writes no order when the dashboard has no authored widgets.
22
+ portable: {
23
+ leaveOutWhenEmptied: [{ resourceType: DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE, attribute: "widget_ids", reason: "it only ordered the left-out widgets" }],
24
+ },
25
+ };
@@ -0,0 +1,31 @@
1
+ import { type TfBlock, type TfValue } from "../../engine/tf/index.js";
2
+ import type { StateAdoptionFacet } from "../../graph/types.js";
3
+ export declare const DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE = "elementum_dashboard_widget_order";
4
+ /**
5
+ * The dashboard's widget order block, or undefined when it has no widget
6
+ * resource. It takes the dashboard's own label (one order per dashboard), as
7
+ * `ei export` names it. `widgetLabels` is in authored order.
8
+ */
9
+ export declare function dashboardWidgetOrderToTf(dashboardLabel: string, ownerId: TfValue, dashboardId: TfValue, widgetLabels: readonly string[]): TfBlock | undefined;
10
+ /** Attributes `inDashboardWidgetOrder` reads. */
11
+ export declare const KNOWN_DASHBOARD_WIDGET_ORDER_ATTRS: ReadonlySet<string>;
12
+ /** The order block whose `dashboard_id` references `dashboardType.dashboardLabel`. */
13
+ export declare function dashboardWidgetOrderFor(orderBlocks: readonly TfBlock[], dashboardType: string, dashboardLabel: string): TfBlock | undefined;
14
+ /**
15
+ * `widgetBlocks` in the order the dashboard's widget order lists them, so pull
16
+ * prints widgets in the platform's order instead of the parser's label order.
17
+ * Widgets it doesn't list keep their relative order after the listed ones.
18
+ */
19
+ export declare function inDashboardWidgetOrder(widgetBlocks: readonly TfBlock[], orderBlock: TfBlock | undefined): readonly TfBlock[];
20
+ /**
21
+ * A dashboard whose order has no state would plan a hidden create (a live
22
+ * reorder): a workspace pulled before widget order was managed, or a pull that
23
+ * left one of the dashboard's widgets out of source and released the order
24
+ * with it. When the dashboard is in state but its order isn't, import the live
25
+ * order, keyed `<owner id>:<dashboard id>:<widget ids>` with the ids of the
26
+ * widgets build lists that state already holds. The provider then tracks only
27
+ * those widgets, so a widget source doesn't hold never shows as a change, and
28
+ * any reorder of the listed ones shows as a visible in-place `widget_ids`
29
+ * update.
30
+ */
31
+ export declare const dashboardWidgetOrderStateAdoption: StateAdoptionFacet;
@@ -0,0 +1,102 @@
1
+ /**
2
+ * A dashboard's widget order: `elementum_dashboard_widget_order` lists the
3
+ * dashboard's widget resources in authored `widgets` key order. Without it a
4
+ * widget keeps the position the platform gave it at create (the widget count
5
+ * then), and every add or delete shifts the rest, so the rendered order drifts
6
+ * between applies.
7
+ */
8
+ import { resourceRefLabel } from "../../engine/pull/context.js";
9
+ import { expr, isTfExpr } from "../../engine/tf/index.js";
10
+ import { DASHBOARD_WIDGET_RESOURCE_TYPE } from "../dashboard-widget/module.js";
11
+ export const DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE = "elementum_dashboard_widget_order";
12
+ /**
13
+ * The dashboard's widget order block, or undefined when it has no widget
14
+ * resource. It takes the dashboard's own label (one order per dashboard), as
15
+ * `ei export` names it. `widgetLabels` is in authored order.
16
+ */
17
+ export function dashboardWidgetOrderToTf(dashboardLabel, ownerId, dashboardId, widgetLabels) {
18
+ if (widgetLabels.length === 0)
19
+ return undefined;
20
+ return {
21
+ kind: "resource",
22
+ type: DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE,
23
+ label: dashboardLabel,
24
+ attrs: {
25
+ owner_id: ownerId,
26
+ dashboard_id: dashboardId,
27
+ widget_ids: widgetLabels.map((label) => expr.resourceAttr(DASHBOARD_WIDGET_RESOURCE_TYPE, label, ["id"])),
28
+ },
29
+ };
30
+ }
31
+ /** Attributes `inDashboardWidgetOrder` reads. */
32
+ export const KNOWN_DASHBOARD_WIDGET_ORDER_ATTRS = new Set(["owner_id", "dashboard_id", "widget_ids"]);
33
+ /** The order block whose `dashboard_id` references `dashboardType.dashboardLabel`. */
34
+ export function dashboardWidgetOrderFor(orderBlocks, dashboardType, dashboardLabel) {
35
+ return orderBlocks.find((block) => resourceRefLabel(block.attrs["dashboard_id"], dashboardType) === dashboardLabel);
36
+ }
37
+ /**
38
+ * `widgetBlocks` in the order the dashboard's widget order lists them, so pull
39
+ * prints widgets in the platform's order instead of the parser's label order.
40
+ * Widgets it doesn't list keep their relative order after the listed ones.
41
+ */
42
+ export function inDashboardWidgetOrder(widgetBlocks, orderBlock) {
43
+ const widgetIds = orderBlock?.attrs["widget_ids"];
44
+ if (!Array.isArray(widgetIds))
45
+ return widgetBlocks;
46
+ const position = new Map();
47
+ for (const [index, value] of widgetIds.entries()) {
48
+ const label = resourceRefLabel(value, DASHBOARD_WIDGET_RESOURCE_TYPE);
49
+ if (label !== undefined)
50
+ position.set(label, index);
51
+ }
52
+ const at = (block) => position.get(block.label ?? "") ?? Number.MAX_SAFE_INTEGER;
53
+ return [...widgetBlocks].sort((a, b) => at(a) - at(b));
54
+ }
55
+ /**
56
+ * A dashboard whose order has no state would plan a hidden create (a live
57
+ * reorder): a workspace pulled before widget order was managed, or a pull that
58
+ * left one of the dashboard's widgets out of source and released the order
59
+ * with it. When the dashboard is in state but its order isn't, import the live
60
+ * order, keyed `<owner id>:<dashboard id>:<widget ids>` with the ids of the
61
+ * widgets build lists that state already holds. The provider then tracks only
62
+ * those widgets, so a widget source doesn't hold never shows as a change, and
63
+ * any reorder of the listed ones shows as a visible in-place `widget_ids`
64
+ * update.
65
+ */
66
+ export const dashboardWidgetOrderStateAdoption = {
67
+ importsFor(blocks, state) {
68
+ const out = [];
69
+ for (const block of blocks) {
70
+ if (block.kind !== "resource" || block.type !== DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE || block.label === undefined)
71
+ continue;
72
+ if (state.has(block.type, block.label))
73
+ continue;
74
+ const owner = block.attrs["owner_id"];
75
+ const dashboard = block.attrs["dashboard_id"];
76
+ if (!isTfExpr(owner) || owner.$expr !== "resource-attr")
77
+ continue;
78
+ if (!isTfExpr(dashboard) || dashboard.$expr !== "resource-attr")
79
+ continue;
80
+ const ownerId = state.idOf(owner.type, owner.label);
81
+ const dashboardId = state.idOf(dashboard.type, dashboard.label);
82
+ if (ownerId === undefined || dashboardId === undefined)
83
+ continue;
84
+ const widgetIds = Array.isArray(block.attrs["widget_ids"]) ? block.attrs["widget_ids"] : [];
85
+ const tracked = widgetIds.flatMap((value) => {
86
+ const label = resourceRefLabel(value, DASHBOARD_WIDGET_RESOURCE_TYPE);
87
+ const id = label === undefined ? undefined : state.idOf(DASHBOARD_WIDGET_RESOURCE_TYPE, label);
88
+ return id === undefined ? [] : [id];
89
+ });
90
+ out.push({ type: block.type, label: block.label, id: `${ownerId}:${dashboardId}:${tracked.join(",")}` });
91
+ }
92
+ return out;
93
+ },
94
+ warning(imports) {
95
+ const names = imports.slice(0, 5).map((i) => i.label).join(", ");
96
+ const more = imports.length > 5 ? `, … (+${imports.length - 5} more)` : "";
97
+ return [
98
+ `${imports.length} dashboard(s) have no ${DASHBOARD_WIDGET_ORDER_RESOURCE_TYPE} state (a workspace pulled before widget order was managed, or a pull that left one of the dashboard's widgets out): ${names}${more}.`,
99
+ "Importing their live widget order for the widgets in source; a widget_ids change in the plan reorders the dashboard to match the widgets' order in source.",
100
+ ].join("\n");
101
+ },
102
+ };
@@ -24,6 +24,7 @@ export interface ElementFromTfViewBlocks {
24
24
  readonly relationshipBlocks: readonly TfBlock[];
25
25
  readonly dashboardBlocks: readonly TfBlock[];
26
26
  readonly dashboardWidgetBlocks: readonly TfBlock[];
27
+ readonly dashboardWidgetOrderBlocks?: readonly TfBlock[];
27
28
  readonly widgetBlocks: readonly TfBlock[];
28
29
  }
29
30
  export declare function elementFromTf(elementBlock: TfBlock, fieldBlocks: readonly TfBlock[], ctx: FromTfContext, viewBlocks?: ElementFromTfViewBlocks, accessPolicyBlocks?: readonly TfBlock[], roleBlocks?: readonly TfBlock[]): ElementFromTfResult;