sf-plugin-data 0.1.0 → 0.2.0

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 (269) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +572 -240
  3. package/docs/artifact-format.md +527 -633
  4. package/docs/capabilities.md +1159 -168
  5. package/docs/git-workflow.md +135 -12
  6. package/docs/handover.md +7826 -12
  7. package/lib/api.d.ts +7 -0
  8. package/lib/api.js +7 -0
  9. package/lib/artifacts/code-fields.d.ts +49 -0
  10. package/lib/artifacts/code-fields.js +142 -0
  11. package/lib/artifacts/data-graph-document.d.ts +29 -0
  12. package/lib/artifacts/data-graph-document.js +52 -0
  13. package/lib/artifacts/data-space-field.d.ts +65 -0
  14. package/lib/artifacts/data-space-field.js +98 -0
  15. package/lib/artifacts/data-stream-document.d.ts +264 -0
  16. package/lib/artifacts/data-stream-document.js +680 -0
  17. package/lib/artifacts/data-transform-document.d.ts +152 -0
  18. package/lib/artifacts/data-transform-document.js +560 -0
  19. package/lib/artifacts/dependency-selection.d.ts +51 -0
  20. package/lib/artifacts/dependency-selection.js +154 -0
  21. package/lib/artifacts/dlo-document.d.ts +93 -0
  22. package/lib/artifacts/dlo-document.js +253 -0
  23. package/lib/artifacts/enum-case.d.ts +39 -0
  24. package/lib/artifacts/enum-case.js +67 -0
  25. package/lib/artifacts/git-deploy-selection.d.ts +68 -0
  26. package/lib/artifacts/git-deploy-selection.js +474 -0
  27. package/lib/artifacts/identity-resolution-document.d.ts +133 -0
  28. package/lib/artifacts/identity-resolution-document.js +625 -0
  29. package/lib/artifacts/mapping-document.d.ts +1 -0
  30. package/lib/artifacts/mapping-document.js +1 -0
  31. package/lib/artifacts/native-calculated-insight-document.d.ts +142 -0
  32. package/lib/artifacts/native-calculated-insight-document.js +321 -0
  33. package/lib/artifacts/native-data-graph-document.d.ts +124 -0
  34. package/lib/artifacts/native-data-graph-document.js +780 -0
  35. package/lib/artifacts/native-dmo-document.d.ts +151 -0
  36. package/lib/artifacts/native-dmo-document.js +313 -0
  37. package/lib/artifacts/native-mapping-document.d.ts +67 -0
  38. package/lib/artifacts/native-mapping-document.js +187 -0
  39. package/lib/artifacts/native-relationship-document.d.ts +76 -0
  40. package/lib/artifacts/native-relationship-document.js +232 -0
  41. package/lib/artifacts/path-selector.d.ts +55 -0
  42. package/lib/artifacts/path-selector.js +167 -0
  43. package/lib/artifacts/read-deploy-input.d.ts +222 -6
  44. package/lib/artifacts/read-deploy-input.js +1213 -53
  45. package/lib/artifacts/segment-document.d.ts +183 -0
  46. package/lib/artifacts/segment-document.js +570 -0
  47. package/lib/artifacts/verbatim-document.d.ts +203 -0
  48. package/lib/artifacts/verbatim-document.js +339 -0
  49. package/lib/artifacts/write-data-graph.d.ts +17 -0
  50. package/lib/artifacts/write-data-graph.js +162 -0
  51. package/lib/artifacts/write-data-stream.d.ts +11 -0
  52. package/lib/artifacts/write-data-stream.js +175 -0
  53. package/lib/artifacts/write-data-transform.d.ts +11 -0
  54. package/lib/artifacts/write-data-transform.js +180 -0
  55. package/lib/artifacts/write-dlo.d.ts +11 -0
  56. package/lib/artifacts/write-dlo.js +158 -0
  57. package/lib/artifacts/write-identity-resolution.d.ts +18 -0
  58. package/lib/artifacts/write-identity-resolution.js +165 -0
  59. package/lib/artifacts/write-mapping-definition.d.ts +17 -0
  60. package/lib/artifacts/write-mapping-definition.js +127 -0
  61. package/lib/artifacts/write-member-export.d.ts +88 -0
  62. package/lib/artifacts/write-member-export.js +199 -0
  63. package/lib/artifacts/write-native-calculated-insight.d.ts +21 -0
  64. package/lib/artifacts/write-native-calculated-insight.js +176 -0
  65. package/lib/artifacts/write-native-dmo.d.ts +11 -0
  66. package/lib/artifacts/write-native-dmo.js +158 -0
  67. package/lib/artifacts/write-native-mapping.d.ts +11 -0
  68. package/lib/artifacts/write-native-mapping.js +157 -0
  69. package/lib/artifacts/write-native-relationship.d.ts +11 -0
  70. package/lib/artifacts/write-native-relationship.js +157 -0
  71. package/lib/artifacts/write-segment.d.ts +26 -0
  72. package/lib/artifacts/write-segment.js +212 -0
  73. package/lib/commands/data360/delete.d.ts +280 -0
  74. package/lib/commands/data360/delete.js +2297 -0
  75. package/lib/commands/data360/deploy.d.ts +234 -15
  76. package/lib/commands/data360/deploy.js +2292 -100
  77. package/lib/commands/data360/publish.d.ts +93 -0
  78. package/lib/commands/data360/publish.js +292 -0
  79. package/lib/commands/data360/retrieve.d.ts +260 -13
  80. package/lib/commands/data360/retrieve.js +1880 -85
  81. package/lib/commands/data360/segment/members/export.d.ts +101 -0
  82. package/lib/commands/data360/segment/members/export.js +318 -0
  83. package/lib/errors/codes/calculated-insight.d.ts +2 -0
  84. package/lib/errors/codes/calculated-insight.js +25 -0
  85. package/lib/errors/codes/data-graph.d.ts +2 -0
  86. package/lib/errors/codes/data-graph.js +22 -0
  87. package/lib/errors/codes/data-stream.d.ts +2 -0
  88. package/lib/errors/codes/data-stream.js +70 -0
  89. package/lib/errors/codes/data-transform.d.ts +2 -0
  90. package/lib/errors/codes/data-transform.js +35 -0
  91. package/lib/errors/codes/dependency.d.ts +2 -0
  92. package/lib/errors/codes/dependency.js +11 -0
  93. package/lib/errors/codes/dlo.d.ts +2 -0
  94. package/lib/errors/codes/dlo.js +31 -0
  95. package/lib/errors/codes/dmo.d.ts +2 -0
  96. package/lib/errors/codes/dmo.js +28 -0
  97. package/lib/errors/codes/general.d.ts +2 -0
  98. package/lib/errors/codes/general.js +57 -0
  99. package/lib/errors/codes/identity-resolution.d.ts +2 -0
  100. package/lib/errors/codes/identity-resolution.js +24 -0
  101. package/lib/errors/codes/mapping.d.ts +2 -0
  102. package/lib/errors/codes/mapping.js +42 -0
  103. package/lib/errors/codes/relationship.d.ts +2 -0
  104. package/lib/errors/codes/relationship.js +21 -0
  105. package/lib/errors/codes/segment.d.ts +2 -0
  106. package/lib/errors/codes/segment.js +49 -0
  107. package/lib/errors/registry.d.ts +60 -0
  108. package/lib/errors/registry.js +123 -0
  109. package/lib/plugin.d.ts +1 -0
  110. package/lib/plugin.js +3 -1
  111. package/lib/services/acquire-retrieve-selection.d.ts +43 -0
  112. package/lib/services/acquire-retrieve-selection.js +145 -0
  113. package/lib/services/bind-identity-resolution-dependencies.d.ts +53 -0
  114. package/lib/services/bind-identity-resolution-dependencies.js +238 -0
  115. package/lib/services/bind-segment-dependencies.d.ts +49 -0
  116. package/lib/services/bind-segment-dependencies.js +115 -0
  117. package/lib/services/bounded-reads.d.ts +17 -0
  118. package/lib/services/bounded-reads.js +42 -0
  119. package/lib/services/calculated-insight-sql-checks.d.ts +33 -0
  120. package/lib/services/calculated-insight-sql-checks.js +193 -0
  121. package/lib/services/command-dlo.d.ts +48 -0
  122. package/lib/services/command-dlo.js +103 -0
  123. package/lib/services/command-native-data-graph.d.ts +54 -0
  124. package/lib/services/command-native-data-graph.js +485 -0
  125. package/lib/services/command-native-data-stream.d.ts +104 -0
  126. package/lib/services/command-native-data-stream.js +257 -0
  127. package/lib/services/command-native-dmo.d.ts +124 -0
  128. package/lib/services/command-native-dmo.js +338 -0
  129. package/lib/services/command-native-mapping.d.ts +65 -0
  130. package/lib/services/command-native-mapping.js +129 -0
  131. package/lib/services/command-native-relationship.d.ts +46 -0
  132. package/lib/services/command-native-relationship.js +103 -0
  133. package/lib/services/cross-dataspace-deploy.d.ts +111 -0
  134. package/lib/services/cross-dataspace-deploy.js +493 -0
  135. package/lib/services/cross-dataspace-rename.d.ts +74 -0
  136. package/lib/services/cross-dataspace-rename.js +1314 -0
  137. package/lib/services/cross-dataspace-sql.d.ts +109 -0
  138. package/lib/services/cross-dataspace-sql.js +1301 -0
  139. package/lib/services/cross-space-context.d.ts +23 -0
  140. package/lib/services/cross-space-context.js +36 -0
  141. package/lib/services/crud-plan.d.ts +137 -0
  142. package/lib/services/crud-plan.js +408 -0
  143. package/lib/services/data-space-check.d.ts +89 -0
  144. package/lib/services/data-space-check.js +162 -0
  145. package/lib/services/data-space-prefix.d.ts +77 -0
  146. package/lib/services/data-space-prefix.js +127 -0
  147. package/lib/services/data-transform-space.d.ts +31 -0
  148. package/lib/services/data-transform-space.js +79 -0
  149. package/lib/services/delete-calculated-insight.d.ts +44 -0
  150. package/lib/services/delete-calculated-insight.js +101 -0
  151. package/lib/services/delete-data-transform.d.ts +52 -0
  152. package/lib/services/delete-data-transform.js +222 -0
  153. package/lib/services/delete-dmo-field.d.ts +211 -0
  154. package/lib/services/delete-dmo-field.js +472 -0
  155. package/lib/services/delete-identity-resolution.d.ts +43 -0
  156. package/lib/services/delete-identity-resolution.js +295 -0
  157. package/lib/services/delete-segment.d.ts +42 -0
  158. package/lib/services/delete-segment.js +248 -0
  159. package/lib/services/deploy-result.d.ts +54 -0
  160. package/lib/services/deploy-result.js +60 -0
  161. package/lib/services/escaped-copy.d.ts +23 -0
  162. package/lib/services/escaped-copy.js +88 -0
  163. package/lib/services/execute-calculated-insight-deploy.d.ts +42 -0
  164. package/lib/services/execute-calculated-insight-deploy.js +96 -0
  165. package/lib/services/execute-data-transform-deploy.d.ts +56 -0
  166. package/lib/services/execute-data-transform-deploy.js +168 -0
  167. package/lib/services/execute-native-identity-resolution-deploy.d.ts +48 -0
  168. package/lib/services/execute-native-identity-resolution-deploy.js +360 -0
  169. package/lib/services/execute-segment-deploy.d.ts +45 -0
  170. package/lib/services/execute-segment-deploy.js +393 -0
  171. package/lib/services/local-file-removal.d.ts +36 -0
  172. package/lib/services/local-file-removal.js +103 -0
  173. package/lib/services/native-calculated-insight.d.ts +87 -0
  174. package/lib/services/native-calculated-insight.js +164 -0
  175. package/lib/services/native-crm-data-stream.d.ts +91 -0
  176. package/lib/services/native-crm-data-stream.js +272 -0
  177. package/lib/services/native-data-graph-context.d.ts +12 -0
  178. package/lib/services/native-data-graph-context.js +139 -0
  179. package/lib/services/native-data-graph-crd.d.ts +261 -0
  180. package/lib/services/native-data-graph-crd.js +866 -0
  181. package/lib/services/native-data-stream.d.ts +329 -0
  182. package/lib/services/native-data-stream.js +1830 -0
  183. package/lib/services/native-dlo.d.ts +163 -0
  184. package/lib/services/native-dlo.js +402 -0
  185. package/lib/services/native-dmo.d.ts +191 -0
  186. package/lib/services/native-dmo.js +614 -0
  187. package/lib/services/native-mapping.d.ts +255 -0
  188. package/lib/services/native-mapping.js +1226 -0
  189. package/lib/services/native-relationship.d.ts +132 -0
  190. package/lib/services/native-relationship.js +512 -0
  191. package/lib/services/operation-diagnostic.d.ts +83 -0
  192. package/lib/services/operation-diagnostic.js +272 -0
  193. package/lib/services/preflight-calculated-insight-deploy.d.ts +58 -0
  194. package/lib/services/preflight-calculated-insight-deploy.js +95 -0
  195. package/lib/services/preflight-data-transform-deploy.d.ts +33 -0
  196. package/lib/services/preflight-data-transform-deploy.js +104 -0
  197. package/lib/services/preflight-identity-resolution-deploy.d.ts +107 -0
  198. package/lib/services/preflight-identity-resolution-deploy.js +281 -0
  199. package/lib/services/preflight-segment-deploy.d.ts +31 -0
  200. package/lib/services/preflight-segment-deploy.js +109 -0
  201. package/lib/services/publish-calculated-insight.d.ts +40 -0
  202. package/lib/services/publish-calculated-insight.js +95 -0
  203. package/lib/services/publish-segment.d.ts +65 -0
  204. package/lib/services/publish-segment.js +194 -0
  205. package/lib/services/readback-pace.d.ts +16 -0
  206. package/lib/services/readback-pace.js +23 -0
  207. package/lib/services/retrieve-data-transform.d.ts +26 -0
  208. package/lib/services/retrieve-data-transform.js +65 -0
  209. package/lib/services/retrieve-identity-resolution.d.ts +40 -0
  210. package/lib/services/retrieve-identity-resolution.js +87 -0
  211. package/lib/services/retrieve-inventory.d.ts +32 -0
  212. package/lib/services/retrieve-inventory.js +151 -0
  213. package/lib/services/retrieve-segment.d.ts +120 -0
  214. package/lib/services/retrieve-segment.js +502 -0
  215. package/lib/services/segment-lookup.d.ts +46 -0
  216. package/lib/services/segment-lookup.js +108 -0
  217. package/lib/services/segment-members.d.ts +144 -0
  218. package/lib/services/segment-members.js +402 -0
  219. package/lib/services/select-native-retrieve.d.ts +60 -0
  220. package/lib/services/select-native-retrieve.js +226 -0
  221. package/lib/services/settle-calculated-insight.d.ts +22 -0
  222. package/lib/services/settle-calculated-insight.js +53 -0
  223. package/lib/services/sql-tokens.d.ts +58 -0
  224. package/lib/services/sql-tokens.js +147 -0
  225. package/lib/transport/api-version.d.ts +36 -0
  226. package/lib/transport/api-version.js +89 -0
  227. package/lib/transport/bound-ssot.d.ts +27 -0
  228. package/lib/transport/bound-ssot.js +116 -0
  229. package/lib/transport/calculated-insight-rest.d.ts +28 -0
  230. package/lib/transport/calculated-insight-rest.js +62 -0
  231. package/lib/transport/connect-client.d.ts +94 -32
  232. package/lib/transport/connect-client.js +318 -178
  233. package/lib/transport/connect-diagnostic.d.ts +89 -0
  234. package/lib/transport/connect-diagnostic.js +331 -0
  235. package/lib/transport/data-graph-rest.d.ts +27 -0
  236. package/lib/transport/data-graph-rest.js +76 -0
  237. package/lib/transport/data-stream-rest.d.ts +62 -0
  238. package/lib/transport/data-stream-rest.js +348 -0
  239. package/lib/transport/data-transform-rest.d.ts +25 -0
  240. package/lib/transport/data-transform-rest.js +100 -0
  241. package/lib/transport/dlo-native-rest.d.ts +22 -0
  242. package/lib/transport/dlo-native-rest.js +89 -0
  243. package/lib/transport/dlo-rest.d.ts +23 -0
  244. package/lib/transport/dlo-rest.js +135 -0
  245. package/lib/transport/dmo-native-rest.d.ts +18 -0
  246. package/lib/transport/dmo-native-rest.js +55 -0
  247. package/lib/transport/dmo-rest.d.ts +30 -0
  248. package/lib/transport/dmo-rest.js +163 -0
  249. package/lib/transport/mapping-rest.d.ts +63 -0
  250. package/lib/transport/mapping-rest.js +341 -0
  251. package/lib/transport/project-metadata.d.ts +36 -0
  252. package/lib/transport/project-metadata.js +118 -0
  253. package/lib/transport/relationship-rest.d.ts +43 -0
  254. package/lib/transport/relationship-rest.js +201 -0
  255. package/package.json +29 -6
  256. package/lib/artifacts/dmo-document.d.ts +0 -181
  257. package/lib/artifacts/dmo-document.js +0 -848
  258. package/lib/artifacts/dmo-update-delta.d.ts +0 -28
  259. package/lib/artifacts/dmo-update-delta.js +0 -86
  260. package/lib/artifacts/write-other-dmo.d.ts +0 -17
  261. package/lib/artifacts/write-other-dmo.js +0 -140
  262. package/lib/services/execute-dmo-create.d.ts +0 -24
  263. package/lib/services/execute-dmo-create.js +0 -118
  264. package/lib/services/execute-dmo-deploy.d.ts +0 -33
  265. package/lib/services/execute-dmo-deploy.js +0 -197
  266. package/lib/services/preflight-dmo-deploy.d.ts +0 -69
  267. package/lib/services/preflight-dmo-deploy.js +0 -161
  268. package/lib/services/retrieve-other-dmo.d.ts +0 -46
  269. package/lib/services/retrieve-other-dmo.js +0 -140
@@ -1,57 +1,473 @@
1
+ import { DataTransformError, dataTransformSpaceMismatch, } from '../../artifacts/data-transform-document.js';
2
+ import { escapedCopyCode } from '../../services/escaped-copy.js';
3
+ import { createDataTransformClient } from '../../transport/data-transform-rest.js';
4
+ import { preflightDataTransformDeploy } from '../../services/preflight-data-transform-deploy.js';
5
+ import { DataTransformScheduleError, executeDataTransformDeploy, rejectedTransformWrite, } from '../../services/execute-data-transform-deploy.js';
6
+ import { resolveDataTransformTargetId } from '../../services/delete-data-transform.js';
7
+ import { verifyDataTransformInputDigest } from '../../artifacts/read-deploy-input.js';
8
+ import { operateNativeDataGraph, nativeGraphLimitations, } from '../../services/command-native-data-graph.js';
9
+ import { nativeDataGraphReadContext } from '../../services/native-data-graph-context.js';
10
+ import { createDataGraphClient } from '../../transport/data-graph-rest.js';
11
+ import { verifyNativeDataGraphInputDigest } from '../../artifacts/read-deploy-input.js';
12
+ import { explainInput, explainSpaceMismatch, explanationOf, hintOf, operationDiagnostic, } from '../../services/operation-diagnostic.js';
13
+ import { SegmentError } from '../../artifacts/segment-document.js';
14
+ import { bindSegmentChildren } from '../../services/bind-segment-dependencies.js';
15
+ import { annotateDiagnostics, formatDiagnostic } from '../../errors/registry.js';
16
+ import { getConnectDiagnostic, retainConnectDiagnostic, } from '../../transport/connect-diagnostic.js';
17
+ import { preflightDataStream, executeDataStream, } from '../../services/command-native-data-stream.js';
18
+ import { verifyDataStreamInputDigest } from '../../artifacts/read-deploy-input.js';
19
+ import { DataStreamError } from '../../artifacts/data-stream-document.js';
20
+ import { dataStreamApiVersion } from '../../transport/api-version.js';
21
+ import { ConnectClient } from '../../transport/connect-client.js';
22
+ import { createDataStreamClient, createDataStreamReferenceReader, } from '../../transport/data-stream-rest.js';
23
+ import { preflightMapping, executeMapping } from '../../services/command-native-mapping.js';
24
+ import { createMappingClient } from '../../transport/mapping-rest.js';
25
+ import { openBoundSsot } from '../../transport/bound-ssot.js';
26
+ import { NativeMappingError } from '../../artifacts/native-mapping-document.js';
27
+ import { preflightRelationship, executeRelationship, } from '../../services/command-native-relationship.js';
28
+ import { createRelationshipClient } from '../../transport/relationship-rest.js';
29
+ import { NativeRelationshipError } from '../../artifacts/native-relationship-document.js';
30
+ import { preflightDmo, executeDmo, admitDmoFieldRemoval, refusedDmo, mappedFieldMappings, } from '../../services/command-native-dmo.js';
31
+ import { checkFieldRemoval, removeFieldsChecked } from '../../services/delete-dmo-field.js';
32
+ import { paceReadback, readbackPace } from '../../services/readback-pace.js';
33
+ import { nativeDmoConfirmed } from '../../services/native-dmo.js';
34
+ import { createDmoClient } from '../../transport/dmo-rest.js';
35
+ import { isNativeDmoInput } from '../../artifacts/read-deploy-input.js';
36
+ import { NativeDmoError } from '../../artifacts/native-dmo-document.js';
37
+ import { preflightDloDeploy, executeDloDeploy } from '../../services/command-dlo.js';
38
+ import { createDloClient } from '../../transport/dlo-rest.js';
39
+ import { normalizeDlo, unwrapDlo, validateDloDocument } from '../../artifacts/dlo-document.js';
40
+ import { reportedIdentity } from '../../artifacts/data-space-field.js';
41
+ import { DataSpaceError, dataSpaceCheckCode, dataSpaceCheckOf, } from '../../services/data-space-check.js';
42
+ import { nativeDmoWriteScope, normalizeNativeDmo, unwrapNativeDmo, } from '../../artifacts/native-dmo-document.js';
43
+ import { isDeepStrictEqual } from 'node:util';
44
+ import { prefixMismatch, prefixMismatchError, prefixMismatchWarning, prefixRuleCoversName, prefixRuleCoversRead, } from '../../services/data-space-prefix.js';
45
+ import path from 'node:path';
46
+ import { CrossSpaceError, crossSpaceNeedsRulesets, crossSpaceRefusal, crossSpaceSource, fileDataSpaces, planCrossSpaceInputs, precheckCopyFiles, readRulesetEntries, writeCopyFile, } from '../../services/cross-dataspace-deploy.js';
47
+ import { crossSpaceUnsupported } from '../../services/cross-dataspace-rename.js';
48
+ import { authoredDocument, authoredNative, verifyDloInputDigest, } from '../../artifacts/read-deploy-input.js';
49
+ import { calculatedInsightReadContext, readCalculatedInsight, } from '../../services/native-calculated-insight.js';
50
+ import { preflightCalculatedInsightDeploy } from '../../services/preflight-calculated-insight-deploy.js';
51
+ import { executeCalculatedInsightDeploy } from '../../services/execute-calculated-insight-deploy.js';
52
+ import { CalculatedInsightError, calculatedInsightSpaceMismatch, } from '../../artifacts/native-calculated-insight-document.js';
53
+ import { requireRunSpace, streamFailureCause } from '../../services/native-data-stream.js';
54
+ import { IdentityResolutionError, identityResolutionSpaceMismatch, } from '../../artifacts/identity-resolution-document.js';
55
+ import { DataGraphError } from '../../artifacts/data-graph-document.js';
56
+ import { nativeDataGraphSpaceMismatch } from '../../artifacts/native-data-graph-document.js';
57
+ import { verifyCalculatedInsightInputDigest } from '../../artifacts/read-deploy-input.js';
1
58
  import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
2
- import { DeployInputError, readDeployInputs } from '../../artifacts/read-deploy-input.js';
3
- import { preflightDmoDeploy } from '../../services/preflight-dmo-deploy.js';
4
- import { executeDmoDeploy } from '../../services/execute-dmo-deploy.js';
59
+ import { AuthInfo, ConfigAggregator, Connection, StateAggregator } from '@salesforce/core';
60
+ import { nativeApiVersion, operationApiVersion } from '../../transport/api-version.js';
61
+ import { preflightNativeIdentityResolutionDeploy, nativeIdentityResolutionDocument, } from '../../services/preflight-identity-resolution-deploy.js';
62
+ import { executeNativeIdentityResolutionDeploy } from '../../services/execute-native-identity-resolution-deploy.js';
63
+ import { createHash } from 'node:crypto';
64
+ import { retrieveIdentityResolution } from '../../services/retrieve-identity-resolution.js';
65
+ import { bindIdentityResolutionDependencies, verifyIdentityResolutionOutputs, } from '../../services/bind-identity-resolution-dependencies.js';
66
+ import { verifyIdentityResolutionInputDigest } from '../../artifacts/read-deploy-input.js';
67
+ import { captureDeployInputDigest, DeployInputError, readDeployInputs, skippedVerbatimWarnings, } from '../../artifacts/read-deploy-input.js';
68
+ import { executeSegmentDeploy } from '../../services/execute-segment-deploy.js';
69
+ import { preflightSegmentDeploy } from '../../services/preflight-segment-deploy.js';
70
+ import { verifySegmentInputDigest } from '../../artifacts/read-deploy-input.js';
5
71
  import { plugin as packageMetadata } from '../../plugin.js';
72
+ import { silentSqlFailureWarnings } from '../../services/calculated-insight-sql-checks.js';
73
+ import { GitSelectionError, selectGitDeployInputs } from '../../artifacts/git-deploy-selection.js';
74
+ import { componentKey, crudPhase, identityResolutionEdges, inputDependencies, inputKey, planDeployStages, runCrudStages, streamDloCollisions, streamLandingDlo, transformDloNames, } from '../../services/crud-plan.js';
75
+ import { dependencyKey, DependencySelectionError, documentDependencyNode, orderDependencyNodes, } from '../../artifacts/dependency-selection.js';
76
+ /**
77
+ * Resolve optional target auth with an explicit bootstrap version before core initialization.
78
+ * @param {string} [aliasOrUsername] Explicit target or configured default when omitted.
79
+ * @returns {Promise<object | undefined>} Command-owned target connection or absent optional auth.
80
+ */
81
+ const resolveTargetOrg = async (aliasOrUsername) => {
82
+ try {
83
+ const aggregator = await ConfigAggregator.create();
84
+ const state = await StateAggregator.getInstance();
85
+ const target = aliasOrUsername ?? aggregator.getPropertyValue('target-org');
86
+ const username = target ? state.aliases.resolveUsername(target) : undefined;
87
+ const connection = await Connection.create({
88
+ authInfo: await AuthInfo.create({ username }),
89
+ connectionOptions: { version: '68.0' },
90
+ });
91
+ // Org.create would probe org traits through another unversioned connection.
92
+ return {
93
+ getOrgId: () => connection.getAuthInfoFields().orgId,
94
+ getUsername: () => connection.getUsername(),
95
+ getConnection: (version) => {
96
+ if (version)
97
+ connection.setApiVersion(version);
98
+ return connection;
99
+ },
100
+ };
101
+ }
102
+ catch (error) {
103
+ if (aliasOrUsername)
104
+ throw error;
105
+ return undefined;
106
+ }
107
+ };
108
+ /**
109
+ * Notice for a transform schedule the deploy sends: a schedule copied from another org makes the
110
+ * transform run in this one.
111
+ * @param {Record<string, unknown> | undefined} schedule Schedule of the file.
112
+ * @returns {{code: string, message: string}} TRANSFORM_SCHEDULE_CHANGE notice.
113
+ */
114
+ function transformScheduleNotice(schedule) {
115
+ const frequency = typeof schedule?.frequency === 'string' ? schedule.frequency : undefined;
116
+ return {
117
+ code: 'TRANSFORM_SCHEDULE_CHANGE',
118
+ message: frequency?.toLowerCase() === 'none'
119
+ ? 'The schedule of the file turns the transform schedule off in this org.'
120
+ : `The schedule of the file (${frequency ?? 'as written'}) replaces the transform schedule in this org; the transform then runs on it there.`,
121
+ };
122
+ }
123
+ /**
124
+ * Native route order: relationships need mapped DMOs, so they follow DLOs, DMOs and mappings.
125
+ * @param {DeployInput} input Native input.
126
+ * @returns {number} Rank.
127
+ */
128
+ const rank = (input) => input.document.kind === 'dlo'
129
+ ? 0
130
+ : input.document.kind === 'dmo'
131
+ ? 1
132
+ : input.document.kind === 'mapping'
133
+ ? 2
134
+ : 3;
135
+ /**
136
+ * Add the run's data space prefix to the DMO options, if there is one.
137
+ * @param {[] | [DmoCommandOptions]} options DMO options (field removal).
138
+ * @param {object} prefix The prefix option, or none.
139
+ * @param {string} [prefix.dataSpacePrefix] The run's data space prefix.
140
+ * @returns {[] | [DmoCommandOptions]} Options with the prefix.
141
+ */
142
+ function withDataSpacePrefix(options, prefix) {
143
+ if (options.length > 0)
144
+ return [{ ...options[0], ...prefix }];
145
+ return prefix.dataSpacePrefix === undefined ? [] : [prefix];
146
+ }
6
147
  /** Preview or sequential guarded deployment of explicitly selected authored configuration. */
7
148
  export default class Deploy extends SfCommand {
8
149
  static aliases = ['datacloud:deploy', 'd360:deploy', 'dc:deploy'];
9
150
  static summary = 'Deploy explicit authored Data360 configuration or preview without writes.';
10
- static description = 'Requires explicit files/directories OR exact dmo:ApiName selectors. Repeated selections coalesce. Bare types and implicit deploy-all are forbidden. Preview is strictly read-only. Execution preflights the whole selection, then creates or updates only object and existing non-primary field labels sequentially with fresh checks and qualified readback. Other changes block before writes. Stops on first blocked or failed item; no retry or rollback. No local report/artifact writes.';
151
+ static description = 'Data transforms (data-transform:Name, data360/dataTransforms/Name.dataTransform.json, auto/API68, in the run data space: c__dataSpace must name it and equal definition.dataSpaceName when the definition names one; TRANSFORM_DATASPACE_MISMATCH otherwise, also for an org transform of that name in another data space, resolved from its dataSpaceName or, without one, from its MktDataTransform record read with SOQL (one without any data space is handled in default only); a create outside default needs definition.dataSpaceName) deploy by name: the complete transform list is read, no match creates, one match updates or is unchanged (the file equals the transform as retrieve writes it), a match that differs only in letter case is refused (TRANSFORM_IDENTITY_MISMATCH), two or more are refused (TRANSFORM_TARGET_NOT_RESOLVED). The file is sent as written and Salesforce decides, for a transform of any owner (Salesforce refuses writes to system transforms; a 4xx answer to the first write is reported as rejected); --allow-processing is not needed. Create is validated by Salesforce first; preview is GET-only. The optional schedule key of the file is the desired schedule: absent leaves the schedule alone; otherwise, when it differs from the org schedule as retrieve projects it, it is sent with one schedule PUT after the definition and read back, and an explicit {"frequency":"None"} turns it off (retrieve leaves the key out for a transform without a schedule). A deployed schedule makes the transform run in the target org (TRANSFORM_SCHEDULE_CHANGE in preview and deploy). No run writes. Several transforms deploy one after another in their phase, selected by member, file, directory or --changed-since. Exact data-stream:ApiName deploys canonical data360/data-stream/ApiName.data-stream-meta.json using auto/API68 in the run data space: its c__dataSpace list must name it and, for an existing stream, equal the data spaces of its DLO (a new stream lists the run data space alone, sent as the DLO dataspaceInfo of the create); data spaces change only through the DLO file (STREAM_DATASPACE_MISMATCH). An Ingestion API stream file is sent as written and Salesforce decides: create carries the primary key, the additive and formula mappings and the refresh mode (Salesforce creates UPSERT only); update sends new, changed and removed additive and formula mappings in one PATCH, a removed one as an empty formula (Salesforce refuses changing or removing an existing mapping; reported as rejected). Refused before any write: an additive mapping whose source label names no event field, or several (UNSUPPORTED_STREAM_MAPPING_SOURCE; Salesforce would store a mapping that never carries data), and a change of the refresh mode, DLO label, category, event time field or primary key (UNSUPPORTED_STREAM_SETTINGS_CHANGE; Salesforce answers 200 and keeps the old value). Create/update requires --allow-processing. A stream file of any other connector (connectorInfo.connectorType, for example SalesforceDotCom; only Salesforce CRM is tested live) is translated into the create input (GET spellings renamed, plain field mappings left out) and sent as written: absent (404) creates, otherwise one PATCH of datastreamType and the changed parts, or unchanged; Salesforce decides and its answer is reported (it refuses a CRM refresh mode change); a plain mapping change cannot be sent (UNSUPPORTED_STREAM_SETTINGS_CHANGE). A stream label change (CRM and Ingestion API) is sent as one Metadata API updateMetadata of the DataStreamDefinition of the stream (refusal STREAM_LABEL_UPDATE_REJECTED; a failed read of the record before it STREAM_LABEL_READ_FAILED, with nothing sent; a label still unchanged is STREAM_CHANGE_NOT_APPLIED). Generated target identities are independently resolved; mismatching label intent blocks. Requires explicit files/directories OR exact family:ApiName selectors OR --changed-since Git selection (every family; files deleted in the range are reported in result.selection.deletions and never deleted by deploy (sf data360 delete --changed-since deletes them)). Canonical native DLO/DMO/mapping/relationship JSON defaults to API68 (auto); numeric pins >=61 are retained without upgrade. Any mix of families runs in phases: data streams, then native DLO/DMO/mapping/relationship, then data transforms, then IR/CI/Segment, then data graphs; a phase starts only after every item of the previous phase settled, and the first blocked or failed item stops the run. A DLO file named like the landing DLO of a stream this deploy creates is refused after the read-only comparison of that stream and before any write (DATA_STREAM_DLO_COLLISION); beside an existing stream it deploys and Salesforce decides. Native mixed selections execute DLO then DMO then mapping then relationship, independently settling parents before mapping and relationship dependency checks. A selection with a mapping or relationship may also hold IR, CI and Segment inputs: they run afterwards in the ordered batch, only once every native item settled; preview reports items whose parent an earlier phase creates as planned-dependencies (DEPENDENCIES_PLANNED; MAPPING_DEPENDENCIES_PLANNED for a mapping): a mapping or transform on the landing DLO of a stream preview creates, items on a DLO or DMO the native phase creates, and a graph on a DMO or IR output created earlier. An IR runs before a CI or Segment that uses its unified or link DMO (name derived from the ruleset file), and those start only after the IR is PUBLISHED. A relationship (relationship:Name, data360/relationship/Name.relationship-meta.json) is matched to the org by the name in the file, otherwise by its binding (source DMO and field, target object and field; the target may be a DMO or a CRM object with owner SObject): absent is created with one POST and read back until ACTIVE (a stated label is then set), present with the values of the file (and stated label) is unchanged, and other values are sent as one Metadata API updateMetadata of the whole FieldSrcTrgtRelationship record over the connection of the command and read back (updated); Salesforce decides, and its refusal is RELATIONSHIP_UPDATE_REJECTED (it accepts label, cardinality, source and target field, not target object or owner); after an UNKNOWN_EXCEPTION answer the relationship is read again and, if unchanged, the update is sent once more. Deploy never deletes relationships. The source DMO and a target DMO must be mapped; otherwise Salesforce answers 400 and that answer is reported. Mapping uses exact mapping:ApiName from data360/mapping/ApiName.mapping-meta.json, unique target binding lookup and server-generated target names; create and unchanged repeats are supported; desired-state updates at native API 61 and up remove the authored pairs the file drops, one at a time, then add the new pairs in one batch; any data type, same-name or not, and one source onto several targets are sent as listed and Salesforce decides (preview names pairs of different data types with MAPPING_FIELD_TYPES_DIFFER). The key pair, its key-qualifier pair and the system pairs are never removed (MAPPING_PROTECTED_PAIR_REQUIRED when a file drops one; MAPPING_PROTECTED_LAYOUT_UNPROVEN when the key pair cannot be identified). Generated/key pairs and retained selectors are protected. A pair is removed even when another mapping of the same DMO targets the same field; the field stays mapped until the last such pair is gone. The optional label of a mapping file (spec.label; absent leaves the org label alone) is compared with the org label read through the Metadata API; when it differs, one Metadata API updateMetadata of the ObjectSourceTargetMap record is sent after the create or pair writes settled, carrying the new label and every pair the mapping currently has and no other (a pair left out is kept, a pair sent is added), and the label and pairs are read back; preview shows the planned change (labelChange). A refusal is MAPPING_LABEL_UPDATE_REJECTED (rejected when the label is the only change, unknown after other writes); a failed read MAPPING_LABEL_READ_FAILED. Any DMO may be the mapping target and Salesforce decides (it refuses platform-generated DMOs; that answer is reported). On a target other than an unprefixed custom DMO the generated system and key qualifier pairs are recognised from the target read and never sent, and the first mapping onto a standard DMO (creationType Standard) that is not yet enabled activates it permanently: preview and create carry the notice MAPPING_ACTIVATES_STANDARD_DMO without changing outcome or exit status. Qualification is limited to empty custom fixtures; populated-data behavior is not established. Preview never writes and reports planned dependencies without claiming nonexistent parents are ready. A native DMO changed since a Git reference or selected beside Segment/CI/IR inputs joins the ordered batch on the native route. Prerequisites are checked, never pulled in: each must be selected explicitly or already exist in the target. Native DMO target-name lookup selects confirmed-404 POST or existing-name PATCH with independent GET confirmation. A custom DMO field missing from the file blocks the update unless --allow-field-removal is set; then one Metadata API destructive change for CustomField removes those fields after the PATCH, and readback confirms their absence. A mapped field is removed only when the same selection contains every mapping holding its pair and each mapping file omits that pair; all-native selections check this before the first write (DMO_FIELD_REMOVAL_MAPPED otherwise), then remove the field in the DMO position with one Metadata API destructive change. Salesforce drops the mapping pairs of the field with it; reads before and after confirm that exactly those pairs went and nothing else changed (DMO_FIELD_REMOVAL_SIDE_EFFECT otherwise), and the mappings deployed afterwards find the pairs already gone. A deploy never removes the primary key or a standard, system or generated field: retrieve leaves generated fields out of the file, so a field missing from the file is kept. Platform-owned fields are removed only with sf data360 delete --field. An existing DMO other than an unprefixed custom one (a standard DMO, a platform-generated one such as Derived, Bridge or Adg, or a namespaced custom DMO) takes custom-field additions, label edits and removals plus object label and description changes only: its standard, system and generated fields are never sent or removed by a deploy, may be absent from the file and must match the target when listed (UNSUPPORTED_DMO_FIELD_CHANGE); a new field must be a plain custom field (UNSUPPORTED_DMO_FIELD_ADDITION); its category is ignored and its label is sent only when it differs. A new namespaced name is refused (UNSUPPORTED_DMO_TARGET); Salesforce answers for the rest. Native DLOs use dlo:Name__dll from data360/dlo/Name__dll.dlo-meta.json, whose top-level c__dataSpace list names every data space of the DLO and must hold the run data space (DLO_DATASPACE_MISMATCH); before any read or write the run data space and every listed name are checked against the org (one GET /ssot/data-spaces; UNKNOWN_DATASPACE). A new DLO is created in the run data space, then added to the other listed ones; an existing one is added to listed data spaces it is not in (one PUT naming only this DLO, which keeps every other member, then the DLO is read until it lists them) and removed from unlisted ones only with --allow-dataspace-removal (DLO_DATASPACE_REMOVAL_NOT_ALLOWED otherwise). Target lookup selects PATCH by target ID, or POST only on confirmed HTTP404; auth/permission/lookup failures stop. Preview is read-only; native DLO deploy does not require --allow-processing. Inventory is unavailable. Graph artifacts (*.native-dataGraph.json) use native API68 (auto or explicit 68.0; other versions are rejected) in the run data space (c__dataSpace; definition.dataspaceName, when present, must equal it, and the create sends it; a file of another data space, or an org graph of that name in another one, is DATA_GRAPH_DATASPACE_MISMATCH before any write; a root DMO the read names in another data space is DATA_GRAPH_DEPENDENCY_OTHER_DATASPACE): confirmed absence creates with --allow-processing; an existing graph is updated with one PUT of the file as written, confirmed by independent ready reads; Salesforce decides and a 4xx answer is reported as rejected (it refuses removed fields and related objects, a root change and another related object in place of an existing one). Key-qualifier fields Salesforce added are kept when the file leaves them out. A join change of an existing related object is refused before any write (DATA_GRAPH_JOIN_CHANGE), because Salesforce accepts it but keeps the old join; a graph read back with another join than sent is DATA_GRAPH_CHANGE_NOT_APPLIED. Settings the file leaves out keep their org values; clearing one needs an explicit value. Name and data space identify the graph: a file with another name creates or addresses another graph, and the old graph is not renamed. Identical ready configuration is unchanged without acknowledgement. --wait-timeout sets the native Graph invocation budget in integer seconds (default 1800); readiness retries wait at least 20 seconds with stderr progress. Processing can take seconds to many minutes, up to 30 minutes depending on objects, fields, data volume and service load. In a mixed deploy graphs run last; a graph whose root or related object is the unified or link DMO of a selected IR starts only after that IR is PUBLISHED. --wait-timeout applies to every graph and needs at least one graph in the selection. Calculated insights (calculated-insight:Name__cio, data360/calculatedInsights/Name__cio.calculatedInsight-meta.json joined with its .calculatedInsight-meta.sql) use auto or 68.0 in the run data space, which c__dataSpace in the JSON must name (CI_DATASPACE_MISMATCH); c__dataSpace is sent as dataSpaceName in every create and update. The insight is read by name: absent (HTTP 404) creates it with one POST, present is unchanged when the org holds every key of the file and is updated with one PATCH otherwise; afterwards it is read until it holds the file. The file is sent as written and Salesforce decides (a 4xx answer is reported as rejected); only what the create/update input names differently is translated: dataSpace as dataSpaceName, isFromPackage as createdFromPackage, sourceCiDevName as sourceDeveloperName, UPPER_SNAKE values of definitionType, publishScheduleInterval, historyPublishScheduleInterval and queryDialect as PascalCase, null values are left out, and a PATCH leaves out a definitionType equal to the org value (Salesforce refuses any definitionType on PATCH). The insight runs after the selected DMOs, IRs and insights its SQL names. --draft creates a draft and sends draft: true on update; an update of a DRAFT insight stays a draft. Publication is never implicit (sf data360 publish). --allow-processing is not needed. Repeated selections coalesce. Bare types and implicit deploy-all are forbidden. Preview is strictly read-only. Each phase stage preflights all of its own items before its first write: a batch of Segment, CI or IR inputs (with DLO/DMO beside them when no mapping or relationship is selected) is preflighted as a whole, and an IR dependent stage only after the IR is PUBLISHED; all-native DLO/DMO/mapping execution admits each ordered item only after earlier parents settle. In a selection that also holds a mapping or relationship, only the local checks of the IR/CI/Segment inputs (version, data space, file shape, dependency identities and order) run before the native writes; their Git snapshot, prerequisite and target checks run in their later stage, so a blocker there can follow earlier native writes, which stay reported. Preview runs every stage read-only, also after a blocked one. Segment (segment:Name, the portable Name.segment.json joined with one Name.segment.<model>.sql per model; a missing or extra SQL file or SQL left in the JSON is INVALID_SOURCE) uses auto or 68.0 in the run data space, which c__dataSpace must name (SEGMENT_DATASPACE_MISMATCH); its segmentOn DMO and Waterfall children are in the same data space (SEGMENT_DEPENDENCY_OTHER_DATASPACE). The file carries the name Salesforce stores (<prefix>_<Name> in a non-default data space; a name without the prefix is SEGMENT_NAME_NOT_STORED), sent unchanged; the create names the data space (?dataspace=). Other versions are refused (INVALID_SCOPE). It is read by its exact name: absent (HTTP 404 ITEM_NOT_FOUND) creates it with one POST, present updates it with one PATCH or is unchanged. The authored definition (label, description, segmentOn DMO, DBT SQL models, UI criteria or another segment type, lookback) is sent as written and Salesforce decides; its error is reported. The optional schedule key of the file is the desired refresh schedule: absent leaves the schedule alone; otherwise, when it differs from the org schedule as retrieve projects it, the POST or PATCH carries it, and an explicit {"frequency":"None"} turns it off (Salesforce refuses that for DBT segments; retrieve leaves the key out for a segment without a schedule). A deployed schedule makes the segment publish in the target org (SEGMENT_SCHEDULE_CHANGE in preview and deploy). The segmentOn DMO must exist (one native read binds its ID for the readback). A Waterfall file lists its child segments by API name (childSegments): each is read in the target and sent by its ID there, a selected child is deployed first (preview: planned-dependencies), and the children the selection does not hold are read before the first write of the run, so a child neither in the target nor selected stops it before any write (SEGMENT_CHILD_NOT_FOUND); a file without childSegments keeps the children of the org segment. Create and update require --allow-processing; identical configuration is unchanged without acknowledgement. Parameters have no write in the API, so a segment with parameters is retrieved as-is (UNSUPPORTED_SEGMENT_VARIANT). Segment XML is unsupported input. Segment deletion is separate: sf data360 delete -m segment:Name reads the segment from the org by name and runs fresh checks. Native IR uses auto or numeric68 in the run data space (c__dataSpace; every DMO, field, DLO source and output it names is in that data space, named as stored there, ds2_Individual__dlm with FirstName__c outside default; the ruleset name is <prefix>_<type>_<rulesetId> outside default, IDENTITY_RESOLUTION_NAME_NOT_STORED before any write otherwise; a ruleset or component of another data space is IDENTITY_RESOLUTION_DATASPACE_MISMATCH or IDENTITY_RESOLUTION_DEPENDENCY_OTHER_DATASPACE): confirmed exact absence supports CREATE with --allow-processing acknowledging processing and generated-output provisioning; existing settled owners support complete matching and reconciliation PATCH with --allow-processing or read-only identical no-op without acknowledgement. Ordered source priorities, object defaults and explicit field overrides are preserved; fields:[] restores inheritance. Automatic run, explicit run and delete are unsupported; no API67 fallback is attempted. --async (IR only) returns as soon as Salesforce accepts an IR create or update (creation-processing / update-processing, mutation acknowledged-processing) instead of waiting minutes for PUBLISHED: publish, settings and generated outputs are not confirmed; rerun the same deploy to check (IDENTITY_RESOLUTION_NOT_SETTLED while in flight, unchanged once settled). --async is refused when the selection holds a graph, CI or Segment on the unified DMO of that IR (IDENTITY_RESOLUTION_ASYNC_DEPENDENTS). Selections mixing IR with other non-native families require auto. Other changes block before writes. Stops on first blocked or failed item; no retry or rollback. No local report/artifact writes.';
11
152
  static flags = {
12
- 'target-org': Flags.optionalOrg(),
153
+ 'target-org': Flags.string({
154
+ char: 'o',
155
+ summary: 'Authenticated org alias or username; resolved only after local admission.',
156
+ }),
13
157
  'api-version': Flags.orgApiVersion({
14
- default: '65.0',
15
- summary: 'Target API version (currently 65.0).',
158
+ default: 'auto',
159
+ summary: 'Native DLO/DMO/mapping default or auto68, numeric >=61 retained; other families keep their qualified versions.',
160
+ parse: async (value, context, options) => value === 'auto' ? value : Flags.orgApiVersion().parse(value, context, options),
16
161
  }),
17
- 'data-space': Flags.string({
18
- default: 'default',
19
- summary: 'Target logical data space (currently default).',
162
+ dataspace: Flags.string({
163
+ aliases: ['data-space'],
164
+ summary: 'The run data space; omitted means default, and the org must have it. --data-space is a compatibility alias. A DLO or data stream file must list it in c__dataSpace; every other file must name it in c__dataSpace (or use --allow-cross-dataspace).',
20
165
  }),
21
166
  'source-dir': Flags.string({
22
167
  char: 'd',
23
168
  multiple: true,
24
169
  multipleNonGreedy: true,
25
170
  summary: 'Explicit authored JSON file or directory; repeatable.',
171
+ exclusive: ['changed-since'],
26
172
  }),
27
173
  metadata: Flags.string({
28
174
  char: 'm',
29
175
  multiple: true,
30
176
  multipleNonGreedy: true,
31
- summary: 'Exact dmo:ApiName project member; repeatable.',
177
+ summary: 'Exact data-transform:Name, data-stream:ApiName, mapping:ApiName, relationship:Name, dlo:Name__dll, dmo:ApiName, segment:ApiName, calculated-insight:ApiName__cio, data-graph:ApiName or identity-resolution:ExactObjectApiName member.',
178
+ exclusive: ['changed-since'],
179
+ }),
180
+ 'changed-since': Flags.string({
181
+ summary: 'Select canonical plugin files of every family changed since the merge base with a commit reference; deleted files are reported, not deleted (use sf data360 delete --changed-since).',
182
+ exclusive: ['source-dir', 'metadata'],
183
+ }),
184
+ 'allow-processing': Flags.boolean({
185
+ default: false,
186
+ summary: 'Acknowledge stream create/update, Graph create/update and Segment/IR processing; IR CREATE also provisions generated outputs. Data transforms and calculated insights do not need it.',
187
+ }),
188
+ 'allow-field-removal': Flags.boolean({
189
+ default: false,
190
+ summary: 'Native DMO only: remove custom target fields missing from the file with a Metadata API destructive change. A mapped field needs every mapping holding its pair, without the pair, in the same selection; Salesforce drops the pair together with the field. The primary key and standard, system or generated fields missing from the file are kept, never removed (retrieve leaves generated fields out); sf data360 delete --field removes those.',
191
+ }),
192
+ 'allow-cross-dataspace': Flags.boolean({
193
+ char: 'c',
194
+ default: false,
195
+ summary: 'Only with more than one data space: deploy files of another data space into --dataspace. DMO, mapping, relationship, DLO (membership only), UI, Waterfall and SQL (DBT) segment, calculated insight, data graph, identity resolution, STL transform (load, join, formula, filter, sqlFilter, aggregate, appendV2 and output nodes) and DCSQL transform files are translated in memory by rule, the SQL of insights, DBT segments and DCSQL transforms and STL expressions name by name (prefix, ssot__; identity resolution outputs from the ruleset list when their ruleset is not deployed with them); each translated file gets a copy file under its new name after it deployed. Other kinds and any name that cannot be placed exactly are refused before any write. With --preview it lists every rewrite (for SQL with its file, line and column).',
196
+ }),
197
+ 'allow-dataspace-removal': Flags.boolean({
198
+ default: false,
199
+ summary: 'DLO only: remove a DLO from the org data spaces its c__dataSpace list no longer names (DELETE of that data space member). Without it such a removal is refused before any write.',
200
+ }),
201
+ async: Flags.boolean({
202
+ default: false,
203
+ summary: 'IR only: return once Salesforce accepts the IR create/update instead of waiting for PUBLISHED. Skips confirming publish, settings and generated outputs; rerun the same deploy to check.',
204
+ }),
205
+ 'wait-timeout': Flags.integer({
206
+ min: 1,
207
+ summary: 'Wait budget in seconds for each selected native data graph; default 1800, no write retries.',
208
+ }),
209
+ draft: Flags.boolean({
210
+ default: false,
211
+ summary: 'CI only (auto or 68.0): create as a draft and send draft: true on update; never publishes.',
32
212
  }),
33
213
  preview: Flags.boolean({
34
214
  default: false,
35
215
  summary: 'Strictly read-only target comparison; never executes deployment.',
36
216
  }),
37
217
  };
218
+ createDataTransformClient = createDataTransformClient;
219
+ preflightDataTransform = preflightDataTransformDeploy;
220
+ executeDataTransform = executeDataTransformDeploy;
221
+ resolveDataTransformTarget = resolveDataTransformTargetId;
222
+ verifyDataTransformInput = verifyDataTransformInputDigest;
223
+ nativeGraphContext = nativeDataGraphReadContext;
224
+ nativeGraphClient = createDataGraphClient;
225
+ operateNativeGraph = operateNativeDataGraph;
226
+ verifyNativeDataGraphInput = verifyNativeDataGraphInputDigest;
227
+ preflightDataStream = preflightDataStream;
228
+ executeDataStream = executeDataStream;
229
+ verifyDataStreamInput = verifyDataStreamInputDigest;
230
+ createDataStreamClients = (connection, target, version) => {
231
+ const reader = new ConnectClient(connection, version);
232
+ return {
233
+ // Writes go over the command's shared bound sender, never a child CLI process.
234
+ streams: createDataStreamClient(target, reader, version, this.ssotSender(target, version)),
235
+ ...createDataStreamReferenceReader(reader, version),
236
+ dlo: {
237
+ get: (name) => reader.get(`/services/data/v${version}/ssot/data-lake-objects/${encodeURIComponent(name)}`),
238
+ },
239
+ };
240
+ };
241
+ createMappingClient = createMappingClient;
242
+ preflightMapping = preflightMapping;
243
+ executeMapping = executeMapping;
244
+ createRelationshipClient = createRelationshipClient;
245
+ preflightRelationship = preflightRelationship;
246
+ executeRelationship = executeRelationship;
247
+ resolveTargetOrg = resolveTargetOrg;
248
+ /** Read-only binding of the Waterfall child segments a deploy does not select. */
249
+ bindChildSegments = bindSegmentChildren;
250
+ createDmoClient = createDmoClient;
251
+ preflightNativeDmo = preflightDmo;
252
+ executeNativeDmo = executeDmo;
253
+ admitNativeDmoRemoval = admitDmoFieldRemoval;
254
+ preflightDlo = preflightDloDeploy;
255
+ executeDlo = executeDloDeploy;
256
+ verifyDloInput = verifyDloInputDigest;
257
+ createDloClient = createDloClient;
258
+ // Native DLO/DMO/mapping/relationship/stream reads and writes share one bound Connection per
259
+ // org and version instead of one CLI process per call. Only the Metadata API destructive
260
+ // deploys (DMO field removal, mapping remove) still start `sf project deploy start`.
261
+ // Tests replace this seam.
262
+ createSsotSender = (target, version) => openBoundSsot(target, version);
263
+ ssotSenders;
264
+ /**
265
+ * One shared bound sender per org and API version.
266
+ * @param {string} target Resolved username.
267
+ * @param {string} version Numeric API version.
268
+ * @returns {BoundSsot} Lazily opened sender.
269
+ */
270
+ ssotSender(target, version) {
271
+ const key = `${target}\n${version}`;
272
+ // Tests build commands without field initializers, so both fields may be absent.
273
+ this.ssotSenders ??= new Map();
274
+ let sender = this.ssotSenders.get(key);
275
+ if (!sender) {
276
+ sender = (this.createSsotSender ?? openBoundSsot)(target, version);
277
+ this.ssotSenders.set(key, sender);
278
+ }
279
+ return sender;
280
+ }
281
+ calculatedInsightContext = calculatedInsightReadContext;
282
+ preflightCalculatedInsight = preflightCalculatedInsightDeploy;
283
+ executeCalculatedInsight = executeCalculatedInsightDeploy;
284
+ verifyCalculatedInsightInput = verifyCalculatedInsightInputDigest;
38
285
  resolveInputs = readDeployInputs;
39
- preflight = preflightDmoDeploy;
40
- execute = executeDmoDeploy;
286
+ selectGitInputs = selectGitDeployInputs;
287
+ preflightSegment = preflightSegmentDeploy;
288
+ verifySegmentInput = verifySegmentInputDigest;
289
+ captureInput = captureDeployInputDigest;
290
+ executeSegment = executeSegmentDeploy;
291
+ preflightIdentityResolution = preflightNativeIdentityResolutionDeploy;
292
+ executeIdentityResolution = executeNativeIdentityResolutionDeploy;
293
+ verifyIdentityResolutionInput = verifyIdentityResolutionInputDigest;
294
+ /**
295
+ * Bind exact CREATE absence or independently settled owner/outputs before batch mutation.
296
+ * @param {IdentityResolutionDeployInput} input Immutable authored IR input.
297
+ * @param {Connection} connection Fixed API68 operation receiver.
298
+ * @param {ApiVersionSelection} selection Fixed per-operation selection.
299
+ * @returns {Promise<string>} Private stable target fingerprint.
300
+ */
301
+ async bindIdentityResolution(input, connection, selection) {
302
+ // The ruleset's data space: deploy refused a file outside the run's before any stage.
303
+ const dataSpace = input.document.c__dataSpace;
304
+ const dataSpacePrefix = dataSpace === 'default'
305
+ ? undefined
306
+ : await dataSpaceCheckOf(this, async () => {
307
+ throw new DataSpaceError('TARGET_ORG_REQUIRED');
308
+ }).prefixOf(dataSpace);
309
+ const preview = await this.preflightIdentityResolution(input.document, connection, selection, dataSpace, dataSpacePrefix === undefined ? {} : { dataSpacePrefix });
310
+ if (preview.outcome === 'create')
311
+ return createHash('sha256')
312
+ .update(JSON.stringify({
313
+ phase: 'precreate',
314
+ absenceProof: preview.absenceProof,
315
+ binding: preview.precreateBinding,
316
+ }))
317
+ .digest('hex');
318
+ if (!['update', 'unchanged'].includes(preview.outcome))
319
+ throw retainConnectDiagnostic(new Error('IR target binding unavailable'), getConnectDiagnostic(preview));
320
+ const dependencies = await bindIdentityResolutionDependencies(input.document, connection, selection, dataSpace);
321
+ const acquired = await retrieveIdentityResolution(connection, input.document.identity.apiName, selection, dataSpace);
322
+ if (!acquired.candidate || !acquired.expectations || acquired.blockers.length > 0)
323
+ throw retainConnectDiagnostic(new Error('IR target binding unavailable'), getConnectDiagnostic(acquired));
324
+ const outputs = await verifyIdentityResolutionOutputs({
325
+ targetApiName: input.document.identity.apiName,
326
+ targetId: acquired.expectations.native.id,
327
+ dataSpace,
328
+ }, acquired.expectations.outputs.map(({ identity, sourceApiName }) => ({
329
+ identity,
330
+ targetApiName: sourceApiName,
331
+ })), connection, selection);
332
+ return createHash('sha256')
333
+ .update(JSON.stringify({ phase: 'existing', dependencies, owner: acquired.expectations, outputs }))
334
+ .digest('hex');
335
+ }
41
336
  /**
42
- * Validate all inputs and preflight the whole selection before any sequential execution.
337
+ * Read one component whose name breaks the data space prefix rule, to tell a create from an
338
+ * update before the first write of the run, the way each type's own stage tells them apart: a
339
+ * DMO's GET 404, an insight's 404 with a Salesforce error code, a transform's name missing from
340
+ * the complete inventory (ignoring case), a graph's exact not-found answer. Any other failure
341
+ * stops the run.
342
+ * @param {PrefixType} type Kind of component.
343
+ * @param {string} name Its name.
344
+ * @param {string} space The run's data space.
345
+ * @param {unknown} targetOrg The --target-org flag value.
346
+ * @returns {Promise<{native: unknown} | undefined>} The raw read, or undefined when absent.
347
+ */
348
+ async readPrefixTarget(type, name, space, targetOrg) {
349
+ const org = targetOrg && typeof targetOrg === 'object'
350
+ ? targetOrg
351
+ : await (this.resolveTargetOrg ?? resolveTargetOrg)(targetOrg);
352
+ const target = org?.getUsername();
353
+ if (!org || !target)
354
+ throw new DataSpaceError('TARGET_ORG_REQUIRED');
355
+ if (type === 'dmo')
356
+ try {
357
+ return {
358
+ native: await (this.createDmoClient ?? createDmoClient)(target, '68.0', undefined, this.ssotSender(target, '68.0')).get(name),
359
+ };
360
+ }
361
+ catch (error) {
362
+ if (error instanceof NativeDmoError &&
363
+ error.code === 'DMO_HTTP_ERROR' &&
364
+ error.status === 404)
365
+ return undefined;
366
+ throw error;
367
+ }
368
+ const connection = org.getConnection('68.0');
369
+ if (type === 'calculated-insight') {
370
+ const read = await readCalculatedInsight((this.calculatedInsightContext ?? calculatedInsightReadContext)(connection, space), name);
371
+ return read.state === 'absent' ? undefined : { native: read.raw };
372
+ }
373
+ if (type === 'data-transform') {
374
+ const client = (this.createDataTransformClient ?? createDataTransformClient)(connection, '68.0', space);
375
+ const targetId = await (this.resolveDataTransformTarget ?? resolveDataTransformTargetId)(client, name);
376
+ return targetId === undefined ? undefined : { native: await client.get(targetId) };
377
+ }
378
+ const context = await (this.nativeGraphContext ?? nativeDataGraphReadContext)(connection, space);
379
+ const read = await context.get(name);
380
+ if (read.status === 200)
381
+ return { native: read.body };
382
+ // The item route's exact not-found answer (live API 68; HTTP 400, not 404).
383
+ if (read.status === 400 &&
384
+ isDeepStrictEqual(read.body, [
385
+ { errorCode: 'INTERNAL_ERROR', message: `Data Graph not found with name ${name}` },
386
+ ]))
387
+ return undefined;
388
+ throw retainConnectDiagnostic(new Error('Data graph read failed'), getConnectDiagnostic(read));
389
+ }
390
+ /**
391
+ * Validate inputs, then admit native items in dependency order or preflight the whole remaining
392
+ * selection before sequential execution.
43
393
  * @returns {Promise<DeployEnvelope>} Versioned preview or execution outcomes with mutation evidence.
44
394
  */
45
395
  async run() {
46
396
  const { flags } = await this.parse(Deploy);
397
+ // The run's data space: every request of a converted family names it explicitly.
398
+ const effectiveScope = flags.dataspace ?? 'default';
399
+ const dloOptions = { allowDataspaceRemoval: flags['allow-dataspace-removal'] };
400
+ // Passed to the native DMO services only when the removal was explicitly allowed.
401
+ // A refused removal of a mapped field names its mappings through this read-only inventory and
402
+ // repeats the target org and data space exactly as they were passed.
403
+ const passedOrg = flags['target-org'];
404
+ const fieldRemoval = (mappings, dmoReader) => flags['allow-field-removal'] === true
405
+ ? [
406
+ {
407
+ allowFieldRemoval: true,
408
+ mappedFieldGuide: {
409
+ mappings,
410
+ ...(typeof passedOrg === 'string' ? { targetOrg: passedOrg } : {}),
411
+ ...(flags.dataspace === undefined ? {} : { dataspace: flags.dataspace }),
412
+ },
413
+ // Reads before and after the one removal: fields gone, exactly their pairs dropped
414
+ // by Salesforce, every other mapping, pair and field unchanged.
415
+ precheckRemoval: async (apiName, fields, coverage) => {
416
+ await checkFieldRemoval(apiName, fields, { dmo: dmoReader(), mappings: mappings() }, coverage, effectiveScope);
417
+ },
418
+ removeChecked: async (apiName, fields, remove, coverage) => {
419
+ const dropped = await removeFieldsChecked(apiName, fields, { dmo: dmoReader(), mappings: mappings() }, remove, coverage, effectiveScope);
420
+ return dropped.map(({ mapping, sourceFieldDeveloperName, targetFieldDeveloperName }) => ({
421
+ mapping,
422
+ sourceFieldDeveloperName,
423
+ targetFieldDeveloperName,
424
+ }));
425
+ },
426
+ },
427
+ ]
428
+ : [];
429
+ /**
430
+ * The run's data space prefix as an option, read from the run's one data space check (already
431
+ * done before any stage); none in the default data space or when the list names none.
432
+ * @returns {Promise<{dataSpacePrefix?: string}>} The option.
433
+ */
434
+ const dataSpacePrefixOption = async () => {
435
+ if (effectiveScope === 'default')
436
+ return {};
437
+ const prefix = await dataSpaceCheckOf(this, async () => {
438
+ throw new DataSpaceError('TARGET_ORG_REQUIRED');
439
+ }).prefixOf(effectiveScope);
440
+ return prefix === undefined ? {} : { dataSpacePrefix: prefix };
441
+ };
47
442
  const cwd = process.cwd();
443
+ /**
444
+ * A file path as the output shows it: relative to the working directory.
445
+ * @param {string} file Absolute path.
446
+ * @returns {string} Shown path.
447
+ */
448
+ const shown = (file) => path.relative(cwd, file) || file;
449
+ // Opens the shared bound sender for the run's one data space list read.
450
+ const openSpaceSender = async () => {
451
+ const checkOrg = passedOrg && typeof passedOrg === 'object'
452
+ ? passedOrg
453
+ : flags['target-org'] === undefined && !this.resolveTargetOrg
454
+ ? undefined
455
+ : await (this.resolveTargetOrg ?? resolveTargetOrg)(flags['target-org']);
456
+ const checkTarget = checkOrg?.getUsername();
457
+ if (!checkTarget)
458
+ throw new DataSpaceError('TARGET_ORG_REQUIRED');
459
+ return this.ssotSender(checkTarget, '68.0');
460
+ };
461
+ let crossPlan;
462
+ // The mapping as Salesforce holds it (also an unchanged one), read back, for its copy file.
463
+ const mappingTargets = new Map();
48
464
  const plugin = {
49
465
  name: packageMetadata.name,
50
466
  version: packageMetadata.version,
51
467
  };
52
468
  const envelope = {
53
469
  contract: 'sf-data360-deploy',
54
- contractVersion: '1.0.0',
470
+ contractVersion: '1.1.0',
55
471
  status: 'blocked',
56
472
  metadata: {
57
473
  operation: 'deploy',
@@ -69,140 +485,1916 @@ export default class Deploy extends SfCommand {
69
485
  generatedAt: new Date().toISOString(),
70
486
  },
71
487
  result: {
72
- scope: { dataSpace: flags['data-space'] },
488
+ scope: { dataSpace: effectiveScope },
73
489
  selection: { sourceDir: flags['source-dir'] ?? [], metadata: flags.metadata ?? [] },
74
490
  items: [],
75
491
  },
76
492
  };
77
- const finish = (status, code) => {
493
+ const families = new Map();
494
+ // Prefix rule warnings of existing components, shown in the human output too.
495
+ const prefixWarnings = new Set();
496
+ // Calculated insight SQL that fails after publish, shown in the human output too.
497
+ const sqlWarnings = new Set();
498
+ const mappingNames = new Map();
499
+ const processingDlos = new Set();
500
+ const mappingChanges = new Map();
501
+ const finish = (status, code, error) => {
78
502
  envelope.status = status;
79
- if (code)
503
+ if (code) {
504
+ const mappedFields = mappedFieldMappings(error);
505
+ const mutations = envelope.result.items.map((item) => 'mutation' in item ? item.mutation : undefined);
506
+ // Without an unknown write, say plainly what happened instead of the generic warning.
507
+ const rejected = 'Deployment did not complete: Salesforce rejected a write and nothing was written for that item. Read its diagnostic, correct the input and rerun. No automatic retry or rollback was performed.';
508
+ const settled = error !== undefined || mutations.includes('unknown')
509
+ ? undefined
510
+ : code === 'INVALID_SCOPE'
511
+ ? `${flags.preview ? 'Preview' : 'Deployment'} did not start: the requested --api-version or --dataspace is not supported for a selected family, and nothing was sent to the org. Use a supported version and data space, then rerun.`
512
+ : flags.preview
513
+ ? code === 'DEPLOY_PREVIEW_BLOCKED'
514
+ ? 'Preview found an item the deploy would refuse or could not check; nothing was sent to the org. Read the item diagnostics, fix the cause, then preview again. No deployment executed.'
515
+ : undefined
516
+ : mutations.includes('rejected')
517
+ ? rejected
518
+ : mutations.every((mutation) => mutation === undefined || mutation === 'not-attempted')
519
+ ? 'Deployment did not complete and nothing was written to the org. Read the item diagnostics, fix the cause, then rerun.'
520
+ : undefined;
80
521
  envelope.diagnostics.errors.push({
81
522
  code,
82
- message: flags.preview
83
- ? 'Preview did not complete. Check explicit authored inputs, target authentication and supported scope. No deployment executed.'
84
- : 'Deployment did not complete. Check item outcomes, explicit inputs, target authentication and supported scope. Mutation may have occurred for unknown mutations; inspect target before any further attempt. No automatic retry or rollback was performed.',
523
+ message: settled ??
524
+ operationDiagnostic(error, flags.preview
525
+ ? 'Preview did not complete. Check explicit authored inputs, target authentication and supported scope. No deployment executed.'
526
+ : // A rejected write without any unknown one wrote nothing: no unknown mutation to inspect.
527
+ mutations.includes('rejected') && !mutations.includes('unknown')
528
+ ? rejected
529
+ : // A blocked run whose items wrote nothing was refused before any write; a
530
+ // failed run may have written before its error, so it keeps the warning.
531
+ status === 'blocked' &&
532
+ mutations.every((mutation) => mutation === undefined || mutation === 'not-attempted')
533
+ ? 'Deployment was refused before any write; nothing was sent to the org. Fix the reported cause, then rerun.'
534
+ : 'Deployment did not complete. Check item outcomes, explicit inputs, target authentication and supported scope. Mutation may have occurred for unknown mutations; inspect target before any further attempt. No automatic retry or rollback was performed.'),
85
535
  retryable: false,
536
+ ...hintOf(error),
537
+ ...(mappedFields ? { mappedFields } : {}),
86
538
  });
539
+ }
87
540
  if (status !== 'success')
88
541
  process.exitCode = 1;
542
+ annotateDiagnostics(envelope);
89
543
  if (!this.jsonEnabled()) {
90
544
  this.log(flags.preview
91
545
  ? `Deploy preview: ${status}${code ? ` (${code})` : ''}. No deployment executed.`
92
546
  : `Deploy execution: ${status}${code ? ` (${code})` : ''}. No automatic retry or rollback performed.`);
547
+ // The default data space goes without saying; any other is named.
548
+ if (effectiveScope !== 'default')
549
+ this.log(`Data space: ${effectiveScope}.`);
550
+ const crossDataSpace = envelope.result.crossDataSpace;
551
+ for (const translated of crossDataSpace?.files ?? []) {
552
+ this.log(`Translated from ${translated.from}: ${shown(translated.path)} (${translated.family}).`);
553
+ for (const rewrite of translated.rewrites)
554
+ this.log(` ${rewrite.at}: ${rewrite.from} -> ${rewrite.to} (${rewrite.rule}).`);
555
+ for (const entry of translated.unresolved)
556
+ this.log(` Cannot place ${entry.at}: ${entry.name} (${entry.reason}).`);
557
+ }
558
+ if (flags.preview)
559
+ for (const copy of crossDataSpace?.plannedCopies ?? [])
560
+ this.log(`Planned copy file: ${shown(copy)}.`);
561
+ for (const copy of crossDataSpace?.copies ?? [])
562
+ this.log(copy.outcome === 'not-written'
563
+ ? `Copy file not written for ${shown(copy.source)}: ${copy.reason}.`
564
+ : `Copy file ${copy.outcome === 'written' ? 'written' : 'unchanged (same content)'}: ${shown(copy.path)}.`);
565
+ for (const deletion of envelope.result.selection.deletions ?? [])
566
+ this.log(`Not deleted: ${deletion.family}:${deletion.apiName} (file deleted in the Git range; deploy never deletes; delete it with sf data360 delete --changed-since ${envelope.result.selection.changedSince ?? '<ref>'} --confirm-delete after a --preview).`);
567
+ for (const warning of envelope.diagnostics.warnings)
568
+ if (warning.startsWith('Skipped ') ||
569
+ prefixWarnings.has(warning) ||
570
+ sqlWarnings.has(warning))
571
+ this.log(`Warning: ${warning}`);
93
572
  for (const item of envelope.result.items) {
94
- this.log(item.operation === 'preview'
95
- ? `Preview: ${item.outcome}.`
96
- : `Execution: ${item.outcome}; mutation: ${item.mutation}.`);
573
+ const family = families.get(item.path) ?? ('family' in item ? item.family : undefined) ?? 'dmo';
574
+ const apiName = mappingNames.get(item.path) ??
575
+ (item.operation === 'execute' && item.targetApiName
576
+ ? item.targetApiName
577
+ : item.identity.apiName);
578
+ const component = `${family}:${apiName}`;
579
+ if (item.operation === 'execute' &&
580
+ ((item.outcome === 'created' && item.mutation === 'confirmed-created') ||
581
+ (item.outcome === 'updated' && item.mutation === 'confirmed-updated')))
582
+ this.log(`${item.outcome} ${family} ${apiName}${processingDlos.has(item.path) ? ' (server is still processing)' : ''}`);
583
+ else if (item.operation === 'execute' && item.mutation === 'acknowledged-processing')
584
+ this.log(`${item.outcome} ${family} ${apiName} (accepted; publish not confirmed - rerun the same deploy to check)`);
585
+ else
586
+ this.log(item.operation === 'preview'
587
+ ? `Planned ${item.outcome}: ${component}.`
588
+ : `${item.outcome === 'created' ? 'Created' : item.outcome === 'updated' ? 'Updated' : item.outcome === 'unchanged' ? 'Unchanged' : item.outcome === 'failed' ? 'Failed' : item.outcome === 'blocked' ? 'Blocked' : 'Not attempted'}: ${component}; mutation: ${item.mutation}.`);
589
+ if (item.operation === 'execute' &&
590
+ item.outcome === 'updated' &&
591
+ item.mutation === 'confirmed-updated') {
592
+ const changes = mappingChanges.get(item.path);
593
+ for (const [label, pairs] of [
594
+ ['Deleted', changes?.deleted],
595
+ ['Added', changes?.added],
596
+ ])
597
+ if (pairs?.length)
598
+ this.log(`${label} field mappings: ${pairs.map((pair) => `${pair.sourceFieldDeveloperName} -> ${pair.targetFieldDeveloperName}`).join(', ')}.`);
599
+ if (changes?.label !== undefined)
600
+ this.log(`Label set to ${JSON.stringify(changes.label)}.`);
601
+ }
602
+ if (item.operation === 'preview' && 'labelChange' in item && item.labelChange)
603
+ this.log(`Planned label change: ${item.labelChange.from === undefined ? '' : `${JSON.stringify(item.labelChange.from)} -> `}${JSON.stringify(item.labelChange.to)}.`);
604
+ if ('dataSpaceChanges' in item && item.dataSpaceChanges)
605
+ for (const [label, done, spaces] of [
606
+ ['add the DLO to', 'added the DLO to', item.dataSpaceChanges.add],
607
+ ['remove the DLO from', 'removed the DLO from', item.dataSpaceChanges.remove],
608
+ ])
609
+ if (spaces.length > 0)
610
+ this.log(item.operation === 'preview'
611
+ ? `Planned data space change: ${label} ${spaces.join(', ')}.`
612
+ : `Data space change: ${done} ${spaces.join(', ')}.`);
613
+ if (item.operation === 'preview' && 'plan' in item)
614
+ for (const step of item.plan)
615
+ this.log(`Planned field ${step.operation}: ${step.sourceFieldDeveloperName} -> ${step.targetFieldDeveloperName}${'developerName' in step ? ` (${step.developerName})` : ''}.`);
616
+ // The same diagnostic can come from the preflight and the execution of one item.
617
+ const logged = new Set();
618
+ for (const diagnostic of [
619
+ ...item.diagnostics,
620
+ ...(item.operation === 'execute' && 'preflight' in item
621
+ ? (item.preflight?.diagnostics ?? [])
622
+ : []),
623
+ ]) {
624
+ const line = formatDiagnostic(diagnostic);
625
+ if (logged.has(line))
626
+ continue;
627
+ logged.add(line);
628
+ this.log(line);
629
+ }
97
630
  if (item.operation === 'execute' && item.mutation === 'unknown')
98
631
  this.log('Mutation may have occurred. Inspect target before any further attempt.');
99
632
  }
633
+ if (!flags.preview) {
634
+ const created = envelope.result.items.filter((item) => item.operation === 'execute' &&
635
+ item.outcome === 'created' &&
636
+ item.mutation === 'confirmed-created').length;
637
+ const updated = envelope.result.items.filter((item) => item.operation === 'execute' &&
638
+ item.outcome === 'updated' &&
639
+ item.mutation === 'confirmed-updated').length;
640
+ const failed = envelope.result.items.filter((item) => item.operation === 'execute' && item.outcome === 'failed').length;
641
+ const processing = envelope.result.items.filter((item) => item.operation === 'execute' && item.mutation === 'acknowledged-processing').length;
642
+ this.log(`Deployed: ${created + updated} (${created} created / ${updated} updated / ${failed} failed)${processing ? `; accepted, still processing: ${processing}` : ''}`);
643
+ }
644
+ for (const diagnostic of envelope.diagnostics.errors)
645
+ this.log(formatDiagnostic(diagnostic));
100
646
  }
101
647
  return envelope;
102
648
  };
103
649
  try {
104
- const inputs = await this.resolveInputs({
650
+ const changedSince = flags['changed-since'];
651
+ if (changedSince !== undefined &&
652
+ (flags['source-dir'] !== undefined || flags.metadata !== undefined))
653
+ return finish('blocked', 'INVALID_SELECTION');
654
+ let sourceDirectories = flags['source-dir'];
655
+ let gitDlos;
656
+ let gitCalculatedInsights;
657
+ let gitSegments;
658
+ let gitIdentityResolutions;
659
+ let gitCaptured;
660
+ if (changedSince !== undefined) {
661
+ envelope.result.selection.changedSince = changedSince;
662
+ const selected = await this.selectGitInputs({ cwd, ref: changedSince });
663
+ envelope.provenance.git = selected.provenance;
664
+ envelope.diagnostics.warnings.push(...(selected.warnings ?? []));
665
+ if (selected.deletions?.length)
666
+ envelope.result.selection.deletions = selected.deletions.map((deletion) => ({
667
+ family: deletion.family,
668
+ apiName: deletion.identity.apiName,
669
+ path: deletion.path,
670
+ }));
671
+ if (selected.paths.length === 0)
672
+ return finish('success');
673
+ gitCaptured = selected.capturedInputs ?? [];
674
+ sourceDirectories = selected.paths;
675
+ gitDlos = selected.dlos;
676
+ gitCalculatedInsights = selected.calculatedInsights;
677
+ gitSegments = selected.segments;
678
+ gitIdentityResolutions = selected.identityResolutions;
679
+ }
680
+ const authoredInputs = await this.resolveInputs({
105
681
  cwd,
106
- sourceDir: flags['source-dir'],
682
+ sourceDir: sourceDirectories,
107
683
  metadata: flags.metadata,
108
684
  });
109
- if (inputs.length === 0)
685
+ let resolvedInputs = authoredInputs;
686
+ // Verbatim files (retrieved as-is) in a selected folder were skipped with a warning.
687
+ const skipped = skippedVerbatimWarnings(resolvedInputs);
688
+ envelope.diagnostics.warnings.push(...skipped);
689
+ // Bind every resolved input, of every family, to the bytes the Git selection admitted.
690
+ if (gitCaptured) {
691
+ if (resolvedInputs.length !== gitCaptured.length)
692
+ throw new GitSelectionError('INVALID_GIT_SELECTION');
693
+ for (const input of resolvedInputs)
694
+ if (!gitCaptured.some((captured) => captured.path === input.path &&
695
+ captured.inputDigest === input.inputDigest &&
696
+ JSON.stringify(captured.document) === JSON.stringify(input.document)))
697
+ throw new GitSelectionError('INVALID_GIT_SELECTION');
698
+ }
699
+ // --allow-cross-dataspace: files of another data space are translated into the run's one, in
700
+ // memory, before any other check. Only then is the space list read early (the same single
701
+ // read the data space check below reuses); a selection of the run's data space reads nothing.
702
+ if (flags['allow-cross-dataspace'] === true &&
703
+ authoredInputs.some((input) => crossSpaceSource(input.document, effectiveScope) !== undefined)) {
704
+ let plan;
705
+ try {
706
+ const check = dataSpaceCheckOf(this, openSpaceSender);
707
+ await check.require([
708
+ effectiveScope,
709
+ ...authoredInputs.flatMap((input) => fileDataSpaces(input.document)),
710
+ ]);
711
+ const spaces = await check.entries();
712
+ // The ruleset list is read once, only when a file names an identity resolution output.
713
+ const rulesets = crossSpaceNeedsRulesets(authoredInputs, effectiveScope, spaces)
714
+ ? await readRulesetEntries(openSpaceSender)
715
+ : undefined;
716
+ plan = planCrossSpaceInputs(authoredInputs, effectiveScope, spaces, rulesets);
717
+ }
718
+ catch (error) {
719
+ return finish('blocked', dataSpaceCheckCode(error, 'TARGET_ORG_REQUIRED'), error);
720
+ }
721
+ crossPlan = plan;
722
+ envelope.result.crossDataSpace = { files: plan.files, plannedCopies: [] };
723
+ const refusal = crossSpaceRefusal(plan, effectiveScope, shown);
724
+ if (refusal)
725
+ return finish('blocked', refusal.code, refusal);
726
+ try {
727
+ envelope.result.crossDataSpace.plannedCopies = await precheckCopyFiles(plan.inputs.filter((input) => plan.files.some((entry) => entry.path === input.path)), shown);
728
+ }
729
+ catch (error) {
730
+ return finish('blocked', error instanceof CrossSpaceError ? error.code : 'OUTPUT_FAILED', error);
731
+ }
732
+ resolvedInputs = plan.inputs;
733
+ }
734
+ // SQL Salesforce accepts but cannot run: a warning per finding, read from the authored files
735
+ // (their lines and columns); the deploy goes ahead.
736
+ for (const input of authoredInputs)
737
+ if (input.document.kind === 'calculated-insight') {
738
+ const { native, companionPath } = input;
739
+ // An injected planning-only input carries no SQL.
740
+ if (typeof native?.expression !== 'string' || companionPath === undefined)
741
+ continue;
742
+ for (const warning of silentSqlFailureWarnings(native.expression, native.queryDialect, shown(companionPath))) {
743
+ sqlWarnings.add(warning);
744
+ envelope.diagnostics.warnings.push(warning);
745
+ }
746
+ }
747
+ if (flags.async &&
748
+ !resolvedInputs.some((input) => input.document.kind === 'identity-resolution'))
749
+ return finish('blocked', 'INVALID_ASYNC_SCOPE');
750
+ // An IR that returns before PUBLISHED cannot be the parent of a graph, CI or Segment
751
+ // selected beside it (they read its unified DMO).
752
+ if (flags.async && identityResolutionEdges(resolvedInputs).size > 0)
753
+ return finish('blocked', 'IDENTITY_RESOLUTION_ASYNC_DEPENDENTS');
754
+ const transformInputs = resolvedInputs.filter((input) => input.document.kind === 'data-transform');
755
+ if (transformInputs.length > 0 && !['auto', '68.0'].includes(flags['api-version']))
756
+ return finish('blocked', 'INVALID_TRANSFORM_SCOPE');
757
+ if (flags.draft &&
758
+ (!['auto', '68.0'].includes(flags['api-version']) ||
759
+ resolvedInputs.length === 0 ||
760
+ resolvedInputs.some((input) => input.document.kind !== 'calculated-insight')))
761
+ return finish('blocked', 'INVALID_DRAFT_SCOPE');
762
+ for (const input of resolvedInputs)
763
+ families.set(input.path, input.document.kind === 'native-data-graph' ? 'data-graph' : input.document.kind);
764
+ // Every selected file was a skipped verbatim file: nothing to deploy.
765
+ if (resolvedInputs.length === 0 && skipped.length > 0)
766
+ return finish('success');
767
+ if (resolvedInputs.length === 0 && changedSince === undefined)
110
768
  return finish('blocked', 'INVALID_SELECTION');
111
- const org = flags['target-org'];
112
- if (!org)
113
- return finish('blocked', 'TARGET_ORG_REQUIRED');
114
- envelope.provenance.targetOrgId = org.getOrgId();
115
- const connection = org.getConnection(flags['api-version']);
116
- let failed = false;
117
- let blocked = false;
118
- for (const input of inputs) {
769
+ const graphInputs = resolvedInputs.filter((input) => input.document.kind === 'native-data-graph');
770
+ if (flags['wait-timeout'] !== undefined &&
771
+ (graphInputs.length === 0 ||
772
+ !Number.isSafeInteger(flags['wait-timeout']) ||
773
+ flags['wait-timeout'] < 1))
774
+ return finish('blocked', 'INVALID_WAIT_TIMEOUT_SCOPE');
775
+ if (graphInputs.length > 0) {
119
776
  try {
120
- const preview = await this.preflight(input.document, connection, flags['api-version'], flags['data-space'], true);
121
- envelope.result.items.push({
122
- ...preview,
123
- identity: { ...input.document.identity },
124
- operation: 'preview',
125
- path: input.path,
126
- });
127
- if (preview.outcome === 'blocked' || preview.outcome === 'blocked-changes')
128
- blocked = true;
777
+ operationApiVersion(flags['api-version'], 'data-graph');
129
778
  }
130
779
  catch {
131
- failed = true;
132
- envelope.result.items.push({
133
- identity: { ...input.document.identity },
134
- operation: 'preview',
135
- path: input.path,
136
- outcome: 'blocked',
137
- target: 'unknown',
138
- absenceProof: 'none',
139
- diagnostics: [
140
- {
141
- code: 'PREFLIGHT_FAILED',
142
- message: 'Target preview failed; no deployment was executed.',
143
- },
144
- ],
145
- });
780
+ return finish('blocked', 'INVALID_SCOPE');
781
+ }
782
+ }
783
+ const streamInputs = resolvedInputs.filter((input) => input.document.kind === 'data-stream');
784
+ let streamVersion = '68.0';
785
+ if (streamInputs.length > 0) {
786
+ try {
787
+ streamVersion = dataStreamApiVersion(flags['api-version']);
788
+ }
789
+ catch {
790
+ return finish('blocked', 'INVALID_SCOPE');
146
791
  }
147
792
  }
148
- if (!flags.preview) {
149
- const items = inputs.map((input, index) => {
150
- const { outcome, target, absenceProof, diagnostics } = envelope.result.items[index];
151
- return {
152
- identity: { ...input.document.identity },
793
+ const legacyInputs = resolvedInputs.filter((input) => input.document.kind !== 'native-data-graph' &&
794
+ input.document.kind !== 'data-transform' &&
795
+ input.document.kind !== 'data-stream');
796
+ const isP1 = (input) => crudPhase(input) === 'P1';
797
+ // Selections with a mapping or relationship (explicit or Git) and all-native explicit
798
+ // selections run their P1 inputs (DLO, DMO, mapping, relationship) on the native route as
799
+ // the first stage; P3 inputs (IR, CI, Segment) follow in the dependency batch. A native
800
+ // DLO/DMO-only Git selection, or one beside P3 inputs only, stays in the batch as before.
801
+ // A transform reads and writes DLOs, so selected DLOs must settle before it (P1 before P2).
802
+ const nativeRoute = legacyInputs.some((input) => input.document.kind === 'mapping' || input.document.kind === 'relationship') ||
803
+ transformInputs.length > 0 ||
804
+ (legacyInputs.every((input) => isP1(input)) && changedSince === undefined);
805
+ const edges = identityResolutionEdges(legacyInputs);
806
+ const stageResult = (status, code, error) => ({
807
+ status,
808
+ ...(code === undefined ? {} : { code }),
809
+ ...(error === undefined ? {} : { error }),
810
+ });
811
+ const runNativeStage = async (nativeInputs, earlier) => {
812
+ let version;
813
+ try {
814
+ version = nativeApiVersion(flags['api-version']);
815
+ }
816
+ catch {
817
+ return stageResult('blocked', 'INVALID_SCOPE');
818
+ }
819
+ // Sort the freshly admitted selection, never preflight dependent mappings before parents settle.
820
+ nativeInputs.sort((a, b) => rank(a) - rank(b) || a.path.localeCompare(b.path));
821
+ const verify = async () => {
822
+ for (const input of nativeInputs)
823
+ await captureDeployInputDigest(input);
824
+ };
825
+ await verify();
826
+ const injected = flags['target-org'];
827
+ const org = injected && typeof injected === 'object'
828
+ ? injected
829
+ : flags['target-org'] === undefined && !this.resolveTargetOrg
830
+ ? undefined
831
+ : await (this.resolveTargetOrg ?? resolveTargetOrg)(flags['target-org']);
832
+ if (!org || !org.getUsername())
833
+ return stageResult('blocked', 'TARGET_ORG_REQUIRED');
834
+ const target = org.getUsername();
835
+ envelope.provenance.targetOrgId = org.getOrgId();
836
+ envelope.metadata.apiVersion = flags['api-version'] ?? 'auto';
837
+ envelope.metadata.soapApiVersion = version;
838
+ const source = (this.createDloClient ?? createDloClient)(target, version, this.ssotSender(target, version));
839
+ const dmo = (this.createDmoClient ?? createDmoClient)(target, version, undefined, this.ssotSender(target, version));
840
+ const mapping = () => (this.createMappingClient ?? createMappingClient)(target, version, undefined, effectiveScope, this.ssotSender(target, version));
841
+ const relationship = () => (this.createRelationshipClient ?? createRelationshipClient)(target, version, effectiveScope, this.ssotSender(target, version));
842
+ // The run's data space prefix: a mapping onto a standard DMO copy that is not activated yet
843
+ // is sent in the default spelling once, and a DMO file for such a copy is refused.
844
+ const dataSpacePrefix = await dataSpacePrefixOption();
845
+ // Parents settle before dependents: mappings and relationships need their DMOs.
846
+ const hasMappings = nativeInputs.some((input) => input.document.kind === 'mapping' || input.document.kind === 'relationship');
847
+ // Lower-case component keys planned for creation: by earlier stages (a stream's landing
848
+ // DLO) and by this stage.
849
+ const plannedParents = new Set(earlier);
850
+ // Field removal beside mappings. Every selected DMO is admitted read-only before the first
851
+ // write of the batch: a mapped field it omits must lose all its pairs through selected
852
+ // mapping files, otherwise the whole batch is refused. An admitted DMO removes such a
853
+ // field in its normal position; Salesforce drops the pairs with it, so the mapping files
854
+ // deployed afterwards find them already gone.
855
+ const [removal] = fieldRemoval(mapping, () => dmo);
856
+ const covered = new Map();
857
+ if (removal) {
858
+ const selectedMappings = nativeInputs
859
+ .filter((input) => input.document.kind === 'mapping')
860
+ .map((input) => {
861
+ const spec = input.document
862
+ .spec;
863
+ return {
864
+ apiName: input.document.identity.apiName,
865
+ path: input.path,
866
+ source: spec.sourceEntityDeveloperName,
867
+ target: spec.targetEntityDeveloperName,
868
+ targetFields: spec.fieldMappings.map((pair) => pair.targetFieldDeveloperName),
869
+ };
870
+ });
871
+ for (const input of nativeInputs) {
872
+ if (input.document.kind !== 'dmo')
873
+ continue;
874
+ const identity = reportedIdentity(input.document, effectiveScope);
875
+ try {
876
+ const admission = await (this.admitNativeDmoRemoval ?? admitDmoFieldRemoval)(input.document, dmo, effectiveScope, removal.mappedFieldGuide, selectedMappings);
877
+ if (admission.coveredMappedFields.length > 0)
878
+ covered.set(input.path, {
879
+ fields: admission.coveredMappedFields,
880
+ sources: selectedMappings
881
+ .filter((entry) => entry.target === identity.apiName)
882
+ .map((entry) => entry.source),
883
+ });
884
+ }
885
+ catch (error) {
886
+ // Preview reports the refusal as its error; execution as the one blocked item.
887
+ if (flags.preview)
888
+ throw error;
889
+ envelope.result.items.push({
890
+ ...refusedDmo(error),
891
+ family: 'dmo',
892
+ identity,
893
+ operation: 'execute',
894
+ path: input.path,
895
+ });
896
+ return stageResult('blocked');
897
+ }
898
+ }
899
+ await verify();
900
+ }
901
+ for (const input of nativeInputs) {
902
+ await verify();
903
+ const kind = input.document.kind;
904
+ const identity = reportedIdentity(input.document, effectiveScope);
905
+ const dmoOptions = withDataSpacePrefix(removal
906
+ ? [
907
+ {
908
+ ...removal,
909
+ coveredMappedFields: covered.get(input.path)?.fields ?? [],
910
+ coveredMappingSources: covered.get(input.path)?.sources ?? [],
911
+ },
912
+ ]
913
+ : [], dataSpacePrefix);
914
+ if (flags.preview) {
915
+ const spec = kind === 'mapping'
916
+ ? input.document
917
+ .spec
918
+ : undefined;
919
+ const planned = spec &&
920
+ (plannedParents.has(componentKey('dlo', spec.sourceEntityDeveloperName)) ||
921
+ plannedParents.has(componentKey('dmo', spec.targetEntityDeveloperName)));
922
+ if (kind === 'relationship') {
923
+ const binding = input.document.spec;
924
+ // A DMO this batch creates cannot be listed yet; nothing is asserted about it.
925
+ const relationshipPreview = plannedParents.has(componentKey('dmo', binding.sourceObjectName)) ||
926
+ plannedParents.has(componentKey('dmo', binding.targetObjectName))
927
+ ? {
928
+ family: 'relationship',
929
+ outcome: 'planned-dependencies',
930
+ target: 'unknown',
931
+ absenceProof: 'none',
932
+ diagnostics: [
933
+ {
934
+ code: 'RELATIONSHIP_DEPENDENCIES_PLANNED',
935
+ message: 'Selected DMO creation must settle before relationship comparison; no relationship existence or write outcome is asserted.',
936
+ },
937
+ ],
938
+ }
939
+ : await (this.preflightRelationship ?? preflightRelationship)(input.document, relationship(), effectiveScope);
940
+ await verify();
941
+ envelope.result.items.push({
942
+ ...relationshipPreview,
943
+ identity,
944
+ operation: 'preview',
945
+ path: input.path,
946
+ });
947
+ continue;
948
+ }
949
+ const preview = planned
950
+ ? {
951
+ family: 'mapping',
952
+ outcome: 'planned-dependencies',
953
+ target: 'unknown',
954
+ absenceProof: 'none',
955
+ diagnostics: [
956
+ {
957
+ code: 'MAPPING_DEPENDENCIES_PLANNED',
958
+ message: 'Selected parent creation must settle before mapping comparison; no mapping existence or write outcome is asserted.',
959
+ },
960
+ ],
961
+ }
962
+ : kind === 'mapping'
963
+ ? await (this.preflightMapping ?? preflightMapping)(input.document, mapping(), { source, target: dmo, ...dataSpacePrefix }, effectiveScope)
964
+ : kind === 'dlo'
965
+ ? await (this.preflightDlo ?? preflightDloDeploy)(input.document, source, effectiveScope, dloOptions)
966
+ : await (this.preflightNativeDmo ?? preflightDmo)(input.document, dmo, effectiveScope, ...dmoOptions);
967
+ await verify();
968
+ envelope.result.items.push({
969
+ ...preview,
970
+ identity,
971
+ operation: 'preview',
972
+ path: input.path,
973
+ });
974
+ if (preview.outcome === 'blocked')
975
+ // Later preview stages still run; hand on what this stage plans so far.
976
+ return {
977
+ ...stageResult('blocked'),
978
+ planned: [...plannedParents],
979
+ };
980
+ if (preview.outcome === 'create')
981
+ plannedParents.add(componentKey(kind, identity.apiName));
982
+ continue;
983
+ }
984
+ // Each executor independently admits and settles this item before the next dependency read.
985
+ const result = kind === 'relationship'
986
+ ? await (this.executeRelationship ?? executeRelationship)(input.document, relationship(), effectiveScope)
987
+ : kind === 'mapping'
988
+ ? await (this.executeMapping ?? executeMapping)(input.document, mapping(), { source, target: dmo, ...dataSpacePrefix }, (changes) => mappingChanges.set(input.path, changes), effectiveScope, (apiName) => mappingNames.set(input.path, apiName), (_apiName, document) => mappingTargets.set(input.path, document))
989
+ : kind === 'dlo'
990
+ ? await (this.executeDlo ?? executeDloDeploy)(input.document, source, effectiveScope, dloOptions)
991
+ : await (this.executeNativeDmo ?? executeDmo)(input.document, dmo, effectiveScope, ...dmoOptions);
992
+ const { serverProcessing, ...execution } = result;
993
+ if (kind === 'dlo' && serverProcessing)
994
+ processingDlos.add(input.path);
995
+ envelope.result.items.push({
996
+ ...execution,
997
+ family: kind,
998
+ identity,
153
999
  operation: 'execute',
154
1000
  path: input.path,
155
- outcome: 'not-attempted',
156
- mutation: 'not-attempted',
157
- preflight: { outcome, target, absenceProof, diagnostics },
158
- diagnostics: [],
159
- };
160
- });
161
- // Keep whole-selection evidence, but never mistake admission for attempted execution.
162
- envelope.result.items = items;
163
- if (!failed && !blocked) {
164
- for (const [index, input] of inputs.entries()) {
165
- const item = items[index];
166
- // Set conservative evidence before awaiting; an unexpected throw cannot erase it.
167
- item.outcome = 'failed';
168
- item.mutation = 'unknown';
1001
+ });
1002
+ if (result.outcome === 'blocked' || result.outcome === 'failed')
1003
+ return stageResult(result.outcome);
1004
+ if (hasMappings && kind !== 'mapping' && kind !== 'relationship') {
1005
+ // Independently verify definitions; only DLO reads expose an ACTIVE settlement status.
1006
+ let settled = false;
169
1007
  try {
170
- const result = await this.execute(input.document, connection, flags['api-version'], flags['data-space']);
171
- Object.assign(item, result);
1008
+ for (let attempt = 0; attempt < readbackPace.attempts; attempt++) {
1009
+ await paceReadback(attempt);
1010
+ const raw = kind === 'dlo'
1011
+ ? unwrapDlo(await source.get(identity.apiName))
1012
+ : unwrapNativeDmo(await dmo.get(identity.apiName));
1013
+ const actual = kind === 'dlo'
1014
+ ? normalizeDlo(raw, effectiveScope)
1015
+ : normalizeNativeDmo(raw, effectiveScope);
1016
+ if (actual.identity.apiName !== identity.apiName ||
1017
+ (actual.kind === 'dmo' && actual.c__dataSpace !== identity.dataSpace))
1018
+ break;
1019
+ const desired = input.document
1020
+ .spec;
1021
+ const fields = new Map(actual.spec.fields.map((field) => [field.name, field]));
1022
+ if (kind === 'dmo'
1023
+ ? // Same comparison the DMO executor used: category case and write-only keys.
1024
+ nativeDmoConfirmed(input.document, actual, [], nativeDmoWriteScope(raw) === 'standard')
1025
+ : raw.status === 'ACTIVE' &&
1026
+ actual.spec.label === desired.label &&
1027
+ actual.spec.category === desired.category &&
1028
+ (desired.eventDateTimeFieldName === undefined ||
1029
+ actual.spec.eventDateTimeFieldName === desired.eventDateTimeFieldName) &&
1030
+ (desired.recordModifiedFieldName === undefined ||
1031
+ actual.spec.recordModifiedFieldName === desired.recordModifiedFieldName) &&
1032
+ desired.fields.every((field) => {
1033
+ const found = fields.get(field.name);
1034
+ return (found &&
1035
+ Object.entries(field).every(([key, value]) => (key === 'isDynamicLookup' &&
1036
+ value === false &&
1037
+ found[key] === undefined) ||
1038
+ isDeepStrictEqual(found[key], value)));
1039
+ })) {
1040
+ settled = true;
1041
+ processingDlos.delete(input.path);
1042
+ break;
1043
+ }
1044
+ }
172
1045
  }
173
1046
  catch {
174
- item.diagnostics = [
1047
+ /* An unconfirmed independent parent read stops dependent writes. */
1048
+ }
1049
+ if (!settled) {
1050
+ Object.assign(envelope.result.items.at(-1), {
1051
+ outcome: 'failed',
1052
+ mutation: 'unknown',
1053
+ diagnostics: [
1054
+ {
1055
+ code: 'NATIVE_PARENT_SETTLEMENT_UNCONFIRMED',
1056
+ message: 'Selected parent did not independently confirm its requested definition and family-specific readiness; dependent deployment stopped.',
1057
+ },
1058
+ ],
1059
+ });
1060
+ return stageResult('failed');
1061
+ }
1062
+ }
1063
+ }
1064
+ await verify();
1065
+ // Preview: parents this stage plans to create; later stages report dependents as planned.
1066
+ return { status: 'success', planned: [...plannedParents] };
1067
+ };
1068
+ const runBatchStage = async (stageInputs, planned) => {
1069
+ const base = envelope.result.items.length;
1070
+ // Git snapshots minus those another stage owns; a snapshot missing from the whole
1071
+ // selection stays, so its count check still blocks.
1072
+ const stagePaths = new Set(stageInputs.map((input) => input.path));
1073
+ const otherPaths = new Set(legacyInputs.map((input) => input.path).filter((file) => !stagePaths.has(file)));
1074
+ const own = (list) => list?.filter((item) => !otherPaths.has(item.path));
1075
+ const stageGitDlos = own(gitDlos);
1076
+ const stageGitCalculatedInsights = own(gitCalculatedInsights);
1077
+ const stageGitSegments = own(gitSegments);
1078
+ const stageGitIdentityResolutions = own(gitIdentityResolutions);
1079
+ // The flag parser admits only auto or a numeric version; refuse anything else unparsed.
1080
+ if (!/^(?:auto|\d{2,3}\.0)$/u.test(flags['api-version']))
1081
+ return stageResult('blocked', 'INVALID_SCOPE');
1082
+ const admitted = stageInputs.filter((input) => input.document.kind !== 'mapping' && input.document.kind !== 'relationship');
1083
+ // Native DMO items keep the native version rule (auto is 68.0), not another family's pin.
1084
+ const admitVersion = (input) => {
1085
+ if (isNativeDmoInput(input))
1086
+ nativeApiVersion(flags['api-version']);
1087
+ else if (input.document.kind === 'identity-resolution')
1088
+ operationApiVersion(flags['api-version'], 'identity-resolution');
1089
+ else
1090
+ operationApiVersion(flags['api-version'], input.document.kind);
1091
+ };
1092
+ // A Segment runs on API68 only; any other pin is refused before the first target read.
1093
+ if (admitted.some((input) => input.document.kind === 'segment'))
1094
+ try {
1095
+ operationApiVersion(flags['api-version'], 'segment');
1096
+ }
1097
+ catch {
1098
+ return stageResult('blocked', 'INVALID_SCOPE');
1099
+ }
1100
+ const hasDlos = admitted.some((input) => input.document.kind === 'dlo');
1101
+ if (hasDlos) {
1102
+ try {
1103
+ for (const input of admitted)
1104
+ admitVersion(input);
1105
+ }
1106
+ catch {
1107
+ return stageResult('blocked', 'INVALID_SCOPE');
1108
+ }
1109
+ for (const input of admitted)
1110
+ if (input.document.kind === 'dlo')
1111
+ validateDloDocument(input.document);
1112
+ }
1113
+ if (stageGitDlos) {
1114
+ const current = admitted.filter((input) => input.document.kind === 'dlo');
1115
+ if (current.length !== stageGitDlos.length ||
1116
+ stageGitDlos.some((captured) => !current.some((input) => input.path === captured.path &&
1117
+ input.inputDigest === captured.inputDigest &&
1118
+ // A translated DLO (-c) still binds to the file's own document.
1119
+ JSON.stringify(authoredDocument(input)) === JSON.stringify(captured.document))))
1120
+ throw new GitSelectionError('INVALID_GIT_SELECTION');
1121
+ for (const input of stageGitDlos)
1122
+ await this.verifyDloInput(input);
1123
+ }
1124
+ const hasCalculatedInsights = admitted.some((input) => input.document.kind === 'calculated-insight');
1125
+ if (hasCalculatedInsights) {
1126
+ try {
1127
+ for (const input of admitted)
1128
+ admitVersion(input);
1129
+ }
1130
+ catch {
1131
+ return stageResult('blocked', 'INVALID_SCOPE');
1132
+ }
1133
+ }
1134
+ if (stageGitCalculatedInsights) {
1135
+ const current = admitted.filter((input) => input.document.kind === 'calculated-insight');
1136
+ if (current.length !== stageGitCalculatedInsights.length ||
1137
+ stageGitCalculatedInsights.some((captured) => !current.some((input) => input.path === captured.path &&
1138
+ input.companionPath === captured.companionPath &&
1139
+ input.inputDigest === captured.inputDigest &&
1140
+ // A translated insight (-c) still binds to the files' own insight.
1141
+ JSON.stringify(authoredNative(input)) === JSON.stringify(captured.native))))
1142
+ throw new GitSelectionError('INVALID_GIT_SELECTION');
1143
+ for (const captured of stageGitCalculatedInsights)
1144
+ await this.verifyCalculatedInsightInput(captured);
1145
+ }
1146
+ // Bind every captured Git owner to the original immutable authored bytes, never drop IR.
1147
+ if (stageGitIdentityResolutions) {
1148
+ const current = admitted.filter((input) => input.document.kind === 'identity-resolution');
1149
+ if (current.length !== stageGitIdentityResolutions.length ||
1150
+ stageGitIdentityResolutions.some((captured) => !current.some((input) => input.path === captured.path &&
1151
+ input.inputDigest === captured.inputDigest &&
1152
+ JSON.stringify(input.document) === JSON.stringify(captured.document))))
1153
+ throw new GitSelectionError('INVALID_GIT_SELECTION');
1154
+ for (const captured of stageGitIdentityResolutions)
1155
+ await this.verifyIdentityResolutionInput(captured);
1156
+ }
1157
+ let inputs = admitted;
1158
+ const hasIdentityResolutions = inputs.some((input) => input.document.kind === 'identity-resolution');
1159
+ if (hasIdentityResolutions) {
1160
+ for (const input of inputs) {
1161
+ const family = input.document.kind === 'identity-resolution'
1162
+ ? 'identity-resolution'
1163
+ : input.document.kind === 'segment'
1164
+ ? 'segment'
1165
+ : input.document.kind === 'calculated-insight'
1166
+ ? 'calculated-insight'
1167
+ : input.document.kind === 'dlo'
1168
+ ? 'dlo'
1169
+ : 'dmo';
1170
+ try {
1171
+ admitVersion(input);
1172
+ }
1173
+ catch {
1174
+ return stageResult('blocked', 'INVALID_SCOPE');
1175
+ }
1176
+ if (family === 'identity-resolution') {
1177
+ try {
1178
+ nativeIdentityResolutionDocument(input.document);
1179
+ }
1180
+ catch (error) {
1181
+ return stageResult('blocked', error instanceof Error && /^IDENTITY_RESOLUTION_[A-Z0-9_]+$/u.test(error.message)
1182
+ ? error.message
1183
+ : 'INVALID_SOURCE');
1184
+ }
1185
+ }
1186
+ }
1187
+ }
1188
+ if (stageGitSegments) {
1189
+ const current = inputs.filter((input) => input.document.kind === 'segment');
1190
+ if (current.length !== stageGitSegments.length ||
1191
+ stageGitSegments.some((captured) => !current.some((input) => input.path === captured.path && input.inputDigest === captured.inputDigest)))
1192
+ throw new GitSelectionError('INVALID_GIT_SELECTION');
1193
+ for (const captured of stageGitSegments)
1194
+ await this.verifySegmentInput(captured);
1195
+ }
1196
+ if (inputs.length === 0)
1197
+ return stageResult('blocked', 'INVALID_SELECTION');
1198
+ const hasNativeDmos = inputs.some((input) => isNativeDmoInput(input));
1199
+ let nativeDmoVersion = '68.0';
1200
+ try {
1201
+ if (hasNativeDmos)
1202
+ nativeDmoVersion = nativeApiVersion(flags['api-version']);
1203
+ }
1204
+ catch {
1205
+ return stageResult('blocked', 'INVALID_SCOPE');
1206
+ }
1207
+ const hasSegments = inputs.some((input) => input.document.kind === 'segment');
1208
+ // Ordered in the run's data space: a calculated insight after the DMOs and insights its
1209
+ // SQL names (in its own space; a reference into another space is refused).
1210
+ if (hasSegments || hasIdentityResolutions || hasCalculatedInsights || hasDlos) {
1211
+ const nodes = inputs.map((input) => input.document.kind === 'segment' ||
1212
+ input.document.kind === 'identity-resolution' ||
1213
+ input.document.kind === 'calculated-insight' ||
1214
+ input.document.kind === 'dlo'
1215
+ ? documentDependencyNode(input.document, 'deploy', effectiveScope)
1216
+ : {
1217
+ identity: {
1218
+ kind: 'dmo',
1219
+ ...reportedIdentity(input.document, effectiveScope),
1220
+ },
1221
+ dependencies: [],
1222
+ });
1223
+ // Keyed like the nodes, so a DLO uses the space its node names.
1224
+ const byKey = new Map(inputs.map((input, index) => [dependencyKey(nodes[index].identity), input]));
1225
+ inputs = orderDependencyNodes(nodes).map((key) => byKey.get(key));
1226
+ }
1227
+ // Preserve original Segment JSON snapshots and bind mixed-batch DMO bytes before target reads.
1228
+ const captured = hasSegments || hasIdentityResolutions || hasCalculatedInsights || hasDlos || hasNativeDmos
1229
+ ? await Promise.all(inputs.map(async (input) => ({
1230
+ input,
1231
+ digest: input.document.kind === 'segment' ? undefined : await this.captureInput(input),
1232
+ })))
1233
+ : [];
1234
+ const verifyInputs = async () => {
1235
+ for (const input of stageGitDlos ?? [])
1236
+ await this.verifyDloInput(input);
1237
+ for (const input of stageGitCalculatedInsights ?? [])
1238
+ await this.verifyCalculatedInsightInput(input);
1239
+ for (const { input, digest } of captured) {
1240
+ if (input.document.kind === 'calculated-insight')
1241
+ await this.verifyCalculatedInsightInput(input);
1242
+ if (input.document.kind === 'identity-resolution')
1243
+ await this.verifyIdentityResolutionInput(input);
1244
+ if (input.document.kind === 'segment')
1245
+ await this.verifySegmentInput(input);
1246
+ else if ((await this.captureInput(input)) !== digest)
1247
+ throw new DependencySelectionError('DEPENDENCY_INPUT_CHANGED');
1248
+ }
1249
+ };
1250
+ await verifyInputs();
1251
+ const familySelection = (input) => input.document.kind === 'segment'
1252
+ ? (() => {
1253
+ const version = operationApiVersion(flags['api-version'], 'segment');
1254
+ return Object.freeze({
1255
+ requested: version,
1256
+ restSelector: `v${version}`,
1257
+ soapNumeric: version,
1258
+ });
1259
+ })()
1260
+ : input.document.kind === 'dlo' ||
1261
+ input.document.kind === 'identity-resolution' ||
1262
+ input.document.kind === 'calculated-insight'
1263
+ ? Object.freeze({ requested: '68.0', restSelector: 'v68.0', soapNumeric: '68.0' })
1264
+ : isNativeDmoInput(input)
1265
+ ? Object.freeze({
1266
+ requested: nativeDmoVersion,
1267
+ restSelector: `v${nativeDmoVersion}`,
1268
+ soapNumeric: nativeDmoVersion,
1269
+ })
1270
+ : selection;
1271
+ const routes = (input) => input.document.kind === 'segment'
1272
+ ? [
1273
+ {
1274
+ operation: 'segment.deploy',
1275
+ apiVersion: familySelection(input).soapNumeric,
1276
+ transport: 'native',
1277
+ },
1278
+ {
1279
+ operation: 'dependency.get',
1280
+ apiVersion: familySelection(input).soapNumeric,
1281
+ transport: 'native',
1282
+ },
1283
+ ]
1284
+ : input.document.kind === 'dlo'
1285
+ ? [
1286
+ {
1287
+ operation: 'dlo.deploy',
1288
+ apiVersion: '68.0',
1289
+ transport: 'native',
1290
+ },
1291
+ ]
1292
+ : input.document.kind === 'identity-resolution'
1293
+ ? [
1294
+ {
1295
+ operation: 'identity-resolutions.get',
1296
+ apiVersion: '68.0',
1297
+ transport: 'native',
1298
+ },
1299
+ {
1300
+ operation: irAdmissions.get(input.path)?.outcome === 'create'
1301
+ ? 'dependency.get'
1302
+ : 'dependency-and-output.get',
1303
+ apiVersion: '68.0',
1304
+ transport: 'native',
1305
+ },
1306
+ ...(irAdmissions.get(input.path)?.outcome === 'create'
1307
+ ? [
1308
+ {
1309
+ operation: 'data-model-objects.list',
1310
+ apiVersion: '68.0',
1311
+ transport: 'native',
1312
+ },
1313
+ ]
1314
+ : []),
175
1315
  {
176
- code: 'EXECUTION_UNCONFIRMED',
177
- message: 'Mutation may have occurred. Inspect target before any further attempt; no retry or rollback was performed.',
1316
+ operation: irAdmissions.get(input.path)?.route.operation ??
1317
+ 'identity-resolutions.patch',
1318
+ apiVersion: '68.0',
1319
+ transport: 'native',
178
1320
  },
179
- ];
1321
+ ]
1322
+ : input.document.kind === 'calculated-insight'
1323
+ ? [
1324
+ {
1325
+ operation: 'calculated-insight.deploy',
1326
+ apiVersion: '68.0',
1327
+ transport: 'native',
1328
+ },
1329
+ {
1330
+ operation: 'calculated-insight.get',
1331
+ apiVersion: '68.0',
1332
+ transport: 'native',
1333
+ },
1334
+ ]
1335
+ : isNativeDmoInput(input)
1336
+ ? [
1337
+ {
1338
+ operation: 'dmo.deploy',
1339
+ apiVersion: nativeDmoVersion,
1340
+ transport: 'native',
1341
+ },
1342
+ ]
1343
+ : undefined;
1344
+ const injectedOrg = flags['target-org'];
1345
+ const org = injectedOrg && typeof injectedOrg === 'object'
1346
+ ? injectedOrg
1347
+ : flags['target-org'] === undefined && !this.resolveTargetOrg
1348
+ ? undefined
1349
+ : await (this.resolveTargetOrg ?? resolveTargetOrg)(flags['target-org']);
1350
+ if (!org)
1351
+ return stageResult('blocked', 'TARGET_ORG_REQUIRED');
1352
+ envelope.provenance.targetOrgId = org.getOrgId();
1353
+ // auto is 68.0; each family below still pins its own version.
1354
+ const batchVersion = flags['api-version'] === 'auto' ? '68.0' : flags['api-version'];
1355
+ const selection = Object.freeze({
1356
+ requested: batchVersion,
1357
+ restSelector: `v${batchVersion}`,
1358
+ soapNumeric: batchVersion,
1359
+ });
1360
+ envelope.metadata.soapApiVersion = inputs.every((input) => input.document.kind === 'identity-resolution')
1361
+ ? '68.0'
1362
+ : selection.soapNumeric;
1363
+ const connection = org.getConnection(selection.soapNumeric);
1364
+ // Core Org may reuse and mutate one receiver; pin a distinct operation-local view instead.
1365
+ const connectionFor = (input) => {
1366
+ if (input.document.kind !== 'identity-resolution' &&
1367
+ input.document.kind !== 'segment' &&
1368
+ input.document.kind !== 'calculated-insight' &&
1369
+ input.document.kind !== 'dlo')
1370
+ return connection;
1371
+ const receiver = Object.create(connection);
1372
+ const version = familySelection(input).soapNumeric;
1373
+ Object.defineProperty(receiver, 'version', { value: version });
1374
+ Object.defineProperty(receiver, 'getApiVersion', { value: () => version });
1375
+ Object.defineProperty(receiver, '_refreshDelegate', { value: undefined });
1376
+ return receiver;
1377
+ };
1378
+ const dloClient = () => {
1379
+ const username = org.getUsername();
1380
+ if (!username)
1381
+ throw new Error('TARGET_ORG_REQUIRED');
1382
+ return this.createDloClient(username, '68.0', this.ssotSender(username, '68.0'));
1383
+ };
1384
+ const dmoClient = () => {
1385
+ const username = org.getUsername();
1386
+ if (!username)
1387
+ throw new Error('TARGET_ORG_REQUIRED');
1388
+ return (this.createDmoClient ?? createDmoClient)(username, nativeDmoVersion, undefined, this.ssotSender(username, nativeDmoVersion));
1389
+ };
1390
+ // Read-only mapping inventory for a refused mapped-field removal; built only on refusal.
1391
+ const dmoMappings = () => {
1392
+ const username = org.getUsername();
1393
+ if (!username)
1394
+ throw new Error('TARGET_ORG_REQUIRED');
1395
+ return (this.createMappingClient ?? createMappingClient)(username, nativeDmoVersion, undefined, effectiveScope, this.ssotSender(username, nativeDmoVersion));
1396
+ };
1397
+ const previewNativeDmo = async (input) => (this.preflightNativeDmo ?? preflightDmo)(input.document, dmoClient(), effectiveScope, ...withDataSpacePrefix(fieldRemoval(dmoMappings, dmoClient), await dataSpacePrefixOption()));
1398
+ const irAdmissions = new Map();
1399
+ const irBindings = new Map();
1400
+ const verifyIrBinding = async (input) => {
1401
+ if (input.document.kind !== 'identity-resolution')
1402
+ return;
1403
+ const fingerprint = await this.bindIdentityResolution(input, connectionFor(input), familySelection(input));
1404
+ const prior = irBindings.get(input.path);
1405
+ if (prior !== undefined && prior !== fingerprint)
1406
+ throw new Error('IR binding drift');
1407
+ irBindings.set(input.path, fingerprint);
1408
+ };
1409
+ const ciContexts = new Map();
1410
+ const ciIntent = (input) => {
1411
+ if (input.document.kind !== 'calculated-insight')
1412
+ return {};
1413
+ let context = ciContexts.get(input.path);
1414
+ if (!context) {
1415
+ context = this.calculatedInsightContext(connectionFor(input), effectiveScope);
1416
+ ciContexts.set(input.path, context);
1417
+ }
1418
+ context.check();
1419
+ return { context, ...(flags.draft ? { draft: true } : {}) };
1420
+ };
1421
+ let failed = false;
1422
+ let blocked = false;
1423
+ for (const input of inputs) {
1424
+ // A parent created by an earlier stage of this preview does not exist yet: report the
1425
+ // item as planned instead of comparing it against a target that cannot hold it.
1426
+ const parents = inputDependencies(input, edges).filter((key) => planned.has(key));
1427
+ if (parents.length > 0) {
1428
+ envelope.result.items.push({
1429
+ family: input.document.kind,
1430
+ outcome: 'planned-dependencies',
1431
+ target: 'unknown',
1432
+ absenceProof: 'none',
1433
+ diagnostics: [
1434
+ {
1435
+ code: 'DEPENDENCIES_PLANNED',
1436
+ message: `Selected parent ${parents.join(', ')} is created earlier in this deploy and must settle before this item is compared; no existence or write outcome is asserted.`,
1437
+ },
1438
+ ],
1439
+ identity: reportedIdentity(input.document, effectiveScope),
1440
+ operation: 'preview',
1441
+ path: input.path,
1442
+ });
1443
+ continue;
1444
+ }
1445
+ try {
1446
+ const segment = input.document.kind === 'segment';
1447
+ if (segment)
1448
+ await this.verifySegmentInput(input);
1449
+ const preview = input.document.kind === 'dlo'
1450
+ ? await this.preflightDlo(input.document, dloClient(), effectiveScope, dloOptions)
1451
+ : input.document.kind === 'calculated-insight'
1452
+ ? await this.preflightCalculatedInsight(input.native, connectionFor(input), familySelection(input), effectiveScope, ciIntent(input))
1453
+ : input.document.kind === 'identity-resolution'
1454
+ ? await this.preflightIdentityResolution(input.document, connectionFor(input), familySelection(input), effectiveScope, await dataSpacePrefixOption())
1455
+ : segment
1456
+ ? await this.preflightSegment(input.document, connectionFor(input), familySelection(input), effectiveScope)
1457
+ : await previewNativeDmo(input);
1458
+ if (input.document.kind === 'dlo')
1459
+ await this.verifyDloInput(input);
1460
+ if (input.document.kind === 'identity-resolution') {
1461
+ await this.verifyIdentityResolutionInput(input);
1462
+ irAdmissions.set(input.path, preview);
1463
+ if (['create', 'update', 'unchanged'].includes(preview.outcome))
1464
+ await verifyIrBinding(input);
1465
+ const effects = preview
1466
+ .requiredEffects;
1467
+ if (!flags.preview &&
1468
+ (preview.outcome === 'create' || preview.outcome === 'update') &&
1469
+ (flags['allow-processing'] !== true ||
1470
+ !effects?.includes('processing') ||
1471
+ (preview.outcome === 'create' &&
1472
+ !effects.includes('generated-output-provisioning')))) {
1473
+ blocked = true;
1474
+ preview.diagnostics.push({
1475
+ code: 'PROCESSING_ACKNOWLEDGEMENT_REQUIRED',
1476
+ message: 'IR processing and CREATE generated-output provisioning require explicit --allow-processing. No batch writes were attempted.',
1477
+ });
1478
+ }
180
1479
  }
181
- if (item.mutation === 'unknown' || item.outcome === 'failed') {
182
- failed = true;
183
- break;
1480
+ if (input.document.kind === 'calculated-insight')
1481
+ await this.verifyCalculatedInsightInput(input);
1482
+ if (segment) {
1483
+ await this.verifySegmentInput(input);
1484
+ const effects = preview.requiredEffects;
1485
+ if (!flags.preview &&
1486
+ ['create', 'update'].includes(preview.outcome) &&
1487
+ (flags['allow-processing'] !== true || !effects?.includes('processing'))) {
1488
+ blocked = true;
1489
+ preview.diagnostics.push({
1490
+ code: 'PROCESSING_ACKNOWLEDGEMENT_REQUIRED',
1491
+ message: 'Segment create and update start processing in Data Cloud and need --allow-processing. Nothing was written.',
1492
+ });
1493
+ }
184
1494
  }
185
- if (item.outcome === 'blocked') {
1495
+ envelope.result.items.push({
1496
+ ...preview,
1497
+ ...(routes(input) ? { routes: routes(input) } : {}),
1498
+ identity: reportedIdentity(input.document, effectiveScope),
1499
+ operation: 'preview',
1500
+ path: input.path,
1501
+ });
1502
+ if (preview.outcome === 'blocked' || preview.outcome === 'blocked-changes')
186
1503
  blocked = true;
187
- break;
1504
+ }
1505
+ catch (error) {
1506
+ failed = true;
1507
+ envelope.result.items.push({
1508
+ identity: reportedIdentity(input.document, effectiveScope),
1509
+ operation: 'preview',
1510
+ path: input.path,
1511
+ outcome: 'blocked',
1512
+ target: 'unknown',
1513
+ absenceProof: 'none',
1514
+ diagnostics: [
1515
+ {
1516
+ // A native DMO refusal names its own reason (for example a standard target),
1517
+ // and so does an escaped-text refusal of any family.
1518
+ code: error instanceof NativeDmoError ||
1519
+ error?.code === escapedCopyCode
1520
+ ? error.code
1521
+ : 'PREFLIGHT_FAILED',
1522
+ message: operationDiagnostic(error, 'Target preview failed; no deployment was executed.'),
1523
+ ...(mappedFieldMappings(error)
1524
+ ? { mappedFields: mappedFieldMappings(error) }
1525
+ : {}),
1526
+ },
1527
+ ],
1528
+ });
1529
+ }
1530
+ }
1531
+ if (flags.preview && !failed)
1532
+ await verifyInputs();
1533
+ if (!flags.preview) {
1534
+ const items = inputs.map((input, index) => {
1535
+ const { outcome, target, absenceProof, diagnostics } = envelope.result.items[base + index];
1536
+ return {
1537
+ identity: reportedIdentity(input.document, effectiveScope),
1538
+ operation: 'execute',
1539
+ path: input.path,
1540
+ outcome: 'not-attempted',
1541
+ mutation: 'not-attempted',
1542
+ preflight: { outcome, target, absenceProof, diagnostics },
1543
+ ...(routes(input) ? { routes: routes(input) } : {}),
1544
+ ...(input.document.kind === 'dlo' ? { family: 'dlo' } : {}),
1545
+ ...(input.document.kind === 'identity-resolution'
1546
+ ? {
1547
+ family: 'identity-resolution',
1548
+ route: envelope.result.items[base + index]
1549
+ .route,
1550
+ requiredEffects: envelope.result.items[base + index].requiredEffects,
1551
+ }
1552
+ : {}),
1553
+ ...(input.document.kind === 'calculated-insight'
1554
+ ? {
1555
+ family: 'calculated-insight',
1556
+ route: envelope.result.items[base + index].route,
1557
+ }
1558
+ : {}),
1559
+ ...(input.document.kind === 'segment'
1560
+ ? {
1561
+ family: 'segment',
1562
+ route: {
1563
+ apiVersion: familySelection(input).soapNumeric,
1564
+ method: envelope.result.items[base + index].outcome ===
1565
+ 'create'
1566
+ ? 'POST'
1567
+ : 'PATCH',
1568
+ resource: 'segments',
1569
+ },
1570
+ requiredEffects: envelope.result.items[base + index]
1571
+ .requiredEffects,
1572
+ }
1573
+ : {}),
1574
+ diagnostics: [],
1575
+ };
1576
+ });
1577
+ // Keep whole-selection evidence, but never mistake admission for attempted execution.
1578
+ envelope.result.items.splice(base, items.length, ...items);
1579
+ if (!failed && !blocked) {
1580
+ for (const [index, input] of inputs.entries()) {
1581
+ const item = items[index];
1582
+ try {
1583
+ await verifyInputs();
1584
+ // Re-admit every pending dependent before any next write, including a DMO write.
1585
+ for (const pending of inputs.slice(index)) {
1586
+ if (pending.document.kind === 'dlo') {
1587
+ await this.preflightDlo(pending.document, dloClient(), effectiveScope, dloOptions);
1588
+ continue;
1589
+ }
1590
+ if (pending.document.kind === 'identity-resolution') {
1591
+ await verifyIrBinding(pending);
1592
+ const fresh = await this.preflightIdentityResolution(pending.document, connectionFor(pending), familySelection(pending), effectiveScope, await dataSpacePrefixOption());
1593
+ if ((irAdmissions.get(pending.path)?.outcome === 'create') !==
1594
+ (fresh.outcome === 'create') ||
1595
+ !['create', 'unchanged', 'update'].includes(fresh.outcome) ||
1596
+ ((fresh.outcome === 'update' || fresh.outcome === 'create') &&
1597
+ (flags['allow-processing'] !== true ||
1598
+ !fresh.requiredEffects.includes('processing') ||
1599
+ (fresh.outcome === 'create' &&
1600
+ !fresh.requiredEffects.includes('generated-output-provisioning')))))
1601
+ throw new DependencySelectionError('IDENTITY_RESOLUTION_FRESH_ADMISSION_BLOCKED');
1602
+ continue;
1603
+ }
1604
+ if (pending.document.kind !== 'segment')
1605
+ continue;
1606
+ const fresh = await this.preflightSegment(pending.document, connectionFor(pending), familySelection(pending), effectiveScope);
1607
+ if (!['unchanged', 'update', 'create'].includes(fresh.outcome) ||
1608
+ (['update', 'create'].includes(fresh.outcome) &&
1609
+ (flags['allow-processing'] !== true ||
1610
+ !fresh.requiredEffects.includes('processing'))))
1611
+ throw new DependencySelectionError('SEGMENT_FRESH_ADMISSION_BLOCKED');
1612
+ }
1613
+ await verifyInputs();
1614
+ }
1615
+ catch (error) {
1616
+ item.outcome = 'blocked';
1617
+ item.diagnostics = [
1618
+ {
1619
+ code: 'DEPLOY_FRESH_ADMISSION_BLOCKED',
1620
+ message: operationDiagnostic(error, 'Fresh input or dependency admission failed before this item. No further writes were attempted.'),
1621
+ },
1622
+ ];
1623
+ blocked = true;
1624
+ break;
1625
+ }
1626
+ // Set conservative evidence only at dispatch; admission failures cannot imply a write.
1627
+ item.outcome = 'failed';
1628
+ item.mutation = 'unknown';
1629
+ try {
1630
+ const result = input.document.kind === 'dlo'
1631
+ ? await this.executeDlo(input.document, dloClient(), effectiveScope, dloOptions)
1632
+ : input.document.kind === 'calculated-insight'
1633
+ ? await this.executeCalculatedInsight(input.native, connectionFor(input), familySelection(input), effectiveScope, { ...ciIntent(input), verifyInput: verifyInputs })
1634
+ : input.document.kind === 'identity-resolution'
1635
+ ? await this.executeIdentityResolution(input.document, connectionFor(input), familySelection(input), effectiveScope, {
1636
+ allowProcessing: flags['allow-processing'] === true,
1637
+ verifyInput: async () => {
1638
+ await verifyInputs();
1639
+ await verifyIrBinding(input);
1640
+ },
1641
+ allowGeneratedOutputProvisioning: flags['allow-processing'] === true,
1642
+ ...(flags.async ? { async: true } : {}),
1643
+ ...(await dataSpacePrefixOption()),
1644
+ })
1645
+ : input.document.kind === 'segment'
1646
+ ? await this.executeSegment(input.document, connectionFor(input), familySelection(input), effectiveScope, {
1647
+ allowProcessing: flags['allow-processing'] === true,
1648
+ verifyInput: verifyInputs,
1649
+ })
1650
+ : await (this.executeNativeDmo ?? executeDmo)(input.document, dmoClient(), effectiveScope, ...withDataSpacePrefix(fieldRemoval(dmoMappings, dmoClient), await dataSpacePrefixOption()));
1651
+ const { serverProcessing, ...execution } = result;
1652
+ if (['dlo', 'segment'].includes(input.document.kind) && serverProcessing)
1653
+ processingDlos.add(input.path);
1654
+ Object.assign(item, execution);
1655
+ }
1656
+ catch (error) {
1657
+ item.diagnostics = [
1658
+ {
1659
+ code: 'EXECUTION_UNCONFIRMED',
1660
+ message: operationDiagnostic(error, 'Mutation may have occurred. Inspect target before any further attempt; no retry or rollback was performed.'),
1661
+ },
1662
+ ];
1663
+ }
1664
+ if (item.mutation === 'unknown' || item.outcome === 'failed') {
1665
+ failed = true;
1666
+ break;
1667
+ }
1668
+ if (item.outcome === 'blocked') {
1669
+ blocked = true;
1670
+ break;
1671
+ }
188
1672
  }
189
1673
  }
190
1674
  }
1675
+ return {
1676
+ ...stageResult(failed ? 'failed' : blocked ? 'blocked' : 'success', failed
1677
+ ? flags.preview
1678
+ ? 'PREFLIGHT_FAILED'
1679
+ : 'DEPLOY_EXECUTION_FAILED'
1680
+ : blocked
1681
+ ? flags.preview
1682
+ ? 'DEPLOY_PREVIEW_BLOCKED'
1683
+ : 'DEPLOY_EXECUTION_BLOCKED'
1684
+ : undefined),
1685
+ // Preview: what this stage creates, or could not compare, is planned for later stages.
1686
+ ...(flags.preview
1687
+ ? {
1688
+ planned: inputs
1689
+ .filter((_, index) => ['create', 'planned-dependencies'].includes(envelope.result.items[base + index]?.outcome))
1690
+ .map((input) => inputKey(input)),
1691
+ }
1692
+ : {}),
1693
+ };
1694
+ };
1695
+ const runStreamStage = async (streamInputs) => {
1696
+ const version = streamVersion;
1697
+ const verify = async () => {
1698
+ for (const input of streamInputs)
1699
+ await (this.verifyDataStreamInput ?? verifyDataStreamInputDigest)(input);
1700
+ };
1701
+ await verify();
1702
+ const injected = flags['target-org'];
1703
+ const org = injected && typeof injected === 'object'
1704
+ ? injected
1705
+ : await (this.resolveTargetOrg ?? resolveTargetOrg)(flags['target-org']);
1706
+ if (!org?.getUsername())
1707
+ return stageResult('blocked', 'TARGET_ORG_REQUIRED');
1708
+ envelope.provenance.targetOrgId = org.getOrgId();
1709
+ envelope.metadata.soapApiVersion = version;
1710
+ const clients = this.createDataStreamClients(org.getConnection(version), org.getUsername(), version);
1711
+ const created = [];
1712
+ const routes = [
1713
+ { operation: 'data-stream.deploy', apiVersion: version, transport: 'native' },
1714
+ { operation: 'dlo.get', apiVersion: version, transport: 'native' },
1715
+ { operation: 'connection.read', apiVersion: version, transport: 'native' },
1716
+ ];
1717
+ // The read-only comparison of one stream. A check that refuses the stream (for example
1718
+ // a connection that already has a stream) is reported on the stream's item.
1719
+ const comparison = async (input) => {
1720
+ try {
1721
+ return {
1722
+ check: await this.preflightDataStream(input.document, clients, effectiveScope),
1723
+ };
1724
+ }
1725
+ catch (error) {
1726
+ if (!(error instanceof DataStreamError))
1727
+ throw error;
1728
+ const message = operationDiagnostic(error, flags.preview
1729
+ ? 'Preview stopped; nothing was written. Correct the reported check before another attempt.'
1730
+ : 'No write attempted; correct the reported check before another attempt.');
1731
+ envelope.result.items.push(flags.preview
1732
+ ? {
1733
+ family: 'data-stream',
1734
+ outcome: 'blocked',
1735
+ target: 'unknown',
1736
+ absenceProof: 'none',
1737
+ requiredEffects: [],
1738
+ diagnostics: [{ code: error.code, message }],
1739
+ routes,
1740
+ identity: reportedIdentity(input.document, effectiveScope),
1741
+ operation: 'preview',
1742
+ path: input.path,
1743
+ }
1744
+ : {
1745
+ family: 'data-stream',
1746
+ outcome: 'blocked',
1747
+ mutation: 'not-attempted',
1748
+ diagnostics: [{ code: error.code, message }],
1749
+ routes,
1750
+ identity: reportedIdentity(input.document, effectiveScope),
1751
+ operation: 'execute',
1752
+ path: input.path,
1753
+ });
1754
+ return { blocked: stageResult('blocked', error.code, error) };
1755
+ }
1756
+ };
1757
+ // A new stream creates and owns its landing DLO: a selected DLO file of the same name
1758
+ // would write that object a second time. P0 is the first stage, so this read-only
1759
+ // check refuses the pair before any write. An existing stream's DLO file is a normal
1760
+ // sibling and Salesforce decides.
1761
+ const colliding = new Set(streamDloCollisions(resolvedInputs).map((name) => name.toLowerCase()));
1762
+ for (const input of streamInputs) {
1763
+ const landing = streamLandingDlo(input);
1764
+ if (!landing || !colliding.has(landing.toLowerCase()))
1765
+ continue;
1766
+ await verify();
1767
+ const compared = await comparison(input);
1768
+ if ('blocked' in compared)
1769
+ return compared.blocked;
1770
+ if (compared.check.outcome !== 'create')
1771
+ continue;
1772
+ envelope.diagnostics.warnings.push(`DLO ${landing} is the landing DLO of new data stream ${input.document.identity.apiName}; remove the DLO file from the selection.`);
1773
+ return stageResult('blocked', 'DATA_STREAM_DLO_COLLISION');
1774
+ }
1775
+ for (const input of streamInputs) {
1776
+ await verify();
1777
+ if (flags.preview) {
1778
+ const compared = await comparison(input);
1779
+ if ('blocked' in compared)
1780
+ return compared.blocked;
1781
+ const preview = compared.check;
1782
+ await verify();
1783
+ envelope.result.items.push({
1784
+ ...preview,
1785
+ routes,
1786
+ identity: reportedIdentity(input.document, effectiveScope),
1787
+ operation: 'preview',
1788
+ path: input.path,
1789
+ });
1790
+ // The landing DLO does not exist before the stream is created.
1791
+ const landing = streamLandingDlo(input);
1792
+ if (preview.outcome === 'create' && landing)
1793
+ created.push(componentKey('dlo', landing));
1794
+ }
1795
+ else {
1796
+ const result = await this.executeDataStream(input.document, clients, {
1797
+ allowProcessing: flags['allow-processing'] === true,
1798
+ verifyInput: verify,
1799
+ dataSpace: effectiveScope,
1800
+ });
1801
+ envelope.result.items.push({
1802
+ ...result,
1803
+ routes,
1804
+ identity: reportedIdentity(input.document, effectiveScope),
1805
+ operation: 'execute',
1806
+ path: input.path,
1807
+ });
1808
+ // The error behind the item, so the command's message carries its explanation too.
1809
+ if (result.outcome === 'blocked' || result.outcome === 'failed')
1810
+ return stageResult(result.outcome, result.diagnostics[0]?.code, streamFailureCause(result));
1811
+ }
1812
+ }
1813
+ await verify();
1814
+ return { status: 'success', planned: created };
1815
+ };
1816
+ const runTransformStage = async (input, planned) => {
1817
+ const identity = {
1818
+ dataSpace: input.document.c__dataSpace,
1819
+ apiName: input.document.definition.name,
1820
+ };
1821
+ const routes = [
1822
+ { operation: 'data-transform.deploy', apiVersion: '68.0', transport: 'native' },
1823
+ ];
1824
+ let dispatched = false;
1825
+ try {
1826
+ const verifyInput = async () => this.verifyDataTransformInput(input);
1827
+ await verifyInput();
1828
+ // A DLO this transform reads or writes is created earlier in this preview: it does not
1829
+ // exist yet, so the transform is reported as planned instead of compared.
1830
+ const parents = transformDloNames(input)
1831
+ .map((name) => componentKey('dlo', name))
1832
+ .filter((key) => planned.has(key));
1833
+ if (flags.preview && parents.length > 0) {
1834
+ envelope.result.items.push({
1835
+ family: 'data-transform',
1836
+ outcome: 'planned-dependencies',
1837
+ target: 'unknown',
1838
+ absenceProof: 'none',
1839
+ diagnostics: [
1840
+ {
1841
+ code: 'DEPENDENCIES_PLANNED',
1842
+ message: `Selected parent ${parents.join(', ')} is created earlier in this deploy and must settle before this item is compared; no existence or write outcome is asserted.`,
1843
+ },
1844
+ ],
1845
+ identity,
1846
+ operation: 'preview',
1847
+ path: input.path,
1848
+ });
1849
+ return stageResult('success');
1850
+ }
1851
+ const injected = flags['target-org'];
1852
+ const org = injected && typeof injected === 'object'
1853
+ ? injected
1854
+ : await this.resolveTargetOrg(flags['target-org']);
1855
+ if (!org?.getUsername())
1856
+ return stageResult('blocked', 'TARGET_ORG_REQUIRED');
1857
+ envelope.provenance.targetOrgId = org.getOrgId();
1858
+ envelope.metadata.soapApiVersion = '68.0';
1859
+ const connection = org.getConnection('68.0');
1860
+ const client = this.createDataTransformClient(connection, '68.0', effectiveScope);
1861
+ // Create or update by name: the complete inventory names at most one target (two or
1862
+ // more matches ignoring case are refused); none means create.
1863
+ const targetId = await (this.resolveDataTransformTarget ?? resolveDataTransformTargetId)(client, identity.apiName);
1864
+ const selection = targetId === undefined
1865
+ ? { operation: 'create' }
1866
+ : { operation: 'update', targetId };
1867
+ if (flags.preview) {
1868
+ const plan = await this.preflightDataTransform(input.document, selection, client, {
1869
+ skipServerValidation: true,
1870
+ });
1871
+ await verifyInput();
1872
+ envelope.result.items.push({
1873
+ family: 'data-transform',
1874
+ outcome: plan.operation,
1875
+ identity,
1876
+ routes,
1877
+ operation: 'preview',
1878
+ path: input.path,
1879
+ diagnostics: [
1880
+ {
1881
+ code: 'TRANSFORM_PREVIEW_LIMITATIONS',
1882
+ message: 'GET-only preview; server validation pending. The target was chosen by name from the current transform list; Salesforce decides at deploy time.',
1883
+ },
1884
+ ...(plan.writeSchedule ? [transformScheduleNotice(plan.document.schedule)] : []),
1885
+ ],
1886
+ });
1887
+ }
1888
+ else {
1889
+ const result = await this.executeDataTransform(input.document, selection, client, {
1890
+ verifyInput,
1891
+ onDispatch: () => {
1892
+ dispatched = true;
1893
+ },
1894
+ });
1895
+ if (result.serverProcessing)
1896
+ processingDlos.add(input.path);
1897
+ envelope.result.items.push({
1898
+ ...(result.serverProcessing ? { serverProcessing: true } : {}),
1899
+ family: 'data-transform',
1900
+ identity,
1901
+ routes,
1902
+ operation: 'execute',
1903
+ path: input.path,
1904
+ outcome: result.operation === 'create'
1905
+ ? 'created'
1906
+ : result.operation === 'update'
1907
+ ? 'updated'
1908
+ : 'unchanged',
1909
+ mutation: result.operation === 'create'
1910
+ ? 'confirmed-created'
1911
+ : result.operation === 'update'
1912
+ ? 'confirmed-updated'
1913
+ : 'not-attempted',
1914
+ diagnostics: [
1915
+ ...(result.scheduleWritten
1916
+ ? [transformScheduleNotice(input.document.schedule)]
1917
+ : []),
1918
+ ...(result.serverProcessing
1919
+ ? [
1920
+ {
1921
+ code: 'TRANSFORM_SERVER_PROCESSING',
1922
+ message: 'Definition written and read back; server is still processing. Computation completion is not established.',
1923
+ },
1924
+ ]
1925
+ : []),
1926
+ ],
1927
+ });
1928
+ }
1929
+ return stageResult('success');
1930
+ }
1931
+ catch (error) {
1932
+ // The definition was written and confirmed; only the schedule was not.
1933
+ if (error instanceof DataTransformScheduleError) {
1934
+ const written = error.definition === 'create' ? 'created' : 'updated';
1935
+ envelope.result.items.push({
1936
+ family: 'data-transform',
1937
+ identity,
1938
+ routes,
1939
+ operation: 'execute',
1940
+ path: input.path,
1941
+ outcome: 'failed',
1942
+ mutation: error.definition === 'create' ? 'confirmed-created' : 'confirmed-updated',
1943
+ diagnostics: [
1944
+ {
1945
+ code: error.code,
1946
+ message: error.code === 'TRANSFORM_SCHEDULE_REJECTED'
1947
+ ? operationDiagnostic(error.cause, `The transform definition was ${written}; Salesforce rejected the schedule of the file, so the schedule in the org is unchanged. Correct the schedule, then rerun the deploy.`)
1948
+ : `The transform definition was ${written}, but the transform was still processing at the end of the wait, so the schedule was not sent. Rerun the deploy once the transform is ACTIVE.`,
1949
+ },
1950
+ ],
1951
+ });
1952
+ return stageResult('failed', error.code, error.cause ?? error);
1953
+ }
1954
+ if (!flags.preview)
1955
+ envelope.result.items.push({
1956
+ family: 'data-transform',
1957
+ identity,
1958
+ routes,
1959
+ operation: 'execute',
1960
+ path: input.path,
1961
+ outcome: 'failed',
1962
+ mutation: rejectedTransformWrite(error)
1963
+ ? 'rejected'
1964
+ : dispatched
1965
+ ? 'unknown'
1966
+ : 'not-attempted',
1967
+ diagnostics: [],
1968
+ });
1969
+ return stageResult(dispatched ? 'failed' : 'blocked', error instanceof DataTransformError ? error.code : 'TRANSFORM_DEPLOY_FAILED', error);
1970
+ }
1971
+ };
1972
+ // Several transforms deploy one after another; execution stops at the first that does not
1973
+ // succeed, preview compares every one.
1974
+ const runTransformsStage = async (inputs, planned) => {
1975
+ let first;
1976
+ for (const input of inputs) {
1977
+ const result = await runTransformStage(input, planned);
1978
+ if (result.status === 'success')
1979
+ continue;
1980
+ first ??= result;
1981
+ if (!flags.preview)
1982
+ break;
1983
+ }
1984
+ return first ?? stageResult('success');
1985
+ };
1986
+ const runGraphStage = async (graphs, planned) => {
1987
+ const snapshot = JSON.stringify(flags);
1988
+ const graphEdges = identityResolutionEdges(resolvedInputs);
1989
+ let target;
1990
+ for (const input of graphs) {
1991
+ const verifyInput = async () => {
1992
+ if (JSON.stringify(flags) !== snapshot)
1993
+ throw new Error('Input drift');
1994
+ await (this.verifyNativeDataGraphInput ?? verifyNativeDataGraphInputDigest)(input);
1995
+ };
1996
+ await verifyInput();
1997
+ const identity = {
1998
+ dataSpace: input.document.c__dataSpace,
1999
+ apiName: input.document.definition.name,
2000
+ };
2001
+ const routes = [
2002
+ { operation: 'data-graph.deploy', apiVersion: '68.0', transport: 'native' },
2003
+ ];
2004
+ // A root or related DMO (or the IR that creates it) is created earlier in this preview:
2005
+ // the graph is reported as planned instead of compared against a target without it.
2006
+ const parents = inputDependencies(input, graphEdges).filter((key) => planned.has(key));
2007
+ if (flags.preview && parents.length > 0) {
2008
+ envelope.result.items.push({
2009
+ family: 'data-graph',
2010
+ outcome: 'planned-dependencies',
2011
+ target: 'unknown',
2012
+ absenceProof: 'none',
2013
+ diagnostics: [
2014
+ {
2015
+ code: 'DEPENDENCIES_PLANNED',
2016
+ message: `Selected parent ${parents.join(', ')} is created earlier in this deploy and must settle before this item is compared; no existence or write outcome is asserted.`,
2017
+ },
2018
+ ],
2019
+ identity,
2020
+ operation: 'preview',
2021
+ path: input.path,
2022
+ routes,
2023
+ });
2024
+ continue;
2025
+ }
2026
+ if (!target) {
2027
+ const org = await this.resolveTargetOrg(flags['target-org']);
2028
+ if (!org)
2029
+ return stageResult('blocked', 'TARGET_ORG_REQUIRED');
2030
+ const connection = org.getConnection('68.0');
2031
+ const context = await this.nativeGraphContext(connection, effectiveScope);
2032
+ envelope.provenance.targetOrgId = context.orgId;
2033
+ envelope.metadata.soapApiVersion = '68.0';
2034
+ envelope.diagnostics.warnings.push(nativeGraphLimitations);
2035
+ target = { connection, context };
2036
+ }
2037
+ const { connection, context } = target;
2038
+ const result = await this.operateNativeGraph(input.document, context, this.nativeGraphClient(connection, '68.0', effectiveScope), {
2039
+ operation: 'deploy',
2040
+ preview: flags.preview,
2041
+ confirmed: flags['allow-processing'] === true,
2042
+ waitTimeoutSeconds: flags['wait-timeout'] ?? 1800,
2043
+ progress: (message) => {
2044
+ // oclif logToStderr suppresses output in JSON mode; progress must remain visible.
2045
+ process.stderr.write(`${message}\n`);
2046
+ },
2047
+ verifyInput,
2048
+ });
2049
+ if (flags.preview)
2050
+ envelope.result.items.push({
2051
+ identity,
2052
+ path: input.path,
2053
+ family: 'data-graph',
2054
+ operation: 'preview',
2055
+ outcome: result.outcome === 'create'
2056
+ ? 'create'
2057
+ : result.outcome === 'update'
2058
+ ? 'update'
2059
+ : result.outcome === 'unchanged'
2060
+ ? 'unchanged'
2061
+ : 'blocked',
2062
+ target: result.outcome === 'create'
2063
+ ? 'absent'
2064
+ : result.outcome === 'unchanged' || result.outcome === 'update'
2065
+ ? 'present'
2066
+ : (result.target ?? 'unknown'),
2067
+ absenceProof: 'none',
2068
+ diagnostics: result.diagnostics ?? [],
2069
+ routes,
2070
+ });
2071
+ else
2072
+ envelope.result.items.push({
2073
+ identity,
2074
+ path: input.path,
2075
+ family: 'data-graph',
2076
+ operation: 'execute',
2077
+ outcome: result.outcome === 'created'
2078
+ ? 'created'
2079
+ : result.outcome === 'updated'
2080
+ ? 'updated'
2081
+ : result.outcome === 'unchanged'
2082
+ ? 'unchanged'
2083
+ : result.outcome === 'failed'
2084
+ ? 'failed'
2085
+ : 'blocked',
2086
+ mutation: result.mutation === 'confirmed-created'
2087
+ ? 'confirmed-created'
2088
+ : result.mutation === 'confirmed-updated'
2089
+ ? 'confirmed-updated'
2090
+ : result.mutation === 'unknown'
2091
+ ? 'unknown'
2092
+ : result.mutation === 'rejected'
2093
+ ? 'rejected'
2094
+ : 'not-attempted',
2095
+ diagnostics: result.failedCheck
2096
+ ? [
2097
+ {
2098
+ code: 'DATA_GRAPH_CREATE_UNCONFIRMED',
2099
+ message: `The create request was sent but ${result.failedCheck === 'deadline' ? '--wait-timeout ran out before the graph was confirmed' : `the ${result.failedCheck} check could not confirm the graph`}; it may exist. Retrieve it or deploy again to reconcile.`,
2100
+ },
2101
+ ]
2102
+ : (result.diagnostics ?? []),
2103
+ routes,
2104
+ });
2105
+ if (result.outcome === 'blocked' || result.outcome === 'failed') {
2106
+ // A block that names its cause on the item needs no generic explanation.
2107
+ const named = result.outcome === 'blocked' && (result.diagnostics?.length ?? 0) > 0;
2108
+ // A named block reads as a block in preview and deploy alike.
2109
+ return stageResult(result.outcome, named
2110
+ ? flags.preview
2111
+ ? 'DEPLOY_PREVIEW_BLOCKED'
2112
+ : 'DEPLOY_EXECUTION_BLOCKED'
2113
+ : flags.preview
2114
+ ? 'DEPLOY_PREVIEW_FAILED'
2115
+ : 'DEPLOY_EXECUTION_FAILED', named ? undefined : result);
2116
+ }
2117
+ }
2118
+ return stageResult('success');
2119
+ };
2120
+ const stages = planDeployStages(resolvedInputs, { nativeRoute });
2121
+ if (stages.length === 0) {
2122
+ if (changedSince === undefined)
2123
+ return finish('blocked', 'INVALID_SELECTION');
2124
+ // An empty Git admission still checks its captured snapshots in the batch.
2125
+ stages.push({ phase: 'P3', inputs: [] });
191
2126
  }
192
- return finish(failed ? 'failed' : blocked ? 'blocked' : 'success', failed
193
- ? flags.preview
194
- ? 'PREFLIGHT_FAILED'
195
- : 'DEPLOY_EXECUTION_FAILED'
196
- : blocked
197
- ? flags.preview
198
- ? 'DEPLOY_PREVIEW_BLOCKED'
199
- : 'DEPLOY_EXECUTION_BLOCKED'
200
- : undefined);
2127
+ // A P3 stage after an earlier writing stage (P0 streams, P1 native, P2 transform) must be
2128
+ // admissible before that first write: its version, data space and every local (no org
2129
+ // access) file and dependency shape check.
2130
+ if (stages[0]?.phase !== 'P3' && stages.some((stage) => stage.phase === 'P3')) {
2131
+ try {
2132
+ for (const input of legacyInputs)
2133
+ if (crudPhase(input) === 'P3')
2134
+ operationApiVersion(flags['api-version'], input.document.kind);
2135
+ }
2136
+ catch {
2137
+ return finish('blocked', 'INVALID_SCOPE');
2138
+ }
2139
+ const later = legacyInputs.filter((input) => crudPhase(input) === 'P3');
2140
+ try {
2141
+ for (const input of later)
2142
+ if (input.document.kind === 'identity-resolution')
2143
+ nativeIdentityResolutionDocument(input.document);
2144
+ orderDependencyNodes(later.map((input) => documentDependencyNode(input.document, 'deploy', effectiveScope)));
2145
+ }
2146
+ catch (error) {
2147
+ return finish('blocked',
2148
+ // Same codes as the batch path, plus the validators' own codes.
2149
+ error instanceof DependencySelectionError ||
2150
+ error instanceof CalculatedInsightError ||
2151
+ error instanceof IdentityResolutionError
2152
+ ? error.code
2153
+ : error instanceof Error && /^IDENTITY_RESOLUTION_[A-Z0-9_]+$/u.test(error.message)
2154
+ ? error.message
2155
+ : 'INVALID_SOURCE');
2156
+ }
2157
+ }
2158
+ // The run's data space and every data space a selected file names must exist in the org:
2159
+ // one read per run, before the first stage reads or writes anything (preview too).
2160
+ try {
2161
+ await dataSpaceCheckOf(this, openSpaceSender).require([
2162
+ effectiveScope,
2163
+ ...resolvedInputs.flatMap((input) => {
2164
+ const named = input.document.c__dataSpace;
2165
+ // A DLO or stream file lists spaces; a calculated insight names one in its identity.
2166
+ return Array.isArray(named)
2167
+ ? named
2168
+ : typeof named === 'string'
2169
+ ? [named]
2170
+ : input.document.kind === 'calculated-insight'
2171
+ ? [input.document.identity.dataSpace]
2172
+ : [];
2173
+ }),
2174
+ ]);
2175
+ }
2176
+ catch (error) {
2177
+ // The check's own code, or the failure's (an expired session keeps its own code).
2178
+ return finish('blocked', dataSpaceCheckCode(error, 'TARGET_ORG_REQUIRED'), error);
2179
+ }
2180
+ // A stream file must list the run's data space and every single-space file (calculated
2181
+ // insight, segment, data transform, data graph, identity resolution) must name it: checked
2182
+ // for every selected file before any stage writes anything. In a non-default data space
2183
+ // Salesforce stores a segment as <prefix>_<Name> (it adds the prefix to a name without it)
2184
+ // and an identity resolution ruleset as <prefix>_<type>_<rulesetId>, so their files there
2185
+ // must carry that name.
2186
+ try {
2187
+ const { dataSpacePrefix: prefix } = await dataSpacePrefixOption();
2188
+ for (const input of resolvedInputs)
2189
+ if (input.document.kind === 'data-stream')
2190
+ requireRunSpace(input.document, effectiveScope);
2191
+ else if (input.document.kind === 'calculated-insight' &&
2192
+ input.document.identity.dataSpace !== effectiveScope)
2193
+ throw calculatedInsightSpaceMismatch(input.document.identity, effectiveScope, true);
2194
+ else if (input.document.kind === 'segment') {
2195
+ const { apiName } = input.document.identity;
2196
+ if (input.document.c__dataSpace !== effectiveScope)
2197
+ throw explainSpaceMismatch(new SegmentError('SEGMENT_DATASPACE_MISMATCH'), apiName, input.document.c__dataSpace, effectiveScope, true);
2198
+ // Without the prefix the stored name cannot be checked: refused, never guessed.
2199
+ if (effectiveScope !== 'default' && prefix === undefined)
2200
+ throw explainInput(new SegmentError('SEGMENT_NAME_NOT_STORED'), `The org's data space list names no prefix for the data space ${effectiveScope}, so the name Salesforce would store for segment ${apiName} (<prefix>_<Name>) cannot be checked. Nothing was sent; check the data space in Data Cloud.`);
2201
+ if (prefix !== undefined && !apiName.startsWith(`${prefix}_`))
2202
+ throw explainInput(new SegmentError('SEGMENT_NAME_NOT_STORED'), `Salesforce stores a segment of the data space ${effectiveScope} as ${prefix}_<Name>, so segment ${apiName} would be created as ${prefix}_${apiName} and not be found again under the name of the file. Name the file and identity.apiName ${prefix}_${apiName}, or retrieve the segment.`);
2203
+ }
2204
+ else if (input.document.kind === 'data-transform' &&
2205
+ input.document.c__dataSpace !== effectiveScope)
2206
+ throw dataTransformSpaceMismatch(String(input.document.definition.name), input.document.c__dataSpace, effectiveScope, crossSpaceUnsupported(input.document) ===
2207
+ undefined);
2208
+ else if (input.document.kind === 'native-data-graph' &&
2209
+ input.document.c__dataSpace !== effectiveScope)
2210
+ throw nativeDataGraphSpaceMismatch(String(input.document.definition.name), input.document.c__dataSpace, effectiveScope, 'file', true);
2211
+ else if (input.document.kind === 'identity-resolution') {
2212
+ const { apiName } = input.document.identity;
2213
+ // A file without its data space is not an admitted file (INVALID_SOURCE).
2214
+ if (typeof input.document.c__dataSpace !== 'string')
2215
+ throw new Error('Identity resolution file without c__dataSpace');
2216
+ if (input.document.c__dataSpace !== effectiveScope)
2217
+ throw identityResolutionSpaceMismatch(apiName, input.document.c__dataSpace, effectiveScope, 'file', true);
2218
+ // Outside default Salesforce names a ruleset <prefix>_<type>_<rulesetId>: a file name
2219
+ // without the org's prefix could not be read back after its create. Never guessed.
2220
+ if (effectiveScope !== 'default' && prefix === undefined)
2221
+ throw explainInput(new IdentityResolutionError('IDENTITY_RESOLUTION_NAME_NOT_STORED'), `The org's data space list names no prefix for the data space ${effectiveScope}, so the name Salesforce stores for ruleset ${apiName} (<prefix>_<type>_<rulesetId>) cannot be checked. Nothing was sent; check the data space in Data Cloud.`);
2222
+ if (prefix !== undefined && !apiName.startsWith(`${prefix}_`))
2223
+ throw explainInput(new IdentityResolutionError('IDENTITY_RESOLUTION_NAME_NOT_STORED'), `Salesforce names a ruleset of the data space ${effectiveScope} ${prefix}_<type>_<rulesetId>, so ruleset ${apiName} would be stored as ${prefix}_${apiName} and not be found again under the name of the file. Name the file and identity.apiName ${prefix}_${apiName}, or retrieve the ruleset.`);
2224
+ }
2225
+ }
2226
+ catch (error) {
2227
+ return finish('blocked', error instanceof DataStreamError ||
2228
+ error instanceof CalculatedInsightError ||
2229
+ error instanceof SegmentError ||
2230
+ error instanceof DataTransformError ||
2231
+ error instanceof DataGraphError ||
2232
+ error instanceof IdentityResolutionError
2233
+ ? error.code
2234
+ : 'INVALID_SOURCE', error);
2235
+ }
2236
+ // Names unique in the org (custom DMOs, calculated insights, transforms, graphs) carry the
2237
+ // prefix of their data space. Every selected file is checked locally before the first
2238
+ // write of the run; only a name that breaks the rule is read: absent is refused (a create),
2239
+ // present is a warning (an update goes ahead). An org with only default reads nothing here.
2240
+ try {
2241
+ const spaces = await dataSpaceCheckOf(this, async () => {
2242
+ throw new DataSpaceError('TARGET_ORG_REQUIRED');
2243
+ }).entries();
2244
+ for (const input of resolvedInputs) {
2245
+ const { document } = input;
2246
+ const named = document.kind === 'dmo'
2247
+ ? { type: 'dmo', name: document.identity.apiName }
2248
+ : document.kind === 'calculated-insight'
2249
+ ? { type: 'calculated-insight', name: document.identity.apiName }
2250
+ : document.kind === 'data-transform'
2251
+ ? { type: 'data-transform', name: String(document.definition.name) }
2252
+ : document.kind === 'native-data-graph'
2253
+ ? { type: 'data-graph', name: String(document.definition.name) }
2254
+ : undefined;
2255
+ if (!named || !prefixRuleCoversName(named.type, named.name))
2256
+ continue;
2257
+ // A DMO file of another data space is refused in its own stage, before any write.
2258
+ if (document.kind === 'dmo' && document.c__dataSpace !== effectiveScope)
2259
+ continue;
2260
+ const mismatch = prefixMismatch(named.name, named.type, effectiveScope, spaces);
2261
+ if (!mismatch)
2262
+ continue;
2263
+ const read = await this.readPrefixTarget(named.type, named.name, effectiveScope, flags['target-org']);
2264
+ if (read === undefined)
2265
+ throw prefixMismatchError(mismatch);
2266
+ if (prefixRuleCoversRead(named.type, read.native)) {
2267
+ const warning = prefixMismatchWarning(mismatch);
2268
+ prefixWarnings.add(warning);
2269
+ envelope.diagnostics.warnings.push(warning);
2270
+ }
2271
+ }
2272
+ }
2273
+ catch (error) {
2274
+ return finish('blocked', dataSpaceCheckCode(error, 'PREFLIGHT_FAILED'), error);
2275
+ }
2276
+ // A Waterfall names child segments that must exist in the target or be selected. Its own
2277
+ // stage may follow writing stages, so the children it does not find in the selection are
2278
+ // read (read-only) before the first stage: a missing one stops the run before any write.
2279
+ // Selection matches the exact name, as the child read in the Waterfall's own stage does.
2280
+ const selectedSegments = new Set(resolvedInputs
2281
+ .filter((input) => input.document.kind === 'segment')
2282
+ .map((input) => String(input.document.identity?.apiName)));
2283
+ const waterfalls = resolvedInputs.flatMap((input) => {
2284
+ if (input.document.kind !== 'segment')
2285
+ return [];
2286
+ const document = input.document;
2287
+ // The family checks refuse a malformed file later; only a listed name is read here.
2288
+ const listed = document.spec?.childSegments;
2289
+ const unselected = (Array.isArray(listed) ? listed : []).filter((child) => typeof child === 'string' && !selectedSegments.has(child));
2290
+ return unselected.length > 0
2291
+ ? [
2292
+ {
2293
+ input,
2294
+ document: { ...document, spec: { ...document.spec, childSegments: unselected } },
2295
+ },
2296
+ ]
2297
+ : [];
2298
+ });
2299
+ if (waterfalls.length > 0) {
2300
+ const org = await this.resolveTargetOrg(flags['target-org']);
2301
+ if (!org)
2302
+ return finish('blocked', 'TARGET_ORG_REQUIRED');
2303
+ envelope.provenance.targetOrgId = org.getOrgId();
2304
+ const receiver = Object.create(org.getConnection('68.0'));
2305
+ Object.defineProperty(receiver, 'version', { value: '68.0' });
2306
+ Object.defineProperty(receiver, 'getApiVersion', { value: () => '68.0' });
2307
+ Object.defineProperty(receiver, '_refreshDelegate', { value: undefined });
2308
+ for (const { input, document } of waterfalls) {
2309
+ try {
2310
+ await this.bindChildSegments(document, receiver, '68.0');
2311
+ }
2312
+ catch (error) {
2313
+ const code = error instanceof SegmentError ? error.code : 'SEGMENT_DEPENDENCY_ACQUISITION_FAILED';
2314
+ const diagnostics = [
2315
+ {
2316
+ code,
2317
+ message: operationDiagnostic(error, 'The child segments of this Waterfall were checked before any write; nothing was written.'),
2318
+ },
2319
+ ];
2320
+ envelope.result.items.push((flags.preview
2321
+ ? {
2322
+ family: 'segment',
2323
+ identity: reportedIdentity(document, effectiveScope),
2324
+ operation: 'preview',
2325
+ path: input.path,
2326
+ outcome: 'blocked',
2327
+ target: 'unknown',
2328
+ absenceProof: 'none',
2329
+ diagnostics,
2330
+ }
2331
+ : {
2332
+ family: 'segment',
2333
+ identity: reportedIdentity(document, effectiveScope),
2334
+ operation: 'execute',
2335
+ path: input.path,
2336
+ outcome: 'blocked',
2337
+ mutation: 'not-attempted',
2338
+ diagnostics,
2339
+ }));
2340
+ return finish('blocked', flags.preview ? 'DEPLOY_PREVIEW_BLOCKED' : 'DEPLOY_EXECUTION_BLOCKED');
2341
+ }
2342
+ }
2343
+ }
2344
+ // Preview runs every stage read-only, even after a blocked one; execution stops there.
2345
+ const outcome = await runCrudStages(stages, async (stage, planned) => stage.phase === 'P0'
2346
+ ? runStreamStage(stage.inputs)
2347
+ : stage.phase === 'P1'
2348
+ ? runNativeStage(stage.inputs, planned)
2349
+ : stage.phase === 'P2'
2350
+ ? runTransformsStage(stage.inputs, planned)
2351
+ : stage.phase === 'P4'
2352
+ ? runGraphStage(stage.inputs, planned)
2353
+ : runBatchStage(stage.inputs, planned), { continueAfterBlocked: flags.preview });
2354
+ // Each translated item that deployed gets its copy file, only now and only to a new path.
2355
+ if (crossPlan && envelope.result.crossDataSpace && !flags.preview) {
2356
+ const copies = [];
2357
+ for (const input of crossPlan.inputs) {
2358
+ if (!crossPlan.files.some((entry) => entry.path === input.path))
2359
+ continue;
2360
+ const item = envelope.result.items.find((entry) => entry.path === input.path && entry.operation === 'execute');
2361
+ if (!item ||
2362
+ !['created', 'updated', 'unchanged'].includes(String(item.outcome)) ||
2363
+ item.mutation === 'unknown')
2364
+ continue;
2365
+ const copy = await writeCopyFile(input, input.document.kind === 'relationship' ? item.targetApiName : undefined, mappingTargets.get(input.path));
2366
+ if (copy)
2367
+ copies.push(copy);
2368
+ // A copy that was not written does not fail the deploy; --json still shows it.
2369
+ if (copy?.outcome === 'not-written')
2370
+ envelope.diagnostics.warnings.push(`Copy file not written for ${shown(copy.source)}: ${copy.reason ?? 'unknown reason'}.`);
2371
+ }
2372
+ envelope.result.crossDataSpace.copies = copies;
2373
+ }
2374
+ return finish(outcome.status, outcome.code, outcome.error);
201
2375
  }
202
2376
  catch (error) {
203
- if (error instanceof DeployInputError)
2377
+ if (error instanceof GitSelectionError) {
2378
+ envelope.diagnostics.errors.push({
2379
+ code: error.code,
2380
+ message: error.code === 'BLOCKED_GIT_LIFECYCLE'
2381
+ ? 'Git selection blocks renames, conflicts, unstaged or unidentifiable deletions of plugin files, half-deleted calculated insight pairs and a relevant untracked addition combined with any tracked worktree deletion. Stage intended changes to permit Git-inferred rename detection, then resolve unsupported lifecycle changes. Git cannot guarantee historical rename intent.'
2382
+ : 'Git selection failed. Use a valid commit reference and canonical files under data360/ (DLO, DMO, mapping, relationship, data stream, data transform, data graph, identity resolution, calculated insight, Segment JSON and SQL) with matching identities and unchanged admitted bytes.',
2383
+ retryable: false,
2384
+ });
2385
+ return finish('blocked');
2386
+ }
2387
+ if (error instanceof NativeDmoError ||
2388
+ error instanceof NativeMappingError ||
2389
+ error instanceof NativeRelationshipError)
2390
+ return finish('blocked', error.code, error);
2391
+ // A named verbatim file names its kind, name and reason; an invalid authored file its key.
2392
+ if (error instanceof DeployInputError &&
2393
+ (error.code === 'VERBATIM_NOT_DEPLOYABLE' || explanationOf(error) !== undefined))
2394
+ return finish('blocked', error.code, error);
2395
+ if (error instanceof DeployInputError || error instanceof DependencySelectionError)
204
2396
  return finish('blocked', error.code);
205
- return finish('failed', flags.preview ? 'DEPLOY_PREVIEW_FAILED' : 'DEPLOY_EXECUTION_FAILED');
2397
+ return finish('failed', flags.preview ? 'DEPLOY_PREVIEW_FAILED' : 'DEPLOY_EXECUTION_FAILED', error);
206
2398
  }
207
2399
  }
208
2400
  }