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,1359 @@
1
+ import { dataTransformName, validateDataTransformDocument } from './data-transform-document.js';
2
+ import { validateNativeDataGraphDocument } from './native-data-graph-document.js';
3
+ import { validateAnyDataStreamDocument } from './data-stream-document.js';
4
+ import { nativeMappingName, validateNativeMappingDocument } from './native-mapping-document.js';
5
+ import { nativeRelationshipName, relationshipDmoName, validateNativeRelationshipDocument, } from './native-relationship-document.js';
6
+ import { nativeDmoName, validateNativeDmoDocument } from './native-dmo-document.js';
7
+ import { dloName, validateDloDocument } from './dlo-document.js';
8
+ import { dataGraphName } from './data-graph-document.js';
9
+ import { lstat, open, readdir, realpath } from 'node:fs/promises';
10
+ import path from 'node:path';
11
+ import { createHash } from 'node:crypto';
12
+ import { joinSegmentFiles, segmentName } from './segment-document.js';
13
+ import { identityResolutionName, validateIdentityResolutionDocument, } from './identity-resolution-document.js';
14
+ import { calculatedInsightName, calculatedInsightReference as calculatedInsightReference, parseNativeCalculatedInsight, } from './native-calculated-insight-document.js';
15
+ import { isVerbatimDocument, parseVerbatimDocument, verbatimRefusalMessage, verbatimIdentity, verbatimSkipWarning, } from './verbatim-document.js';
16
+ import { explanationOf, replaceExplanation } from '../services/operation-diagnostic.js';
17
+ /** Refusals of the c__dataSpace key that a selected file keeps instead of INVALID_SOURCE. */
18
+ const dataSpaceFieldCodes = [
19
+ 'LEGACY_DATASPACE_KEY',
20
+ 'INVALID_DATASPACE_FIELD',
21
+ 'UNSUPPORTED_DATASPACE_FILTER',
22
+ ];
23
+ const ciMemberInfix = '.calculatedInsight-meta.';
24
+ const ciJsonSuffix = '.calculatedInsight-meta.json';
25
+ /**
26
+ * A calculated insight file: its JSON, its SQL or any other file of that name stem.
27
+ * @param {string} file Path.
28
+ * @returns {boolean} Whether the base name holds `.calculatedInsight-meta.`.
29
+ */
30
+ const isCalculatedInsightMember = (file) => path.basename(file).includes(ciMemberInfix);
31
+ const segmentMemberInfix = '.segment.';
32
+ const segmentJsonSuffix = '.segment.json';
33
+ /**
34
+ * A segment file: its JSON or one of its SQL files.
35
+ * @param {string} file Path.
36
+ * @returns {boolean} Whether the base name is `X.segment.json` or `X.segment.*.sql`.
37
+ */
38
+ export const isSegmentMember = (file) => {
39
+ const entry = path.basename(file).toLowerCase();
40
+ return (entry.endsWith(segmentJsonSuffix) ||
41
+ (entry.includes(segmentMemberInfix) && entry.endsWith('.sql')));
42
+ };
43
+ /** Payload-free local selection refusal. */
44
+ export class DeployInputError extends Error {
45
+ code;
46
+ constructor(code, message) {
47
+ super(message ??
48
+ (code === 'UNSUPPORTED_SEGMENT_XML'
49
+ ? 'Select the single .segment.json artifact; legacy Segment XML is not supported.'
50
+ : 'Select explicit, bounded, authored-only sources without links or conflicting identities.'));
51
+ this.code = code;
52
+ this.name = 'DeployInputError';
53
+ }
54
+ }
55
+ /**
56
+ * Refuse an unusable DLO, DMO, mapping, relationship, data stream, data transform, segment or identity resolution file, keeping the validator's explanation of the offending key.
57
+ * @param {unknown} error Validator refusal.
58
+ * @returns {DeployInputError} INVALID_SOURCE refusal.
59
+ */
60
+ function invalidSource(error) {
61
+ const explanation = explanationOf(error);
62
+ // A refused c__dataSpace key keeps its own code; every other refusal is INVALID_SOURCE.
63
+ const code = error?.code;
64
+ const refusal = new DeployInputError(dataSpaceFieldCodes.find((known) => known === code) ?? 'INVALID_SOURCE', explanation);
65
+ if (explanation !== undefined)
66
+ replaceExplanation(refusal, explanation);
67
+ return refusal;
68
+ }
69
+ /**
70
+ * Refuse an explicitly named verbatim file before any API call.
71
+ * @param {VerbatimDocument} document Verbatim document.
72
+ * @returns {DeployInputError} Refusal naming kind, name and reason.
73
+ */
74
+ function verbatimRefusal(document) {
75
+ const message = verbatimRefusalMessage(document);
76
+ const error = new DeployInputError('VERBATIM_NOT_DEPLOYABLE', message);
77
+ replaceExplanation(error, message);
78
+ return error;
79
+ }
80
+ /**
81
+ * Identify a native DMO input by its canonical path.
82
+ * @param {object} input Captured input.
83
+ * @param {string} input.path Selected path.
84
+ * @returns {boolean} Native canonical path.
85
+ */
86
+ export function isNativeDmoInput(input) {
87
+ return input.path.endsWith('.dmo-meta.json');
88
+ }
89
+ /**
90
+ * Admit canonical native DMO content with immutable byte binding.
91
+ * @param {string} file Absolute selected member.
92
+ * @returns {Promise<NativeDmoDeployInput>} Frozen source input.
93
+ */
94
+ async function readNativeDmoInput(file) {
95
+ const name = path.basename(file).slice(0, -'.dmo-meta.json'.length);
96
+ const directory = path.dirname(file);
97
+ if (!nativeDmoName.test(name) ||
98
+ path.basename(directory) !== 'dmo' ||
99
+ path.basename(path.dirname(directory)) !== 'data360')
100
+ throw new DeployInputError('INVALID_SELECTION');
101
+ const bytes = await memberBytes(file);
102
+ let document;
103
+ try {
104
+ document = validateNativeDmoDocument(strictJson(decode(bytes)));
105
+ if (document.identity.apiName !== name)
106
+ throw new Error('Identity mismatch');
107
+ }
108
+ catch (error) {
109
+ throw invalidSource(error);
110
+ }
111
+ const after = await memberBytes(file);
112
+ if (!after.equals(bytes))
113
+ refuse();
114
+ const freeze = (value) => {
115
+ for (const child of Object.values(value))
116
+ if (child && typeof child === 'object')
117
+ freeze(child);
118
+ Object.freeze(value);
119
+ };
120
+ freeze(document);
121
+ return Object.freeze({
122
+ path: file,
123
+ document,
124
+ inputDigest: createHash('sha256').update(bytes).digest('hex'),
125
+ });
126
+ }
127
+ /**
128
+ * Admit canonical mapping JSON without a Metadata XML fallback.
129
+ * @param {string} file Exact local mapping member.
130
+ * @returns {Promise<MappingDeployInput>} Immutable content and byte binding.
131
+ */
132
+ async function readMappingInput(file) {
133
+ const name = path.basename(file).slice(0, -'.mapping-meta.json'.length);
134
+ const directory = path.dirname(file);
135
+ if (!nativeMappingName.test(name) ||
136
+ path.basename(directory) !== 'mapping' ||
137
+ path.basename(path.dirname(directory)) !== 'data360')
138
+ throw new DeployInputError('INVALID_SELECTION');
139
+ const bytes = await memberBytes(file);
140
+ let document;
141
+ try {
142
+ document = validateNativeMappingDocument(strictJson(decode(bytes)));
143
+ if (document.identity.apiName !== name)
144
+ throw new Error('Identity mismatch');
145
+ }
146
+ catch (error) {
147
+ throw invalidSource(error);
148
+ }
149
+ const after = await memberBytes(file);
150
+ if (!after.equals(bytes))
151
+ refuse();
152
+ const freeze = (value) => {
153
+ for (const child of Object.values(value))
154
+ if (child && typeof child === 'object')
155
+ freeze(child);
156
+ Object.freeze(value);
157
+ };
158
+ freeze(document);
159
+ return Object.freeze({
160
+ path: file,
161
+ document,
162
+ inputDigest: createHash('sha256').update(bytes).digest('hex'),
163
+ });
164
+ }
165
+ /**
166
+ * Admit only canonical stream JSON using the existing bounded no-link exact-byte reader.
167
+ * @param {string} file Absolute selected member.
168
+ * @returns {Promise<DataStreamDeployInput>} Detached frozen intent and byte binding.
169
+ */
170
+ async function readDataStreamInput(file) {
171
+ const suffix = '.data-stream-meta.json';
172
+ const name = path.basename(file).slice(0, -suffix.length);
173
+ const directory = path.dirname(file);
174
+ if (!/^[A-Za-z][A-Za-z0-9_]{0,199}$/u.test(name) ||
175
+ path.basename(directory) !== 'data-stream' ||
176
+ path.basename(path.dirname(directory)) !== 'data360')
177
+ throw new DeployInputError('INVALID_SELECTION');
178
+ const bytes = await memberBytes(file);
179
+ let document;
180
+ try {
181
+ document = validateAnyDataStreamDocument(strictJson(decode(bytes)));
182
+ if (document.identity.apiName !== name)
183
+ throw new Error('Identity mismatch');
184
+ }
185
+ catch (error) {
186
+ throw invalidSource(error);
187
+ }
188
+ const after = await memberBytes(file);
189
+ if (!after.equals(bytes))
190
+ refuse();
191
+ return Object.freeze({
192
+ path: file,
193
+ document,
194
+ inputDigest: createHash('sha256').update(bytes).digest('hex'),
195
+ });
196
+ }
197
+ /**
198
+ * Re-admit every exact local byte and immutable logical input before relying on it.
199
+ * @param {DataStreamDeployInput} input Captured stream admission.
200
+ * @returns {Promise<void>} Resolves only without local drift.
201
+ */
202
+ export async function verifyDataStreamInputDigest(input) {
203
+ try {
204
+ const current = await readDataStreamInput(input.path);
205
+ if (current.inputDigest !== input.inputDigest ||
206
+ JSON.stringify(current.document) !== JSON.stringify(authoredDocument(input)))
207
+ refuse();
208
+ }
209
+ catch {
210
+ throw new DeployInputError('UNSAFE_SOURCE');
211
+ }
212
+ }
213
+ /**
214
+ * Admit native Graph bytes using the existing bounded no-link reader.
215
+ * @param {string} file Exact native artifact.
216
+ * @returns {Promise<NativeDataGraphDeployInput>} Byte-bound source.
217
+ */
218
+ async function readNativeDataGraphInput(file) {
219
+ const name = path.basename(file).slice(0, -'.native-dataGraph.json'.length);
220
+ const directory = path.dirname(file);
221
+ if (!dataGraphName.test(name) ||
222
+ path.basename(directory) !== 'dataGraphs' ||
223
+ path.basename(path.dirname(directory)) !== 'data360')
224
+ throw new DeployInputError('INVALID_SELECTION');
225
+ const bytes = await memberBytes(file);
226
+ let document;
227
+ try {
228
+ document = validateNativeDataGraphDocument(strictJson(decode(bytes)));
229
+ if (document.definition.name !== name)
230
+ throw new Error('Identity mismatch');
231
+ }
232
+ catch (error) {
233
+ throw invalidSource(error);
234
+ }
235
+ const after = await memberBytes(file);
236
+ if (!after.equals(bytes))
237
+ refuse();
238
+ return Object.freeze({
239
+ path: file,
240
+ document,
241
+ inputDigest: createHash('sha256').update(bytes).digest('hex'),
242
+ });
243
+ }
244
+ /**
245
+ * Re-admit native Graph exact bytes and logical intent before mutation.
246
+ * @param {NativeDataGraphDeployInput} input Captured source.
247
+ */
248
+ export async function verifyNativeDataGraphInputDigest(input) {
249
+ const fresh = await readNativeDataGraphInput(input.path);
250
+ if (fresh.inputDigest !== input.inputDigest ||
251
+ JSON.stringify(fresh.document) !== JSON.stringify(authoredDocument(input)))
252
+ refuse();
253
+ }
254
+ /**
255
+ * Admit only canonical input-shaped Transform JSON with exact name and byte binding.
256
+ * @param {string} file Absolute selected member.
257
+ * @returns {Promise<DataTransformDeployInput>} Immutable admitted input.
258
+ */
259
+ async function readDataTransformInput(file) {
260
+ const suffix = '.dataTransform.json';
261
+ const name = path.basename(file).slice(0, -suffix.length);
262
+ const directory = path.dirname(file);
263
+ if (!file.endsWith(suffix) ||
264
+ !dataTransformName.test(name) ||
265
+ path.basename(directory) !== 'dataTransforms' ||
266
+ path.basename(path.dirname(directory)) !== 'data360')
267
+ throw new DeployInputError('INVALID_SELECTION');
268
+ const bytes = await memberBytes(file);
269
+ let document;
270
+ try {
271
+ document = validateDataTransformDocument(strictJson(decode(bytes)));
272
+ if (document.definition.name !== name)
273
+ throw new Error('Identity mismatch');
274
+ }
275
+ catch (error) {
276
+ throw invalidSource(error);
277
+ }
278
+ const after = await memberBytes(file);
279
+ if (!after.equals(bytes))
280
+ refuse();
281
+ const freeze = (value) => {
282
+ for (const child of Object.values(value))
283
+ if (child && typeof child === 'object')
284
+ freeze(child);
285
+ Object.freeze(value);
286
+ };
287
+ freeze(document);
288
+ return Object.freeze({
289
+ path: file,
290
+ document,
291
+ inputDigest: createHash('sha256').update(bytes).digest('hex'),
292
+ });
293
+ }
294
+ /**
295
+ * Re-admit exact Transform bytes and logical intent immediately before mutation.
296
+ * @param {DataTransformDeployInput} input Captured immutable admission.
297
+ * @returns {Promise<void>} Resolves only without local drift.
298
+ */
299
+ export async function verifyDataTransformInputDigest(input) {
300
+ try {
301
+ const current = await readDataTransformInput(input.path);
302
+ if (current.inputDigest !== input.inputDigest ||
303
+ JSON.stringify(current.document) !== JSON.stringify(authoredDocument(input)))
304
+ refuse();
305
+ }
306
+ catch {
307
+ throw new DeployInputError('UNSAFE_SOURCE');
308
+ }
309
+ }
310
+ /**
311
+ * Admit canonical relationship JSON whose file name is the relationship name.
312
+ * @param {string} file Exact local relationship member.
313
+ * @returns {Promise<RelationshipDeployInput>} Immutable content and byte binding.
314
+ */
315
+ export async function readRelationshipInput(file) {
316
+ const name = path.basename(file).slice(0, -'.relationship-meta.json'.length);
317
+ const directory = path.dirname(file);
318
+ if (!file.endsWith('.relationship-meta.json') ||
319
+ !nativeRelationshipName.test(name) ||
320
+ path.basename(directory) !== 'relationship' ||
321
+ path.basename(path.dirname(directory)) !== 'data360')
322
+ throw new DeployInputError('INVALID_SELECTION');
323
+ const bytes = await memberBytes(file);
324
+ let document;
325
+ try {
326
+ document = validateNativeRelationshipDocument(strictJson(decode(bytes)));
327
+ if (document.identity.apiName !== name)
328
+ throw new Error('Identity mismatch');
329
+ }
330
+ catch (error) {
331
+ throw invalidSource(error);
332
+ }
333
+ const after = await memberBytes(file);
334
+ if (!after.equals(bytes))
335
+ refuse();
336
+ const freeze = (value) => {
337
+ for (const child of Object.values(value))
338
+ if (child && typeof child === 'object')
339
+ freeze(child);
340
+ Object.freeze(value);
341
+ };
342
+ freeze(document);
343
+ return Object.freeze({
344
+ path: file,
345
+ document,
346
+ inputDigest: createHash('sha256').update(bytes).digest('hex'),
347
+ });
348
+ }
349
+ // The file's own content of an input whose document a cross-data-space deploy translated in
350
+ // memory: every re-check of the file's bytes compares against this, never the translation.
351
+ const authoredDocuments = new WeakMap();
352
+ /**
353
+ * The document the file holds: for an input translated into another data space, the original.
354
+ * @param {{document: unknown}} input Admitted input.
355
+ * @param {unknown} input.document Its document, translated or as read.
356
+ * @returns {unknown} The file's document.
357
+ */
358
+ export function authoredDocument(input) {
359
+ return authoredDocuments.has(input) ? authoredDocuments.get(input) : input.document;
360
+ }
361
+ // The same for the insight document (JSON with SQL) of a translated calculated insight.
362
+ const authoredNatives = new WeakMap();
363
+ /**
364
+ * The insight document the files hold: for an insight translated into another data space, the
365
+ * original.
366
+ * @param {{native: unknown}} input Admitted calculated insight input.
367
+ * @param {unknown} input.native Its insight document, translated or as read.
368
+ * @returns {unknown} The files' insight document.
369
+ */
370
+ export function authoredNative(input) {
371
+ return authoredNatives.has(input) ? authoredNatives.get(input) : input.native;
372
+ }
373
+ /**
374
+ * A frozen copy of an admitted input that carries a translated document (and for a calculated
375
+ * insight its translated insight document); its file checks still compare against what the
376
+ * files hold.
377
+ * @param {T} input Admitted input.
378
+ * @param {unknown} document Translated document.
379
+ * @param {unknown} [native] Translated insight document of a calculated insight.
380
+ * @returns {T} The translated input.
381
+ * @template T
382
+ */
383
+ export function translatedDeployInput(input, document, native) {
384
+ const freeze = (value) => {
385
+ if (!value || typeof value !== 'object' || Object.isFrozen(value))
386
+ return;
387
+ for (const child of Object.values(value))
388
+ freeze(child);
389
+ Object.freeze(value);
390
+ };
391
+ freeze(document);
392
+ freeze(native);
393
+ const translated = Object.freeze({
394
+ ...input,
395
+ document,
396
+ ...(native === undefined ? {} : { native }),
397
+ });
398
+ authoredDocuments.set(translated, authoredDocument(input));
399
+ if (native !== undefined)
400
+ authoredNatives.set(translated, authoredNative(input));
401
+ return translated;
402
+ }
403
+ /**
404
+ * Admit strict single-file source-backed DLO content and freeze its exact bytes.
405
+ * @param {string} file Absolute selected member.
406
+ * @returns {Promise<DloDeployInput>} Immutable local input.
407
+ */
408
+ async function readDloInput(file) {
409
+ const suffix = '.dlo-meta.json';
410
+ const name = path.basename(file).slice(0, -suffix.length);
411
+ const directory = path.dirname(file);
412
+ if (!file.endsWith(suffix) ||
413
+ !dloName.test(name) ||
414
+ path.basename(directory) !== 'dlo' ||
415
+ path.basename(path.dirname(directory)) !== 'data360')
416
+ throw new DeployInputError('INVALID_SELECTION');
417
+ const bytes = await memberBytes(file);
418
+ let document;
419
+ try {
420
+ document = validateDloDocument(strictJson(decode(bytes)));
421
+ if (document.identity.apiName !== name)
422
+ throw new Error('Identity mismatch');
423
+ }
424
+ catch (error) {
425
+ throw invalidSource(error);
426
+ }
427
+ const after = await memberBytes(file);
428
+ if (!after.equals(bytes))
429
+ refuse();
430
+ const freeze = (value) => {
431
+ for (const child of Object.values(value))
432
+ if (child && typeof child === 'object')
433
+ freeze(child);
434
+ Object.freeze(value);
435
+ };
436
+ freeze(document);
437
+ return Object.freeze({
438
+ path: file,
439
+ document,
440
+ inputDigest: createHash('sha256').update(bytes).digest('hex'),
441
+ });
442
+ }
443
+ /**
444
+ * Verify only immutable local bytes and identity, independent of legitimate remote stage changes.
445
+ * @param {DloDeployInput} input Original input.
446
+ * @returns {Promise<void>} Resolves only without local drift.
447
+ */
448
+ export async function verifyDloInputDigest(input) {
449
+ try {
450
+ const current = await readDloInput(input.path);
451
+ if (current.inputDigest !== input.inputDigest ||
452
+ JSON.stringify(current.document) !== JSON.stringify(authoredDocument(input)))
453
+ refuse();
454
+ }
455
+ catch {
456
+ throw new DeployInputError('UNSAFE_SOURCE');
457
+ }
458
+ }
459
+ /**
460
+ * Narrow executable families; IR admission does not authorize public routing.
461
+ * @param {DeployInput} input Admitted input.
462
+ * @returns {boolean} Whether an existing public route supports this family.
463
+ */
464
+ export function isSupportedDeployInput(input) {
465
+ return input.document.kind === 'segment' || input.document.kind === 'calculated-insight';
466
+ }
467
+ /**
468
+ * Admit one canonical IR file with immutable logical content and exact byte digest.
469
+ * @param {string} file Exact absolute member.
470
+ * @returns {Promise<IdentityResolutionDeployInput>} Detached frozen admission.
471
+ */
472
+ async function readIdentityResolutionInput(file) {
473
+ const suffix = '.identityResolution.json';
474
+ const name = path.basename(file).slice(0, -suffix.length);
475
+ const directory = path.dirname(file);
476
+ if (!file.endsWith(suffix) ||
477
+ !identityResolutionName.test(name) ||
478
+ path.basename(directory) !== 'identityResolution' ||
479
+ path.basename(path.dirname(directory)) !== 'data360')
480
+ throw new DeployInputError('INVALID_SELECTION');
481
+ const bytes = await memberBytes(file);
482
+ let document;
483
+ try {
484
+ document = validateIdentityResolutionDocument(strictJson(decode(bytes)));
485
+ if (document.identity.apiName !== name)
486
+ throw new Error('Identity mismatch');
487
+ }
488
+ catch (error) {
489
+ throw invalidSource(error);
490
+ }
491
+ const after = await memberBytes(file);
492
+ if (!after.equals(bytes))
493
+ refuse();
494
+ const freeze = (value) => {
495
+ for (const child of Object.values(value))
496
+ if (child && typeof child === 'object')
497
+ freeze(child);
498
+ Object.freeze(value);
499
+ };
500
+ freeze(document);
501
+ return Object.freeze({
502
+ path: file,
503
+ document,
504
+ inputDigest: createHash('sha256').update(bytes).digest('hex'),
505
+ });
506
+ }
507
+ /**
508
+ * Re-admit an IR snapshot before relying on the original immutable bytes.
509
+ * @param {IdentityResolutionDeployInput} input Captured admission.
510
+ * @returns {Promise<void>} Resolves only for unchanged exact bytes.
511
+ */
512
+ export async function verifyIdentityResolutionInputDigest(input) {
513
+ try {
514
+ const current = await readIdentityResolutionInput(input.path);
515
+ if (current.inputDigest !== input.inputDigest ||
516
+ JSON.stringify(current.document) !== JSON.stringify(authoredDocument(input)))
517
+ refuse();
518
+ }
519
+ catch {
520
+ throw new DeployInputError('UNSAFE_SOURCE');
521
+ }
522
+ }
523
+ const skippedWarnings = new WeakMap();
524
+ /**
525
+ * The warnings of the verbatim files a {@link readDeployInputs} call skipped, one per file.
526
+ * @param {readonly unknown[]} inputs Array that call returned.
527
+ * @returns {readonly string[]} Warnings; empty for any other array.
528
+ */
529
+ export function skippedVerbatimWarnings(inputs) {
530
+ return skippedWarnings.get(inputs) ?? [];
531
+ }
532
+ const refuse = () => {
533
+ throw new DeployInputError('UNSAFE_SOURCE');
534
+ };
535
+ const decode = (bytes) => new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
536
+ const canonical = (value) => process.platform === 'win32' ? value.toLowerCase() : value;
537
+ /**
538
+ * Inspect every path component without admitting symlinks, junctions or canonical aliases.
539
+ * @param {string} file Absolute selected path.
540
+ * @returns {Promise<import('node:fs').Stats>} Checked filesystem entry.
541
+ */
542
+ async function inspect(file) {
543
+ const parent = path.dirname(file);
544
+ if (parent !== file) {
545
+ const ancestor = await inspect(parent);
546
+ if (!ancestor.isDirectory())
547
+ refuse();
548
+ }
549
+ const stat = await lstat(file);
550
+ if (stat.isSymbolicLink() || canonical(await realpath(file)) !== canonical(file))
551
+ refuse();
552
+ return stat;
553
+ }
554
+ /**
555
+ * Parse JSON without silently accepting duplicate or escaped-equivalent object keys.
556
+ * @param {string} text Complete UTF-8 source.
557
+ * @returns {unknown} Parsed JSON value.
558
+ */
559
+ function strictJson(text) {
560
+ const value = JSON.parse(text);
561
+ const stack = [];
562
+ const tokens = /"(?:[^"\\]|\\.)*"|[{}[\]]/gu;
563
+ for (const token of text.matchAll(tokens)) {
564
+ switch (token[0]) {
565
+ case '{': {
566
+ stack.push(new Set());
567
+ break;
568
+ }
569
+ case '[': {
570
+ stack.push(undefined);
571
+ break;
572
+ }
573
+ case '}':
574
+ case ']': {
575
+ stack.pop();
576
+ break;
577
+ }
578
+ default: {
579
+ if (/^\s*:/u.test(text.slice(token.index + token[0].length))) {
580
+ const key = JSON.parse(token[0]);
581
+ const keys = stack.at(-1);
582
+ if (keys.has(key))
583
+ throw new DeployInputError('INVALID_SOURCE');
584
+ keys.add(key);
585
+ }
586
+ }
587
+ }
588
+ }
589
+ return value;
590
+ }
591
+ /**
592
+ * Read bounded exact bytes while binding the open handle and no-link path before and after.
593
+ * @param {string} file Absolute member path.
594
+ * @returns {Promise<Buffer>} Admitted original bytes.
595
+ */
596
+ async function memberBytes(file) {
597
+ const before = await inspect(file);
598
+ if (!before.isFile() || before.nlink !== 1 || before.size > 1_048_576)
599
+ refuse();
600
+ const handle = await open(file, 'r');
601
+ try {
602
+ const opened = await handle.stat();
603
+ if (opened.dev !== before.dev || opened.ino !== before.ino || opened.nlink !== 1)
604
+ refuse();
605
+ const buffer = Buffer.alloc(1_048_577);
606
+ let length = 0;
607
+ while (length < buffer.length) {
608
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
609
+ if (!bytesRead)
610
+ break;
611
+ length += bytesRead;
612
+ }
613
+ const after = await handle.stat();
614
+ const current = await inspect(file);
615
+ if (length > 1_048_576 ||
616
+ length !== before.size ||
617
+ after.size !== before.size ||
618
+ after.mtimeMs !== before.mtimeMs ||
619
+ after.ctimeMs !== before.ctimeMs ||
620
+ current.dev !== before.dev ||
621
+ current.ino !== before.ino ||
622
+ current.nlink !== 1 ||
623
+ current.mtimeMs !== before.mtimeMs ||
624
+ current.ctimeMs !== before.ctimeMs)
625
+ refuse();
626
+ return buffer.subarray(0, length);
627
+ }
628
+ finally {
629
+ await handle.close();
630
+ }
631
+ }
632
+ /** The kind a verbatim file must carry, by the suffix of its canonical file name. */
633
+ const verbatimSuffixes = [
634
+ ['.dmo-meta.json', 'dmo'],
635
+ ['.dlo-meta.json', 'dlo'],
636
+ ['.mapping-meta.json', 'mapping'],
637
+ ['.relationship-meta.json', 'relationship'],
638
+ ['.data-stream-meta.json', 'data-stream'],
639
+ ['.dataTransform.json', 'data-transform'],
640
+ ['.native-dataGraph.json', 'native-data-graph'],
641
+ ['.identityResolution.json', 'identity-resolution'],
642
+ [ciJsonSuffix, 'calculated-insight'],
643
+ [segmentJsonSuffix, 'segment'],
644
+ ];
645
+ /**
646
+ * The verbatim document a selected file belongs to: the file itself, or the JSON of the
647
+ * calculated insight or segment whose SQL file it is. Its kind and name must match the file name.
648
+ * @param {string} file Absolute selected file.
649
+ * @returns {Promise<{path: string; document: VerbatimDocument} | undefined>} JSON path and
650
+ * verbatim document, or undefined for anything else (the family reader then decides).
651
+ */
652
+ async function verbatimMember(file) {
653
+ const entry = path.basename(file);
654
+ const directory = path.dirname(file);
655
+ let json = file;
656
+ if (isCalculatedInsightMember(file))
657
+ json = path.join(directory, `${entry.slice(0, entry.indexOf(ciMemberInfix))}${ciJsonSuffix}`);
658
+ else if (isSegmentMember(file) && entry.includes(segmentMemberInfix))
659
+ json = path.join(directory, `${entry.slice(0, entry.indexOf(segmentMemberInfix))}${segmentJsonSuffix}`);
660
+ const suffix = verbatimSuffixes.find(([ending]) => json.endsWith(ending));
661
+ if (!suffix)
662
+ return undefined;
663
+ let document;
664
+ try {
665
+ document = parseVerbatimDocument(decode(await memberBytes(json)));
666
+ }
667
+ catch {
668
+ return undefined;
669
+ }
670
+ return document &&
671
+ document.kind === suffix[1] &&
672
+ path.basename(json) === `${document.identity.apiName}${suffix[0]}`
673
+ ? { path: json, document }
674
+ : undefined;
675
+ }
676
+ /**
677
+ * Admit a segment from its JSON or one of its SQL files: the JSON joined with exactly one
678
+ * `<apiName>.segment.<model>.sql` per model, every byte bound as one component. A missing JSON or
679
+ * SQL file, SQL left in the JSON, or any other `<apiName>.segment.*` file beside them is
680
+ * INVALID_SOURCE.
681
+ * @param {string} file Absolute selected JSON or SQL file.
682
+ * @returns {Promise<SegmentDeployInput>} Detached immutable admission.
683
+ */
684
+ async function readSegmentDeployInput(file) {
685
+ const entry = path.basename(file);
686
+ const marker = entry.indexOf(segmentMemberInfix);
687
+ const name = marker > 0 ? entry.slice(0, marker) : '';
688
+ const directory = path.dirname(file);
689
+ if (path.basename(directory) !== 'segments' ||
690
+ path.basename(path.dirname(directory)) !== 'data360')
691
+ throw new DeployInputError('INVALID_SELECTION');
692
+ if (!segmentName.test(name))
693
+ throw new DeployInputError('INVALID_SOURCE');
694
+ const jsonName = `${name}${segmentJsonSuffix}`;
695
+ const jsonPath = path.join(directory, jsonName);
696
+ await inspect(directory);
697
+ const prefix = `${name}${segmentMemberInfix}`;
698
+ const codeFiles = [];
699
+ let hasJson = false;
700
+ const entries = await readdir(directory);
701
+ // eslint-disable-next-line unicorn/no-array-sort -- Sort the fresh directory listing within the existing TypeScript library target.
702
+ for (const member of entries.sort()) {
703
+ if (!member.toLowerCase().startsWith(prefix.toLowerCase()))
704
+ continue;
705
+ if (member === jsonName) {
706
+ hasJson = true;
707
+ continue;
708
+ }
709
+ const match = /^([A-Za-z0-9][A-Za-z0-9_]*)\.sql$/u.exec(member.slice(prefix.length));
710
+ if (!member.startsWith(prefix) || !match)
711
+ throw new DeployInputError('INVALID_SOURCE');
712
+ codeFiles.push({ path: path.join(directory, member), name: match[1] });
713
+ }
714
+ if (!hasJson || codeFiles.length > 64)
715
+ throw new DeployInputError('INVALID_SOURCE');
716
+ const members = [jsonPath, ...codeFiles.map((code) => code.path)];
717
+ const bytes = [];
718
+ for (const member of members)
719
+ bytes.push(await memberBytes(member));
720
+ let document;
721
+ try {
722
+ document = joinSegmentFiles(strictJson(decode(bytes[0])), codeFiles.map((code, index) => ({
723
+ extension: 'sql',
724
+ name: code.name,
725
+ text: decode(bytes[index + 1]),
726
+ })));
727
+ if (document.identity.apiName !== name)
728
+ throw new Error('Identity mismatch');
729
+ }
730
+ catch (error) {
731
+ throw invalidSource(error);
732
+ }
733
+ for (const [index, member] of members.entries()) {
734
+ const after = await memberBytes(member);
735
+ if (!after.equals(bytes[index]))
736
+ refuse();
737
+ }
738
+ const hash = createHash('sha256');
739
+ for (const content of bytes)
740
+ hash.update(String(content.length)).update(':').update(content);
741
+ const freeze = (value) => {
742
+ for (const child of Object.values(value))
743
+ if (child && typeof child === 'object')
744
+ freeze(child);
745
+ Object.freeze(value);
746
+ };
747
+ freeze(document);
748
+ // The files as found on disk, in model order.
749
+ const byModel = new Map(codeFiles.map((code) => [code.name.toLowerCase(), code.path]));
750
+ const models = document.spec.segmentType === 'DBT' ? document.spec.models : [];
751
+ const codePaths = models.map((model) => byModel.get(model.name.toLowerCase()));
752
+ return Object.freeze({
753
+ path: jsonPath,
754
+ codePaths: Object.freeze(codePaths),
755
+ document,
756
+ inputDigest: hash.digest('hex'),
757
+ });
758
+ }
759
+ /**
760
+ * Admit a calculated insight from its JSON or its SQL file: the JSON joined with exactly its
761
+ * declared code files (`<apiName>.calculatedInsight-meta.sql`), every byte bound as one component.
762
+ * A missing JSON or SQL file, or any other `<apiName>.calculatedInsight-meta.*` file beside them,
763
+ * is INVALID_SOURCE.
764
+ * @param {string} file Absolute selected JSON or code file.
765
+ * @returns {Promise<CalculatedInsightDeployInput>} Complete immutable admission.
766
+ */
767
+ async function readCalculatedInsightInput(file) {
768
+ const base = path.basename(file);
769
+ const marker = base.indexOf(ciMemberInfix);
770
+ const apiName = marker > 0 ? base.slice(0, marker) : '';
771
+ const directory = path.dirname(file);
772
+ if (path.basename(directory) !== 'calculatedInsights' ||
773
+ path.basename(path.dirname(directory)) !== 'data360')
774
+ throw new DeployInputError('INVALID_SELECTION');
775
+ if (!calculatedInsightName.test(apiName))
776
+ throw new DeployInputError('INVALID_SOURCE');
777
+ const jsonName = `${apiName}${ciJsonSuffix}`;
778
+ const jsonPath = path.join(directory, jsonName);
779
+ await inspect(directory);
780
+ const prefix = `${apiName}${ciMemberInfix}`;
781
+ const codeFiles = [];
782
+ let hasJson = false;
783
+ const entries = await readdir(directory);
784
+ // eslint-disable-next-line unicorn/no-array-sort -- Sort the fresh directory listing within the existing TypeScript library target.
785
+ for (const entry of entries.sort()) {
786
+ if (!entry.toLowerCase().startsWith(prefix.toLowerCase()))
787
+ continue;
788
+ if (entry === jsonName) {
789
+ hasJson = true;
790
+ continue;
791
+ }
792
+ const match = /^(?:([A-Za-z0-9][A-Za-z0-9_]*)\.)?([a-z]+)$/u.exec(entry.slice(prefix.length));
793
+ if (!entry.startsWith(prefix) || !match || match[2] === 'json')
794
+ throw new DeployInputError('INVALID_SOURCE');
795
+ codeFiles.push({
796
+ path: path.join(directory, entry),
797
+ extension: match[2],
798
+ ...(match[1] === undefined ? {} : { name: match[1] }),
799
+ });
800
+ }
801
+ if (!hasJson || codeFiles.length > 16)
802
+ throw new DeployInputError('INVALID_SOURCE');
803
+ const members = [jsonPath, ...codeFiles.map((code) => code.path)];
804
+ const bytes = [];
805
+ for (const member of members)
806
+ bytes.push(await memberBytes(member));
807
+ let native;
808
+ let document;
809
+ try {
810
+ const json = decode(bytes[0]);
811
+ strictJson(json);
812
+ native = parseNativeCalculatedInsight(json, codeFiles.map((code, index) => ({
813
+ extension: code.extension,
814
+ ...(code.name === undefined ? {} : { name: code.name }),
815
+ text: decode(bytes[index + 1]),
816
+ })));
817
+ if (native.apiName !== apiName)
818
+ throw new Error('Identity mismatch');
819
+ document = calculatedInsightReference(native);
820
+ }
821
+ catch (error) {
822
+ throw invalidSource(error);
823
+ }
824
+ for (const [index, member] of members.entries()) {
825
+ const after = await memberBytes(member);
826
+ if (!after.equals(bytes[index]))
827
+ refuse();
828
+ }
829
+ const hash = createHash('sha256');
830
+ for (const content of bytes)
831
+ hash.update(String(content.length)).update(':').update(content);
832
+ const freeze = (value) => {
833
+ for (const child of Object.values(value))
834
+ if (child && typeof child === 'object')
835
+ freeze(child);
836
+ Object.freeze(value);
837
+ };
838
+ freeze(native);
839
+ freeze(document);
840
+ return Object.freeze({
841
+ path: jsonPath,
842
+ companionPath: codeFiles[0].path,
843
+ native,
844
+ document,
845
+ inputDigest: hash.digest('hex'),
846
+ });
847
+ }
848
+ /**
849
+ * Re-admit the JSON and SQL files before relying on captured logical content or bytes.
850
+ * @param {CalculatedInsightDeployInput} input Original immutable admission.
851
+ * @returns {Promise<void>} Resolves only for unchanged original bytes.
852
+ */
853
+ export async function verifyCalculatedInsightInputDigest(input) {
854
+ try {
855
+ const current = await readCalculatedInsightInput(input.path);
856
+ if (current.companionPath !== input.companionPath ||
857
+ current.inputDigest !== input.inputDigest ||
858
+ JSON.stringify(current.native) !== JSON.stringify(authoredNative(input)) ||
859
+ JSON.stringify(current.document) !== JSON.stringify(authoredDocument(input)))
860
+ refuse();
861
+ }
862
+ catch {
863
+ throw new DeployInputError('UNSAFE_SOURCE');
864
+ }
865
+ }
866
+ /**
867
+ * Revalidate JSON bytes and logical intent before relying on captured admission.
868
+ * @param {SegmentDeployInput} input Previously admitted JSON.
869
+ * @returns {Promise<void>} Resolves only if original bytes and content remain unchanged.
870
+ */
871
+ export async function verifySegmentInputDigest(input) {
872
+ try {
873
+ const current = await readSegmentDeployInput(input.path);
874
+ if (JSON.stringify(current.codePaths) !== JSON.stringify(input.codePaths) ||
875
+ current.inputDigest !== input.inputDigest ||
876
+ JSON.stringify(current.document) !== JSON.stringify(authoredDocument(input)))
877
+ refuse();
878
+ }
879
+ catch {
880
+ throw new DeployInputError('UNSAFE_SOURCE');
881
+ }
882
+ }
883
+ /**
884
+ * Capture admitted exact bytes without changing the existing input shape or Segment JSON digest.
885
+ * @param {DeployInput} input Previously admitted local input.
886
+ * @returns {Promise<string>} Exact byte digest after identity/content re-admission.
887
+ */
888
+ export async function captureDeployInputDigest(input) {
889
+ if (input.document.kind === 'data-transform') {
890
+ await verifyDataTransformInputDigest(input);
891
+ return input.inputDigest;
892
+ }
893
+ if (input.document.kind === 'native-data-graph') {
894
+ await verifyNativeDataGraphInputDigest(input);
895
+ return input.inputDigest;
896
+ }
897
+ if (input.document.kind === 'data-stream') {
898
+ await verifyDataStreamInputDigest(input);
899
+ return input.inputDigest;
900
+ }
901
+ if (input.document.kind === 'mapping') {
902
+ const current = await readMappingInput(input.path);
903
+ if (current.inputDigest !== input.inputDigest ||
904
+ JSON.stringify(current.document) !== JSON.stringify(authoredDocument(input)))
905
+ refuse();
906
+ return current.inputDigest;
907
+ }
908
+ if (input.document.kind === 'relationship') {
909
+ const current = await readRelationshipInput(input.path);
910
+ if (current.inputDigest !== input.inputDigest ||
911
+ JSON.stringify(current.document) !== JSON.stringify(authoredDocument(input)))
912
+ refuse();
913
+ return current.inputDigest;
914
+ }
915
+ if (isNativeDmoInput(input)) {
916
+ const current = await readNativeDmoInput(input.path);
917
+ if (current.inputDigest !== input.inputDigest ||
918
+ JSON.stringify(current.document) !== JSON.stringify(authoredDocument(input)))
919
+ refuse();
920
+ return current.inputDigest;
921
+ }
922
+ if (input.document.kind === 'dlo') {
923
+ await verifyDloInputDigest(input);
924
+ return input.inputDigest;
925
+ }
926
+ if (input.document.kind === 'identity-resolution') {
927
+ await verifyIdentityResolutionInputDigest(input);
928
+ return input.inputDigest;
929
+ }
930
+ if (input.document.kind === 'calculated-insight') {
931
+ await verifyCalculatedInsightInputDigest(input);
932
+ return input.inputDigest;
933
+ }
934
+ await verifySegmentInputDigest(input);
935
+ return input.inputDigest;
936
+ }
937
+ /**
938
+ * Resolve explicit authored files/directories or exact project-relative DMO/Segment selectors, read-only.
939
+ * Limits are 256 files, 1 MiB per file, 1024 visited entries and 16 directory levels.
940
+ * Repeated identical selections coalesce; different files claiming one identity fail closed.
941
+ * @param {DeployInputFlags} flags Explicit mutually exclusive source modes and captured cwd.
942
+ * @returns {Promise<DeployInput[]>} Sorted, independently validated authored inputs.
943
+ */
944
+ export async function readDeployInputs(flags) {
945
+ const { sourceDir, metadata } = flags;
946
+ const values = sourceDir ?? metadata;
947
+ if ((sourceDir === undefined) === (metadata === undefined) ||
948
+ !values?.length ||
949
+ values.some((value) => typeof value !== 'string' || !value.trim() || value !== value.trim()))
950
+ throw new DeployInputError('INVALID_SELECTION');
951
+ if (!path.isAbsolute(flags.cwd))
952
+ throw new DeployInputError('INVALID_SELECTION');
953
+ const selectors = metadata?.map((value) => {
954
+ if (value.startsWith('data-transform:') && dataTransformName.test(value.slice(15)))
955
+ return { kind: 'data-transform', name: value.slice(15) };
956
+ if (/^data-stream:[A-Za-z][A-Za-z0-9_]{0,199}$/u.test(value))
957
+ return { kind: 'data-stream', name: value.slice(12) };
958
+ if (value.startsWith('mapping:') && nativeMappingName.test(value.slice(8)))
959
+ return { kind: 'mapping', name: value.slice(8) };
960
+ if (value.startsWith('relationship:') && nativeRelationshipName.test(value.slice(13)))
961
+ return { kind: 'relationship', name: value.slice(13) };
962
+ if (value.startsWith('dmo:') && nativeDmoName.test(value.slice(4)))
963
+ return { kind: 'dmo', name: value.slice(4) };
964
+ if (value.startsWith('dlo:') && dloName.test(value.slice(4)) && value.endsWith('__dll'))
965
+ return { kind: 'dlo', name: value.slice(4) };
966
+ if (value.startsWith('data-graph:') && dataGraphName.test(value.slice(11)))
967
+ return { kind: 'data-graph', name: value.slice(11) };
968
+ if (value.startsWith('identity-resolution:') && identityResolutionName.test(value.slice(20)))
969
+ return { kind: 'identity-resolution', name: value.slice(20) };
970
+ if (value.startsWith('calculated-insight:') && calculatedInsightName.test(value.slice(19)))
971
+ return { kind: 'calculated-insight', name: value.slice(19) };
972
+ if (value.startsWith('segment:') && segmentName.test(value.slice(8)))
973
+ return { kind: 'segment', name: value.slice(8) };
974
+ throw new DeployInputError('INVALID_SELECTION');
975
+ });
976
+ const roots = selectors
977
+ ? selectors.map(({ kind, name }) => kind === 'data-transform'
978
+ ? path.join(flags.cwd, 'data360', 'dataTransforms', `${name}.dataTransform.json`)
979
+ : kind === 'dmo'
980
+ ? path.join(flags.cwd, 'data360', 'dmo', `${name}.dmo-meta.json`)
981
+ : kind === 'data-stream'
982
+ ? path.join(flags.cwd, 'data360', 'data-stream', `${name}.data-stream-meta.json`)
983
+ : kind === 'mapping'
984
+ ? path.join(flags.cwd, 'data360', 'mapping', `${name}.mapping-meta.json`)
985
+ : kind === 'relationship'
986
+ ? path.join(flags.cwd, 'data360', 'relationship', `${name}.relationship-meta.json`)
987
+ : kind === 'dlo'
988
+ ? path.join(flags.cwd, 'data360', 'dlo', `${name}.dlo-meta.json`)
989
+ : kind === 'data-graph'
990
+ ? path.join(flags.cwd, 'data360', 'dataGraphs', `${name}.native-dataGraph.json`)
991
+ : kind === 'calculated-insight'
992
+ ? path.join(flags.cwd, 'data360', 'calculatedInsights', `${name}${ciJsonSuffix}`)
993
+ : kind === 'identity-resolution'
994
+ ? path.join(flags.cwd, 'data360', 'identityResolution', `${name}.identityResolution.json`)
995
+ : path.join(flags.cwd, 'data360', 'segments', `${name}.segment.json`))
996
+ : sourceDir.map((value) => {
997
+ if (value.includes(String.fromCodePoint(0)) ||
998
+ /[*?]/u.test(value) ||
999
+ value.split(/[\\/]/u).includes('..') ||
1000
+ /^[A-Za-z]:[^\\/]/u.test(value))
1001
+ throw new DeployInputError('INVALID_SELECTION');
1002
+ return path.resolve(flags.cwd, value);
1003
+ });
1004
+ const candidates = new Map();
1005
+ // Files named directly (a selector or an exact --source-dir file), not found in a folder.
1006
+ const named = new Set();
1007
+ let visited = 0;
1008
+ const walk = async (file, depth) => {
1009
+ if (++visited > 1024 || depth > 16)
1010
+ refuse();
1011
+ if (depth === 0)
1012
+ named.add(canonical(file));
1013
+ const stat = await inspect(file);
1014
+ if (stat.isDirectory()) {
1015
+ if (path.dirname(file) === file)
1016
+ refuse();
1017
+ const entries = await readdir(file);
1018
+ // eslint-disable-next-line unicorn/no-array-sort -- Sort the fresh directory listing within the existing TypeScript library target.
1019
+ for (const entry of entries.sort())
1020
+ await walk(path.join(file, entry), depth + 1);
1021
+ }
1022
+ else {
1023
+ if (file.endsWith('.marketSegmentDefinition-meta.xml')) {
1024
+ if (depth === 0)
1025
+ throw new DeployInputError('UNSUPPORTED_SEGMENT_XML');
1026
+ return;
1027
+ }
1028
+ if (!stat.isFile() ||
1029
+ (path.extname(file) !== '.json' &&
1030
+ !isCalculatedInsightMember(file) &&
1031
+ !isSegmentMember(file)) ||
1032
+ stat.nlink !== 1 ||
1033
+ stat.size > 1_048_576)
1034
+ refuse();
1035
+ candidates.set(canonical(file), file);
1036
+ if (candidates.size > 256)
1037
+ refuse();
1038
+ }
1039
+ };
1040
+ try {
1041
+ for (const root of new Set(roots)) {
1042
+ if (selectors) {
1043
+ const selected = await lstat(root);
1044
+ if (!selected.isFile())
1045
+ refuse();
1046
+ }
1047
+ await walk(root, 0);
1048
+ }
1049
+ if (candidates.size === 0)
1050
+ throw new DeployInputError('INVALID_SELECTION');
1051
+ const inputs = [];
1052
+ const identities = new Set();
1053
+ const skipped = new Set();
1054
+ const warnings = [];
1055
+ // eslint-disable-next-line unicorn/no-array-sort -- Sort a fresh candidate array within the existing TypeScript library target.
1056
+ for (const file of [...candidates.values()].sort()) {
1057
+ // A file retrieved as-is is never sent: refused when named, otherwise skipped with a warning.
1058
+ const verbatim = await verbatimMember(file);
1059
+ if (verbatim) {
1060
+ if (flags.verbatim !== 'skip' && named.has(canonical(file)))
1061
+ throw verbatimRefusal(verbatim.document);
1062
+ if (!skipped.has(canonical(verbatim.path))) {
1063
+ skipped.add(canonical(verbatim.path));
1064
+ warnings.push(verbatimSkipWarning(verbatim.document, verbatim.path));
1065
+ }
1066
+ continue;
1067
+ }
1068
+ if (isCalculatedInsightMember(file)) {
1069
+ const input = await readCalculatedInsightInput(file);
1070
+ const key = `calculated-insight:${input.document.identity.dataSpace}:${input.document.identity.apiName}`.toLowerCase();
1071
+ if (inputs.some((prior) => prior.document.kind === 'calculated-insight' &&
1072
+ canonical(prior.path) === canonical(input.path)))
1073
+ continue;
1074
+ if (identities.has(key))
1075
+ throw new DeployInputError('DUPLICATE_IDENTITY');
1076
+ if (selectors &&
1077
+ !selectors.some((item) => item.kind === 'calculated-insight' && item.name === input.document.identity.apiName))
1078
+ throw new DeployInputError('INVALID_SELECTION');
1079
+ identities.add(key);
1080
+ inputs.push(input);
1081
+ continue;
1082
+ }
1083
+ if (file.endsWith('.dataTransform.json')) {
1084
+ const input = await readDataTransformInput(file);
1085
+ const name = input.document.definition.name;
1086
+ const key = `data-transform:default:${name}`.toLowerCase();
1087
+ if (identities.has(key))
1088
+ throw new DeployInputError('DUPLICATE_IDENTITY');
1089
+ if (selectors &&
1090
+ !selectors.some((item) => item.kind === 'data-transform' && item.name === name))
1091
+ throw new DeployInputError('INVALID_SELECTION');
1092
+ identities.add(key);
1093
+ inputs.push(input);
1094
+ continue;
1095
+ }
1096
+ if (file.endsWith('.data-stream-meta.json')) {
1097
+ const input = await readDataStreamInput(file);
1098
+ const key =
1099
+ // A stream name is unique in the org, whatever data spaces its DLO belongs to.
1100
+ `data-stream:${input.document.identity.apiName}`.toLowerCase();
1101
+ if (identities.has(key))
1102
+ throw new DeployInputError('DUPLICATE_IDENTITY');
1103
+ if (selectors &&
1104
+ !selectors.some((item) => item.kind === 'data-stream' && item.name === input.document.identity.apiName))
1105
+ throw new DeployInputError('INVALID_SELECTION');
1106
+ identities.add(key);
1107
+ inputs.push(input);
1108
+ continue;
1109
+ }
1110
+ if (file.endsWith('.mapping-meta.json')) {
1111
+ const input = await readMappingInput(file);
1112
+ const key = `mapping:${input.document.c__dataSpace}:${input.document.identity.apiName}`.toLowerCase();
1113
+ if (identities.has(key))
1114
+ throw new DeployInputError('DUPLICATE_IDENTITY');
1115
+ if (selectors &&
1116
+ !selectors.some((item) => item.kind === 'mapping' && item.name === input.document.identity.apiName))
1117
+ throw new DeployInputError('INVALID_SELECTION');
1118
+ identities.add(key);
1119
+ inputs.push(input);
1120
+ continue;
1121
+ }
1122
+ if (file.endsWith('.relationship-meta.json')) {
1123
+ const input = await readRelationshipInput(file);
1124
+ const key = `relationship:${input.document.c__dataSpace}:${input.document.identity.apiName}`.toLowerCase();
1125
+ // Deploy matches relationships by binding, so two files with one binding are one identity.
1126
+ const { sourceObjectName, sourceFieldName, targetObjectName, targetFieldName } = input.document.spec;
1127
+ const binding = `relationship-binding:${input.document.c__dataSpace}:${sourceObjectName}:${sourceFieldName}:${targetObjectName}:${targetFieldName}`.toLowerCase();
1128
+ if (identities.has(key) || identities.has(binding))
1129
+ throw new DeployInputError('DUPLICATE_IDENTITY');
1130
+ identities.add(binding);
1131
+ if (selectors &&
1132
+ !selectors.some((item) => item.kind === 'relationship' && item.name === input.document.identity.apiName))
1133
+ throw new DeployInputError('INVALID_SELECTION');
1134
+ identities.add(key);
1135
+ inputs.push(input);
1136
+ continue;
1137
+ }
1138
+ if (file.endsWith('.dmo-meta.json')) {
1139
+ const input = await readNativeDmoInput(file);
1140
+ const key = `dmo:${input.document.c__dataSpace}:${input.document.identity.apiName}`.toLowerCase();
1141
+ if (identities.has(key))
1142
+ throw new DeployInputError('DUPLICATE_IDENTITY');
1143
+ if (selectors &&
1144
+ !selectors.some((item) => item.kind === 'dmo' && item.name === input.document.identity.apiName))
1145
+ throw new DeployInputError('INVALID_SELECTION');
1146
+ identities.add(key);
1147
+ inputs.push(input);
1148
+ continue;
1149
+ }
1150
+ if (file.endsWith('.dlo-meta.json')) {
1151
+ const input = await readDloInput(file);
1152
+ // A DLO name is unique in the org, whatever data spaces it belongs to.
1153
+ const key = `dlo:${input.document.identity.apiName}`.toLowerCase();
1154
+ if (identities.has(key))
1155
+ throw new DeployInputError('DUPLICATE_IDENTITY');
1156
+ if (selectors &&
1157
+ !selectors.some((item) => item.kind === 'dlo' && item.name === input.document.identity.apiName))
1158
+ throw new DeployInputError('INVALID_SELECTION');
1159
+ identities.add(key);
1160
+ inputs.push(input);
1161
+ continue;
1162
+ }
1163
+ if (file.endsWith('.native-dataGraph.json')) {
1164
+ const input = await readNativeDataGraphInput(file);
1165
+ const name = input.document.definition.name;
1166
+ // A graph name is unique in the org, whatever data space it is in.
1167
+ const key = `data-graph:${name}`.toLowerCase();
1168
+ if (identities.has(key))
1169
+ throw new DeployInputError('DUPLICATE_IDENTITY');
1170
+ if (selectors &&
1171
+ !selectors.some((item) => item.kind === 'data-graph' && item.name === name))
1172
+ throw new DeployInputError('INVALID_SELECTION');
1173
+ identities.add(key);
1174
+ inputs.push(input);
1175
+ continue;
1176
+ }
1177
+ if (file.endsWith('.identityResolution.json')) {
1178
+ const input = await readIdentityResolutionInput(file);
1179
+ const key = `identity-resolution:${input.document.c__dataSpace}:${input.document.identity.apiName}`.toLowerCase();
1180
+ if (identities.has(key))
1181
+ throw new DeployInputError('DUPLICATE_IDENTITY');
1182
+ if (selectors &&
1183
+ !selectors.some((item) => item.kind === 'identity-resolution' && item.name === input.document.identity.apiName))
1184
+ throw new DeployInputError('INVALID_SELECTION');
1185
+ identities.add(key);
1186
+ inputs.push(input);
1187
+ continue;
1188
+ }
1189
+ if (isSegmentMember(file)) {
1190
+ const paired = await readSegmentDeployInput(file);
1191
+ const key = `segment:${paired.document.c__dataSpace}:${paired.document.identity.apiName}`.toLowerCase();
1192
+ const prior = inputs.find((input) => input.document.kind === 'segment' && canonical(input.path) === canonical(paired.path));
1193
+ if (prior)
1194
+ continue;
1195
+ if (identities.has(key))
1196
+ throw new DeployInputError('DUPLICATE_IDENTITY');
1197
+ if (selectors &&
1198
+ !selectors.some((item) => item.kind === 'segment' && item.name === paired.document.identity.apiName))
1199
+ throw new DeployInputError('INVALID_SELECTION');
1200
+ identities.add(key);
1201
+ inputs.push(paired);
1202
+ continue;
1203
+ }
1204
+ throw new DeployInputError('INVALID_SOURCE');
1205
+ }
1206
+ if (warnings.length > 0)
1207
+ skippedWarnings.set(inputs, Object.freeze(warnings));
1208
+ return inputs;
1209
+ }
1210
+ catch (error) {
1211
+ if (error instanceof DeployInputError)
1212
+ throw error;
1213
+ throw new DeployInputError('UNSAFE_SOURCE');
1214
+ }
1215
+ }
1216
+ /**
1217
+ * Admit a deleted verbatim file (retrieved as-is): it is deleted by family and name, needs no SQL
1218
+ * file and no spec. A relationship's source DMO comes from the raw list entry it keeps.
1219
+ * @param {DeletedArtifactKind} kind Family derived from the canonical path.
1220
+ * @param {string} name Canonical name derived from the path.
1221
+ * @param {Buffer} bytes Exact revision bytes (the JSON file).
1222
+ * @returns {object | undefined} Identity, the frozen verbatim document and a relationship's
1223
+ * source DMO; undefined when the bytes are not a verbatim document of that family.
1224
+ */
1225
+ function admitDeletedVerbatim(kind, name, bytes) {
1226
+ let value;
1227
+ try {
1228
+ value = strictJson(decode(bytes));
1229
+ }
1230
+ catch {
1231
+ return undefined;
1232
+ }
1233
+ if (!isVerbatimDocument(value, kind === 'data-graph' ? 'native-data-graph' : kind))
1234
+ return undefined;
1235
+ const source = value.verbatim.native
1236
+ ?.sourceObject?.name;
1237
+ if (value.identity.apiName !== name ||
1238
+ (kind === 'relationship' && (typeof source !== 'string' || !relationshipDmoName.test(source))))
1239
+ throw new DeployInputError('INVALID_SOURCE');
1240
+ return {
1241
+ identity: verbatimIdentity(value),
1242
+ document: Object.freeze(value),
1243
+ ...(kind === 'relationship' ? { sourceObjectName: source } : {}),
1244
+ };
1245
+ }
1246
+ /**
1247
+ * Admit bytes of a file read from a Git revision (no worktree file exists) by the family
1248
+ * validator, and take the identity from the content, which must agree with the canonical name.
1249
+ * The file is read as retrieve writes it (retrieve mode): a delete needs its family, identity
1250
+ * and what the delete itself uses, not a deployable definition.
1251
+ * @param {DeletedArtifactKind} kind Family derived from the canonical path.
1252
+ * @param {string} name Canonical name derived from the path.
1253
+ * @param {Buffer} bytes Exact revision bytes (the JSON file).
1254
+ * @param {Array<{name?: string; bytes: Buffer}>} [code] SQL file bytes from the same revision: the
1255
+ * calculated insight's one SQL file, or one per segment model (`name` is the model).
1256
+ * @returns {object} Content identity and the validated base document (deeply frozen), plus the
1257
+ * source DMO of a relationship.
1258
+ */
1259
+ export function admitDeletedArtifact(kind, name, bytes, code) {
1260
+ const verbatim = admitDeletedVerbatim(kind, name, bytes);
1261
+ if (verbatim)
1262
+ return verbatim;
1263
+ try {
1264
+ const value = strictJson(decode(bytes));
1265
+ let identity;
1266
+ let document;
1267
+ let sourceObjectName;
1268
+ switch (kind) {
1269
+ case 'dmo': {
1270
+ const dmo = validateNativeDmoDocument(value, 'retrieve');
1271
+ document = dmo;
1272
+ identity = { dataSpace: dmo.c__dataSpace, apiName: dmo.identity.apiName };
1273
+ break;
1274
+ }
1275
+ case 'dlo': {
1276
+ document = validateDloDocument(value, 'retrieve');
1277
+ ({ identity } = document);
1278
+ break;
1279
+ }
1280
+ case 'mapping': {
1281
+ const mapping = validateNativeMappingDocument(value, 'retrieve');
1282
+ document = mapping;
1283
+ identity = { dataSpace: mapping.c__dataSpace, apiName: mapping.identity.apiName };
1284
+ break;
1285
+ }
1286
+ case 'relationship': {
1287
+ const relationship = validateNativeRelationshipDocument(value, 'retrieve');
1288
+ document = relationship;
1289
+ identity = { dataSpace: relationship.c__dataSpace, apiName: relationship.identity.apiName };
1290
+ sourceObjectName = relationship.spec.sourceObjectName;
1291
+ break;
1292
+ }
1293
+ case 'data-stream': {
1294
+ document = validateAnyDataStreamDocument(value, 'retrieve');
1295
+ ({ identity } = document);
1296
+ break;
1297
+ }
1298
+ case 'data-transform': {
1299
+ const transform = validateDataTransformDocument(value, 'retrieve');
1300
+ document = transform;
1301
+ identity = {
1302
+ dataSpace: transform.c__dataSpace,
1303
+ apiName: transform.definition.name,
1304
+ };
1305
+ break;
1306
+ }
1307
+ case 'data-graph': {
1308
+ const graph = validateNativeDataGraphDocument(value, 'retrieve');
1309
+ document = graph;
1310
+ identity = { dataSpace: graph.c__dataSpace, apiName: graph.definition.name };
1311
+ break;
1312
+ }
1313
+ case 'identity-resolution': {
1314
+ const ruleset = validateIdentityResolutionDocument(value, 'retrieve');
1315
+ document = ruleset;
1316
+ identity = { dataSpace: ruleset.c__dataSpace, apiName: ruleset.identity.apiName };
1317
+ break;
1318
+ }
1319
+ case 'calculated-insight': {
1320
+ if (code?.length !== 1 || code[0].name !== undefined)
1321
+ throw new Error('Missing SQL');
1322
+ const native = parseNativeCalculatedInsight(decode(bytes), [
1323
+ { extension: 'sql', text: decode(code[0].bytes) },
1324
+ ]);
1325
+ document = calculatedInsightReference(native);
1326
+ identity = { dataSpace: native.dataSpace, apiName: native.apiName };
1327
+ break;
1328
+ }
1329
+ case 'segment': {
1330
+ document = joinSegmentFiles(value, (code ?? []).map((file) => ({
1331
+ extension: 'sql',
1332
+ ...(file.name === undefined ? {} : { name: file.name }),
1333
+ text: decode(file.bytes),
1334
+ })), 'retrieve');
1335
+ identity = { dataSpace: document.c__dataSpace, apiName: document.identity.apiName };
1336
+ break;
1337
+ }
1338
+ }
1339
+ if (identity.apiName !== name)
1340
+ throw new Error('Identity mismatch');
1341
+ const freeze = (target) => {
1342
+ for (const child of Object.values(target))
1343
+ if (child && typeof child === 'object')
1344
+ freeze(child);
1345
+ Object.freeze(target);
1346
+ };
1347
+ freeze(document);
1348
+ return {
1349
+ identity: identity.dataSpace === undefined
1350
+ ? { apiName: identity.apiName }
1351
+ : { dataSpace: identity.dataSpace, apiName: identity.apiName },
1352
+ document,
1353
+ ...(sourceObjectName === undefined ? {} : { sourceObjectName }),
1354
+ };
1355
+ }
1356
+ catch {
1357
+ throw new DeployInputError('INVALID_SOURCE');
1358
+ }
1359
+ }