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
@@ -1,29 +1,137 @@
1
1
  import { Org } from '@salesforce/core';
2
- import { buildDmoCreateRequestFromDocument } from '../artifacts/dmo-document.js';
2
+ import { buildNativeIdentityResolutionCreate, buildNativeIdentityResolutionUpdate, nativeIdentityResolutionDocument, } from '../services/preflight-identity-resolution-deploy.js';
3
+ import { apiDiagnostic, connectDiagnostic, diagnosticDataProperty, diagnosticRequestId, getConnectDiagnostic, retainConnectDiagnostic, } from './connect-diagnostic.js';
4
+ import { segmentWriteBody, validateSegmentDocument } from '../artifacts/segment-document.js';
5
+ /** Native 404 codes that name an item as absent or deleted, read from a single REST error. */
6
+ const nativeAbsenceCodes = ['ITEM_NOT_FOUND', 'ENTITY_IS_DELETED'];
7
+ /**
8
+ * The request header that makes Connect REST answer in plain text. By default it HTML-escapes
9
+ * every string of a response (`<>"'\&` read as `&lt; &gt; &quot; &#39; &#92; &amp;`) while it
10
+ * stores what a write sends as is, so a retrieved label, description, formula or SQL would not be
11
+ * what Salesforce holds (live API 68: data transforms, DLOs, data streams, calculated insights,
12
+ * segments; DB entry data360:connect-rest-entity-encoding-header-api68).
13
+ */
14
+ export const plainTextHeaders = Object.freeze({
15
+ 'X-Chatter-Entity-Encoding': 'false',
16
+ });
17
+ /**
18
+ * The request with {@link plainTextHeaders} when it goes to a Data 360 (`/ssot/`) route; any
19
+ * other request as it is. Only `/ssot/` routes get the header: a Data 360 read on any other
20
+ * route still returns HTML-escaped text.
21
+ * @param {Parameters<Connection['request']>[0]} request Request as built.
22
+ * @returns {Parameters<Connection['request']>[0]} Request to send.
23
+ */
24
+ export function plainTextRequest(request) {
25
+ const object = typeof request === 'string' ? { method: 'GET', url: request } : request;
26
+ if (!/\/services\/data\/[^/?#]+\/ssot\//u.test(String(object.url)))
27
+ return request;
28
+ return { ...object, headers: { ...object.headers, ...plainTextHeaders } };
29
+ }
3
30
  /** An intentionally payload-free diagnostic safe for JSON and console output. */
4
31
  export class ConnectError extends Error {
5
32
  code;
6
33
  statusCode;
7
- constructor(code, statusCode) {
34
+ nativeCode;
35
+ constructor(code, statusCode, nativeCode) {
8
36
  super(code === 'AUTHENTICATION_FAILED'
9
37
  ? 'Salesforce authentication failed.'
10
38
  : 'Data360 request failed.');
11
39
  this.code = code;
12
40
  this.statusCode = statusCode;
41
+ this.nativeCode = nativeCode;
13
42
  this.name = 'ConnectError';
14
43
  }
15
44
  }
45
+ /**
46
+ * Bounded retry of in-process requests. GETs retry after network errors and HTTP 429/503;
47
+ * writes retry only when the request provably never reached Salesforce. `sleep` and `warn`
48
+ * are replaceable (tests, commands); `warn` defaults to one stderr line so JSON stdout stays clean.
49
+ */
50
+ export const connectRetry = {
51
+ attempts: 3,
52
+ delaysMs: [1000, 2000],
53
+ maxRetryAfterMs: 60_000,
54
+ sleep: async (milliseconds) => {
55
+ await new Promise((resolve) => {
56
+ setTimeout(resolve, milliseconds);
57
+ });
58
+ },
59
+ warn: (message) => {
60
+ process.stderr.write(`Warning: ${message}\n`);
61
+ },
62
+ };
63
+ // Codes raised before a connection exists: the request never reached Salesforce.
64
+ const unsentCodes = new Set(['ECONNREFUSED', 'ENOTFOUND', 'EHOSTUNREACH', 'EAI_AGAIN']);
65
+ const readRetryCodes = new Set([...unsentCodes, 'ETIMEDOUT', 'ECONNRESET', 'ECONNABORTED']);
66
+ const networkCodes = new WeakMap();
67
+ /**
68
+ * Find a Node network error code on the error or its first two causes.
69
+ * @param {unknown} error Raw transport failure.
70
+ * @returns {string | undefined} A known retry candidate code.
71
+ */
72
+ function networkCode(error) {
73
+ let current = error;
74
+ for (let depth = 0; depth < 3 && current && typeof current === 'object'; depth++) {
75
+ const code = diagnosticDataProperty(current, 'code');
76
+ if (typeof code === 'string' && readRetryCodes.has(code))
77
+ return code;
78
+ current = diagnosticDataProperty(current, 'cause');
79
+ }
80
+ return undefined;
81
+ }
82
+ /**
83
+ * Decide whether and how long to wait before the next attempt.
84
+ * @param {string} method HTTP method.
85
+ * @param {number} attempt One-based number of the failed attempt.
86
+ * @param {unknown} error The failure thrown by that attempt.
87
+ * @returns {{ wait: number; reason: string } | undefined} Wait in ms, or undefined to give up.
88
+ */
89
+ function retryPlan(method, attempt, error) {
90
+ if (attempt >= connectRetry.attempts || !error || typeof error !== 'object')
91
+ return;
92
+ const backoff = connectRetry.delaysMs[Math.min(attempt, connectRetry.delaysMs.length) - 1] ?? 0;
93
+ const code = networkCodes.get(error);
94
+ if (code) {
95
+ if (method !== 'GET' && !unsentCodes.has(code))
96
+ return;
97
+ return { wait: backoff, reason: code };
98
+ }
99
+ const diagnostic = getConnectDiagnostic(error);
100
+ if (method !== 'GET' || !diagnostic || diagnostic.kind === 'api-error')
101
+ return;
102
+ let wait = backoff;
103
+ if (diagnostic.retryAfter !== undefined) {
104
+ wait = /^\d+$/u.test(diagnostic.retryAfter)
105
+ ? Number(diagnostic.retryAfter) * 1000
106
+ : Math.max(0, Date.parse(diagnostic.retryAfter) - Date.now());
107
+ wait = Math.min(wait, connectRetry.maxRetryAfterMs);
108
+ }
109
+ return { wait, reason: `HTTP ${diagnostic.statusCode}` };
110
+ }
16
111
  /** Bounded SSOT transport; Salesforce core owns credentials. */
17
112
  export class ConnectClient {
18
113
  connection;
19
- apiVersion;
20
114
  origin;
21
115
  prefix;
22
- constructor(connection, apiVersion) {
116
+ selection;
117
+ constructor(connection, selection) {
23
118
  this.connection = connection;
24
- this.apiVersion = apiVersion;
25
- if (!/^\d{2,3}\.0$/u.test(apiVersion))
119
+ // Numeric compatibility is normalized immediately; bare latest needs resolved SOAP evidence.
120
+ const candidate = typeof selection === 'string'
121
+ ? { requested: selection, restSelector: `v${selection}`, soapNumeric: selection }
122
+ : selection;
123
+ if (!candidate ||
124
+ typeof candidate.soapNumeric !== 'string' ||
125
+ !/^\d{2,3}\.0$/u.test(candidate.soapNumeric) ||
126
+ !((candidate.requested === 'latest' && candidate.restSelector === 'latest') ||
127
+ (candidate.requested === candidate.soapNumeric &&
128
+ candidate.restSelector === `v${candidate.soapNumeric}`)))
26
129
  throw new ConnectError('INVALID_REQUEST');
130
+ this.selection = Object.freeze({
131
+ requested: candidate.requested,
132
+ restSelector: candidate.restSelector,
133
+ soapNumeric: candidate.soapNumeric,
134
+ });
27
135
  try {
28
136
  const instance = new URL(connection.instanceUrl);
29
137
  if (instance.protocol !== 'https:' ||
@@ -38,7 +146,7 @@ export class ConnectClient {
38
146
  catch {
39
147
  throw new ConnectError('INVALID_REQUEST');
40
148
  }
41
- this.prefix = `/services/data/v${apiVersion}/ssot/`;
149
+ this.prefix = `/services/data/${this.selection.restSelector}/ssot/`;
42
150
  }
43
151
  /**
44
152
  * Load existing Salesforce CLI authentication without exposing token fields.
@@ -59,7 +167,7 @@ export class ConnectClient {
59
167
  }
60
168
  }
61
169
  /**
62
- * Read a single SSOT response. Does not infer pagination or retry a failed call.
170
+ * Read a single SSOT response. Does not infer pagination; see `connectRetry` for the bounded retry.
63
171
  * @template T
64
172
  * @param {string} path Root-relative SSOT path or same-origin absolute URL, with optional query.
65
173
  * @returns {Promise<T>} The unmodified resource response; callers must validate its schema.
@@ -68,62 +176,198 @@ export class ConnectClient {
68
176
  return this.read(path);
69
177
  }
70
178
  /**
71
- * Create one validated authored DMO at the fixed API65 endpoint, without retry or redirect.
72
- * A per-call receiver masks JSforce's refresh delegate (which otherwise replays POST on 401).
73
- * Never mutates the supplied connection or exposes a generic write route.
74
- * @param {unknown} document Independently validated authored-only default-space document.
75
- * @returns {Promise<unknown>} Untrusted response, never proof of successful creation.
179
+ * Create one native API68 Segment in the data space of the file (`?dataspace=`), without
180
+ * redirect or replay. The definition goes as written (`segmentWriteBody`); without a schedule in
181
+ * the file it does not refresh.
182
+ * @param {unknown} value Complete admitted portable definition.
183
+ * @param {ReadonlyMap<string, string>} [children] Waterfall child API name to target definition ID.
184
+ * @returns {Promise<unknown>} Untrusted acknowledgement, not settlement.
76
185
  */
77
- async createDataModelObject(document) {
78
- if (this.apiVersion !== '65.0')
186
+ async createSegment(value, children) {
187
+ if (this.selection.requested !== '68.0')
79
188
  throw new ConnectError('INVALID_REQUEST');
80
- const body = JSON.stringify(buildDmoCreateRequestFromDocument(document, 'default'));
189
+ const document = validateSegmentDocument(value);
81
190
  return this.send({
82
191
  method: 'POST',
83
- url: this.safeUrl(`${this.prefix}data-model-objects`),
84
- body,
192
+ // The create names the data space of the file (live API 68: in a non-default data space
193
+ // Salesforce stores the segment as <prefix>_<Name>, and keeps a name that has it already).
194
+ url: this.safeUrl(`${this.prefix}segments?dataspace=${encodeURIComponent(document.c__dataSpace)}`),
195
+ body: JSON.stringify(segmentWriteBody(document, true, false, children)),
85
196
  headers: { 'content-type': 'application/json' },
86
- }, this.writeReceiver());
197
+ }, this.noRefreshReceiver());
87
198
  }
88
199
  /**
89
- * Send one PATCH to an exact API65 DMO route without refresh, retry or redirect.
90
- * Callers must qualify the patch and authorize execution independently; this is transport only.
91
- * @param {string} dataModelObjectName Exact qualified DMO API name.
92
- * @param {DmoUpdatePatch} patch Caller-qualified update payload, not validated here.
93
- * @returns {Promise<unknown>} Untrusted response, never proof of a successful update.
200
+ * PATCH the full authored definition on the native API68 Segment route; the schedule keys go
201
+ * along only when `schedule` is set (the schedule of the file differs from the org's).
202
+ * @param {unknown} value Complete independently admitted desired Segment document.
203
+ * @param {boolean} [schedule] Whether to send the schedule of the file.
204
+ * @param {ReadonlyMap<string, string>} [children] Waterfall child API name to target definition ID.
205
+ * @returns {Promise<unknown>} Untrusted single-attempt response, never settlement evidence.
94
206
  */
95
- async patchDataModelObject(dataModelObjectName, patch) {
96
- if (this.apiVersion !== '65.0' || !/^[A-Za-z][A-Za-z0-9_]*__dlm$/u.test(dataModelObjectName))
207
+ async patchSegment(value, schedule = false, children) {
208
+ if (this.selection.requested !== '68.0')
97
209
  throw new ConnectError('INVALID_REQUEST');
98
- try {
99
- return await this.send({
100
- method: 'PATCH',
101
- url: this.safeUrl(`${this.prefix}data-model-objects/${dataModelObjectName}`),
102
- body: JSON.stringify(patch),
103
- headers: { 'content-type': 'application/json' },
104
- }, this.writeReceiver());
105
- }
106
- catch (error) {
107
- if (error instanceof ConnectError)
108
- throw error;
210
+ const document = validateSegmentDocument(value);
211
+ return this.send({
212
+ method: 'PATCH',
213
+ url: this.safeUrl(`${this.prefix}segments/${document.identity.apiName}`),
214
+ body: JSON.stringify(segmentWriteBody(document, false, schedule, children)),
215
+ headers: { 'content-type': 'application/json' },
216
+ }, this.noRefreshReceiver());
217
+ }
218
+ /**
219
+ * Create exactly one native68 IR owner without refresh, replay or redirect.
220
+ * @param {unknown} value Complete independently admitted portable definition.
221
+ * @param {string} [dataSpacePrefix] Prefix of the ruleset's data space; required outside default.
222
+ * @returns {Promise<unknown>} Untrusted response, never settlement evidence.
223
+ */
224
+ async createIdentityResolution(value, dataSpacePrefix) {
225
+ if (this.selection.requested !== '68.0')
109
226
  throw new ConnectError('INVALID_REQUEST');
110
- }
227
+ return this.send({
228
+ method: 'POST',
229
+ url: this.safeUrl(`${this.prefix}identity-resolutions`),
230
+ body: JSON.stringify(buildNativeIdentityResolutionCreate(value, dataSpacePrefix)),
231
+ headers: { 'content-type': 'application/json' },
232
+ }, this.noRefreshReceiver());
233
+ }
234
+ /**
235
+ * PATCH the complete preserved input shape on one exact native68 owner; never run processing.
236
+ * @param {unknown} value Complete independently admitted desired definition.
237
+ * @param {unknown} [current] Current target definition; lists it has and the file empties are sent empty.
238
+ * @returns {Promise<unknown>} Untrusted response, never settlement evidence.
239
+ */
240
+ async patchIdentityResolution(value, current) {
241
+ if (this.selection.requested !== '68.0')
242
+ throw new ConnectError('INVALID_REQUEST');
243
+ const document = nativeIdentityResolutionDocument(value);
244
+ return this.send({
245
+ method: 'PATCH',
246
+ url: this.safeUrl(`${this.prefix}identity-resolutions/${document.identity.apiName}`),
247
+ body: JSON.stringify(buildNativeIdentityResolutionUpdate(document, current)),
248
+ headers: { 'content-type': 'application/json' },
249
+ }, this.noRefreshReceiver());
250
+ }
251
+ /**
252
+ * Delete exactly one native68 owner by its freshly resolved Salesforce record ID.
253
+ * No name routing, refresh, replay, redirect or arbitrary DELETE path is exposed.
254
+ * @param {string} id Independently bound target-local IR record ID.
255
+ * @returns {Promise<void>} Acknowledged HTTP204 only, never owner absence proof.
256
+ */
257
+ async deleteIdentityResolution(id) {
258
+ if (this.selection.requested !== '68.0' ||
259
+ typeof id !== 'string' ||
260
+ !/^1ir[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/u.test(id))
261
+ throw new ConnectError('INVALID_REQUEST');
262
+ const noContent = Symbol('identity-resolution-deleted');
263
+ const response = await this.send({ method: 'DELETE', url: this.safeUrl(`${this.prefix}identity-resolutions/${id}`) }, this.noRefreshReceiver(), noContent);
264
+ if (response !== noContent)
265
+ throw new ConnectError('REQUEST_FAILED');
266
+ }
267
+ /**
268
+ * Delete one exact native68 Segment by API name, without replay or redirect.
269
+ * @param {string} apiName Freshly matched target API name.
270
+ * @returns {Promise<void>} HTTP204 acknowledgement, not independent absence proof.
271
+ */
272
+ async deleteSegment(apiName) {
273
+ if (this.selection.requested !== '68.0' || !/^[A-Za-z][A-Za-z0-9_]{0,199}$/u.test(apiName))
274
+ throw new ConnectError('INVALID_REQUEST');
275
+ const noContent = Symbol('segment-deleted');
276
+ const response = await this.send({ method: 'DELETE', url: this.safeUrl(`${this.prefix}segments/${apiName}`) }, this.noRefreshReceiver(), noContent);
277
+ if (response !== noContent)
278
+ throw new ConnectError('REQUEST_FAILED');
111
279
  }
112
- writeReceiver() {
280
+ /**
281
+ * Publish one native API68 Segment by its record ID: one POST without a body, never resent
282
+ * after a reset, timeout, 429 or 503 (only a request that provably never left is repeated).
283
+ * @param {string} marketSegmentId Freshly read `1sg` record ID of the segment.
284
+ * @returns {Promise<unknown>} Untrusted acknowledgement (publishStatus, jobId), not the result.
285
+ */
286
+ async publishSegment(marketSegmentId) {
287
+ if (this.selection.requested !== '68.0' ||
288
+ typeof marketSegmentId !== 'string' ||
289
+ !/^1sg[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/u.test(marketSegmentId))
290
+ throw new ConnectError('INVALID_REQUEST');
291
+ return this.send({
292
+ method: 'POST',
293
+ url: this.safeUrl(`${this.prefix}segments/${marketSegmentId}/actions/publish`),
294
+ // JSforce never sends a POST whose body is undefined (the request hangs unsent);
295
+ // an empty string goes out as Content-Length 0, the bodiless POST the route expects.
296
+ body: '',
297
+ }, this.noRefreshReceiver());
298
+ }
299
+ /**
300
+ * Run one read-only SOQL query (the core `/query` route, outside SSOT) over the command's own
301
+ * connection, without refresh or redirect; the first page only. Callers check `done`.
302
+ * @param {string} query SOQL built only from validated identifiers and static text.
303
+ * @returns {Promise<unknown>} Untrusted query response.
304
+ */
305
+ async soql(query) {
306
+ if (this.selection.restSelector === 'latest' || typeof query !== 'string' || !query.trim())
307
+ throw new ConnectError('INVALID_REQUEST');
308
+ return this.send({
309
+ method: 'GET',
310
+ url: `${this.origin}/services/data/${this.selection.restSelector}/query?q=${encodeURIComponent(query)}`,
311
+ }, this.noRefreshReceiver());
312
+ }
313
+ noRefreshReceiver() {
113
314
  const receiver = Object.create(this.connection);
114
315
  Object.defineProperty(receiver, '_refreshDelegate', { value: undefined });
115
316
  return receiver;
116
317
  }
117
318
  async read(path, noContentResponse) {
118
- return this.send({ method: 'GET', url: this.safeUrl(path) }, this.connection, noContentResponse);
319
+ return this.send({ method: 'GET', url: this.safeUrl(path) }, this.noRefreshReceiver(), noContentResponse);
119
320
  }
120
321
  async send(request, receiver, noContentResponse) {
322
+ const method = typeof request === 'object' ? String(request.method ?? 'GET').toUpperCase() : 'GET';
323
+ for (let attempt = 1;; attempt++) {
324
+ try {
325
+ return await this.sendOnce(request, receiver, noContentResponse);
326
+ }
327
+ catch (error) {
328
+ const plan = retryPlan(method, attempt, error);
329
+ if (!plan)
330
+ throw error;
331
+ const url = typeof request === 'object' ? request.url : request;
332
+ const route = typeof url === 'string' ? url.split('?')[0].replace(this.origin, '') : '';
333
+ connectRetry.warn(`${method} ${route} failed (${plan.reason}); retrying in ${Math.ceil(plan.wait / 1000)} s (attempt ${attempt + 1} of ${connectRetry.attempts}).`);
334
+ await connectRetry.sleep(plan.wait);
335
+ }
336
+ }
337
+ }
338
+ async sendOnce(request, receiver, noContentResponse) {
339
+ let responseStatus;
340
+ let diagnostic;
341
+ const transport = '_transport' in receiver
342
+ ? receiver._transport
343
+ : undefined;
344
+ // Observe this request before JSforce discards numeric wire error status and headers.
345
+ const observer = transport && typeof transport.httpRequest === 'function'
346
+ ? {
347
+ httpRequest: (input, options) => {
348
+ const pending = transport.httpRequest.call(transport, input, options);
349
+ const observed = pending.then((response) => {
350
+ const status = response?.statusCode;
351
+ const headers = diagnosticDataProperty(response, 'headers');
352
+ diagnostic = apiDiagnostic(status, diagnosticDataProperty(response, 'body'), headers, diagnosticRequestId(headers));
353
+ if (typeof status === 'number' &&
354
+ Number.isInteger(status) &&
355
+ status >= 400 &&
356
+ status <= 599)
357
+ responseStatus = status;
358
+ return response;
359
+ });
360
+ return Object.assign(observed, { stream: () => pending.stream() });
361
+ },
362
+ }
363
+ : undefined;
121
364
  try {
122
- return await receiver.request(request,
123
- // Core narrows options to JSON, but its JSforce transport supports a redirect guard.
365
+ return await receiver.request(plainTextRequest(request),
366
+ // Core narrows options to JSON, but JSforce supports request-local transport/redirect guards.
124
367
  {
368
+ ...(observer ? { transport: observer } : {}),
125
369
  noContentResponse,
126
- retry: { maxRetries: 0 },
370
+ retry: { maxRetries: 0, methods: [] },
127
371
  followRedirect: () => {
128
372
  throw new ConnectError('INVALID_REQUEST');
129
373
  },
@@ -135,146 +379,42 @@ export class ConnectClient {
135
379
  const status = error && typeof error === 'object' && 'statusCode' in error ? error.statusCode : undefined;
136
380
  const statusCode = typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599
137
381
  ? status
138
- : undefined;
382
+ : responseStatus;
139
383
  const expired = error &&
140
384
  typeof error === 'object' &&
141
385
  'name' in error &&
142
386
  error.name === 'INVALID_SESSION_ID';
143
- throw new ConnectError(statusCode === 401 || expired ? 'AUTHENTICATION_FAILED' : 'REQUEST_FAILED', statusCode);
144
- }
145
- }
146
- /**
147
- * Read the offset-paginated DMO inventory, without projecting resource fields.
148
- * A short page terminates the list; unsupported continuation shapes fail closed.
149
- * @returns {Promise<Array<Record<string, unknown>>>} Complete raw DMO entries or an error, never a partial list.
150
- */
151
- async listDataModelObjects() {
152
- const result = [];
153
- const identities = new Set();
154
- const limit = 50;
155
- // The official endpoint caps SOQL offsets at 2000. Never probe beyond it.
156
- for (let offset = 0; offset <= 2000; offset += limit) {
157
- const page = await this.get(`${this.prefix}data-model-objects?limit=${limit}&offset=${offset}&orderBy=ASC`);
158
- if (!page || typeof page !== 'object' || Array.isArray(page)) {
159
- throw new ConnectError('INVALID_PAGE');
160
- }
161
- const envelope = page;
162
- if (!Array.isArray(envelope.dataModelObject) ||
163
- envelope.dataModelObject.length > limit ||
164
- // DMO pagination has no documented server-provided continuation URL/token.
165
- ['nextPageUrl', 'nextPageToken'].some((key) => envelope[key] != undefined)) {
166
- throw new ConnectError('INVALID_PAGE');
167
- }
168
- for (const entry of envelope.dataModelObject) {
169
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
170
- throw new ConnectError('INVALID_PAGE');
171
- }
172
- const item = entry;
173
- if (typeof item.name !== 'string' ||
174
- !item.name.trim() ||
175
- typeof item.dataSpaceName !== 'string' ||
176
- !item.dataSpaceName.trim()) {
177
- throw new ConnectError('INVALID_PAGE');
178
- }
179
- const identity = JSON.stringify([item.dataSpaceName, item.name]);
180
- if (identities.has(identity))
181
- throw new ConnectError('INCOMPLETE_LIST');
182
- identities.add(identity);
183
- result.push(item);
184
- }
185
- if (envelope.dataModelObject.length < limit)
186
- return result;
187
- }
188
- // A full final permitted page cannot prove exhaustion, even if exactly full.
189
- throw new ConnectError('INCOMPLETE_LIST');
190
- }
191
- /**
192
- * Acquire raw incoming and outgoing relationships in one explicit data space.
193
- * Pagination metadata must prove exhaustion; raw records are not portable artifacts.
194
- * @param {string} dataModelObjectName Exact DMO API name, including any namespace.
195
- * @param {string} dataSpace Exact server data-space name; never silently defaults.
196
- * @returns {Promise<Array<Record<string, unknown>>>} Complete raw relationships or an error.
197
- */
198
- async listDataModelObjectRelationships(dataModelObjectName, dataSpace) {
199
- if (Number(this.apiVersion) < 64 ||
200
- !/^[A-Za-z][A-Za-z0-9_]*__dlm$/u.test(dataModelObjectName) ||
201
- !/^[A-Za-z][A-Za-z0-9_]*$/u.test(dataSpace))
202
- throw new ConnectError('INVALID_REQUEST');
203
- const result = [];
204
- const identities = new Set();
205
- const limit = 20;
206
- let total;
207
- const envelopeKeys = new Set([
208
- 'relationships',
209
- 'count',
210
- 'totalSize',
211
- 'sortBy',
212
- 'currentPageToken',
213
- 'currentPageUrl',
214
- 'nextPageToken',
215
- 'nextPageUrl',
216
- 'previousPageToken',
217
- 'previousPageUrl',
218
- ]);
219
- // Local safety budget, not a claim about this endpoint's server offset ceiling.
220
- for (let offset = 0; offset <= 2000; offset += limit) {
221
- // JSforce substitutes this private sentinel only for HTTP 204, not malformed JSON.
222
- const emptyResponse = Symbol('relationship-no-content');
223
- const page = await this.read(`${this.prefix}data-model-objects/${dataModelObjectName}/relationships?dataspace=${dataSpace}&limit=${limit}&offset=${offset}&orderBy=ASC&sortBy=DeveloperName`, emptyResponse);
224
- if (page === emptyResponse) {
225
- if (offset === 0)
226
- return [];
227
- throw new ConnectError('INCOMPLETE_LIST');
228
- }
229
- if (!page || typeof page !== 'object' || Array.isArray(page))
230
- throw new ConnectError('INVALID_PAGE');
231
- const envelope = page;
232
- if (Object.keys(envelope).some((key) => !envelopeKeys.has(key)) ||
233
- !Array.isArray(envelope.relationships) ||
234
- envelope.relationships.length > limit ||
235
- (envelope.count !== undefined && envelope.count !== envelope.relationships.length) ||
236
- !Number.isSafeInteger(envelope.totalSize) ||
237
- envelope.totalSize < 0 ||
238
- (envelope.sortBy != undefined && envelope.sortBy !== 'DeveloperName') ||
239
- [...envelopeKeys].some((key) => (key.endsWith('Url') || key.endsWith('Token')) &&
240
- envelope[key] != undefined &&
241
- typeof envelope[key] !== 'string'))
242
- throw new ConnectError('INVALID_PAGE');
243
- if (total !== undefined && total !== envelope.totalSize)
244
- throw new ConnectError('INCOMPLETE_LIST');
245
- total = envelope.totalSize;
246
- for (const entry of envelope.relationships) {
247
- if (!entry || typeof entry !== 'object' || Array.isArray(entry))
248
- throw new ConnectError('INVALID_PAGE');
249
- const item = entry;
250
- const entities = [item.sourceObject, item.targetObject];
251
- if (typeof item.name !== 'string' ||
252
- !item.name.trim() ||
253
- entities.some((entity) => !entity ||
254
- typeof entity !== 'object' ||
255
- Array.isArray(entity) ||
256
- typeof entity.name !== 'string' ||
257
- !entity.name) ||
258
- !entities.some((entity) => entity.name === dataModelObjectName))
259
- throw new ConnectError('INVALID_PAGE');
260
- if (identities.has(item.name))
261
- throw new ConnectError('INCOMPLETE_LIST');
262
- identities.add(item.name);
263
- // Preserve every field, including unfamiliar semantics, for later strict projection.
264
- result.push(item);
265
- }
266
- if (result.length > total)
267
- throw new ConnectError('INVALID_PAGE');
268
- if (result.length === total) {
269
- if (envelope.nextPageUrl || envelope.nextPageToken)
270
- throw new ConnectError('INCOMPLETE_LIST');
271
- return result;
272
- }
273
- if (envelope.relationships.length !== limit)
274
- throw new ConnectError('INCOMPLETE_LIST');
275
- // Response URLs can reference legacy routes/versions. Never follow them.
387
+ // Core preserves the parsed single REST error in data. Never infer absence from
388
+ // HTTP status, message text, raw JSON strings or a mixed/malformed error envelope.
389
+ const nativeError = error;
390
+ const data = nativeError?.data;
391
+ // A GET or DELETE may answer 404 ENTITY_IS_DELETED while an item is being deleted (live
392
+ // API 68, calculated insight); callers decide whether that code means absent.
393
+ const absence = nativeAbsenceCodes.find((value) => value === nativeError?.errorCode);
394
+ const nativeCode = typeof request === 'object' &&
395
+ (request.method === 'GET' || request.method === 'DELETE') &&
396
+ statusCode === 404 &&
397
+ !expired &&
398
+ absence !== undefined &&
399
+ nativeError?.name === absence &&
400
+ !!data &&
401
+ typeof data === 'object' &&
402
+ !Array.isArray(data) &&
403
+ Object.keys(data).length === 2 &&
404
+ 'errorCode' in data &&
405
+ data.errorCode === absence &&
406
+ 'message' in data &&
407
+ typeof data.message === 'string'
408
+ ? absence
409
+ : undefined;
410
+ const code = statusCode === undefined && !expired ? networkCode(error) : undefined;
411
+ const failure = retainConnectDiagnostic(new ConnectError(statusCode === 401 || expired ? 'AUTHENTICATION_FAILED' : 'REQUEST_FAILED', statusCode, nativeCode), diagnostic ??
412
+ apiDiagnostic(statusCode, diagnosticDataProperty(error, 'data')) ??
413
+ connectDiagnostic(statusCode));
414
+ if (code)
415
+ networkCodes.set(failure, code);
416
+ throw failure;
276
417
  }
277
- throw new ConnectError('INCOMPLETE_LIST');
278
418
  }
279
419
  safeUrl(path) {
280
420
  // Reject normalization ambiguities before URL parsing, including nested encodings.