sf-plugin-data 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +589 -2
  3. package/bin/run.js +4 -0
  4. package/docs/artifact-format.md +527 -0
  5. package/docs/capabilities.md +1208 -0
  6. package/docs/git-workflow.md +160 -0
  7. package/docs/handover.md +10446 -0
  8. package/lib/api.d.ts +7 -0
  9. package/lib/api.js +7 -0
  10. package/lib/artifacts/code-fields.d.ts +49 -0
  11. package/lib/artifacts/code-fields.js +142 -0
  12. package/lib/artifacts/data-graph-document.d.ts +29 -0
  13. package/lib/artifacts/data-graph-document.js +52 -0
  14. package/lib/artifacts/data-space-field.d.ts +65 -0
  15. package/lib/artifacts/data-space-field.js +98 -0
  16. package/lib/artifacts/data-stream-document.d.ts +264 -0
  17. package/lib/artifacts/data-stream-document.js +680 -0
  18. package/lib/artifacts/data-transform-document.d.ts +152 -0
  19. package/lib/artifacts/data-transform-document.js +560 -0
  20. package/lib/artifacts/dependency-selection.d.ts +51 -0
  21. package/lib/artifacts/dependency-selection.js +154 -0
  22. package/lib/artifacts/dlo-document.d.ts +93 -0
  23. package/lib/artifacts/dlo-document.js +253 -0
  24. package/lib/artifacts/enum-case.d.ts +39 -0
  25. package/lib/artifacts/enum-case.js +67 -0
  26. package/lib/artifacts/git-deploy-selection.d.ts +68 -0
  27. package/lib/artifacts/git-deploy-selection.js +474 -0
  28. package/lib/artifacts/identity-resolution-document.d.ts +133 -0
  29. package/lib/artifacts/identity-resolution-document.js +625 -0
  30. package/lib/artifacts/mapping-document.d.ts +1 -0
  31. package/lib/artifacts/mapping-document.js +1 -0
  32. package/lib/artifacts/native-calculated-insight-document.d.ts +142 -0
  33. package/lib/artifacts/native-calculated-insight-document.js +321 -0
  34. package/lib/artifacts/native-data-graph-document.d.ts +124 -0
  35. package/lib/artifacts/native-data-graph-document.js +780 -0
  36. package/lib/artifacts/native-dmo-document.d.ts +151 -0
  37. package/lib/artifacts/native-dmo-document.js +313 -0
  38. package/lib/artifacts/native-mapping-document.d.ts +67 -0
  39. package/lib/artifacts/native-mapping-document.js +187 -0
  40. package/lib/artifacts/native-relationship-document.d.ts +76 -0
  41. package/lib/artifacts/native-relationship-document.js +232 -0
  42. package/lib/artifacts/path-selector.d.ts +55 -0
  43. package/lib/artifacts/path-selector.js +167 -0
  44. package/lib/artifacts/read-deploy-input.d.ts +239 -0
  45. package/lib/artifacts/read-deploy-input.js +1359 -0
  46. package/lib/artifacts/segment-document.d.ts +183 -0
  47. package/lib/artifacts/segment-document.js +570 -0
  48. package/lib/artifacts/verbatim-document.d.ts +203 -0
  49. package/lib/artifacts/verbatim-document.js +339 -0
  50. package/lib/artifacts/write-data-graph.d.ts +17 -0
  51. package/lib/artifacts/write-data-graph.js +162 -0
  52. package/lib/artifacts/write-data-stream.d.ts +11 -0
  53. package/lib/artifacts/write-data-stream.js +175 -0
  54. package/lib/artifacts/write-data-transform.d.ts +11 -0
  55. package/lib/artifacts/write-data-transform.js +180 -0
  56. package/lib/artifacts/write-dlo.d.ts +11 -0
  57. package/lib/artifacts/write-dlo.js +158 -0
  58. package/lib/artifacts/write-identity-resolution.d.ts +18 -0
  59. package/lib/artifacts/write-identity-resolution.js +165 -0
  60. package/lib/artifacts/write-mapping-definition.d.ts +17 -0
  61. package/lib/artifacts/write-mapping-definition.js +127 -0
  62. package/lib/artifacts/write-member-export.d.ts +88 -0
  63. package/lib/artifacts/write-member-export.js +199 -0
  64. package/lib/artifacts/write-native-calculated-insight.d.ts +21 -0
  65. package/lib/artifacts/write-native-calculated-insight.js +176 -0
  66. package/lib/artifacts/write-native-dmo.d.ts +11 -0
  67. package/lib/artifacts/write-native-dmo.js +158 -0
  68. package/lib/artifacts/write-native-mapping.d.ts +11 -0
  69. package/lib/artifacts/write-native-mapping.js +157 -0
  70. package/lib/artifacts/write-native-relationship.d.ts +11 -0
  71. package/lib/artifacts/write-native-relationship.js +157 -0
  72. package/lib/artifacts/write-segment.d.ts +26 -0
  73. package/lib/artifacts/write-segment.js +212 -0
  74. package/lib/commands/data360/delete.d.ts +280 -0
  75. package/lib/commands/data360/delete.js +2297 -0
  76. package/lib/commands/data360/deploy.d.ts +303 -0
  77. package/lib/commands/data360/deploy.js +2400 -0
  78. package/lib/commands/data360/publish.d.ts +93 -0
  79. package/lib/commands/data360/publish.js +292 -0
  80. package/lib/commands/data360/retrieve.d.ts +322 -0
  81. package/lib/commands/data360/retrieve.js +1963 -0
  82. package/lib/commands/data360/segment/members/export.d.ts +101 -0
  83. package/lib/commands/data360/segment/members/export.js +318 -0
  84. package/lib/errors/codes/calculated-insight.d.ts +2 -0
  85. package/lib/errors/codes/calculated-insight.js +25 -0
  86. package/lib/errors/codes/data-graph.d.ts +2 -0
  87. package/lib/errors/codes/data-graph.js +22 -0
  88. package/lib/errors/codes/data-stream.d.ts +2 -0
  89. package/lib/errors/codes/data-stream.js +70 -0
  90. package/lib/errors/codes/data-transform.d.ts +2 -0
  91. package/lib/errors/codes/data-transform.js +35 -0
  92. package/lib/errors/codes/dependency.d.ts +2 -0
  93. package/lib/errors/codes/dependency.js +11 -0
  94. package/lib/errors/codes/dlo.d.ts +2 -0
  95. package/lib/errors/codes/dlo.js +31 -0
  96. package/lib/errors/codes/dmo.d.ts +2 -0
  97. package/lib/errors/codes/dmo.js +28 -0
  98. package/lib/errors/codes/general.d.ts +2 -0
  99. package/lib/errors/codes/general.js +57 -0
  100. package/lib/errors/codes/identity-resolution.d.ts +2 -0
  101. package/lib/errors/codes/identity-resolution.js +24 -0
  102. package/lib/errors/codes/mapping.d.ts +2 -0
  103. package/lib/errors/codes/mapping.js +42 -0
  104. package/lib/errors/codes/relationship.d.ts +2 -0
  105. package/lib/errors/codes/relationship.js +21 -0
  106. package/lib/errors/codes/segment.d.ts +2 -0
  107. package/lib/errors/codes/segment.js +49 -0
  108. package/lib/errors/registry.d.ts +60 -0
  109. package/lib/errors/registry.js +123 -0
  110. package/lib/plugin.d.ts +5 -0
  111. package/lib/plugin.js +5 -0
  112. package/lib/services/acquire-retrieve-selection.d.ts +43 -0
  113. package/lib/services/acquire-retrieve-selection.js +145 -0
  114. package/lib/services/bind-identity-resolution-dependencies.d.ts +53 -0
  115. package/lib/services/bind-identity-resolution-dependencies.js +238 -0
  116. package/lib/services/bind-segment-dependencies.d.ts +49 -0
  117. package/lib/services/bind-segment-dependencies.js +115 -0
  118. package/lib/services/bounded-reads.d.ts +17 -0
  119. package/lib/services/bounded-reads.js +42 -0
  120. package/lib/services/calculated-insight-sql-checks.d.ts +33 -0
  121. package/lib/services/calculated-insight-sql-checks.js +193 -0
  122. package/lib/services/command-dlo.d.ts +48 -0
  123. package/lib/services/command-dlo.js +103 -0
  124. package/lib/services/command-native-data-graph.d.ts +54 -0
  125. package/lib/services/command-native-data-graph.js +485 -0
  126. package/lib/services/command-native-data-stream.d.ts +104 -0
  127. package/lib/services/command-native-data-stream.js +257 -0
  128. package/lib/services/command-native-dmo.d.ts +124 -0
  129. package/lib/services/command-native-dmo.js +338 -0
  130. package/lib/services/command-native-mapping.d.ts +65 -0
  131. package/lib/services/command-native-mapping.js +129 -0
  132. package/lib/services/command-native-relationship.d.ts +46 -0
  133. package/lib/services/command-native-relationship.js +103 -0
  134. package/lib/services/cross-dataspace-deploy.d.ts +111 -0
  135. package/lib/services/cross-dataspace-deploy.js +493 -0
  136. package/lib/services/cross-dataspace-rename.d.ts +74 -0
  137. package/lib/services/cross-dataspace-rename.js +1314 -0
  138. package/lib/services/cross-dataspace-sql.d.ts +109 -0
  139. package/lib/services/cross-dataspace-sql.js +1301 -0
  140. package/lib/services/cross-space-context.d.ts +23 -0
  141. package/lib/services/cross-space-context.js +36 -0
  142. package/lib/services/crud-plan.d.ts +137 -0
  143. package/lib/services/crud-plan.js +408 -0
  144. package/lib/services/data-space-check.d.ts +89 -0
  145. package/lib/services/data-space-check.js +162 -0
  146. package/lib/services/data-space-prefix.d.ts +77 -0
  147. package/lib/services/data-space-prefix.js +127 -0
  148. package/lib/services/data-transform-space.d.ts +31 -0
  149. package/lib/services/data-transform-space.js +79 -0
  150. package/lib/services/delete-calculated-insight.d.ts +44 -0
  151. package/lib/services/delete-calculated-insight.js +101 -0
  152. package/lib/services/delete-data-transform.d.ts +52 -0
  153. package/lib/services/delete-data-transform.js +222 -0
  154. package/lib/services/delete-dmo-field.d.ts +211 -0
  155. package/lib/services/delete-dmo-field.js +472 -0
  156. package/lib/services/delete-identity-resolution.d.ts +43 -0
  157. package/lib/services/delete-identity-resolution.js +295 -0
  158. package/lib/services/delete-segment.d.ts +42 -0
  159. package/lib/services/delete-segment.js +248 -0
  160. package/lib/services/deploy-result.d.ts +54 -0
  161. package/lib/services/deploy-result.js +60 -0
  162. package/lib/services/escaped-copy.d.ts +23 -0
  163. package/lib/services/escaped-copy.js +88 -0
  164. package/lib/services/execute-calculated-insight-deploy.d.ts +42 -0
  165. package/lib/services/execute-calculated-insight-deploy.js +96 -0
  166. package/lib/services/execute-data-transform-deploy.d.ts +56 -0
  167. package/lib/services/execute-data-transform-deploy.js +168 -0
  168. package/lib/services/execute-native-identity-resolution-deploy.d.ts +48 -0
  169. package/lib/services/execute-native-identity-resolution-deploy.js +360 -0
  170. package/lib/services/execute-segment-deploy.d.ts +45 -0
  171. package/lib/services/execute-segment-deploy.js +393 -0
  172. package/lib/services/local-file-removal.d.ts +36 -0
  173. package/lib/services/local-file-removal.js +103 -0
  174. package/lib/services/native-calculated-insight.d.ts +87 -0
  175. package/lib/services/native-calculated-insight.js +164 -0
  176. package/lib/services/native-crm-data-stream.d.ts +91 -0
  177. package/lib/services/native-crm-data-stream.js +272 -0
  178. package/lib/services/native-data-graph-context.d.ts +12 -0
  179. package/lib/services/native-data-graph-context.js +139 -0
  180. package/lib/services/native-data-graph-crd.d.ts +261 -0
  181. package/lib/services/native-data-graph-crd.js +866 -0
  182. package/lib/services/native-data-stream.d.ts +329 -0
  183. package/lib/services/native-data-stream.js +1830 -0
  184. package/lib/services/native-dlo.d.ts +163 -0
  185. package/lib/services/native-dlo.js +402 -0
  186. package/lib/services/native-dmo.d.ts +191 -0
  187. package/lib/services/native-dmo.js +614 -0
  188. package/lib/services/native-mapping.d.ts +255 -0
  189. package/lib/services/native-mapping.js +1226 -0
  190. package/lib/services/native-relationship.d.ts +132 -0
  191. package/lib/services/native-relationship.js +512 -0
  192. package/lib/services/operation-diagnostic.d.ts +83 -0
  193. package/lib/services/operation-diagnostic.js +272 -0
  194. package/lib/services/preflight-calculated-insight-deploy.d.ts +58 -0
  195. package/lib/services/preflight-calculated-insight-deploy.js +95 -0
  196. package/lib/services/preflight-data-transform-deploy.d.ts +33 -0
  197. package/lib/services/preflight-data-transform-deploy.js +104 -0
  198. package/lib/services/preflight-identity-resolution-deploy.d.ts +107 -0
  199. package/lib/services/preflight-identity-resolution-deploy.js +281 -0
  200. package/lib/services/preflight-segment-deploy.d.ts +31 -0
  201. package/lib/services/preflight-segment-deploy.js +109 -0
  202. package/lib/services/publish-calculated-insight.d.ts +40 -0
  203. package/lib/services/publish-calculated-insight.js +95 -0
  204. package/lib/services/publish-segment.d.ts +65 -0
  205. package/lib/services/publish-segment.js +194 -0
  206. package/lib/services/readback-pace.d.ts +16 -0
  207. package/lib/services/readback-pace.js +23 -0
  208. package/lib/services/retrieve-data-transform.d.ts +26 -0
  209. package/lib/services/retrieve-data-transform.js +65 -0
  210. package/lib/services/retrieve-identity-resolution.d.ts +40 -0
  211. package/lib/services/retrieve-identity-resolution.js +87 -0
  212. package/lib/services/retrieve-inventory.d.ts +32 -0
  213. package/lib/services/retrieve-inventory.js +151 -0
  214. package/lib/services/retrieve-segment.d.ts +120 -0
  215. package/lib/services/retrieve-segment.js +502 -0
  216. package/lib/services/segment-lookup.d.ts +46 -0
  217. package/lib/services/segment-lookup.js +108 -0
  218. package/lib/services/segment-members.d.ts +144 -0
  219. package/lib/services/segment-members.js +402 -0
  220. package/lib/services/select-native-retrieve.d.ts +60 -0
  221. package/lib/services/select-native-retrieve.js +226 -0
  222. package/lib/services/settle-calculated-insight.d.ts +22 -0
  223. package/lib/services/settle-calculated-insight.js +53 -0
  224. package/lib/services/sql-tokens.d.ts +58 -0
  225. package/lib/services/sql-tokens.js +147 -0
  226. package/lib/transport/api-version.d.ts +36 -0
  227. package/lib/transport/api-version.js +89 -0
  228. package/lib/transport/bound-ssot.d.ts +27 -0
  229. package/lib/transport/bound-ssot.js +116 -0
  230. package/lib/transport/calculated-insight-rest.d.ts +28 -0
  231. package/lib/transport/calculated-insight-rest.js +62 -0
  232. package/lib/transport/connect-client.d.ts +129 -0
  233. package/lib/transport/connect-client.js +446 -0
  234. package/lib/transport/connect-diagnostic.d.ts +89 -0
  235. package/lib/transport/connect-diagnostic.js +331 -0
  236. package/lib/transport/data-graph-rest.d.ts +27 -0
  237. package/lib/transport/data-graph-rest.js +76 -0
  238. package/lib/transport/data-stream-rest.d.ts +62 -0
  239. package/lib/transport/data-stream-rest.js +348 -0
  240. package/lib/transport/data-transform-rest.d.ts +25 -0
  241. package/lib/transport/data-transform-rest.js +100 -0
  242. package/lib/transport/dlo-native-rest.d.ts +22 -0
  243. package/lib/transport/dlo-native-rest.js +89 -0
  244. package/lib/transport/dlo-rest.d.ts +23 -0
  245. package/lib/transport/dlo-rest.js +135 -0
  246. package/lib/transport/dmo-native-rest.d.ts +18 -0
  247. package/lib/transport/dmo-native-rest.js +55 -0
  248. package/lib/transport/dmo-rest.d.ts +30 -0
  249. package/lib/transport/dmo-rest.js +163 -0
  250. package/lib/transport/mapping-rest.d.ts +63 -0
  251. package/lib/transport/mapping-rest.js +341 -0
  252. package/lib/transport/project-metadata.d.ts +36 -0
  253. package/lib/transport/project-metadata.js +118 -0
  254. package/lib/transport/relationship-rest.d.ts +43 -0
  255. package/lib/transport/relationship-rest.js +201 -0
  256. package/package.json +96 -4
@@ -0,0 +1,502 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { SegmentError, opaqueSegmentSchedule, segmentName, unnamedChildSegment, validateSegmentDocument, waterfallChildIds, waterfallSegmentType, } from '../artifacts/segment-document.js';
3
+ import { ConnectClient } from '../transport/connect-client.js';
4
+ import { getConnectDiagnostic, retainConnectDiagnostic } from '../transport/connect-diagnostic.js';
5
+ import { carryNativeResponse } from '../artifacts/verbatim-document.js';
6
+ import { isDataSpaceName } from '../artifacts/data-space-field.js';
7
+ import { explainInput, explanationOf } from './operation-diagnostic.js';
8
+ const configuration = [
9
+ 'apiName',
10
+ 'displayName',
11
+ 'dataSpace',
12
+ 'segmentType',
13
+ 'segmentOnApiName',
14
+ 'includeDbt',
15
+ 'publishInterval',
16
+ 'lookbackPeriod',
17
+ ];
18
+ // These known observations are private only, not portable definition fields.
19
+ const observations = [
20
+ 'marketSegmentDefinitionId',
21
+ 'marketSegmentId',
22
+ 'segmentStatus',
23
+ 'lastSegmentMemberCount',
24
+ 'createdBy',
25
+ 'createdDate',
26
+ 'lastModifiedBy',
27
+ 'lastModifiedDate',
28
+ 'segmentMembershipDmo',
29
+ 'segmentOnId',
30
+ ];
31
+ /**
32
+ * Validate observed audit/generated references without exporting their org-local identities.
33
+ * @param {Record<string, unknown>} raw Independently acquired exact DBT response.
34
+ * @returns {void} Nothing for the bounded observed shapes.
35
+ */
36
+ function validateObservations(raw) {
37
+ for (const key of ['createdBy', 'lastModifiedBy']) {
38
+ if (!Object.hasOwn(raw, key))
39
+ continue;
40
+ const value = raw[key];
41
+ if (!value ||
42
+ typeof value !== 'object' ||
43
+ Object.keys(value).length !== 1 ||
44
+ typeof value.id !== 'string' ||
45
+ !value.id)
46
+ throw new SegmentError('UNKNOWN_SEGMENT_CONFIGURATION');
47
+ }
48
+ for (const key of ['segmentMembershipDmo']) {
49
+ if (!Object.hasOwn(raw, key))
50
+ continue;
51
+ const value = raw[key];
52
+ if (!value ||
53
+ typeof value !== 'object' ||
54
+ Object.keys(value).length !== 2 ||
55
+ !['historyTable', 'latestTable'].every((field) => typeof value[field] === 'string' && value[field]))
56
+ throw new SegmentError('UNKNOWN_SEGMENT_CONFIGURATION');
57
+ }
58
+ for (const key of ['createdDate', 'lastModifiedDate', 'segmentOnId']) {
59
+ if (Object.hasOwn(raw, key) && (typeof raw[key] !== 'string' || !raw[key]))
60
+ throw new SegmentError('UNKNOWN_SEGMENT_CONFIGURATION');
61
+ }
62
+ if (Object.hasOwn(raw, 'parameters') &&
63
+ (!Array.isArray(raw.parameters) || raw.parameters.length > 0))
64
+ throw new SegmentError('UNSUPPORTED_SEGMENT_VARIANT');
65
+ }
66
+ // The schedule keys of a segment GET: none for a segment that does not refresh.
67
+ const scheduleRead = [
68
+ 'publishScheduleInfo',
69
+ 'publishScheduleStartDateTime',
70
+ 'publishScheduleEndDate',
71
+ 'publishScheduleEndDateTime',
72
+ ];
73
+ const scheduleInfoKeys = new Set([
74
+ 'daysOfWeek',
75
+ 'frequency',
76
+ 'interval',
77
+ 'nextScheduledDate',
78
+ 'timeInfo',
79
+ ]);
80
+ /**
81
+ * Whether a read value is set (neither absent nor null).
82
+ * @param {unknown} value Read value.
83
+ * @returns {boolean} Set.
84
+ */
85
+ const present = (value) => value !== undefined && value !== null;
86
+ /**
87
+ * Project the schedule of a segment GET onto the write shape of the file (live API 68,
88
+ * 2026-11-18): `publishScheduleInfo` gives `frequency`, `interval`, `daysOfWeek` (read as a plain
89
+ * list; an empty one is left out) and `time` (from `timeInfo`, which Salesforce reads back as
90
+ * null); `publishScheduleStartDateTime`, `publishScheduleEndDate` and
91
+ * `publishScheduleEndDateTime` give `startDateTime`, `endDate` and `endDateTime`;
92
+ * `nextScheduledDate` is left out, and so is `publishInterval` beside `publishScheduleInfo`.
93
+ * Without `publishScheduleInfo`, a refresh other than NO_REFRESH (an hourly interval) keeps its
94
+ * `publishInterval`. A segment with NO_REFRESH and no dates has no schedule, so retrieve leaves
95
+ * the key out. Schedule details the plugin does not know (another `publishScheduleInfo` key, a
96
+ * `frequency` that is not text, `daysOfWeek` that is not a list) are UNSUPPORTED_SEGMENT_VARIANT
97
+ * on retrieve; a deploy-mode read gives `opaqueSegmentSchedule`, so a file without `schedule`
98
+ * still deploys and keeps the org schedule.
99
+ * @param {Record<string, unknown>} raw The segment inside the GET response.
100
+ * @param {DocumentMode} [mode] `deploy` (target reads) or `retrieve`.
101
+ * @returns {SegmentSchedule | undefined} Projected schedule, or undefined for none.
102
+ */
103
+ export function projectSegmentSchedule(raw, mode = 'deploy') {
104
+ const info = raw.publishScheduleInfo;
105
+ const dates = {
106
+ ...(present(raw.publishScheduleStartDateTime)
107
+ ? { startDateTime: raw.publishScheduleStartDateTime }
108
+ : {}),
109
+ ...(present(raw.publishScheduleEndDate) ? { endDate: raw.publishScheduleEndDate } : {}),
110
+ ...(present(raw.publishScheduleEndDateTime)
111
+ ? { endDateTime: raw.publishScheduleEndDateTime }
112
+ : {}),
113
+ };
114
+ const unknown = () => {
115
+ if (mode === 'retrieve')
116
+ throw new SegmentError('UNSUPPORTED_SEGMENT_VARIANT');
117
+ return { ...opaqueSegmentSchedule };
118
+ };
119
+ if (!present(info)) {
120
+ if (raw.publishInterval === 'NO_REFRESH' && Object.keys(dates).length === 0)
121
+ return undefined;
122
+ if (typeof raw.publishInterval !== 'string')
123
+ return unknown();
124
+ return { publishInterval: raw.publishInterval, ...dates };
125
+ }
126
+ const read = info;
127
+ if (typeof info !== 'object' ||
128
+ Array.isArray(info) ||
129
+ Object.keys(read).some((key) => !scheduleInfoKeys.has(key)) ||
130
+ typeof read.frequency !== 'string' ||
131
+ (present(read.daysOfWeek) && !Array.isArray(read.daysOfWeek)))
132
+ return unknown();
133
+ const days = read.daysOfWeek;
134
+ return {
135
+ frequency: read.frequency,
136
+ ...(present(read.interval) ? { interval: read.interval } : {}),
137
+ ...(days && days.length > 0 ? { daysOfWeek: structuredClone(days) } : {}),
138
+ ...dates,
139
+ ...(present(read.timeInfo) ? { time: structuredClone(read.timeInfo) } : {}),
140
+ };
141
+ }
142
+ const uiConfiguration = [
143
+ 'apiName',
144
+ 'displayName',
145
+ 'dataSpace',
146
+ 'segmentType',
147
+ 'segmentOnApiName',
148
+ 'includeCriteria',
149
+ 'publishInterval',
150
+ 'lookbackPeriod',
151
+ ];
152
+ // Server-owned keys of a UI segment GET beyond the DBT observations.
153
+ const uiObservations = ['lastPublishedEndDateTime', 'publishStatus', 'segmentMembershipTable'];
154
+ // What a GET of another type (Waterfall, Dynamic, ...) must hold.
155
+ const otherConfiguration = [
156
+ 'apiName',
157
+ 'displayName',
158
+ 'dataSpace',
159
+ 'segmentType',
160
+ 'segmentOnApiName',
161
+ 'publishInterval',
162
+ ];
163
+ /**
164
+ * Project a segment of a type other than DBT (UI and the other types) onto the file: the GET
165
+ * minus server-owned keys, with the schedule projected by `projectSegmentSchedule`. A UI
166
+ * segment's `includeCriteria` is parsed from its JSON string (plain text) into an object;
167
+ * another type keeps its lookback when it has one. Retrieve keeps keys the plugin does not know in
168
+ * `spec`; deploy refuses them (UNKNOWN_SEGMENT_CONFIGURATION). Criteria that are not a JSON
169
+ * object, and parameters (no write takes them), are UNSUPPORTED_SEGMENT_VARIANT. A Waterfall's
170
+ * criteria holding only its child segments become `childSegments`, each child named through
171
+ * `children` (definition ID to API name); a child it cannot name keeps the criteria as read on
172
+ * retrieve (deploy refuses that file) and is `unnamedChildSegment` on a deploy-mode read.
173
+ * @param {Record<string, unknown>} raw The segment inside the GET response.
174
+ * @param {string} apiName Requested exact identity.
175
+ * @param {DocumentMode} mode `deploy` (strict observed fields) or `retrieve`.
176
+ * @param {ReadonlyMap<string, string>} children Child definition ID to segment API name.
177
+ * @returns {{candidate: SegmentDocument; runtime: Record<string, unknown>}} Detached portable and private projections.
178
+ */
179
+ function projectTypedSegment(raw, apiName, mode, children) {
180
+ const ui = raw.segmentType === 'UI';
181
+ const required = ui ? uiConfiguration : otherConfiguration;
182
+ const childIds = raw.segmentType === waterfallSegmentType && typeof raw.includeCriteria === 'string'
183
+ ? waterfallChildIds(raw.includeCriteria)
184
+ : undefined;
185
+ const named = childIds?.map((id) => children.get(id));
186
+ const childSegments = named && (mode !== 'retrieve' || named.every((name) => name !== undefined))
187
+ ? named.map((name) => name ?? unnamedChildSegment)
188
+ : undefined;
189
+ const known = new Set([
190
+ ...(childSegments ? ['includeCriteria'] : []),
191
+ ...required,
192
+ ...observations,
193
+ ...uiObservations,
194
+ ...scheduleRead,
195
+ 'lookbackPeriod',
196
+ 'description',
197
+ 'parameters',
198
+ ]);
199
+ const unknown = Object.keys(raw).filter((key) => !known.has(key));
200
+ if (required.some((key) => !Object.hasOwn(raw, key)))
201
+ throw new SegmentError(mode === 'retrieve' ? 'UNSUPPORTED_SEGMENT_VARIANT' : 'UNKNOWN_SEGMENT_CONFIGURATION');
202
+ if (mode !== 'retrieve' && unknown.length > 0)
203
+ throw new SegmentError('UNKNOWN_SEGMENT_CONFIGURATION');
204
+ // An unknown key named like a spec key could not be told apart from it.
205
+ if (unknown.some((key) => ['segmentOn', 'models', 'includeDbt', 'schedule'].includes(key)))
206
+ throw new SegmentError('UNKNOWN_SEGMENT_CONFIGURATION');
207
+ if (Object.hasOwn(raw, 'parameters') && !isDeepStrictEqual(raw.parameters, []))
208
+ throw new SegmentError('UNSUPPORTED_SEGMENT_VARIANT');
209
+ let criteria;
210
+ if (ui) {
211
+ if (typeof raw.includeCriteria !== 'string')
212
+ throw new SegmentError('UNSUPPORTED_SEGMENT_VARIANT');
213
+ try {
214
+ criteria = JSON.parse(raw.includeCriteria);
215
+ }
216
+ catch {
217
+ throw new SegmentError('UNSUPPORTED_SEGMENT_VARIANT');
218
+ }
219
+ if (!criteria || typeof criteria !== 'object' || Array.isArray(criteria))
220
+ throw new SegmentError('UNSUPPORTED_SEGMENT_VARIANT');
221
+ }
222
+ const schedule = projectSegmentSchedule(raw, mode);
223
+ const candidate = validateSegmentDocument({
224
+ schemaVersion: 1,
225
+ kind: 'segment',
226
+ c__dataSpace: raw.dataSpace,
227
+ identity: { apiName },
228
+ spec: {
229
+ displayName: raw.displayName,
230
+ // Salesforce leaves description out of the GET when it is empty.
231
+ description: Object.hasOwn(raw, 'description') ? raw.description : '',
232
+ segmentType: raw.segmentType,
233
+ segmentOn: { kind: 'dmo', apiName: raw.segmentOnApiName },
234
+ ...(ui ? { includeCriteria: criteria } : {}),
235
+ ...(Object.hasOwn(raw, 'lookbackPeriod') ? { lookbackPeriod: raw.lookbackPeriod } : {}),
236
+ ...(schedule ? { schedule } : {}),
237
+ ...(childSegments ? { childSegments } : {}),
238
+ ...Object.fromEntries(unknown.map((key) => [key, raw[key]])),
239
+ },
240
+ }, mode);
241
+ if (mode !== 'retrieve')
242
+ validateObservations(raw);
243
+ return { candidate, runtime: structuredClone(raw) };
244
+ }
245
+ /**
246
+ * Admit an exact response without discarding unknown potentially meaningful fields. Retrieve mode
247
+ * reads `segments[0]` of any wrapper, keeps keys the plugin does not know in `spec` (and extra
248
+ * `includeDbt` keys in `spec.includeDbt`), does not check the observed fields, and refuses only
249
+ * what the file cannot represent (no DBT configuration, parameters, a schedule the file cannot
250
+ * hold, another source kind, a model name unfit for a file), so the segment is written verbatim;
251
+ * the model SQL is kept as read (plain text, plainTextHeaders).
252
+ * Segments of other types than DBT are projected by `projectTypedSegment`.
253
+ * @param {unknown} response Untrusted API68 exact GET response.
254
+ * @param {string} apiName Requested exact identity.
255
+ * @param {DocumentMode} [mode] `deploy` (strict) or `retrieve` (keeps unknown keys).
256
+ * @param {ReadonlyMap<string, string>} [children] Waterfall child definition ID to API name.
257
+ * @returns {{candidate: SegmentDocument; runtime: Record<string, unknown>}} Detached portable and private projections.
258
+ */
259
+ export function projectSegment(response, apiName, mode = 'deploy', children = new Map()) {
260
+ const lenient = mode === 'retrieve';
261
+ if (!response || typeof response !== 'object' || Array.isArray(response))
262
+ throw new SegmentError('INVALID_SEGMENT_RESPONSE');
263
+ const wrapper = response;
264
+ if (!Array.isArray(wrapper.segments) ||
265
+ wrapper.segments.length === 0 ||
266
+ (!lenient && (Object.keys(wrapper).length !== 1 || wrapper.segments.length !== 1)))
267
+ throw new SegmentError('INVALID_SEGMENT_RESPONSE');
268
+ const value = wrapper.segments[0];
269
+ if (!value || typeof value !== 'object' || Array.isArray(value))
270
+ throw new SegmentError('INVALID_SEGMENT_RESPONSE');
271
+ const raw = value;
272
+ // The data space is the segment's own (its name is unique in the org); a caller that requested
273
+ // one compares it.
274
+ if (raw.apiName !== apiName || !isDataSpaceName(raw.dataSpace))
275
+ throw new SegmentError('SEGMENT_IDENTITY_MISMATCH');
276
+ if (raw.segmentType !== 'DBT')
277
+ return projectTypedSegment(raw, apiName, mode, children);
278
+ const known = new Set([
279
+ ...configuration,
280
+ ...observations,
281
+ ...scheduleRead,
282
+ 'description',
283
+ 'includeCriteria',
284
+ 'parameters',
285
+ ]);
286
+ const unknown = Object.keys(raw).filter((key) => !known.has(key));
287
+ // Without its configuration the segment is not a DBT segment the file can hold.
288
+ if (configuration.some((key) => !Object.hasOwn(raw, key)))
289
+ throw new SegmentError(lenient ? 'UNSUPPORTED_SEGMENT_VARIANT' : 'UNKNOWN_SEGMENT_CONFIGURATION');
290
+ if (!lenient && unknown.length > 0)
291
+ throw new SegmentError('UNKNOWN_SEGMENT_CONFIGURATION');
292
+ // An unknown key named like a spec key could not be told apart from it.
293
+ if (unknown.some((key) => ['segmentOn', 'models', 'includeDbt', 'schedule'].includes(key)))
294
+ throw new SegmentError('UNKNOWN_SEGMENT_CONFIGURATION');
295
+ const dbt = raw.includeDbt;
296
+ if (!dbt ||
297
+ typeof dbt !== 'object' ||
298
+ Array.isArray(dbt) ||
299
+ (!lenient && Object.keys(dbt).length !== 1) ||
300
+ !Array.isArray(dbt.models))
301
+ throw new SegmentError('UNSUPPORTED_SEGMENT_VARIANT');
302
+ if (lenient && Object.hasOwn(raw, 'parameters') && !isDeepStrictEqual(raw.parameters, []))
303
+ throw new SegmentError('UNSUPPORTED_SEGMENT_VARIANT');
304
+ const schedule = projectSegmentSchedule(raw, mode);
305
+ // The model SQL reads as stored: the client asks Salesforce for plain text (plainTextHeaders).
306
+ const { models, ...dbtExtra } = dbt;
307
+ const candidate = {
308
+ schemaVersion: 1,
309
+ kind: 'segment',
310
+ c__dataSpace: raw.dataSpace,
311
+ identity: { apiName },
312
+ spec: {
313
+ displayName: raw.displayName,
314
+ // Salesforce leaves description out of the GET when it is empty.
315
+ description: Object.hasOwn(raw, 'description') ? raw.description : '',
316
+ segmentType: raw.segmentType,
317
+ segmentOn: { kind: 'dmo', apiName: raw.segmentOnApiName },
318
+ models,
319
+ lookbackPeriod: raw.lookbackPeriod,
320
+ ...(schedule ? { schedule } : {}),
321
+ ...(Object.keys(dbtExtra).length > 0 ? { includeDbt: dbtExtra } : {}),
322
+ ...Object.fromEntries(unknown.map((key) => [key, raw[key]])),
323
+ },
324
+ };
325
+ const admitted = validateSegmentDocument(candidate, mode);
326
+ if (!lenient)
327
+ validateObservations(raw);
328
+ // includeCriteria is Salesforce's own rendering of includeDbt; the file keeps includeDbt.
329
+ return { candidate: admitted, runtime: structuredClone(raw) };
330
+ }
331
+ /**
332
+ * The refusal of a segment that the org holds in another data space than the run's. Its name is
333
+ * unique in the org (Salesforce stores a non-default segment as `<prefix>_<Name>`), so a read by
334
+ * name finds it wherever it is.
335
+ * @param {string} apiName Segment name.
336
+ * @param {unknown} found The data space the org names for it.
337
+ * @param {string} dataSpace The run's data space.
338
+ * @returns {SegmentError} SEGMENT_DATASPACE_MISMATCH with an explanation.
339
+ */
340
+ export function segmentSpaceMismatch(apiName, found, dataSpace) {
341
+ return explainInput(new SegmentError('SEGMENT_DATASPACE_MISMATCH'), `Segment ${apiName} is in the data space ${isDataSpaceName(found) ? found : '(none named)'}, but the run's data space is ${dataSpace}. Run the command with --dataspace ${isDataSpaceName(found) ? found : '<its data space>'}.`);
342
+ }
343
+ /**
344
+ * Acquire one API68 Segment of the run's data space by its exact (stored) name; the GET needs no
345
+ * data space (live API 68: the stored name is unique in the org), and a segment of another data
346
+ * space is SEGMENT_DATASPACE_MISMATCH.
347
+ * A failed GET is never absence evidence; no runtime writes are available. A retrieve of a
348
+ * Waterfall with child segments, without `children`, names them with one segment list read
349
+ * (their definition IDs are org-specific); when that read fails the criteria stay as read.
350
+ * @param {Connection} connection Authenticated command-owned API68 connection.
351
+ * @param {string} apiName Exact selected identity.
352
+ * @param {string | ApiVersionSelection} apiVersion Requested fixed API version.
353
+ * @param {string} dataSpace The run's data space.
354
+ * @param {DocumentMode} [mode] `deploy` (strict) or `retrieve` (keeps what the plugin does not model).
355
+ * @param {ReadonlyMap<string, string>} [children] Waterfall child definition ID to API name.
356
+ * @returns {Promise<SegmentAcquisition>} Detached portable candidate and private runtime baseline.
357
+ */
358
+ export async function retrieveSegment(connection, apiName, apiVersion, dataSpace, mode = 'deploy', children) {
359
+ const version = typeof apiVersion === 'string' ? apiVersion : apiVersion.requested;
360
+ if (version !== '68.0' ||
361
+ (typeof apiVersion !== 'string' &&
362
+ (apiVersion.soapNumeric !== version || apiVersion.restSelector !== `v${version}`)) ||
363
+ connection.getApiVersion() !== version ||
364
+ !isDataSpaceName(dataSpace) ||
365
+ !segmentName.test(apiName))
366
+ throw new SegmentError('INVALID_SCOPE');
367
+ const identity = { dataSpace, apiName };
368
+ // The raw GET response travels with the result and the candidate, for a verbatim file when
369
+ // the segment cannot be represented.
370
+ let read;
371
+ try {
372
+ const raw = await new ConnectClient(connection, version).get(`/services/data/v${version}/ssot/segments/${apiName}`);
373
+ read = { native: raw };
374
+ const found = raw?.segments?.[0]?.dataSpace;
375
+ if (raw?.segments?.length && found !== dataSpace)
376
+ throw segmentSpaceMismatch(apiName, found, dataSpace);
377
+ const projection = projectSegment(raw, apiName, mode, children ?? (mode === 'retrieve' ? await segmentChildNames(connection, raw) : undefined));
378
+ return carryNativeResponse({
379
+ identity,
380
+ candidate: carryNativeResponse(projection.candidate, raw),
381
+ blockers: [],
382
+ expectations: { runtime: projection.runtime },
383
+ }, raw);
384
+ }
385
+ catch (error) {
386
+ const result = retainConnectDiagnostic({
387
+ identity,
388
+ blockers: [error instanceof SegmentError ? error.code : 'SEGMENT_ACQUISITION_FAILED'],
389
+ }, getConnectDiagnostic(error));
390
+ // A data space refusal keeps its explanation for the item.
391
+ const explanation = explanationOf(error);
392
+ if (error instanceof SegmentError && explanation !== undefined)
393
+ result.explanation = explanation;
394
+ return read ? carryNativeResponse(result, read.native) : result;
395
+ }
396
+ }
397
+ // One definition-ID-to-name map per command connection (one list read per run).
398
+ const childNameCache = new WeakMap();
399
+ /**
400
+ * Name the child segments of a Waterfall read in retrieve mode (retrieve and delete): one
401
+ * segment list read per connection maps each definition ID to its API name. Nothing is read for
402
+ * another segment type or a Waterfall without children; a failed list read names nothing.
403
+ * @param {Pick<Connection, 'instanceUrl' | 'request'>} connection Authenticated API 68 connection.
404
+ * @param {unknown} response Segment GET response.
405
+ * @returns {Promise<ReadonlyMap<string, string> | undefined>} Definition ID to API name.
406
+ */
407
+ export async function segmentChildNames(connection, response) {
408
+ const raw = response?.segments?.[0];
409
+ if (raw?.segmentType !== waterfallSegmentType ||
410
+ typeof raw.includeCriteria !== 'string' ||
411
+ !waterfallChildIds(raw.includeCriteria))
412
+ return undefined;
413
+ let names = childNameCache.get(connection);
414
+ if (!names) {
415
+ names = (async () => {
416
+ try {
417
+ const map = new Map();
418
+ for (const entry of await listSegmentEntries(connection))
419
+ if (typeof entry.marketSegmentDefinitionId === 'string')
420
+ map.set(entry.marketSegmentDefinitionId, entry.apiName);
421
+ return map;
422
+ }
423
+ catch {
424
+ return undefined;
425
+ }
426
+ })();
427
+ childNameCache.set(connection, names);
428
+ }
429
+ return names;
430
+ }
431
+ /** Largest page the segment list accepts (`batchSize` 1 to 200). */
432
+ const segmentPageSize = 200;
433
+ /**
434
+ * Every segment of the run's data space the API 68 list returns, following its
435
+ * `batchSize`/`offset` paging until `totalSize` (or, without it, until a short or empty page).
436
+ * The list is filtered by each entry's own `dataSpace`, never by a query parameter. Extra envelope
437
+ * keys are ignored; a malformed page stops the listing (SEGMENT_ACQUISITION_FAILED). An entry
438
+ * without a usable API name or data space is skipped with a warning, a segment of another data
439
+ * space is left out and a repeated name is listed once. A page that adds no new name ends the
440
+ * listing (a server ignoring the offset).
441
+ * @param {Pick<Connection, 'instanceUrl' | 'request'>} connection Authenticated API 68 connection.
442
+ * @param {string[]} [warnings] Receives one warning per skipped entry.
443
+ * @param {string} [dataSpace] The run's data space.
444
+ * @returns {Promise<string[]>} Sorted API names.
445
+ */
446
+ export async function listSegmentNames(connection, warnings, dataSpace = 'default') {
447
+ const entries = await listSegmentEntries(connection, warnings, dataSpace);
448
+ const names = entries.map((entry) => entry.apiName);
449
+ names.sort();
450
+ return names;
451
+ }
452
+ /**
453
+ * The entries of the segment list in one data space (or, without one, in every data space), as
454
+ * `listSegmentNames` pages and filters them, in list order.
455
+ * @param {Pick<Connection, 'instanceUrl' | 'request'>} connection Authenticated API 68 connection.
456
+ * @param {string[]} [warnings] Receives one warning per skipped entry.
457
+ * @param {string} [dataSpace] Data space to keep; undefined keeps every one.
458
+ * @param {object} [options] Options.
459
+ * @param {boolean} [options.queryDataSpace] Also send the data space as `dataspace` query parameter
460
+ * (the list filters by it); only the segment lookup asks for it.
461
+ * @returns {Promise<Array<Record<string, unknown> & {apiName: string}>>} Listed segments.
462
+ */
463
+ export async function listSegmentEntries(connection, warnings, dataSpace, options = {}) {
464
+ const scope = options.queryDataSpace === true && dataSpace !== undefined
465
+ ? `&dataspace=${encodeURIComponent(dataSpace)}`
466
+ : '';
467
+ const client = new ConnectClient(connection, '68.0');
468
+ const seen = new Set();
469
+ const names = [];
470
+ for (let offset = 0;;) {
471
+ const page = await client.get(`/services/data/v68.0/ssot/segments?batchSize=${segmentPageSize}&offset=${offset}${scope}`);
472
+ const entries = page?.segments;
473
+ if (!page || typeof page !== 'object' || !Array.isArray(entries))
474
+ throw new SegmentError('SEGMENT_ACQUISITION_FAILED');
475
+ let named = 0;
476
+ let added = 0;
477
+ for (const [index, entry] of entries.entries()) {
478
+ const item = (entry && typeof entry === 'object' ? entry : {});
479
+ const apiName = typeof item.apiName === 'string' ? item.apiName : undefined;
480
+ const usable = apiName !== undefined && segmentName.test(apiName);
481
+ if (!usable || typeof item.dataSpace !== 'string' || !item.dataSpace) {
482
+ warnings?.push(`segment inventory: skipped ${apiName === undefined ? `the entry at position ${offset + index}` : `"${apiName}"`} because it has no usable ${usable ? 'data space' : 'API name'}.`);
483
+ continue;
484
+ }
485
+ named++;
486
+ if (seen.has(apiName))
487
+ continue;
488
+ seen.add(apiName);
489
+ added++;
490
+ if (dataSpace === undefined || item.dataSpace === dataSpace)
491
+ names.push({ ...item, apiName });
492
+ }
493
+ offset += entries.length;
494
+ const total = page.totalSize;
495
+ const more = typeof total === 'number' && Number.isSafeInteger(total)
496
+ ? offset < total
497
+ : entries.length >= segmentPageSize;
498
+ // A page of names listed already means the server ignores the offset.
499
+ if (entries.length === 0 || !more || (named > 0 && added === 0))
500
+ return names;
501
+ }
502
+ }
@@ -0,0 +1,46 @@
1
+ import type { Connection } from '@salesforce/core';
2
+ /** The connection the lookup reads with: a `@salesforce/core` Connection, or its two used members. */
3
+ export type LookupConnection = Pick<Connection, 'instanceUrl' | 'request'>;
4
+ /** One segment of a data space as the segment list (API 68) names it. */
5
+ export type SegmentRow = {
6
+ apiName: string;
7
+ /** Record ID (`1sg…`); differs per org. */
8
+ marketSegmentId: string;
9
+ dataSpace: string;
10
+ /** The DMO the segment is built on. */
11
+ segmentOnApiName?: string;
12
+ segmentStatus?: string;
13
+ publishStatus?: string;
14
+ };
15
+ /** What `resolveSegment` looks for: one data space and the segment's API name or record ID. */
16
+ export type SegmentLookup = {
17
+ dataSpace: string;
18
+ apiName: string;
19
+ } | {
20
+ dataSpace: string;
21
+ marketSegmentId: string;
22
+ };
23
+ /**
24
+ * Every segment of one data space, complete: one paged `GET /ssot/segments?dataspace=` read. An
25
+ * entry the list cannot name (no API name, data space or record ID) makes the read incomplete, so
26
+ * it fails instead of leaving the segment out.
27
+ * @param {LookupConnection} connection Authenticated connection.
28
+ * @param {{dataSpace: string}} options The data space (`default`, or the name of another one).
29
+ * @param {string} options.dataSpace Data space name.
30
+ * @returns {Promise<SegmentRow[]>} Segments in list order.
31
+ * @throws {SegmentError} SEGMENT_ACQUISITION_FAILED when the list is not complete or not readable.
32
+ */
33
+ export declare function listSegments(connection: LookupConnection, options: {
34
+ dataSpace: string;
35
+ }): Promise<SegmentRow[]>;
36
+ /**
37
+ * Find one segment of a data space by its API name or record ID. When the data space has none,
38
+ * the org's other data spaces are listed: a segment found there is refused with
39
+ * SEGMENT_OTHER_DATASPACE (a flow deploy would drop such a segment without an error), otherwise
40
+ * SEGMENT_NOT_FOUND.
41
+ * @param {LookupConnection} connection Authenticated connection.
42
+ * @param {SegmentLookup} lookup Data space and API name or record ID.
43
+ * @returns {Promise<SegmentRow>} The segment.
44
+ * @throws {SegmentError} SEGMENT_NOT_FOUND, SEGMENT_OTHER_DATASPACE or SEGMENT_ACQUISITION_FAILED.
45
+ */
46
+ export declare function resolveSegment(connection: LookupConnection, lookup: SegmentLookup): Promise<SegmentRow>;
@@ -0,0 +1,108 @@
1
+ import { SegmentError } from '../artifacts/segment-document.js';
2
+ import { openBoundSsot } from '../transport/bound-ssot.js';
3
+ import { readOrgDataSpaceEntries } from './data-space-check.js';
4
+ import { explainInput, printableKey } from './operation-diagnostic.js';
5
+ import { listSegmentEntries } from './retrieve-segment.js';
6
+ const segmentId = /^1sg[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/u;
7
+ /**
8
+ * A lookup refusal: a SegmentError whose message starts with what failed.
9
+ * @param {string} code Error code.
10
+ * @returns {SegmentError} The error, to be explained.
11
+ */
12
+ function lookupError(code) {
13
+ const error = new SegmentError(code);
14
+ error.message = 'Segment lookup failed.';
15
+ return error;
16
+ }
17
+ /**
18
+ * A looked-up name or ID as a message shows it: only letters, digits and underscores.
19
+ * @param {string} value API name or record ID.
20
+ * @returns {string} The value, or a placeholder.
21
+ */
22
+ function shown(value) {
23
+ return /^[A-Za-z0-9_]{1,80}$/u.test(value) ? value : '[unprintable value]';
24
+ }
25
+ /**
26
+ * A nonempty text value, or undefined.
27
+ * @param {unknown} value Candidate.
28
+ * @returns {string | undefined} The text.
29
+ */
30
+ function text(value) {
31
+ return typeof value === 'string' && value ? value : undefined;
32
+ }
33
+ /**
34
+ * Every segment of one data space, complete: one paged `GET /ssot/segments?dataspace=` read. An
35
+ * entry the list cannot name (no API name, data space or record ID) makes the read incomplete, so
36
+ * it fails instead of leaving the segment out.
37
+ * @param {LookupConnection} connection Authenticated connection.
38
+ * @param {{dataSpace: string}} options The data space (`default`, or the name of another one).
39
+ * @param {string} options.dataSpace Data space name.
40
+ * @returns {Promise<SegmentRow[]>} Segments in list order.
41
+ * @throws {SegmentError} SEGMENT_ACQUISITION_FAILED when the list is not complete or not readable.
42
+ */
43
+ export async function listSegments(connection, options) {
44
+ const warnings = [];
45
+ const entries = await listSegmentEntries(connection, warnings, options.dataSpace, {
46
+ queryDataSpace: true,
47
+ });
48
+ const incomplete = entries.find((entry) => !segmentId.test(String(entry.marketSegmentId)));
49
+ if (warnings.length > 0 || incomplete)
50
+ throw explainInput(lookupError('SEGMENT_ACQUISITION_FAILED'), `The segment list of the data space ${printableKey(options.dataSpace)} has an entry without ${incomplete ? `a record ID (${shown(incomplete.apiName)})` : 'an API name or data space'}, so it is not complete.`);
51
+ return entries.map((entry) => {
52
+ const segmentOnApiName = text(entry.segmentOnApiName);
53
+ const segmentStatus = text(entry.segmentStatus);
54
+ const publishStatus = text(entry.publishStatus);
55
+ return {
56
+ apiName: entry.apiName,
57
+ marketSegmentId: entry.marketSegmentId,
58
+ dataSpace: entry.dataSpace,
59
+ ...(segmentOnApiName ? { segmentOnApiName } : {}),
60
+ ...(segmentStatus ? { segmentStatus } : {}),
61
+ ...(publishStatus ? { publishStatus } : {}),
62
+ };
63
+ });
64
+ }
65
+ /**
66
+ * Whether a row is the segment a lookup names (exact, case matters; a record ID in its 15- or
67
+ * 18-character form).
68
+ * @param {SegmentRow} row Listed segment.
69
+ * @param {SegmentLookup} lookup What is looked for.
70
+ * @returns {boolean} Match.
71
+ */
72
+ function matches(row, lookup) {
73
+ if ('apiName' in lookup)
74
+ return row.apiName === lookup.apiName;
75
+ // A record ID may come in its 15-character form (the 18-character one adds a case checksum).
76
+ return row.marketSegmentId.slice(0, 15) === lookup.marketSegmentId.slice(0, 15);
77
+ }
78
+ /**
79
+ * Find one segment of a data space by its API name or record ID. When the data space has none,
80
+ * the org's other data spaces are listed: a segment found there is refused with
81
+ * SEGMENT_OTHER_DATASPACE (a flow deploy would drop such a segment without an error), otherwise
82
+ * SEGMENT_NOT_FOUND.
83
+ * @param {LookupConnection} connection Authenticated connection.
84
+ * @param {SegmentLookup} lookup Data space and API name or record ID.
85
+ * @returns {Promise<SegmentRow>} The segment.
86
+ * @throws {SegmentError} SEGMENT_NOT_FOUND, SEGMENT_OTHER_DATASPACE or SEGMENT_ACQUISITION_FAILED.
87
+ */
88
+ export async function resolveSegment(connection, lookup) {
89
+ if ('marketSegmentId' in lookup && !segmentId.test(lookup.marketSegmentId))
90
+ throw explainInput(lookupError('SEGMENT_NOT_FOUND'), `The record ID ${shown(lookup.marketSegmentId)} is not a segment ID (1sg followed by 12 or 15 letters and digits); nothing was read.`);
91
+ const rows = await listSegments(connection, lookup);
92
+ const found = rows.find((row) => matches(row, lookup));
93
+ if (found)
94
+ return found;
95
+ const value = 'apiName' in lookup ? lookup.apiName : lookup.marketSegmentId;
96
+ const what = `${'apiName' in lookup ? 'API name' : 'record ID'} ${shown(value)}`;
97
+ const sender = openBoundSsot('', '68.0', async () => connection);
98
+ const spaces = await readOrgDataSpaceEntries(async () => sender);
99
+ for (const { name } of spaces) {
100
+ if (name === lookup.dataSpace)
101
+ continue;
102
+ const other = await listSegments(connection, { dataSpace: name });
103
+ const elsewhere = other.find((row) => matches(row, lookup));
104
+ if (elsewhere)
105
+ throw explainInput(lookupError('SEGMENT_OTHER_DATASPACE'), `The segment with the ${what} is in the data space ${printableKey(name)}, not in ${printableKey(lookup.dataSpace)}.`);
106
+ }
107
+ throw explainInput(lookupError('SEGMENT_NOT_FOUND'), `No segment of the org has the ${what}; looked in the data space ${printableKey(lookup.dataSpace)} and the org's other data spaces.`);
108
+ }