sf-plugin-data 0.1.0 → 0.3.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 (277) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +618 -240
  3. package/docs/artifact-format.md +528 -633
  4. package/docs/capabilities.md +1160 -168
  5. package/docs/git-workflow.md +135 -12
  6. package/docs/handover.md +7826 -12
  7. package/lib/api.d.ts +13 -0
  8. package/lib/api.js +10 -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 +2347 -0
  75. package/lib/commands/data360/deploy.d.ts +235 -16
  76. package/lib/commands/data360/deploy.js +2339 -102
  77. package/lib/commands/data360/list/dataspace.d.ts +53 -0
  78. package/lib/commands/data360/list/dataspace.js +109 -0
  79. package/lib/commands/data360/publish.d.ts +93 -0
  80. package/lib/commands/data360/publish.js +298 -0
  81. package/lib/commands/data360/retrieve.d.ts +283 -14
  82. package/lib/commands/data360/retrieve.js +1945 -95
  83. package/lib/commands/data360/segment/members/export.d.ts +101 -0
  84. package/lib/commands/data360/segment/members/export.js +320 -0
  85. package/lib/errors/codes/calculated-insight.d.ts +2 -0
  86. package/lib/errors/codes/calculated-insight.js +25 -0
  87. package/lib/errors/codes/data-graph.d.ts +2 -0
  88. package/lib/errors/codes/data-graph.js +22 -0
  89. package/lib/errors/codes/data-stream.d.ts +2 -0
  90. package/lib/errors/codes/data-stream.js +70 -0
  91. package/lib/errors/codes/data-transform.d.ts +2 -0
  92. package/lib/errors/codes/data-transform.js +35 -0
  93. package/lib/errors/codes/dependency.d.ts +2 -0
  94. package/lib/errors/codes/dependency.js +11 -0
  95. package/lib/errors/codes/dlo.d.ts +2 -0
  96. package/lib/errors/codes/dlo.js +31 -0
  97. package/lib/errors/codes/dmo.d.ts +2 -0
  98. package/lib/errors/codes/dmo.js +28 -0
  99. package/lib/errors/codes/general.d.ts +2 -0
  100. package/lib/errors/codes/general.js +58 -0
  101. package/lib/errors/codes/identity-resolution.d.ts +2 -0
  102. package/lib/errors/codes/identity-resolution.js +24 -0
  103. package/lib/errors/codes/mapping.d.ts +2 -0
  104. package/lib/errors/codes/mapping.js +42 -0
  105. package/lib/errors/codes/relationship.d.ts +2 -0
  106. package/lib/errors/codes/relationship.js +21 -0
  107. package/lib/errors/codes/segment.d.ts +2 -0
  108. package/lib/errors/codes/segment.js +49 -0
  109. package/lib/errors/registry.d.ts +60 -0
  110. package/lib/errors/registry.js +123 -0
  111. package/lib/exit-code.d.ts +10 -0
  112. package/lib/exit-code.js +24 -0
  113. package/lib/plugin.d.ts +1 -0
  114. package/lib/plugin.js +3 -1
  115. package/lib/services/acquire-retrieve-selection.d.ts +43 -0
  116. package/lib/services/acquire-retrieve-selection.js +145 -0
  117. package/lib/services/bind-identity-resolution-dependencies.d.ts +53 -0
  118. package/lib/services/bind-identity-resolution-dependencies.js +238 -0
  119. package/lib/services/bind-segment-dependencies.d.ts +49 -0
  120. package/lib/services/bind-segment-dependencies.js +115 -0
  121. package/lib/services/bounded-reads.d.ts +17 -0
  122. package/lib/services/bounded-reads.js +42 -0
  123. package/lib/services/calculated-insight-sql-checks.d.ts +33 -0
  124. package/lib/services/calculated-insight-sql-checks.js +193 -0
  125. package/lib/services/command-dlo.d.ts +48 -0
  126. package/lib/services/command-dlo.js +103 -0
  127. package/lib/services/command-native-data-graph.d.ts +54 -0
  128. package/lib/services/command-native-data-graph.js +485 -0
  129. package/lib/services/command-native-data-stream.d.ts +104 -0
  130. package/lib/services/command-native-data-stream.js +257 -0
  131. package/lib/services/command-native-dmo.d.ts +124 -0
  132. package/lib/services/command-native-dmo.js +338 -0
  133. package/lib/services/command-native-mapping.d.ts +65 -0
  134. package/lib/services/command-native-mapping.js +129 -0
  135. package/lib/services/command-native-relationship.d.ts +46 -0
  136. package/lib/services/command-native-relationship.js +103 -0
  137. package/lib/services/cross-dataspace-deploy.d.ts +111 -0
  138. package/lib/services/cross-dataspace-deploy.js +493 -0
  139. package/lib/services/cross-dataspace-rename.d.ts +74 -0
  140. package/lib/services/cross-dataspace-rename.js +1314 -0
  141. package/lib/services/cross-dataspace-sql.d.ts +109 -0
  142. package/lib/services/cross-dataspace-sql.js +1301 -0
  143. package/lib/services/cross-space-context.d.ts +23 -0
  144. package/lib/services/cross-space-context.js +38 -0
  145. package/lib/services/crud-plan.d.ts +137 -0
  146. package/lib/services/crud-plan.js +408 -0
  147. package/lib/services/data-space-check.d.ts +92 -0
  148. package/lib/services/data-space-check.js +169 -0
  149. package/lib/services/data-space-prefix.d.ts +77 -0
  150. package/lib/services/data-space-prefix.js +127 -0
  151. package/lib/services/data-transform-space.d.ts +31 -0
  152. package/lib/services/data-transform-space.js +79 -0
  153. package/lib/services/delete-calculated-insight.d.ts +44 -0
  154. package/lib/services/delete-calculated-insight.js +101 -0
  155. package/lib/services/delete-data-transform.d.ts +52 -0
  156. package/lib/services/delete-data-transform.js +222 -0
  157. package/lib/services/delete-dmo-field.d.ts +211 -0
  158. package/lib/services/delete-dmo-field.js +472 -0
  159. package/lib/services/delete-identity-resolution.d.ts +43 -0
  160. package/lib/services/delete-identity-resolution.js +295 -0
  161. package/lib/services/delete-segment.d.ts +42 -0
  162. package/lib/services/delete-segment.js +248 -0
  163. package/lib/services/deploy-result.d.ts +54 -0
  164. package/lib/services/deploy-result.js +60 -0
  165. package/lib/services/escaped-copy.d.ts +23 -0
  166. package/lib/services/escaped-copy.js +88 -0
  167. package/lib/services/execute-calculated-insight-deploy.d.ts +42 -0
  168. package/lib/services/execute-calculated-insight-deploy.js +96 -0
  169. package/lib/services/execute-data-transform-deploy.d.ts +56 -0
  170. package/lib/services/execute-data-transform-deploy.js +168 -0
  171. package/lib/services/execute-native-identity-resolution-deploy.d.ts +48 -0
  172. package/lib/services/execute-native-identity-resolution-deploy.js +360 -0
  173. package/lib/services/execute-segment-deploy.d.ts +45 -0
  174. package/lib/services/execute-segment-deploy.js +393 -0
  175. package/lib/services/list-data-spaces.d.ts +17 -0
  176. package/lib/services/list-data-spaces.js +24 -0
  177. package/lib/services/local-file-removal.d.ts +36 -0
  178. package/lib/services/local-file-removal.js +103 -0
  179. package/lib/services/native-calculated-insight.d.ts +87 -0
  180. package/lib/services/native-calculated-insight.js +164 -0
  181. package/lib/services/native-crm-data-stream.d.ts +91 -0
  182. package/lib/services/native-crm-data-stream.js +272 -0
  183. package/lib/services/native-data-graph-context.d.ts +12 -0
  184. package/lib/services/native-data-graph-context.js +139 -0
  185. package/lib/services/native-data-graph-crd.d.ts +261 -0
  186. package/lib/services/native-data-graph-crd.js +866 -0
  187. package/lib/services/native-data-stream.d.ts +329 -0
  188. package/lib/services/native-data-stream.js +1830 -0
  189. package/lib/services/native-dlo.d.ts +163 -0
  190. package/lib/services/native-dlo.js +402 -0
  191. package/lib/services/native-dmo.d.ts +191 -0
  192. package/lib/services/native-dmo.js +614 -0
  193. package/lib/services/native-mapping.d.ts +255 -0
  194. package/lib/services/native-mapping.js +1226 -0
  195. package/lib/services/native-relationship.d.ts +132 -0
  196. package/lib/services/native-relationship.js +512 -0
  197. package/lib/services/operation-diagnostic.d.ts +83 -0
  198. package/lib/services/operation-diagnostic.js +272 -0
  199. package/lib/services/preflight-calculated-insight-deploy.d.ts +58 -0
  200. package/lib/services/preflight-calculated-insight-deploy.js +95 -0
  201. package/lib/services/preflight-data-transform-deploy.d.ts +33 -0
  202. package/lib/services/preflight-data-transform-deploy.js +104 -0
  203. package/lib/services/preflight-identity-resolution-deploy.d.ts +107 -0
  204. package/lib/services/preflight-identity-resolution-deploy.js +281 -0
  205. package/lib/services/preflight-segment-deploy.d.ts +31 -0
  206. package/lib/services/preflight-segment-deploy.js +109 -0
  207. package/lib/services/publish-calculated-insight.d.ts +40 -0
  208. package/lib/services/publish-calculated-insight.js +95 -0
  209. package/lib/services/publish-segment.d.ts +65 -0
  210. package/lib/services/publish-segment.js +194 -0
  211. package/lib/services/readback-pace.d.ts +16 -0
  212. package/lib/services/readback-pace.js +23 -0
  213. package/lib/services/retrieve-data-transform.d.ts +26 -0
  214. package/lib/services/retrieve-data-transform.js +65 -0
  215. package/lib/services/retrieve-identity-resolution.d.ts +40 -0
  216. package/lib/services/retrieve-identity-resolution.js +87 -0
  217. package/lib/services/retrieve-inventory.d.ts +32 -0
  218. package/lib/services/retrieve-inventory.js +151 -0
  219. package/lib/services/retrieve-segment.d.ts +120 -0
  220. package/lib/services/retrieve-segment.js +502 -0
  221. package/lib/services/run-retrieve.d.ts +24 -0
  222. package/lib/services/run-retrieve.js +51 -0
  223. package/lib/services/segment-lookup.d.ts +46 -0
  224. package/lib/services/segment-lookup.js +108 -0
  225. package/lib/services/segment-members.d.ts +144 -0
  226. package/lib/services/segment-members.js +402 -0
  227. package/lib/services/select-native-retrieve.d.ts +60 -0
  228. package/lib/services/select-native-retrieve.js +226 -0
  229. package/lib/services/settle-calculated-insight.d.ts +22 -0
  230. package/lib/services/settle-calculated-insight.js +53 -0
  231. package/lib/services/sql-tokens.d.ts +58 -0
  232. package/lib/services/sql-tokens.js +147 -0
  233. package/lib/transport/api-version.d.ts +36 -0
  234. package/lib/transport/api-version.js +89 -0
  235. package/lib/transport/bound-ssot.d.ts +27 -0
  236. package/lib/transport/bound-ssot.js +116 -0
  237. package/lib/transport/calculated-insight-rest.d.ts +28 -0
  238. package/lib/transport/calculated-insight-rest.js +62 -0
  239. package/lib/transport/connect-client.d.ts +94 -32
  240. package/lib/transport/connect-client.js +318 -178
  241. package/lib/transport/connect-diagnostic.d.ts +89 -0
  242. package/lib/transport/connect-diagnostic.js +331 -0
  243. package/lib/transport/data-graph-rest.d.ts +27 -0
  244. package/lib/transport/data-graph-rest.js +76 -0
  245. package/lib/transport/data-stream-rest.d.ts +62 -0
  246. package/lib/transport/data-stream-rest.js +348 -0
  247. package/lib/transport/data-transform-rest.d.ts +25 -0
  248. package/lib/transport/data-transform-rest.js +100 -0
  249. package/lib/transport/dlo-native-rest.d.ts +22 -0
  250. package/lib/transport/dlo-native-rest.js +89 -0
  251. package/lib/transport/dlo-rest.d.ts +23 -0
  252. package/lib/transport/dlo-rest.js +135 -0
  253. package/lib/transport/dmo-native-rest.d.ts +18 -0
  254. package/lib/transport/dmo-native-rest.js +55 -0
  255. package/lib/transport/dmo-rest.d.ts +30 -0
  256. package/lib/transport/dmo-rest.js +163 -0
  257. package/lib/transport/mapping-rest.d.ts +63 -0
  258. package/lib/transport/mapping-rest.js +341 -0
  259. package/lib/transport/project-metadata.d.ts +36 -0
  260. package/lib/transport/project-metadata.js +118 -0
  261. package/lib/transport/relationship-rest.d.ts +43 -0
  262. package/lib/transport/relationship-rest.js +201 -0
  263. package/package.json +29 -6
  264. package/lib/artifacts/dmo-document.d.ts +0 -181
  265. package/lib/artifacts/dmo-document.js +0 -848
  266. package/lib/artifacts/dmo-update-delta.d.ts +0 -28
  267. package/lib/artifacts/dmo-update-delta.js +0 -86
  268. package/lib/artifacts/write-other-dmo.d.ts +0 -17
  269. package/lib/artifacts/write-other-dmo.js +0 -140
  270. package/lib/services/execute-dmo-create.d.ts +0 -24
  271. package/lib/services/execute-dmo-create.js +0 -118
  272. package/lib/services/execute-dmo-deploy.d.ts +0 -33
  273. package/lib/services/execute-dmo-deploy.js +0 -197
  274. package/lib/services/preflight-dmo-deploy.d.ts +0 -69
  275. package/lib/services/preflight-dmo-deploy.js +0 -161
  276. package/lib/services/retrieve-other-dmo.d.ts +0 -46
  277. package/lib/services/retrieve-other-dmo.js +0 -140
@@ -0,0 +1,1226 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { refuseEscapedCopy } from './escaped-copy.js';
3
+ import { paceReadback, readbackPace } from './readback-pace.js';
4
+ import { explainMismatch, explainSpaceMismatch, replaceExplanation, } from './operation-diagnostic.js';
5
+ import { NativeMappingError, nativeMappingName, normalizeNativeMapping, unwrapNativeMappingCollection, validateNativeMappingDocument, } from '../artifacts/native-mapping-document.js';
6
+ import { normalizeDlo } from '../artifacts/dlo-document.js';
7
+ import { NativeDmoError, isGeneratedDmoField, nativeDmoWriteScope, standardCopyFieldName, standardCopyOrigin, normalizeNativeDmo, unwrapNativeDmo, } from '../artifacts/native-dmo-document.js';
8
+ import { mappingReadBatch, metadataRecords } from '../transport/mapping-rest.js';
9
+ import { getConnectDiagnostic, retainConnectDiagnostic } from '../transport/connect-diagnostic.js';
10
+ const systemSourceFields = new Set([
11
+ 'DataSource__c',
12
+ 'DataSourceObject__c',
13
+ 'InternalOrganization__c',
14
+ ]);
15
+ const keyQualifierField = /^KQ_(\w+)__c$/u;
16
+ /**
17
+ * Recognise a pair Salesforce generates for a system field on a standard DMO. The target field is
18
+ * the source's namesake or `ssot__<Name>Id__c` (`<Name>Id__c` outside the default data space,
19
+ * where a standard DMO copy's fields drop `ssot__`). A target field read as System qualifies any
20
+ * such pair; otherwise only the three known system sources onto their standard-named field do.
21
+ * @param {DloField} from Source field.
22
+ * @param {NativeDmoField} to Target field.
23
+ * @param {boolean} copy The mapping is outside the default data space (a standard DMO copy).
24
+ * @returns {boolean} Whether the pair is generated, not authored.
25
+ */
26
+ function isStandardSystemPair(from, to, copy) {
27
+ if (from.isPrimaryKey || to.isPrimaryKey || keyQualifierField.test(from.name))
28
+ return false;
29
+ const base = `${from.name.slice(0, -'__c'.length)}Id__c`;
30
+ const named = to.name === `ssot__${base}` || (copy && to.name === base);
31
+ if (to.creationType === 'System')
32
+ return named || to.name === from.name;
33
+ return named && systemSourceFields.has(from.name) && to.creationType === 'Standard';
34
+ }
35
+ /**
36
+ * Recognise the generated key qualifier pair of a standard DMO: `KQ_<Key>__c` on both sides,
37
+ * where `<Key>__c` is the source primary key. With a target field it must be a System field that
38
+ * a target primary key names as its qualifier; without one (the DMO has never been mapped) the
39
+ * target only needs a primary key, because Salesforce adds the field with the first mapping.
40
+ * @param {NativeMappingField} pair Mapping pair.
41
+ * @param {Map<string, DloField>} sources Source fields by name.
42
+ * @param {Map<string, NativeDmoField>} targets Target fields by name.
43
+ * @returns {boolean} Whether the pair is generated, not authored.
44
+ */
45
+ function isStandardKeyQualifierPair(pair, sources, targets) {
46
+ const match = keyQualifierField.exec(pair.sourceFieldDeveloperName);
47
+ if (!match || pair.targetFieldDeveloperName !== pair.sourceFieldDeveloperName)
48
+ return false;
49
+ if (!sources.get(`${match[1]}__c`)?.isPrimaryKey)
50
+ return false;
51
+ const to = targets.get(pair.targetFieldDeveloperName);
52
+ const keys = [...targets.values()].filter((field) => field.isPrimaryKey);
53
+ if (!to)
54
+ return keys.length > 0;
55
+ return (to.creationType === 'System' &&
56
+ keys.some((field) => field.keyQualifierName === `KQ_${match[1]}`));
57
+ }
58
+ /**
59
+ * Recognise a pair Salesforce generates on a custom DMO: a system field onto its namesake, or
60
+ * the key qualifier of a target field. Salesforce adds one for the primary key and one for a field
61
+ * that a relationship uses as its source (`KQ_RefId__c` for `RefId__c`, live API 68); the
62
+ * target field names it in `keyQualifierName`.
63
+ * @param {DloField} from Source field.
64
+ * @param {NativeDmoField} to Target field.
65
+ * @param {Map<string, DloField>} sources Source fields by name.
66
+ * @param {Map<string, NativeDmoField>} targets Target fields by name.
67
+ * @returns {boolean} Whether the pair is generated, not authored.
68
+ */
69
+ function isCustomGeneratedPair(from, to, sources, targets) {
70
+ if (from.name !== to.name)
71
+ return false;
72
+ if (systemSourceFields.has(to.name) &&
73
+ to.creationType === 'System' &&
74
+ !from.isPrimaryKey &&
75
+ !to.isPrimaryKey)
76
+ return true;
77
+ const qualifier = keyQualifierField.exec(to.name);
78
+ if (!qualifier || to.creationType !== 'System' || to.usageTag !== 'KeyQualifier')
79
+ return false;
80
+ // The qualifier belongs to a target field that names it, whatever its name and type.
81
+ return ([...sources.values()].some((field) => field.isPrimaryKey) &&
82
+ [...targets.values()].some((field) => field.keyQualifierName === `KQ_${qualifier[1]}`));
83
+ }
84
+ /**
85
+ * Recognise the key qualifier pair Salesforce adds when a relationship uses a non-key target
86
+ * field as its source: `KQ_<S>__c -> <Q>__c`, where `<Q>__c` is a System KeyQualifier field that a target
87
+ * field names in `keyQualifierName` and the mapping maps `<S>__c` onto that naming field. The two
88
+ * names differ (`KQ_RefId__c -> KQ_Name__c` for `RefId__c -> ssot__Name__c`). Only this
89
+ * standard-DMO shape was seen live (API 68); the custom-DMO case is assumed by analogy.
90
+ * @param {NativeMappingField} pair Mapping pair.
91
+ * @param {MappingPairContext} context Fresh fields and the mapping's own pairs.
92
+ * @returns {boolean} Whether the pair is generated, not authored.
93
+ */
94
+ function isMappedFieldQualifierPair(pair, context) {
95
+ const source = keyQualifierField.exec(pair.sourceFieldDeveloperName);
96
+ const to = context.targets.get(pair.targetFieldDeveloperName);
97
+ if (!source || to?.creationType !== 'System' || to.usageTag !== 'KeyQualifier')
98
+ return false;
99
+ const qualifier = pair.targetFieldDeveloperName.slice(0, -'__c'.length);
100
+ return [...context.targets.values()].some((field) => field.keyQualifierName === qualifier &&
101
+ context.pairs.some((other) => other.sourceFieldDeveloperName === `${source[1]}__c` &&
102
+ other.targetFieldDeveloperName === field.name));
103
+ }
104
+ /**
105
+ * Recognise the authored primary-key pair that is never unmapped: the source primary key onto
106
+ * the target primary key, read from the org's flags, whatever their names and types.
107
+ * @param {DloField} from Source field.
108
+ * @param {NativeDmoField} to Target field.
109
+ * @returns {boolean} Whether the pair is the key pair.
110
+ */
111
+ function isKeyPair(from, to) {
112
+ return from.isPrimaryKey === true && to.isPrimaryKey === true;
113
+ }
114
+ /**
115
+ * Compare logical pairs without treating source selectors as portable target identity.
116
+ * @param {NativeMappingField} field Mapping pair.
117
+ * @returns {string} Exact logical pair key.
118
+ */
119
+ function pairKey(field) {
120
+ return `${field.sourceFieldDeveloperName}:${field.targetFieldDeveloperName}`;
121
+ }
122
+ /**
123
+ * Verify the logical binding independently of a server-generated mapping name.
124
+ * @param {NativeMappingDocument} expected Requested binding.
125
+ * @param {NativeMappingDocument} actual Target response.
126
+ */
127
+ function checkBinding(expected, actual) {
128
+ if (expected.c__dataSpace !== actual.c__dataSpace ||
129
+ expected.spec.sourceEntityDeveloperName !== actual.spec.sourceEntityDeveloperName ||
130
+ expected.spec.targetEntityDeveloperName !== actual.spec.targetEntityDeveloperName)
131
+ throw explainMismatch(new NativeMappingError('MAPPING_TARGET_BINDING_MISMATCH'), 'mapping binding readback', expected.identity.apiName, {
132
+ dataSpace: expected.c__dataSpace,
133
+ sourceEntityDeveloperName: expected.spec.sourceEntityDeveloperName,
134
+ targetEntityDeveloperName: expected.spec.targetEntityDeveloperName,
135
+ }, {
136
+ dataSpace: actual.c__dataSpace,
137
+ sourceEntityDeveloperName: actual.spec.sourceEntityDeveloperName,
138
+ targetEntityDeveloperName: actual.spec.targetEntityDeveloperName,
139
+ });
140
+ }
141
+ /**
142
+ * Resolve a unique exact pair through filtered inventory, never source-name 404 fallback.
143
+ * Deploy and delete both find the org mapping of an authored file this way, by its binding.
144
+ * @param {NativeMappingDocument} desired Logical binding.
145
+ * @param {MappingClient} client Target mapping transport.
146
+ * @returns {Promise<NativeMappingDocument | undefined>} Verified detail or confirmed absence.
147
+ */
148
+ export async function resolveNativeMappingTarget(desired, client) {
149
+ let response;
150
+ try {
151
+ response = await client.list(desired.spec.targetEntityDeveloperName, desired.spec.sourceEntityDeveloperName);
152
+ }
153
+ catch (error) {
154
+ if (error instanceof NativeMappingError &&
155
+ error.code === 'MAPPING_HTTP_ERROR' &&
156
+ error.status === 404)
157
+ return;
158
+ throw error;
159
+ }
160
+ // The retained contract has exactly this wrapper and no pagination mechanism.
161
+ if (!response || typeof response !== 'object' || Object.keys(response).length !== 1)
162
+ throw new NativeMappingError('MAPPING_INVENTORY_UNCONFIRMED');
163
+ const entries = unwrapNativeMappingCollection(response, desired.c__dataSpace).map((entry) => normalizeNativeMapping(entry, desired.c__dataSpace));
164
+ for (const entry of entries)
165
+ checkBinding(desired, entry);
166
+ if (entries.length > 1)
167
+ throw new NativeMappingError('AMBIGUOUS_MAPPING_TARGET');
168
+ if (entries.length === 0)
169
+ return;
170
+ const raw = await client.get(entries[0].identity.apiName);
171
+ const document = normalizeNativeMapping(raw, desired.c__dataSpace);
172
+ if (raw.status !== 'ACTIVE')
173
+ throw new NativeMappingError('MAPPING_TARGET_NOT_SETTLED');
174
+ checkBinding(desired, document);
175
+ if (document.identity.apiName !== entries[0].identity.apiName)
176
+ throw new NativeMappingError('MAPPING_TARGET_IDENTITY_MISMATCH');
177
+ return document;
178
+ }
179
+ /**
180
+ * Whether a pair of an existing mapping is one Salesforce generated. This one predicate decides
181
+ * both which org pairs a deploy keeps when the file does not list them and which pairs a
182
+ * retrieve leaves out of the file, so the two cannot diverge. A pair whose source or target
183
+ * field is not read is never generated.
184
+ * @param {NativeMappingField} pair Mapping pair.
185
+ * @param {MappingPairContext} context Fresh source and target fields.
186
+ * @returns {boolean} Whether the pair is generated, not authored.
187
+ */
188
+ export function isGeneratedMappingPair(pair, context) {
189
+ const { sources, targets } = context;
190
+ const from = sources.get(pair.sourceFieldDeveloperName);
191
+ const to = targets.get(pair.targetFieldDeveloperName);
192
+ if (!from || !to)
193
+ return false;
194
+ if (isMappedFieldQualifierPair(pair, context))
195
+ return true;
196
+ return context.standard
197
+ ? isStandardSystemPair(from, to, context.copy === true) ||
198
+ isStandardKeyQualifierPair(pair, sources, targets)
199
+ : isCustomGeneratedPair(from, to, sources, targets);
200
+ }
201
+ /**
202
+ * The default spelling to read when a mapping's target DMO reads 404 in a non-default data space:
203
+ * `ssot__<Name>__dlm` for a target `<prefix>_<Name>__dlm`, where `<prefix>` is the prefix the
204
+ * org's data space list names for the run's data space. Anything else (another failure, the
205
+ * default data space, no prefix, a name without it) is undefined: nothing is guessed.
206
+ * @param {NativeMappingDocument} desired Mapping file.
207
+ * @param {MappingDependencies} dependencies Readers and the data space prefix.
208
+ * @param {unknown} error Failure of the target read.
209
+ * @returns {string | undefined} The default spelling to read, or undefined.
210
+ */
211
+ function activationSpelling(desired, dependencies, error) {
212
+ if (!(error instanceof NativeDmoError) || error.code !== 'DMO_HTTP_ERROR' || error.status !== 404)
213
+ return undefined;
214
+ return standardCopyOrigin(desired.spec.targetEntityDeveloperName, desired.c__dataSpace, dependencies.dataSpacePrefix);
215
+ }
216
+ /**
217
+ * Add to an existing standard DMO copy the fields of its default spelling that the mapping names
218
+ * but the copy does not have yet: a copy holds only mapped fields, and Salesforce adds a field
219
+ * to it when a mapping names it (live API 68, MiddleName__c took the copy from 7 to 8 fields).
220
+ * Only a copy (non-default data space, the space's prefix, creationType Standard) whose default
221
+ * spelling reads as a Standard DMO of the default data space is extended; anything else is left
222
+ * as read, so the pair is refused as before.
223
+ * @param {NativeMappingDocument} desired Mapping file.
224
+ * @param {MappingDependencies} dependencies Readers and the data space prefix.
225
+ * @param {Record<string, unknown>} rawTarget The copy as read.
226
+ * @param {NativeDmoDocument} target The copy's document.
227
+ * @param {DocumentMode} mode Read mode.
228
+ * @returns {Promise<NativeDmoDocument>} The copy, with the default object's missing fields.
229
+ */
230
+ async function withOriginFields(desired, dependencies, rawTarget, target, mode) {
231
+ const present = new Set(target.spec.fields.map((field) => field.name));
232
+ const missing = desired.spec.fieldMappings.some((pair) => !present.has(pair.targetFieldDeveloperName));
233
+ const spelling = standardCopyOrigin(desired.spec.targetEntityDeveloperName, desired.c__dataSpace, dependencies.dataSpacePrefix);
234
+ if (!missing || spelling === undefined || rawTarget.creationType !== 'Standard')
235
+ return target;
236
+ let original;
237
+ try {
238
+ const raw = unwrapNativeDmo(await dependencies.target.get(spelling));
239
+ original = normalizeNativeDmo(raw, 'default', mode);
240
+ if (original.identity.apiName !== spelling || raw.creationType !== 'Standard')
241
+ return target;
242
+ }
243
+ catch {
244
+ return target;
245
+ }
246
+ const added = original.spec.fields
247
+ .map((field) => ({ ...field, name: standardCopyFieldName(field.name) }))
248
+ .filter((field) => !present.has(field.name));
249
+ return { ...target, spec: { ...target.spec, fields: [...target.spec.fields, ...added] } };
250
+ }
251
+ /**
252
+ * Read the source DLO and target DMO of a mapping fresh and check their identity.
253
+ * @param {NativeMappingDocument} desired Mapping whose binding names both.
254
+ * @param {MappingDependencies} dependencies Fresh source and target readers.
255
+ * @param {DocumentMode} [mode] `retrieve` reads both parents leniently; a field without a text
256
+ * name is then left out of the maps, so no pair can match it.
257
+ * In deploy mode, a target that reads 404 in a non-default data space whose default spelling
258
+ * exists ({@link activationSpelling}) is a standard DMO copy that its first mapping creates: its
259
+ * fields are read from the default spelling under the copy's names, and `activation` says how to
260
+ * send the create with the default spelling.
261
+ * @returns {Promise<object>} Field maps, write scope, whether a first mapping activates the DMO,
262
+ * and the default spelling of a copy that does not exist yet.
263
+ */
264
+ async function readMappingParents(desired, dependencies, mode = 'deploy') {
265
+ const source = normalizeDlo(await dependencies.source.get(desired.spec.sourceEntityDeveloperName), desired.c__dataSpace, mode);
266
+ if (
267
+ // normalizeDlo already required the mapping's data space among the DLO's spaces.
268
+ !source.c__dataSpace.includes(desired.c__dataSpace) ||
269
+ source.identity.apiName !== desired.spec.sourceEntityDeveloperName)
270
+ throw new NativeMappingError('MAPPING_DEPENDENCY_IDENTITY_MISMATCH');
271
+ let rawTarget;
272
+ let activation;
273
+ let target;
274
+ try {
275
+ rawTarget = unwrapNativeDmo(await dependencies.target.get(desired.spec.targetEntityDeveloperName));
276
+ target = normalizeNativeDmo(rawTarget, desired.c__dataSpace, mode);
277
+ if (target.c__dataSpace !== desired.c__dataSpace ||
278
+ target.identity.apiName !== desired.spec.targetEntityDeveloperName)
279
+ throw new NativeMappingError('MAPPING_DEPENDENCY_IDENTITY_MISMATCH');
280
+ if (mode === 'deploy')
281
+ target = await withOriginFields(desired, dependencies, rawTarget, target, mode);
282
+ }
283
+ catch (error) {
284
+ const spelling = mode === 'deploy' ? activationSpelling(desired, dependencies, error) : undefined;
285
+ if (spelling === undefined)
286
+ throw error;
287
+ // The copy does not exist yet: its default spelling must be a standard DMO of the default
288
+ // data space; its fields are read under the names the copy will have.
289
+ let original;
290
+ try {
291
+ rawTarget = unwrapNativeDmo(await dependencies.target.get(spelling));
292
+ original = normalizeNativeDmo(rawTarget, 'default', mode);
293
+ }
294
+ catch {
295
+ // No standard DMO under the default spelling: the copy's own 404 stands.
296
+ throw error;
297
+ }
298
+ if (original.identity.apiName !== spelling || rawTarget.creationType !== 'Standard')
299
+ throw error;
300
+ activation = { targetEntityDeveloperName: spelling, fields: new Map() };
301
+ const fields = [];
302
+ for (const field of original.spec.fields) {
303
+ const copy = standardCopyFieldName(field.name);
304
+ if (activation.fields.has(copy))
305
+ throw new NativeMappingError('MAPPING_DEPENDENCY_IDENTITY_MISMATCH');
306
+ activation.fields.set(copy, field.name);
307
+ fields.push({ ...field, name: copy });
308
+ }
309
+ target = {
310
+ ...original,
311
+ c__dataSpace: desired.c__dataSpace,
312
+ identity: { apiName: desired.spec.targetEntityDeveloperName },
313
+ spec: { ...original.spec, fields },
314
+ };
315
+ }
316
+ // Every target but an unprefixed custom DMO is mapped within the standard scope; Salesforce
317
+ // answers for the DMOs it does not map onto (it refuses platform-generated ones).
318
+ const standard = nativeDmoWriteScope(rawTarget) === 'standard';
319
+ // The first mapping enables a standard DMO for good; the raw read says whether that is ahead.
320
+ // A copy that does not exist yet is created (and enabled) by it.
321
+ const activates = activation !== undefined ||
322
+ (rawTarget.creationType === 'Standard' && rawTarget.isEnabled !== true);
323
+ return {
324
+ activates,
325
+ ...(activation ? { activation } : {}),
326
+ context: {
327
+ sources: new Map(source.spec.fields
328
+ .filter((field) => typeof field.name === 'string')
329
+ .map((field) => [field.name, field])),
330
+ targets: new Map(target.spec.fields
331
+ .filter((field) => typeof field.name === 'string')
332
+ .map((field) => [field.name, field])),
333
+ standard,
334
+ pairs: structuredClone(desired.spec.fieldMappings),
335
+ copy: desired.c__dataSpace !== 'default',
336
+ },
337
+ };
338
+ }
339
+ /**
340
+ * Name the pairs of a mapping that Salesforce generated, from fresh reads of its source DLO and
341
+ * target DMO, with the same predicate a deploy uses to keep them.
342
+ * @param {NativeMappingDocument} document Mapping as read.
343
+ * @param {MappingDependencies} dependencies Fresh source and target readers.
344
+ * @param {DocumentMode} [mode] `retrieve` reads the parents leniently.
345
+ * @returns {Promise<NativeMappingField[]>} Generated pairs, in document order.
346
+ */
347
+ export async function generatedMappingPairs(document, dependencies, mode = 'deploy') {
348
+ const { context } = await readMappingParents(document, dependencies, mode);
349
+ return document.spec.fieldMappings.filter((pair) => isGeneratedMappingPair(pair, context));
350
+ }
351
+ /**
352
+ * Retrieve one mapping with its authored pairs only: the pairs Salesforce generated are left
353
+ * out, decided by {@link generatedMappingPairs}. When the source DLO or the target DMO cannot be
354
+ * read nothing is guessed: the retrieve is refused, as a file missing a pair a deploy does not
355
+ * recognise as generated would remove it from the org.
356
+ * @param {string} apiName Observed target mapping name.
357
+ * @param {MappingClient} client Target mapping transport.
358
+ * @param {string} requestScope The run's data space.
359
+ * @param {MappingDependencies} [dependencies] Fresh source and target readers; required.
360
+ * @param {DocumentMode} [mode] `retrieve` keeps pairs the plugin cannot deploy, and may leave
361
+ * none; other callers stay strict.
362
+ * @returns {Promise<NativeMappingDocument>} Authored portable definition.
363
+ */
364
+ export async function retrieveLeanNativeMapping(apiName, client, requestScope, dependencies, mode = 'deploy') {
365
+ const document = await retrieveNativeMapping(apiName, client, requestScope, mode);
366
+ let generated;
367
+ try {
368
+ if (!dependencies)
369
+ throw new NativeMappingError('MAPPING_PARENTS_REQUIRED');
370
+ generated = await generatedMappingPairs(document, dependencies, mode);
371
+ }
372
+ catch (error) {
373
+ const refusal = retainConnectDiagnostic(new NativeMappingError('MAPPING_GENERATED_PAIRS_UNPROVEN'), getConnectDiagnostic(error));
374
+ replaceExplanation(refusal, `${apiName} was not saved: its source data lake object ${document.spec.sourceEntityDeveloperName} and target data model object ${document.spec.targetEntityDeveloperName} must be readable to leave out the pairs Salesforce generates${error instanceof Error && 'code' in error ? ` (${String(error.code)})` : ''}. Nothing was written for it.`);
375
+ throw refusal;
376
+ }
377
+ const omitted = new Set(generated.map((pair) => pairKey(pair)));
378
+ document.spec.fieldMappings = document.spec.fieldMappings.filter((pair) => !omitted.has(pairKey(pair)));
379
+ return document;
380
+ }
381
+ /**
382
+ * The labels (Metadata API masterLabel) of mappings, read in batches of up to 10 names over the
383
+ * bound Connection. Without a Metadata API reader, or for a name without a record, there is none.
384
+ * @param {string[]} names Mapping names.
385
+ * @param {Pick<MappingClient, 'readDefinitions'>} client Mapping reader.
386
+ * @returns {Promise<Map<string, string>>} Label by name.
387
+ */
388
+ export async function readMappingLabels(names, client) {
389
+ const labels = new Map();
390
+ if (names.length === 0 || !client.readDefinitions)
391
+ return labels;
392
+ for (const definition of await client.readDefinitions(names))
393
+ if (typeof definition.masterLabel === 'string' && typeof definition.fullName === 'string')
394
+ labels.set(definition.fullName, definition.masterLabel);
395
+ return labels;
396
+ }
397
+ /**
398
+ * Add the org's label to retrieved mapping documents as `spec.label`, reading up to 10 names per
399
+ * Metadata API call. A label equal to the mapping's own name is the default Salesforce gives a
400
+ * mapping created without one, so it is left out. A failed read leaves the label out of the
401
+ * documents of that batch and returns one warning for the batch; it never fails the retrieve.
402
+ * @param {unknown[]} documents Retrieved documents, changed in place; others are skipped.
403
+ * @param {Pick<MappingClient, 'readDefinitions'>} client Mapping reader.
404
+ * @returns {Promise<string[]>} Warnings for the mappings whose label could not be read.
405
+ */
406
+ export async function labelRetrievedMappings(documents, client) {
407
+ const warnings = [];
408
+ if (!client.readDefinitions)
409
+ return warnings;
410
+ const mappings = documents.filter((document) => {
411
+ const candidate = document;
412
+ return (candidate?.kind === 'mapping' &&
413
+ typeof candidate.identity?.apiName === 'string' &&
414
+ !!candidate.spec &&
415
+ typeof candidate.spec === 'object');
416
+ });
417
+ for (let start = 0; start < mappings.length; start += mappingReadBatch) {
418
+ const batch = mappings.slice(start, start + mappingReadBatch);
419
+ let labels;
420
+ try {
421
+ labels = await readMappingLabels(batch.map((document) => document.identity.apiName), client);
422
+ }
423
+ catch {
424
+ warnings.push(`${batch.map((document) => `mapping:${document.identity.apiName}`).join(', ')}: the label could not be read (Metadata API ObjectSourceTargetMap), so the files leave it out; a deploy of such a file leaves the org's label as it is.`);
425
+ continue;
426
+ }
427
+ for (const document of batch) {
428
+ const label = labels.get(document.identity.apiName);
429
+ if (label !== undefined && label !== '' && label !== document.identity.apiName)
430
+ document.spec.label = label;
431
+ }
432
+ }
433
+ return warnings;
434
+ }
435
+ /**
436
+ * Explain a failed Metadata API read of a mapping record around its label update.
437
+ * @param {string} name Mapping name.
438
+ * @param {string} when What the read was for.
439
+ * @returns {NativeMappingError} MAPPING_LABEL_READ_FAILED with an explanation.
440
+ */
441
+ function labelReadFailed(name, when) {
442
+ const error = new NativeMappingError('MAPPING_LABEL_READ_FAILED');
443
+ replaceExplanation(error, `The Metadata API read of the ObjectSourceTargetMap ${name} ${when} failed, so the label update was not sent.`);
444
+ return error;
445
+ }
446
+ /**
447
+ * Read one mapping record through the Metadata API.
448
+ * @param {string} name Mapping name.
449
+ * @param {Pick<MappingClient, 'readDefinitions'>} client Mapping reader.
450
+ * @returns {Promise<Record<string, unknown> | undefined>} The record, or undefined.
451
+ */
452
+ async function readMappingDefinition(name, client) {
453
+ if (!client.readDefinitions)
454
+ return undefined;
455
+ const definitions = await client.readDefinitions([name]);
456
+ return definitions.find((entry) => entry.fullName === name);
457
+ }
458
+ /**
459
+ * Whether a Metadata API value is an explicit nil (`xsi:nil`), which a write must not send back.
460
+ * @param {unknown} value Record value.
461
+ * @returns {boolean} Explicit nil.
462
+ */
463
+ function metadataNil(value) {
464
+ if (!value || typeof value !== 'object' || Array.isArray(value))
465
+ return false;
466
+ const attributes = value.$;
467
+ return (!!attributes &&
468
+ typeof attributes === 'object' &&
469
+ attributes['xsi:nil'] === 'true');
470
+ }
471
+ /**
472
+ * A Metadata API pair as `updateMetadata` takes it: explicit nils left out, and the texts "true"
473
+ * and "false" that readMetadata returns sent as booleans.
474
+ * @param {unknown} pair One fieldSourceTargetMaps entry.
475
+ * @returns {Record<string, unknown>} The pair to send.
476
+ */
477
+ function definitionPair(pair) {
478
+ return Object.fromEntries(Object.entries((pair ?? {}))
479
+ .filter(([, value]) => !metadataNil(value))
480
+ .map(([key, value]) => [key, value === 'true' ? true : value === 'false' ? false : value]));
481
+ }
482
+ /**
483
+ * The `<object>.<field>` source and target of a Metadata API pair, as one key.
484
+ * @param {Record<string, unknown>} pair One fieldSourceTargetMaps entry.
485
+ * @returns {string} Pair key.
486
+ */
487
+ function definitionPairKey(pair) {
488
+ return `${String(pair.sourceField)}|${String(pair.targetField)}`;
489
+ }
490
+ /**
491
+ * The pair keys of a Metadata API mapping record.
492
+ * @param {Record<string, unknown> | undefined} record Record as read.
493
+ * @returns {Set<string>} Pair keys.
494
+ */
495
+ function definitionPairKeys(record) {
496
+ return new Set(metadataRecords(record?.fieldSourceTargetMaps).map((pair) => definitionPairKey((pair ?? {}))));
497
+ }
498
+ /**
499
+ * Set a mapping's label with one Metadata API `updateMetadata`, after its native pair work has
500
+ * settled, then read the label and pairs back. A pair the update leaves out is kept and a pair it
501
+ * sends is added, so it sends every pair the mapping currently has and no other: the pairs of the
502
+ * fresh readMetadata record that the settled native mapping still holds (readMetadata may still
503
+ * list a pair the deploy just removed). The rest of the record is sent as read, nils left out.
504
+ * @param {NativeMappingDocument} settled The mapping as its settled native read shows it.
505
+ * @param {string} label Desired label.
506
+ * @param {Pick<MappingClient, 'readDefinitions' | 'updateDefinition'>} client Mapping transport.
507
+ */
508
+ async function relabelNativeMapping(settled, label, client) {
509
+ const name = settled.identity.apiName;
510
+ let current;
511
+ try {
512
+ current = await readMappingDefinition(name, client);
513
+ }
514
+ catch {
515
+ throw labelReadFailed(name, 'before its label update');
516
+ }
517
+ const { sourceEntityDeveloperName: from, targetEntityDeveloperName: to } = settled.spec;
518
+ const held = new Set(settled.spec.fieldMappings.map((pair) => `${from}.${pair.sourceFieldDeveloperName}|${to}.${pair.targetFieldDeveloperName}`));
519
+ const pairs = metadataRecords(current?.fieldSourceTargetMaps)
520
+ .map((pair) => definitionPair(pair))
521
+ .filter((pair) => held.has(definitionPairKey(pair)));
522
+ if (!current || !client.updateDefinition || pairs.length === 0)
523
+ throw labelReadFailed(name, 'before its label update');
524
+ const before = definitionPairKeys(current);
525
+ await client.updateDefinition({
526
+ ...Object.fromEntries(Object.entries(current).filter(([, value]) => !metadataNil(value))),
527
+ masterLabel: label,
528
+ fieldSourceTargetMaps: pairs,
529
+ });
530
+ let after;
531
+ try {
532
+ after = await readMappingDefinition(name, client);
533
+ }
534
+ catch {
535
+ after = undefined;
536
+ }
537
+ // Unchanged pairs: none added, and every pair sent still there (a pair readMetadata listed
538
+ // although the deploy had removed it may drop out of the record meanwhile).
539
+ const kept = definitionPairKeys(after);
540
+ if (after?.masterLabel !== label ||
541
+ [...kept].some((key) => !before.has(key)) ||
542
+ pairs.some((pair) => !kept.has(definitionPairKey(pair)))) {
543
+ const error = new NativeMappingError('MAPPING_PERSISTENCE_UNCONFIRMED');
544
+ replaceExplanation(error, `The label update of the mapping ${name} was sent, but reading the mapping back did not show the label ${JSON.stringify(label)} with the pairs unchanged.`);
545
+ throw error;
546
+ }
547
+ }
548
+ /**
549
+ * Compare the label of the file with the org's (Metadata API masterLabel).
550
+ * @param {NativeMappingDocument} desired Mapping file.
551
+ * @param {NativeMappingDocument | undefined} target Org mapping, or undefined for a create.
552
+ * @param {MappingClient} client Mapping reader.
553
+ * @returns {Promise<object>} The label change, or nothing.
554
+ */
555
+ async function planLabel(desired, target, client) {
556
+ const label = desired.spec.label;
557
+ if (label === undefined)
558
+ return {};
559
+ // A create ignores a label (live API 68): it is set by an update right after.
560
+ if (!target)
561
+ return { labelChange: { to: label } };
562
+ let current;
563
+ try {
564
+ current = await readMappingDefinition(target.identity.apiName, client);
565
+ }
566
+ catch {
567
+ throw labelReadFailed(target.identity.apiName, 'to compare its label');
568
+ }
569
+ if (typeof current?.masterLabel !== 'string')
570
+ throw labelReadFailed(target.identity.apiName, 'to compare its label');
571
+ refuseEscapedCopy({ spec: { label } }, { spec: { label: current.masterLabel } }, (code) => new NativeMappingError(code));
572
+ return current.masterLabel === label
573
+ ? {}
574
+ : { labelChange: { from: current.masterLabel, to: label } };
575
+ }
576
+ /**
577
+ * Validate source/target existence and every requested field against fresh definitions.
578
+ * The four exact generated pairs are qualified by the retained three-to-seven create probe.
579
+ * The target is a custom or a standard DMO; on a standard one the generated pairs are recognised
580
+ * from the target's own field read, and `activates` says its first mapping will enable it.
581
+ * @param {NativeMappingDocument} desired Requested definition.
582
+ * @param {MappingDependencies} dependencies Fresh source and target readers.
583
+ * @returns {Promise<object>} Fresh definitions and evidence-backed generated pairs.
584
+ */
585
+ async function validateDependencies(desired, dependencies) {
586
+ const { activates, activation, context } = await readMappingParents(desired, dependencies);
587
+ const { sources, targets } = context;
588
+ const generated = new Set();
589
+ const typeDifferences = [];
590
+ for (const pair of desired.spec.fieldMappings) {
591
+ const from = sources.get(pair.sourceFieldDeveloperName);
592
+ const to = targets.get(pair.targetFieldDeveloperName);
593
+ // A never-mapped standard DMO has no key qualifier field yet; its first mapping adds it.
594
+ if (from && !to && activates && isStandardKeyQualifierPair(pair, sources, targets)) {
595
+ generated.add(pairKey(pair));
596
+ continue;
597
+ }
598
+ if (!from || !to) {
599
+ const error = new NativeMappingError('MAPPING_FIELD_NOT_FOUND');
600
+ replaceExplanation(error, from
601
+ ? `The mapping pair ${pair.sourceFieldDeveloperName} -> ${pair.targetFieldDeveloperName} names the field ${pair.targetFieldDeveloperName}, which does not exist on ${desired.spec.targetEntityDeveloperName}.`
602
+ : `The mapping pair ${pair.sourceFieldDeveloperName} -> ${pair.targetFieldDeveloperName} names the field ${pair.sourceFieldDeveloperName}, which does not exist on ${desired.spec.sourceEntityDeveloperName}.`);
603
+ throw error;
604
+ }
605
+ // Salesforce accepts pairs of different data types (live API 68); preview names them.
606
+ if (from.dataType !== to.dataType)
607
+ typeDifferences.push({
608
+ source: pair.sourceFieldDeveloperName,
609
+ target: pair.targetFieldDeveloperName,
610
+ sourceType: from.dataType,
611
+ targetType: to.dataType,
612
+ });
613
+ if (isGeneratedMappingPair(pair, context))
614
+ generated.add(pairKey(pair));
615
+ }
616
+ return { generated, sources, targets, context, activates, activation, typeDifferences };
617
+ }
618
+ /**
619
+ * Build a minimal names-only native write body, never replaying saved selectors.
620
+ * @param {NativeMappingDocument} desired Binding.
621
+ * @param {NativeMappingField[]} fields Explicit operation-selected pairs.
622
+ * @returns {MappingWriteBody} Native singular fieldMapping input.
623
+ */
624
+ function bodyFor(desired, fields) {
625
+ return {
626
+ sourceEntityDeveloperName: desired.spec.sourceEntityDeveloperName,
627
+ targetEntityDeveloperName: desired.spec.targetEntityDeveloperName,
628
+ fieldMapping: fields.map(({ sourceFieldDeveloperName, targetFieldDeveloperName }) => ({
629
+ sourceFieldDeveloperName,
630
+ targetFieldDeveloperName,
631
+ })),
632
+ };
633
+ }
634
+ /**
635
+ * The create body of a mapping onto a standard DMO copy that does not exist yet, in the default
636
+ * spelling: the default target name, and each target field under its default name.
637
+ * @param {MappingWriteBody} body Create body in the copy spelling (as the file names it).
638
+ * @param {MappingActivation} activation Default spelling of the target and its fields.
639
+ * @returns {MappingWriteBody} The same create in the default spelling.
640
+ */
641
+ function defaultSpellingBody(body, activation) {
642
+ return {
643
+ sourceEntityDeveloperName: body.sourceEntityDeveloperName,
644
+ targetEntityDeveloperName: activation.targetEntityDeveloperName,
645
+ fieldMapping: body.fieldMapping.map((pair) => ({
646
+ sourceFieldDeveloperName: pair.sourceFieldDeveloperName,
647
+ targetFieldDeveloperName: activation.fields.get(pair.targetFieldDeveloperName) ?? pair.targetFieldDeveloperName,
648
+ })),
649
+ };
650
+ }
651
+ /**
652
+ * The answer to a create sent in the default spelling, under the copy's names: Salesforce stores
653
+ * the mapping under the copy, and an echo that still names the default spelling is read in the
654
+ * copy spelling, by the same read of the default object that built the retry.
655
+ * @param {NativeMappingDocument} document Normalised create answer.
656
+ * @param {NativeMappingDocument} desired Mapping file (copy spelling).
657
+ * @param {MappingActivation} activation Default spelling of the target and its fields.
658
+ * @returns {NativeMappingDocument} The answer in the copy spelling.
659
+ */
660
+ function copySpelling(document, desired, activation) {
661
+ if (document.spec.targetEntityDeveloperName !== activation.targetEntityDeveloperName)
662
+ return document;
663
+ const copyNames = new Map([...activation.fields].map(([copy, original]) => [original, copy]));
664
+ return {
665
+ ...document,
666
+ spec: {
667
+ ...document.spec,
668
+ targetEntityDeveloperName: desired.spec.targetEntityDeveloperName,
669
+ fieldMappings: document.spec.fieldMappings.map((pair) => ({
670
+ ...pair,
671
+ targetFieldDeveloperName: copyNames.get(pair.targetFieldDeveloperName) ?? pair.targetFieldDeveloperName,
672
+ })),
673
+ },
674
+ };
675
+ }
676
+ /**
677
+ * Retrieve one exact mapping with all runtime KQ/system pairs retained in portable JSON.
678
+ * @param {string} apiName Observed target mapping name.
679
+ * @param {MappingClient} client Target mapping transport.
680
+ * @param {string} requestScope The run's data space.
681
+ * @param {DocumentMode} [mode] `retrieve` keeps pairs the plugin cannot deploy as returned.
682
+ * @returns {Promise<NativeMappingDocument>} Complete portable definition.
683
+ */
684
+ export async function retrieveNativeMapping(apiName, client, requestScope, mode = 'deploy') {
685
+ if (!nativeMappingName.test(apiName))
686
+ throw new NativeMappingError('INVALID_MAPPING_NAME');
687
+ const document = normalizeNativeMapping(await client.get(apiName), requestScope, mode);
688
+ if (document.identity.apiName !== apiName)
689
+ throw new NativeMappingError('MAPPING_TARGET_IDENTITY_MISMATCH');
690
+ return document;
691
+ }
692
+ /**
693
+ * Plan create, desired-state reconciliation, or no-op without mutation.
694
+ * @param {unknown} value Portable desired mapping.
695
+ * @param {MappingClient} client Target mapping transport.
696
+ * @param {MappingDependencies} dependencies Fresh source/target definition readers.
697
+ * @param {string} requestScope The run's data space.
698
+ * @returns {Promise<NativeMappingDeployPlan>} Bounded operation plan.
699
+ */
700
+ export async function preflightNativeMapping(value, client, dependencies, requestScope) {
701
+ // Cloned: generated pairs of the org are merged into it below, never into the caller's input.
702
+ const desired = structuredClone(validateNativeMappingDocument(value));
703
+ if (desired.c__dataSpace !== requestScope)
704
+ throw explainSpaceMismatch(new NativeMappingError('MAPPING_DATASPACE_MISMATCH'), desired.identity.apiName, desired.c__dataSpace, requestScope, true);
705
+ const { generated, context, activates, activation, typeDifferences } = await validateDependencies(desired, dependencies);
706
+ const notices = typeDifferences.length > 0 ? { typeDifferences } : {};
707
+ const target = await resolveNativeMappingTarget(desired, client);
708
+ if (target) {
709
+ // Pairs Salesforce generated stay part of the mapping when the file does not list them;
710
+ // retrieve leaves out exactly these (generatedMappingPairs uses the same predicate).
711
+ const listed = new Set(desired.spec.fieldMappings.map((pair) => pairKey(pair)));
712
+ for (const pair of target.spec.fieldMappings)
713
+ if (!listed.has(pairKey(pair)) && isGeneratedMappingPair(pair, context))
714
+ desired.spec.fieldMappings.push(structuredClone(pair));
715
+ }
716
+ if (target)
717
+ refuseEscapedCopy(desired, target, (code) => new NativeMappingError(code));
718
+ const labelPlan = await planLabel(desired, target, client);
719
+ if (!target) {
720
+ const fields = desired.spec.fieldMappings.filter((pair) => !generated.has(pairKey(pair)));
721
+ const body = bodyFor(desired, fields);
722
+ return {
723
+ operation: 'create',
724
+ desired,
725
+ writes: [{ body }],
726
+ ...notices,
727
+ ...labelPlan,
728
+ ...(activates ? { activatesStandardDmo: true } : {}),
729
+ ...(activation
730
+ ? { activationRetry: { body: defaultSpellingBody(body, activation), activation } }
731
+ : {}),
732
+ };
733
+ }
734
+ const incoming = new Set(desired.spec.fieldMappings.map((pair) => pairKey(pair)));
735
+ const removals = target.spec.fieldMappings.filter((pair) => !incoming.has(pairKey(pair)));
736
+ const retained = target.spec.fieldMappings.filter((pair) => incoming.has(pairKey(pair)));
737
+ const existing = new Set(target.spec.fieldMappings.map((pair) => pairKey(pair)));
738
+ const added = desired.spec.fieldMappings.filter((pair) => !existing.has(pairKey(pair)));
739
+ if (added.length === 0 && removals.length === 0)
740
+ return labelPlan.labelChange
741
+ ? { operation: 'update', desired, target, retained, writes: [], ...notices, ...labelPlan }
742
+ : { operation: 'noop', desired, target, writes: [], ...notices };
743
+ // Preserve the existing compatible single-add contract; reconciliation has stricter evidence.
744
+ if (removals.length === 0 &&
745
+ added.length === 1 &&
746
+ !target.spec.fieldMappings.some((pair) => pair.sourceFieldDeveloperName === added[0].sourceFieldDeveloperName ||
747
+ pair.targetFieldDeveloperName === added[0].targetFieldDeveloperName))
748
+ return {
749
+ operation: 'update',
750
+ desired,
751
+ target,
752
+ retained,
753
+ writes: [{ body: bodyFor(desired, added) }],
754
+ ...notices,
755
+ ...labelPlan,
756
+ };
757
+ const evidence = await preflightUnmapNativeMapping(target, client, dependencies, removals, requestScope);
758
+ if (evidence.protectedPairs.some((pair) => !incoming.has(pairKey(pair))))
759
+ throw new NativeMappingError('MAPPING_PROTECTED_PAIR_REQUIRED');
760
+ return {
761
+ operation: 'update',
762
+ desired,
763
+ target,
764
+ removals,
765
+ retained,
766
+ evidence,
767
+ writes: added.length > 0 ? [{ body: bodyFor(desired, added) }] : [],
768
+ ...notices,
769
+ ...labelPlan,
770
+ };
771
+ }
772
+ /**
773
+ * Dispatch ordered unmaps then one additions batch, settling with GETs and no write retries.
774
+ * @param {unknown} value Portable desired definition.
775
+ * @param {MappingClient} client Target mapping transport.
776
+ * @param {MappingDependencies} dependencies Source/target readers.
777
+ * @param {Function} [onUpdated] Receive confirmed pair changes for human output only.
778
+ * @param {string} requestScope The run's data space.
779
+ * @returns {Promise<{operation: 'create' | 'update' | 'noop', document: NativeMappingDocument}>} Confirmed definition.
780
+ */
781
+ export async function deployNativeMapping(value, client, dependencies, onUpdated, requestScope) {
782
+ const plan = await preflightNativeMapping(value, client, dependencies, requestScope);
783
+ const reportUpdate = () => {
784
+ if (plan.operation === 'update')
785
+ onUpdated?.({
786
+ deleted: structuredClone(plan.removals ?? []),
787
+ added: structuredClone(plan.writes.flatMap(({ body }) => body.fieldMapping)),
788
+ ...(plan.labelChange ? { label: plan.labelChange.to } : {}),
789
+ });
790
+ };
791
+ if (plan.operation === 'noop')
792
+ return { operation: 'noop', document: plan.target };
793
+ // Only the label differs: no pair write, one label update.
794
+ if (plan.operation === 'update' && !plan.evidence && plan.writes.length === 0) {
795
+ await relabelNativeMapping(plan.target, plan.labelChange.to, client);
796
+ reportUpdate();
797
+ return { operation: 'update', document: plan.target };
798
+ }
799
+ if (plan.operation === 'update' && plan.evidence) {
800
+ const snapshot = await unmapNativeMappingFields(plan.evidence, client, dependencies, () => { }, requestScope);
801
+ if (plan.writes.length > 0) {
802
+ if (!(await checkUnmapSnapshot(snapshot, client, dependencies)))
803
+ throw new NativeMappingError('MAPPING_TARGET_NOT_SETTLED');
804
+ const body = plan.writes[0].body;
805
+ const accepted = normalizeNativeMapping(await client.update(plan.target.identity.apiName, body), requestScope);
806
+ checkBinding(plan.desired, accepted);
807
+ if (accepted.identity.apiName !== plan.target.identity.apiName)
808
+ throw new NativeMappingError('MAPPING_TARGET_IDENTITY_MISMATCH');
809
+ for (const pair of body.fieldMapping) {
810
+ const field = snapshot.target.fields.find((entry) => entry.name === pair.targetFieldDeveloperName);
811
+ field.isMapped = true;
812
+ }
813
+ }
814
+ let settledPairs;
815
+ for (let attempt = 0; attempt < readbackPace.attempts; attempt++) {
816
+ await paceReadback(attempt);
817
+ const raw = (await client.get(plan.target.identity.apiName));
818
+ const document = normalizeNativeMapping(raw, requestScope);
819
+ checkBinding(plan.desired, document);
820
+ const expected = new Set(plan.desired.spec.fieldMappings.map((pair) => pairKey(pair)));
821
+ if (document.identity.apiName !== plan.target.identity.apiName ||
822
+ document.spec.fieldMappings.length !== expected.size ||
823
+ document.spec.fieldMappings.some((pair) => !expected.has(pairKey(pair)) || !pair.developerName) ||
824
+ plan.retained.some((pair) => !isDeepStrictEqual(pair, document.spec.fieldMappings.find((field) => pairKey(field) === pairKey(pair)))))
825
+ throw new NativeMappingError('MAPPING_PERSISTENCE_UNCONFIRMED');
826
+ const entry = snapshot.inventory.find((value) => value.developerName === document.identity.apiName);
827
+ // Only new pair selectors are discovered; every other raw property remains bound.
828
+ if (settledPairs && !isDeepStrictEqual(settledPairs, document.spec.fieldMappings))
829
+ throw new NativeMappingError('MAPPING_PERSISTENCE_UNCONFIRMED');
830
+ settledPairs ??= structuredClone(document.spec.fieldMappings);
831
+ entry.fieldMappings = settledPairs;
832
+ if (await checkUnmapSnapshot(snapshot, client, dependencies)) {
833
+ if (plan.labelChange)
834
+ await relabelNativeMapping(document, plan.labelChange.to, client);
835
+ reportUpdate();
836
+ return { operation: 'update', document };
837
+ }
838
+ }
839
+ throw new NativeMappingError('MAPPING_PERSISTENCE_UNCONFIRMED');
840
+ }
841
+ const write = plan.writes[0];
842
+ let response;
843
+ let retried = false;
844
+ if (plan.operation === 'create')
845
+ try {
846
+ response = await client.create(write.body);
847
+ }
848
+ catch (error) {
849
+ // A standard DMO copy that does not exist yet: Salesforce answers the copy spelling with
850
+ // 404 and takes the first mapping only in the default spelling (stored under the copy).
851
+ // Sent once more, once; never for any other answer.
852
+ if (!plan.activationRetry ||
853
+ !(error instanceof NativeMappingError) ||
854
+ error.code !== 'MAPPING_HTTP_ERROR' ||
855
+ error.status !== 404 ||
856
+ // Only Salesforce's "DMO not found" answer (live: "DMO not found for the given developer
857
+ // name"); any other 404 text is not the missing copy.
858
+ !getConnectDiagnostic(error)?.errors?.some(({ message }) => /\bDMO not found\b/iu.test(message ?? '')))
859
+ throw error;
860
+ retried = true;
861
+ response = await client.create(plan.activationRetry.body);
862
+ }
863
+ else
864
+ response = await client.update(plan.target.identity.apiName, write.body);
865
+ const echoed = normalizeNativeMapping(response, requestScope);
866
+ const accepted = retried && plan.activationRetry
867
+ ? copySpelling(echoed, plan.desired, plan.activationRetry.activation)
868
+ : echoed;
869
+ checkBinding(plan.desired, accepted);
870
+ const name = plan.target?.identity.apiName ?? accepted.identity.apiName;
871
+ if (accepted.identity.apiName !== name)
872
+ throw new NativeMappingError('MAPPING_TARGET_IDENTITY_MISMATCH');
873
+ for (let attempt = 0; attempt < readbackPace.attempts; attempt++) {
874
+ await paceReadback(attempt);
875
+ let document;
876
+ try {
877
+ const raw = await client.get(name);
878
+ document = normalizeNativeMapping(raw, requestScope);
879
+ if (document.identity.apiName !== name)
880
+ throw new NativeMappingError('MAPPING_TARGET_IDENTITY_MISMATCH');
881
+ if (raw.status !== 'ACTIVE')
882
+ continue;
883
+ }
884
+ catch (error) {
885
+ if (error instanceof NativeMappingError &&
886
+ error.code === 'MAPPING_HTTP_ERROR' &&
887
+ error.status === 404)
888
+ continue;
889
+ throw error;
890
+ }
891
+ checkBinding(plan.desired, document);
892
+ const actual = new Map(document.spec.fieldMappings.map((pair) => [pairKey(pair), pair]));
893
+ const desiredPresent = plan.desired.spec.fieldMappings.every((pair) => actual.has(pairKey(pair)));
894
+ const preserved = (plan.target?.spec.fieldMappings ?? accepted.spec.fieldMappings).every((pair) => actual.has(pairKey(pair)) &&
895
+ actual.get(pairKey(pair))?.developerName === pair.developerName);
896
+ if (desiredPresent &&
897
+ preserved &&
898
+ (plan.operation === 'create' || actual.size === plan.desired.spec.fieldMappings.length)) {
899
+ if (plan.labelChange)
900
+ await relabelNativeMapping(document, plan.labelChange.to, client);
901
+ reportUpdate();
902
+ return {
903
+ operation: plan.operation,
904
+ document,
905
+ ...(plan.activatesStandardDmo ? { activatesStandardDmo: true } : {}),
906
+ };
907
+ }
908
+ }
909
+ throw new NativeMappingError('MAPPING_PERSISTENCE_UNCONFIRMED');
910
+ }
911
+ /**
912
+ * Classify exact metadata-backed protected pairs and qualified authored identity pairs.
913
+ * @param {NativeMappingDocument} selected Fresh target definition.
914
+ * @param {MappingClient} client Version-bearing mapping reader.
915
+ * @param {MappingDependencies} dependencies Fresh parent readers.
916
+ * @param {NativeMappingField[]} requestedRemovals Desired-state omissions.
917
+ * @param {string} requestScope The run's data space.
918
+ * @returns {Promise<NativeMappingUnmapPlan>} Complete removal evidence, without mutation.
919
+ */
920
+ export async function preflightUnmapNativeMapping(selected, client, dependencies, requestedRemovals, requestScope) {
921
+ if (selected.c__dataSpace !== requestScope)
922
+ throw explainSpaceMismatch(new NativeMappingError('MAPPING_DATASPACE_MISMATCH'), selected.identity.apiName, selected.c__dataSpace, requestScope);
923
+ const response = await client.list(selected.spec.targetEntityDeveloperName);
924
+ if (!response || typeof response !== 'object' || Object.keys(response).length !== 1)
925
+ throw new NativeMappingError('MAPPING_INVENTORY_UNCONFIRMED');
926
+ const inventory = unwrapNativeMappingCollection(response, requestScope);
927
+ const documents = inventory.map((entry) => normalizeNativeMapping(entry, requestScope));
928
+ if (new Set(documents.map((entry) => entry.identity.apiName.toLowerCase())).size !==
929
+ documents.length ||
930
+ new Set(documents.map((entry) => entry.spec.sourceEntityDeveloperName.toLowerCase())).size !==
931
+ documents.length ||
932
+ documents.some((entry) => entry.spec.targetEntityDeveloperName !== selected.spec.targetEntityDeveloperName) ||
933
+ inventory.some((entry) => entry.status !== 'ACTIVE') ||
934
+ !documents.some((entry) => isDeepStrictEqual(entry, selected)))
935
+ throw new NativeMappingError('MAPPING_INVENTORY_UNCONFIRMED');
936
+ const sourceNames = documents.map((entry) => entry.spec.sourceEntityDeveloperName);
937
+ const parents = await Promise.all(sourceNames.map(async (name) => dependencies.source.get(name)));
938
+ const target = (await dependencies.target.get(selected.spec.targetEntityDeveloperName));
939
+ const parentByName = new Map(sourceNames.map((name, index) => [name, parents[index]]));
940
+ for (const name of sourceNames) {
941
+ if (normalizeDlo(parentByName.get(name), selected.c__dataSpace).identity.apiName !== name)
942
+ throw new NativeMappingError('MAPPING_DEPENDENCY_IDENTITY_MISMATCH');
943
+ }
944
+ const { generated, sources, targets } = await validateDependencies(selected, {
945
+ source: { get: async (name) => parentByName.get(name) },
946
+ target: { get: async () => target },
947
+ });
948
+ const protectedPairs = [];
949
+ const removals = [];
950
+ for (const pair of selected.spec.fieldMappings) {
951
+ const from = sources.get(pair.sourceFieldDeveloperName);
952
+ const to = targets.get(pair.targetFieldDeveloperName);
953
+ if (!pair.developerName)
954
+ throw new NativeMappingError('MAPPING_SELECTOR_REQUIRED');
955
+ if (generated.has(pairKey(pair)) || isKeyPair(from, to)) {
956
+ if (to.isMapped !== true)
957
+ throw new NativeMappingError('MAPPING_PROTECTED_LAYOUT_UNPROVEN');
958
+ protectedPairs.push(pair);
959
+ continue;
960
+ }
961
+ if (!requestedRemovals.some((field) => pairKey(field) === pairKey(pair)))
962
+ continue;
963
+ // A system or key-qualifier field not recognised as generated is never unmapped by a deploy.
964
+ if (to.creationType === 'System' ||
965
+ to.usageTag === 'KeyQualifier' ||
966
+ keyQualifierField.test(to.name))
967
+ throw new NativeMappingError('MAPPING_PROTECTED_LAYOUT_UNPROVEN');
968
+ // Any other pair is removable; Salesforce decides (live API 68, custom and standard fields).
969
+ removals.push(pair);
970
+ }
971
+ // Without an identified key pair nothing proves which pair must survive, so nothing is removed.
972
+ if (!protectedPairs.some((pair) => isKeyPair(sources.get(pair.sourceFieldDeveloperName), targets.get(pair.targetFieldDeveloperName))))
973
+ throw new NativeMappingError('MAPPING_PROTECTED_LAYOUT_UNPROVEN');
974
+ // Independently check every inventory detail, not merely collection echoes.
975
+ for (const entry of inventory) {
976
+ if (!isDeepStrictEqual(await client.get(entry.developerName), entry))
977
+ throw new NativeMappingError('MAPPING_INVENTORY_UNCONFIRMED');
978
+ }
979
+ return structuredClone({
980
+ selected,
981
+ removals,
982
+ protectedPairs,
983
+ inventory,
984
+ sourceNames,
985
+ parents,
986
+ target,
987
+ });
988
+ }
989
+ /**
990
+ * Compare complete parents and inventory against one exact expected snapshot.
991
+ * @param {NativeMappingUnmapPlan} plan Expected immutable evidence.
992
+ * @param {MappingClient} client Mapping reader.
993
+ * @param {MappingDependencies} dependencies Parent readers.
994
+ * @returns {Promise<boolean>} Whether all mappings have settled ACTIVE.
995
+ */
996
+ async function checkUnmapSnapshot(plan, client, dependencies) {
997
+ const parents = await Promise.all(plan.sourceNames.map(async (name) => dependencies.source.get(name)));
998
+ const target = await dependencies.target.get(plan.selected.spec.targetEntityDeveloperName);
999
+ if (!isDeepStrictEqual(parents, plan.parents) || !isDeepStrictEqual(target, plan.target))
1000
+ throw explainMismatch(new NativeMappingError('MAPPING_PARENT_CHANGED'), 'unmap parent preservation', plan.selected.identity.apiName, { parents: plan.parents, target: plan.target }, { parents, target });
1001
+ const response = await client.list(plan.selected.spec.targetEntityDeveloperName);
1002
+ if (!response || typeof response !== 'object' || Object.keys(response).length !== 1)
1003
+ throw new NativeMappingError('MAPPING_INVENTORY_UNCONFIRMED');
1004
+ const entries = unwrapNativeMappingCollection(response, plan.selected.c__dataSpace);
1005
+ if (entries.length !== plan.inventory.length)
1006
+ throw new NativeMappingError('MAPPING_INVENTORY_UNCONFIRMED');
1007
+ let active = true;
1008
+ for (const expected of plan.inventory) {
1009
+ const actual = entries.find((entry) => entry.developerName === expected.developerName);
1010
+ const detail = (await client.get(expected.developerName));
1011
+ for (const value of [actual, detail]) {
1012
+ if (!value ||
1013
+ !['ACTIVE', 'CREATING'].includes(value.status) ||
1014
+ !isDeepStrictEqual({ ...value, status: 'ACTIVE' }, expected))
1015
+ throw explainMismatch(new NativeMappingError('MAPPING_UNMAP_PERSISTENCE_UNCONFIRMED'), 'unmap inventory/detail preservation', expected.developerName, expected, value);
1016
+ if (value.status !== 'ACTIVE')
1017
+ active = false;
1018
+ }
1019
+ }
1020
+ return active;
1021
+ }
1022
+ /**
1023
+ * Unmap qualified observed selectors once each, checking exact schema after every dispatch.
1024
+ * This helper never deletes a parent mapping or admits desired-state retargeting.
1025
+ * @param {NativeMappingUnmapPlan} evidence Fresh complete preflight snapshot.
1026
+ * @param {MappingClient} client Mapping transport.
1027
+ * @param {MappingDependencies} dependencies Parent readers.
1028
+ * @param {Function} onDispatch Called before awaiting each mutation, including lost responses.
1029
+ * @param {string} requestScope The run's data space.
1030
+ * @returns {Promise<NativeMappingUnmapPlan>} Settled retained-pair snapshot for the next operation.
1031
+ */
1032
+ export async function unmapNativeMappingFields(evidence, client, dependencies, onDispatch, requestScope) {
1033
+ const fresh = await preflightUnmapNativeMapping(evidence.selected, client, dependencies, evidence.removals, requestScope);
1034
+ if (!isDeepStrictEqual(fresh, evidence))
1035
+ throw explainMismatch(new NativeMappingError('MAPPING_UNMAP_PLAN_CHANGED'), 'unmap pre-dispatch plan recheck', evidence.selected.identity.apiName, evidence, fresh);
1036
+ const plan = structuredClone(evidence);
1037
+ for (const pair of plan.removals) {
1038
+ if (!(await checkUnmapSnapshot(plan, client, dependencies)))
1039
+ throw new NativeMappingError('MAPPING_TARGET_NOT_SETTLED');
1040
+ const entry = plan.inventory.find((value) => value.developerName === plan.selected.identity.apiName);
1041
+ entry.fieldMappings = entry.fieldMappings.filter((field) => pairKey(field) !== pairKey(pair));
1042
+ const field = plan.target.fields.find((value) => value.name === pair.targetFieldDeveloperName);
1043
+ // The field stays mapped for as long as another mapping of the DMO still targets it.
1044
+ if (!plan.inventory.some((value) => value.developerName !== plan.selected.identity.apiName &&
1045
+ value.fieldMappings.some((other) => other.targetFieldDeveloperName === pair.targetFieldDeveloperName)))
1046
+ delete field.isMapped;
1047
+ onDispatch();
1048
+ await client.deleteField(plan.selected.identity.apiName, pair.developerName);
1049
+ let settled = false;
1050
+ for (let attempt = 0; attempt < readbackPace.attempts; attempt++) {
1051
+ await paceReadback(attempt);
1052
+ if (await checkUnmapSnapshot(plan, client, dependencies)) {
1053
+ settled = true;
1054
+ break;
1055
+ }
1056
+ }
1057
+ if (!settled)
1058
+ throw new NativeMappingError('MAPPING_UNMAP_PERSISTENCE_UNCONFIRMED');
1059
+ }
1060
+ plan.selected.spec.fieldMappings = plan.selected.spec.fieldMappings.filter((pair) => !plan.removals.some((removed) => pairKey(removed) === pairKey(pair)));
1061
+ plan.removals = [];
1062
+ return plan;
1063
+ }
1064
+ /** The system source fields of a standard DMO as its copy names them (`ssot__` left out). */
1065
+ const copySystemFields = new Set([
1066
+ 'DataSourceId__c',
1067
+ 'DataSourceObjectId__c',
1068
+ 'InternalOrganizationId__c',
1069
+ ]);
1070
+ export const defaultMappingDeleteSettle = {
1071
+ attempts: 6,
1072
+ delayMs: 5000,
1073
+ sleep: async (ms) => {
1074
+ await new Promise((resolve) => {
1075
+ setTimeout(resolve, ms);
1076
+ });
1077
+ },
1078
+ };
1079
+ /**
1080
+ * Read what a mapping deletion must leave untouched: the other mappings and the DMO's fields.
1081
+ * @param {string} target Target DMO name.
1082
+ * @param {MappingClient} client Mapping reader.
1083
+ * @param {MappingDependencies} dependencies Parent readers.
1084
+ * @param {string} requestScope The run's data space.
1085
+ * @returns {Promise<object>} Normalised mappings ordered by name, raw DMO and ordered field names.
1086
+ */
1087
+ async function readMappingSurroundings(target, client, dependencies, requestScope) {
1088
+ let entries = [];
1089
+ try {
1090
+ const response = await client.list(target);
1091
+ if (!response || typeof response !== 'object' || Object.keys(response).length !== 1)
1092
+ throw new NativeMappingError('MAPPING_INVENTORY_UNCONFIRMED');
1093
+ entries = unwrapNativeMappingCollection(response, requestScope);
1094
+ }
1095
+ catch (error) {
1096
+ // A DMO without any mapping answers the filtered list with a typed 404.
1097
+ if (!(error instanceof NativeMappingError) ||
1098
+ error.code !== 'MAPPING_HTTP_ERROR' ||
1099
+ error.status !== 404)
1100
+ throw error;
1101
+ }
1102
+ const mappings = entries
1103
+ .map((entry) => normalizeNativeMapping(entry, requestScope))
1104
+ // eslint-disable-next-line unicorn/no-array-sort -- Sort a fresh mapped array within the ES2022 library target.
1105
+ .sort((a, b) => a.identity.apiName.localeCompare(b.identity.apiName));
1106
+ const rawTarget = unwrapNativeDmo(await dependencies.target.get(target));
1107
+ const fields = Array.isArray(rawTarget.fields) ? rawTarget.fields : [];
1108
+ const targetFields = fields.map((field) => String(field.name));
1109
+ targetFields.sort();
1110
+ return { mappings, rawTarget, targetFields };
1111
+ }
1112
+ /**
1113
+ * Qualify a whole-mapping deletion without writing. Salesforce cannot delete the last mapping of
1114
+ * a custom DMO, so that case is refused here with its way out; a standard DMO has no such limit.
1115
+ * @param {string} apiName Exact target-native mapping name.
1116
+ * @param {MappingClient} client Target mapping reader.
1117
+ * @param {Pick<MappingDependencies, 'target' | 'dataSpacePrefix'>} dependencies Fresh DMO reader
1118
+ * and the run's data space prefix (which tells a standard DMO copy).
1119
+ * @param {string} requestScope The run's data space.
1120
+ * @returns {Promise<NativeMappingDeletePlan>} What must be unchanged after the deletion.
1121
+ */
1122
+ export async function preflightDeleteNativeMapping(apiName, client, dependencies, requestScope) {
1123
+ const selected = await retrieveNativeMapping(apiName, client, requestScope);
1124
+ const target = selected.spec.targetEntityDeveloperName;
1125
+ const { mappings, rawTarget, targetFields } = await readMappingSurroundings(target, client, dependencies, requestScope);
1126
+ if (!mappings.some((entry) => isDeepStrictEqual(entry, selected)))
1127
+ throw new NativeMappingError('MAPPING_INVENTORY_UNCONFIRMED');
1128
+ const others = mappings.filter((entry) => entry.identity.apiName !== apiName);
1129
+ // Namespaced custom DMOs share the limit, so test the creation type, not the write scope.
1130
+ if (others.length === 0 && rawTarget.creationType === 'Custom') {
1131
+ const error = new NativeMappingError('MAPPING_LAST_MAPPING_DELETE_BLOCKED');
1132
+ replaceExplanation(error, `${apiName} is the only mapping of the custom DMO ${target}, and Salesforce does not delete the last mapping of a custom DMO. Delete the DMO instead (sf data360 delete --metadata dmo:${target}); that removes its mapping with it.`);
1133
+ throw error;
1134
+ }
1135
+ // A standard DMO copy (non-default data space, the space's prefix, creationType Standard).
1136
+ // Only a copy that keeps another mapping was observed dropping a field (live API 68); the last
1137
+ // mapping of a copy keeps the strict check.
1138
+ const copy = others.length > 0 &&
1139
+ rawTarget.creationType === 'Standard' &&
1140
+ standardCopyOrigin(target, requestScope, dependencies.dataSpacePrefix) !== undefined;
1141
+ if (!copy)
1142
+ return { selected, others, targetFields };
1143
+ const kept = new Set(others.flatMap((entry) => entry.spec.fieldMappings.map((pair) => pair.targetFieldDeveloperName)));
1144
+ // Never released: a primary key, a generated field (KQ_, system, read as System) or the copy
1145
+ // spelling of a system source field of the default object.
1146
+ const rawFields = Array.isArray(rawTarget.fields)
1147
+ ? rawTarget.fields
1148
+ : [];
1149
+ const protectedFields = new Set(rawFields
1150
+ .filter((field) => field.isPrimaryKey === true ||
1151
+ isGeneratedDmoField(field) ||
1152
+ copySystemFields.has(String(field.name)))
1153
+ .map((field) => String(field.name)));
1154
+ const releasableFields = [
1155
+ ...new Set(selected.spec.fieldMappings.map((pair) => pair.targetFieldDeveloperName)),
1156
+ ].filter((name) => !kept.has(name) && targetFields.includes(name) && !protectedFields.has(name));
1157
+ releasableFields.sort();
1158
+ return { selected, others, targetFields, releasableFields };
1159
+ }
1160
+ /**
1161
+ * Delete a mapping with one Metadata API destructive deployment, then confirm its absence and
1162
+ * that the DMO's other mappings and its fields are what they were. On a standard DMO copy the
1163
+ * fields only the deleted mapping targeted may be gone (see {@link NativeMappingDeletePlan}).
1164
+ * @param {string} apiName Exact native name, never a source artifact alias.
1165
+ * @param {MappingClient} client Mapping transport.
1166
+ * @param {MappingDependencies} dependencies Fresh parent readers and the data space prefix.
1167
+ * @param {string} requestScope The run's data space.
1168
+ * @param {NativeMappingDeleteSettle} [settle] Bounded readback budget.
1169
+ * @returns {Promise<{apiName: string}>} Independently verified absence.
1170
+ */
1171
+ export async function deleteNativeMapping(apiName, client, dependencies, requestScope, settle = defaultMappingDeleteSettle) {
1172
+ const before = await preflightDeleteNativeMapping(apiName, client, dependencies, requestScope);
1173
+ await client.remove(apiName);
1174
+ for (let attempt = 0; attempt < settle.attempts; attempt++) {
1175
+ if (attempt > 0)
1176
+ await settle.sleep(settle.delayMs);
1177
+ try {
1178
+ await retrieveNativeMapping(apiName, client, requestScope);
1179
+ continue;
1180
+ }
1181
+ catch (error) {
1182
+ if (!(error instanceof NativeMappingError) ||
1183
+ error.code !== 'MAPPING_HTTP_ERROR' ||
1184
+ error.status !== 404)
1185
+ throw error;
1186
+ }
1187
+ const after = await readMappingSurroundings(before.selected.spec.targetEntityDeveloperName, client, dependencies, requestScope);
1188
+ // A copy may drop the fields only the deleted mapping targeted; every other field stays.
1189
+ const released = new Set((before.releasableFields ?? []).filter((name) => !after.targetFields.includes(name)));
1190
+ const expected = {
1191
+ mappings: before.others,
1192
+ targetFields: before.targetFields.filter((name) => !released.has(name)),
1193
+ };
1194
+ const observed = { mappings: after.mappings, targetFields: after.targetFields };
1195
+ if (!isDeepStrictEqual(observed, expected))
1196
+ throw explainMismatch(new NativeMappingError('MAPPING_DELETE_SIDE_EFFECT'), 'mapping deletion readback of the other mappings and the DMO fields', apiName, expected, observed);
1197
+ return { apiName };
1198
+ }
1199
+ throw new NativeMappingError('MAPPING_DELETION_UNCONFIRMED');
1200
+ }
1201
+ /**
1202
+ * Confirm by its own reads that a mapping is gone after another deletion removed it (the last
1203
+ * mapping of a custom DMO goes with the DMO). Only the typed 404 counts as absence.
1204
+ * @param {string} apiName Exact org mapping name.
1205
+ * @param {MappingClient} client Mapping reader.
1206
+ * @param {string} requestScope The run's data space.
1207
+ * @param {NativeMappingDeleteSettle} [settle] Bounded readback budget.
1208
+ * @returns {Promise<boolean>} True once a read answers 404; false while it stays readable.
1209
+ */
1210
+ export async function confirmNativeMappingAbsent(apiName, client, requestScope, settle = defaultMappingDeleteSettle) {
1211
+ for (let attempt = 0; attempt < settle.attempts; attempt++) {
1212
+ if (attempt > 0)
1213
+ await settle.sleep(settle.delayMs);
1214
+ try {
1215
+ await retrieveNativeMapping(apiName, client, requestScope);
1216
+ }
1217
+ catch (error) {
1218
+ if (error instanceof NativeMappingError &&
1219
+ error.code === 'MAPPING_HTTP_ERROR' &&
1220
+ error.status === 404)
1221
+ return true;
1222
+ throw error;
1223
+ }
1224
+ }
1225
+ return false;
1226
+ }