@arcticdata/dsh-datarc-assistant 26.39.0 → 26.39.1

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 (149) hide show
  1. package/README.md +45 -10
  2. package/api-operations.js +404 -0
  3. package/client.js +452 -87
  4. package/cordis.patch.yml +4 -4
  5. package/entry/SKILL.md +34 -0
  6. package/icon.png +0 -0
  7. package/index.js +35 -47
  8. package/locale/en.json +6 -6
  9. package/locale/zh.json +6 -6
  10. package/native-api.mjs +326 -0
  11. package/native-contracts.js +195 -0
  12. package/native-execution.js +184 -0
  13. package/native-runner.mjs +107 -0
  14. package/native-state.js +67 -0
  15. package/native-tools.js +241 -0
  16. package/operations.js +1260 -0
  17. package/package.json +65 -51
  18. package/{skills → runtime}/datarc-access-permissions/SKILL.md +30 -30
  19. package/{skills → runtime}/datarc-access-permissions/references/api.md +31 -31
  20. package/{skills → runtime}/datarc-access-permissions/references/write-order.md +16 -16
  21. package/{skills → runtime}/datarc-analysis-report/SKILL.md +125 -125
  22. package/{skills → runtime}/datarc-analysis-report/agents/openai.yaml +6 -6
  23. package/{skills → runtime}/datarc-analysis-report/references/analyst-frameworks.md +215 -215
  24. package/{skills → runtime}/datarc-analysis-report/references/api-contracts.md +478 -478
  25. package/{skills → runtime}/datarc-analysis-report/references/direct-card-fallback-design.md +66 -66
  26. package/{skills → runtime}/datarc-analysis-report/references/human-in-the-loop.md +142 -142
  27. package/{skills → runtime}/datarc-analysis-report/references/loop-personalization-policy.md +138 -138
  28. package/{skills → runtime}/datarc-analysis-report/references/manifest-example.json +779 -779
  29. package/{skills → runtime}/datarc-analysis-report/references/narrative-schema.md +160 -160
  30. package/{skills → runtime}/datarc-analysis-report/references/question-syntax.md +151 -151
  31. package/{skills → runtime}/datarc-analysis-report/scripts/run_analysis_report.py +2225 -2225
  32. package/{skills → runtime}/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -1914
  33. package/{skills → runtime}/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -5295
  34. package/{skills → runtime}/datarc-data-search/SKILL.md +243 -243
  35. package/{skills → runtime}/datarc-data-search/scripts/calculate.py +116 -116
  36. package/{skills → runtime}/datarc-data-search/scripts/data-search.mjs +628 -628
  37. package/{skills/datarc-dataseek-search → runtime/datarc-data-search}/scripts/datarc-client.mjs +464 -464
  38. package/{skills → runtime}/datarc-data-search/scripts/search-result.mjs +211 -211
  39. package/{skills → runtime}/datarc-dataseek-batch-evaluation/SKILL.md +59 -59
  40. package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -36
  41. package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -30
  42. package/{skills/datarc-data-search → runtime/datarc-dataseek-batch-evaluation}/scripts/datarc-client.mjs +464 -464
  43. package/{skills → runtime}/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -1020
  44. package/{skills → runtime}/datarc-dataseek-search/SKILL.md +96 -96
  45. package/{skills/datarc-dataseek-batch-evaluation → runtime/datarc-dataseek-search}/scripts/datarc-client.mjs +464 -464
  46. package/{skills → runtime}/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -257
  47. package/{skills → runtime}/datarc-dataseek-semantic-debugging/SKILL.md +44 -44
  48. package/{skills → runtime}/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -4
  49. package/{skills → runtime}/datarc-dataseek-semantic-debugging/evals/evals.json +165 -165
  50. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/dataset.md +77 -77
  51. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -93
  52. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/interventions.md +64 -64
  53. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -47
  54. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/rollback.md +11 -11
  55. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -95
  56. package/{skills → runtime}/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -29
  57. package/{skills → runtime}/datarc-dataseek-testset-generation/SKILL.md +47 -47
  58. package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -464
  59. package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -526
  60. package/{skills → runtime}/datarc-datasource/SKILL.md +97 -97
  61. package/{skills → runtime}/datarc-oauth/SKILL.md +50 -50
  62. package/{skills → runtime}/datarc-oauth/scripts/auth.mjs +192 -192
  63. package/{skills → runtime}/datarc-oauth/scripts/credentials.mjs +237 -237
  64. package/{skills → runtime}/datarc-report-add-card/SKILL.md +90 -90
  65. package/{skills → runtime}/datarc-report-add-card/agents/openai.yaml +4 -4
  66. package/runtime/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
  67. package/{skills → runtime}/datarc-report-add-card/scripts/report-card.mjs +439 -439
  68. package/{skills → runtime}/datarc-semantic-alias/SKILL.md +20 -20
  69. package/{skills → runtime}/datarc-semantic-alias/scripts/alias-plan.mjs +422 -422
  70. package/{skills → runtime}/datarc-semantic-alias/scripts/alias.mjs +11 -11
  71. package/{skills → runtime}/datarc-semantic-calibration/SKILL.md +20 -20
  72. package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -683
  73. package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration.mjs +11 -11
  74. package/{skills → runtime}/datarc-semantic-core/SKILL.md +12 -12
  75. package/{skills → runtime}/datarc-semantic-core/scripts/artifact-journal.mjs +853 -830
  76. package/{skills → runtime}/datarc-semantic-core/scripts/canonical.mjs +48 -48
  77. package/{skills → runtime}/datarc-semantic-core/scripts/case-model.mjs +608 -608
  78. package/{skills → runtime}/datarc-semantic-core/scripts/cli.mjs +180 -180
  79. package/{skills → runtime}/datarc-semantic-core/scripts/datarc-client.mjs +180 -180
  80. package/{skills → runtime}/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -57
  81. package/{skills → runtime}/datarc-semantic-core/scripts/interventions.mjs +693 -693
  82. package/{skills → runtime}/datarc-semantic-core/scripts/live-resolution.mjs +305 -305
  83. package/{skills → runtime}/datarc-semantic-core/scripts/model-scope.mjs +49 -49
  84. package/{skills → runtime}/datarc-semantic-core/scripts/reproduction.mjs +330 -330
  85. package/{skills → runtime}/datarc-semantic-core/scripts/semantic-cli.mjs +799 -740
  86. package/{skills → runtime}/datarc-semantic-core/scripts/shared.mjs +312 -312
  87. package/{skills → runtime}/datarc-semantic-core/scripts/verification.mjs +1111 -1014
  88. package/{skills → runtime}/datarc-semantic-dataset/SKILL.md +20 -20
  89. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -749
  90. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -813
  91. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset.mjs +11 -11
  92. package/{skills → runtime}/datarc-semantic-knowledge/SKILL.md +38 -38
  93. package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -61
  94. package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-generation.json +16 -16
  95. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -347
  96. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -848
  97. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -31
  98. package/{skills → runtime}/datarc-semantic-prompt/SKILL.md +20 -20
  99. package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt-plan.mjs +598 -447
  100. package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt.mjs +15 -15
  101. package/{skills → runtime}/datarc-semantic-synonym/SKILL.md +20 -20
  102. package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -688
  103. package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym.mjs +11 -11
  104. package/{skills → runtime}/datarc-viz-analysis-report/SKILL.md +108 -108
  105. package/{skills → runtime}/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -8
  106. package/{skills → runtime}/datarc-viz-analysis-report/assets/echarts.min.js +45 -45
  107. package/{skills → runtime}/datarc-viz-analysis-report/references/api-contracts.md +163 -163
  108. package/{skills → runtime}/datarc-viz-analysis-report/references/derivation-log.md +157 -157
  109. package/{skills → runtime}/datarc-viz-analysis-report/references/evidence-framework.md +76 -76
  110. package/{skills → runtime}/datarc-viz-analysis-report/references/html-template.md +92 -92
  111. package/{skills → runtime}/datarc-viz-analysis-report/references/provenance-format.md +56 -56
  112. package/{skills → runtime}/datarc-viz-analysis-report/references/question-syntax.md +151 -151
  113. package/{skills → runtime}/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -1708
  114. package/{skills → runtime}/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -964
  115. package/{skills → runtime}/datarc-workspace-configuration/SKILL.md +59 -59
  116. package/{skills → runtime}/datarc-workspace-configuration/references/artifacts.md +75 -75
  117. package/{skills → runtime}/datarc-workspace-configuration/references/verification.md +20 -20
  118. package/{skills → runtime}/datarc-workspace-configuration/scripts/configuration.mjs +722 -662
  119. package/{skills → runtime}/datarc-workspace-context/SKILL.md +43 -43
  120. package/{skills → runtime}/datarc-workspace-context/agents/openai.yaml +4 -4
  121. package/{skills → runtime}/datarc-workspace-context/scripts/datarc-client.mjs +31 -31
  122. package/{skills → runtime}/datarc-workspace-context/scripts/query-display.mjs +114 -114
  123. package/{skills → runtime}/datarc-workspace-context/scripts/workspace-context.mjs +58 -58
  124. package/{skills → runtime}/datarc-workspace-custom-tables/SKILL.md +89 -89
  125. package/{skills → runtime}/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -165
  126. package/{skills → runtime}/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -601
  127. package/{skills → runtime}/datarc-workspace-keywords/SKILL.md +197 -197
  128. package/{skills → runtime}/datarc-workspace-keywords/agents/openai.yaml +4 -4
  129. package/{skills → runtime}/datarc-workspace-keywords/references/api-fields.md +79 -79
  130. package/{skills → runtime}/datarc-workspace-keywords/references/derived-measures.md +177 -177
  131. package/{skills → runtime}/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -145
  132. package/{skills → runtime}/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -2421
  133. package/{skills → runtime}/datarc-workspace-membership/SKILL.md +29 -29
  134. package/{skills → runtime}/datarc-workspace-membership/references/api.md +19 -19
  135. package/{skills → runtime}/datarc-workspace-modeling/SKILL.md +209 -209
  136. package/{skills → runtime}/datarc-workspace-modeling/agents/openai.yaml +4 -4
  137. package/{skills → runtime}/datarc-workspace-modeling/references/join-preview.md +38 -38
  138. package/{skills → runtime}/datarc-workspace-modeling/references/model-plan.md +300 -300
  139. package/{skills → runtime}/datarc-workspace-modeling/references/model-tags.md +95 -95
  140. package/{skills → runtime}/datarc-workspace-modeling/references/modeling-contract.json +29 -29
  141. package/{skills → runtime}/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -2423
  142. package/{skills → runtime}/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -137
  143. package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -238
  144. package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -1261
  145. package/skills-provider.js +51 -0
  146. package/workflow-index.json +434 -0
  147. package/icon.svg +0 -4
  148. package/skills/datarc-report-add-card/scripts/datarc-client.mjs +0 -464
  149. package/skills-index.json +0 -194
@@ -1,312 +1,312 @@
1
- import { canonicalJson, hashWithout } from "./canonical.mjs";
2
- import { DatarcError } from "./datarc-client.mjs";
3
-
4
- export function isRecord(value) {
5
- if (value === null || typeof value !== "object" || Array.isArray(value))
6
- return false;
7
- const prototype = Object.getPrototypeOf(value);
8
- return prototype === Object.prototype || prototype === null;
9
- }
10
-
11
- export function requiredTrimmedString(value) {
12
- return typeof value === "string" ? value.trim() : "";
13
- }
14
-
15
- export function uniquePairs(pairs) {
16
- const seen = new Set();
17
- return pairs.filter(({ word, prop }) => {
18
- const key = JSON.stringify([word, prop]);
19
- if (seen.has(key)) return false;
20
- seen.add(key);
21
- return true;
22
- });
23
- }
24
-
25
- export function normalizeText(value) {
26
- return String(value ?? "")
27
- .normalize("NFKC")
28
- .trim()
29
- .toLocaleLowerCase();
30
- }
31
-
32
- export function isServerChineseCharacter(character) {
33
- const point = character.codePointAt(0);
34
- return [
35
- [0x4e00, 0x9fff],
36
- [0xff00, 0xffef],
37
- [0x2e80, 0x2eff],
38
- [0x3000, 0x303f],
39
- [0x31c0, 0x31ef],
40
- ].some(([start, end]) => start <= point && point <= end);
41
- }
42
-
43
- export function safeOpaqueIdentifier(value) {
44
- const normalized = requiredTrimmedString(value);
45
- return normalized &&
46
- normalized.length <= 255 &&
47
- /^[0-9A-Za-z._:+/-]+$/u.test(normalized)
48
- ? normalized
49
- : null;
50
- }
51
-
52
- export function canonicalPositiveInteger(value) {
53
- if (Number.isSafeInteger(value) && value > 0) return value;
54
- if (typeof value !== "string" || !/^[1-9]\d*$/u.test(value)) return null;
55
- const number = Number(value);
56
- return Number.isSafeInteger(number) ? number : null;
57
- }
58
-
59
- export function requireClient(client) {
60
- if (!client || typeof client.request !== "function")
61
- fail("INVALID_CLIENT", "client.request is required");
62
- }
63
-
64
- export function fail(code, message, details) {
65
- throw new DatarcError(message, code, details);
66
- }
67
-
68
- export function requiredText(value, field) {
69
- if (typeof value !== "string" || !value.trim())
70
- fail("INVALID_INPUT", `${field} must be a nonempty string`);
71
- return value.trim();
72
- }
73
-
74
- export function listOf(value) {
75
- return Array.isArray(value) ? value : [];
76
- }
77
-
78
- export function compact(value) {
79
- return Object.fromEntries(
80
- Object.entries(value).filter(([, item]) => item !== undefined),
81
- );
82
- }
83
-
84
- export function requireArrayResponse(value, code, message) {
85
- if (!Array.isArray(value)) fail(code, message);
86
- return value;
87
- }
88
-
89
- export function normalizeServerWord(value) {
90
- if (typeof value !== "string") return "";
91
- return value.trim().replace(/[A-Z]/g, (character) => character.toLowerCase());
92
- }
93
-
94
- export async function listAllPages(client, path, query = {}) {
95
- const rows = [];
96
- const limit = 100;
97
- for (let offset = 0; ; offset += limit) {
98
- const page = requireArrayResponse(
99
- await client.request("GET", path, {
100
- query: { ...query, offset, limit },
101
- }),
102
- "INVALID_RESPONSE",
103
- "paginated semantic resource response must be an array",
104
- );
105
- rows.push(...page);
106
- if (page.length < limit) return rows;
107
- }
108
- }
109
-
110
- export function assertEnvelopeHash(value, field, confirmation, prefix) {
111
- const expected = hashWithout(value, field);
112
- if (value?.[field] !== expected)
113
- fail("HASH_MISMATCH", `${field} does not match the immutable body`);
114
- if (confirmation !== `${prefix}:${expected}`)
115
- fail("CONFIRMATION_REQUIRED", `confirmation must be ${prefix}:<hash>`);
116
- }
117
-
118
- export function assertState(actual, expected, code, step) {
119
- if (statesEqual(actual, expected)) return;
120
- fail(code, "semantic state changed or did not match the desired state", {
121
- kind: step.kind,
122
- endpoint: step.endpoint,
123
- expected,
124
- actual,
125
- });
126
- }
127
-
128
- export function statesEqual(actual, expected) {
129
- if (actual === null || expected === null) return actual === expected;
130
- const normalizedActual = structuredClone(actual);
131
- if (!("id" in expected)) delete normalizedActual.id;
132
- return canonicalJson(normalizedActual) === canonicalJson(expected);
133
- }
134
-
135
- export function uniqueStates(states) {
136
- const seen = new Set();
137
- return states.filter((state) => {
138
- const key = canonicalJson(state);
139
- if (seen.has(key)) return false;
140
- seen.add(key);
141
- return true;
142
- });
143
- }
144
-
145
- export function canonicalPlanResourceId(value, code) {
146
- const text = typeof value === "string" ? value : String(value ?? "");
147
- if (!/^[1-9]\d*$/u.test(text))
148
- fail(code, "resource id must be a canonical positive integer");
149
- const id = Number(text);
150
- if (!Number.isSafeInteger(id) || String(id) !== text)
151
- fail(code, "resource id must be a canonical positive integer");
152
- return id;
153
- }
154
-
155
- export function validateMutationCaseIds(caseIds, code) {
156
- if (!Array.isArray(caseIds) || caseIds.length === 0)
157
- fail(code, "mutation step requires caseIds");
158
- const seen = new Set();
159
- for (const caseId of caseIds) {
160
- if (
161
- typeof caseId !== "string" ||
162
- !caseId ||
163
- caseId !== caseId.trim() ||
164
- seen.has(caseId)
165
- )
166
- fail(code, "mutation step caseIds are invalid");
167
- seen.add(caseId);
168
- }
169
- return [...seen];
170
- }
171
-
172
- export const READ_ONLY_FIELDS = {
173
- dimension: new Set(["used", "models"]),
174
- measure: new Set([
175
- "used",
176
- "models",
177
- "isValid",
178
- "formula_snapshot",
179
- "formula_dependency",
180
- ]),
181
- };
182
-
183
- export function hasCutAlternatives(value) {
184
- return value !== undefined && (!Array.isArray(value) || value.length > 0);
185
- }
186
-
187
- export function canonicalSynonymId(value) {
188
- const text = typeof value === "string" ? value : String(value ?? "");
189
- if (!/^\d+$/.test(text))
190
- fail("INVALID_SYNONYM_PLAN", "synonym id must be a positive integer");
191
- const id = Number(text);
192
- if (!Number.isSafeInteger(id) || id <= 0)
193
- fail("INVALID_SYNONYM_PLAN", "synonym id must be a positive integer");
194
- return id;
195
- }
196
-
197
- export function bindSummaryAuthorityTargets(plan) {
198
- const authorities = new Map(
199
- plan.authorities.map((authority) => [authority.caseId, authority]),
200
- );
201
- for (const summary of plan.summaries) {
202
- summary.authorityTargets = summary.caseIds.map((caseId) => {
203
- const authority = authorities.get(caseId);
204
- if (!authority)
205
- fail(
206
- "INVALID_PLAN_STRUCTURE",
207
- "plan summary references an unknown case authority",
208
- );
209
- return { caseId, target: structuredClone(authority.target) };
210
- });
211
- }
212
- }
213
-
214
- export function canonicalDatasetId(value) {
215
- const text = typeof value === "string" ? value.trim() : String(value ?? "");
216
- if (!/^\d+$/u.test(text))
217
- fail("INVALID_DATASET_PLAN", "dataset id must be a positive integer");
218
- const id = Number(text);
219
- if (!Number.isSafeInteger(id) || id <= 0)
220
- fail("INVALID_DATASET_PLAN", "dataset id must be a positive integer");
221
- return id;
222
- }
223
-
224
- export function resolveCompletedStep(step, response) {
225
- const responseId = response?.id;
226
- if (
227
- responseId === undefined ||
228
- step.after?.id !== undefined ||
229
- (step.before !== null && step.operation !== "REPLACE")
230
- )
231
- return structuredClone(step);
232
- const after = { ...step.after, id: responseId };
233
- let endpoint = step.endpoint;
234
- if (endpoint.endsWith("/")) endpoint = `${endpoint}${responseId}/`;
235
- return { ...structuredClone(step), endpoint, after };
236
- }
237
-
238
- export function assertPossibleState(actual, expectedStates, code, step) {
239
- if (listOf(expectedStates).some((expected) => statesEqual(actual, expected)))
240
- return;
241
- fail(code, "semantic state is outside every recorded possible state", {
242
- kind: step.kind,
243
- endpoint: step.endpoint,
244
- expectedStates,
245
- actual,
246
- });
247
- }
248
-
249
- export function authoritiesForCaseIds(authorities, caseIds, kind, code) {
250
- return caseIds.map((caseId) => {
251
- const authority = authorities.get(caseId);
252
- if (authority?.kind !== kind)
253
- fail(code, `${kind} step caseIds must match exact authorities`);
254
- return authority;
255
- });
256
- }
257
-
258
- export function matchesAuthority(authority, kind, predicate) {
259
- return authority?.kind === kind && predicate(authority.target);
260
- }
261
-
262
- export function claimStepCaseIds(used, caseIds) {
263
- for (const caseId of caseIds) {
264
- if (used.has(caseId))
265
- fail(
266
- "INVALID_PLAN_STRUCTURE",
267
- "one case authority cannot authorize multiple mutation steps",
268
- );
269
- used.add(caseId);
270
- }
271
- }
272
-
273
- export function coalesceNamedOperation({
274
- caseId,
275
- operation,
276
- groups,
277
- names,
278
- result,
279
- conflictCode,
280
- }) {
281
- const kind = operation.kind;
282
- const nameKey = normalizeText(operation.name);
283
- const targetKey =
284
- operation.id === undefined
285
- ? `${kind}:name:${nameKey}`
286
- : `${kind}:id:${operation.id}`;
287
- const existingNameTarget = names.get(nameKey);
288
- if (existingNameTarget !== undefined && existingNameTarget !== targetKey)
289
- fail(conflictCode, `one ${kind} name cannot select different identities`);
290
- names.set(nameKey, targetKey);
291
-
292
- const desired = structuredClone(operation);
293
- delete desired.caseId;
294
- delete desired.caseIds;
295
- const desiredKey = canonicalJson(desired);
296
- let group = groups.get(targetKey);
297
- if (!group) {
298
- group = {
299
- ...structuredClone(operation),
300
- caseId,
301
- caseIds: [],
302
- desiredKey,
303
- };
304
- groups.set(targetKey, group);
305
- result.push(group);
306
- } else if (group.desiredKey !== desiredKey)
307
- fail(
308
- conflictCode,
309
- `one ${kind} target cannot have different desired states`,
310
- );
311
- group.caseIds.push(caseId);
312
- }
1
+ import { canonicalJson, hashWithout } from "./canonical.mjs";
2
+ import { DatarcError } from "./datarc-client.mjs";
3
+
4
+ export function isRecord(value) {
5
+ if (value === null || typeof value !== "object" || Array.isArray(value))
6
+ return false;
7
+ const prototype = Object.getPrototypeOf(value);
8
+ return prototype === Object.prototype || prototype === null;
9
+ }
10
+
11
+ export function requiredTrimmedString(value) {
12
+ return typeof value === "string" ? value.trim() : "";
13
+ }
14
+
15
+ export function uniquePairs(pairs) {
16
+ const seen = new Set();
17
+ return pairs.filter(({ word, prop }) => {
18
+ const key = JSON.stringify([word, prop]);
19
+ if (seen.has(key)) return false;
20
+ seen.add(key);
21
+ return true;
22
+ });
23
+ }
24
+
25
+ export function normalizeText(value) {
26
+ return String(value ?? "")
27
+ .normalize("NFKC")
28
+ .trim()
29
+ .toLocaleLowerCase();
30
+ }
31
+
32
+ export function isServerChineseCharacter(character) {
33
+ const point = character.codePointAt(0);
34
+ return [
35
+ [0x4e00, 0x9fff],
36
+ [0xff00, 0xffef],
37
+ [0x2e80, 0x2eff],
38
+ [0x3000, 0x303f],
39
+ [0x31c0, 0x31ef],
40
+ ].some(([start, end]) => start <= point && point <= end);
41
+ }
42
+
43
+ export function safeOpaqueIdentifier(value) {
44
+ const normalized = requiredTrimmedString(value);
45
+ return normalized &&
46
+ normalized.length <= 255 &&
47
+ /^[0-9A-Za-z._:+/-]+$/u.test(normalized)
48
+ ? normalized
49
+ : null;
50
+ }
51
+
52
+ export function canonicalPositiveInteger(value) {
53
+ if (Number.isSafeInteger(value) && value > 0) return value;
54
+ if (typeof value !== "string" || !/^[1-9]\d*$/u.test(value)) return null;
55
+ const number = Number(value);
56
+ return Number.isSafeInteger(number) ? number : null;
57
+ }
58
+
59
+ export function requireClient(client) {
60
+ if (!client || typeof client.request !== "function")
61
+ fail("INVALID_CLIENT", "client.request is required");
62
+ }
63
+
64
+ export function fail(code, message, details) {
65
+ throw new DatarcError(message, code, details);
66
+ }
67
+
68
+ export function requiredText(value, field) {
69
+ if (typeof value !== "string" || !value.trim())
70
+ fail("INVALID_INPUT", `${field} must be a nonempty string`);
71
+ return value.trim();
72
+ }
73
+
74
+ export function listOf(value) {
75
+ return Array.isArray(value) ? value : [];
76
+ }
77
+
78
+ export function compact(value) {
79
+ return Object.fromEntries(
80
+ Object.entries(value).filter(([, item]) => item !== undefined),
81
+ );
82
+ }
83
+
84
+ export function requireArrayResponse(value, code, message) {
85
+ if (!Array.isArray(value)) fail(code, message);
86
+ return value;
87
+ }
88
+
89
+ export function normalizeServerWord(value) {
90
+ if (typeof value !== "string") return "";
91
+ return value.trim().replace(/[A-Z]/g, (character) => character.toLowerCase());
92
+ }
93
+
94
+ export async function listAllPages(client, path, query = {}) {
95
+ const rows = [];
96
+ const limit = 100;
97
+ for (let offset = 0; ; offset += limit) {
98
+ const page = requireArrayResponse(
99
+ await client.request("GET", path, {
100
+ query: { ...query, offset, limit },
101
+ }),
102
+ "INVALID_RESPONSE",
103
+ "paginated semantic resource response must be an array",
104
+ );
105
+ rows.push(...page);
106
+ if (page.length < limit) return rows;
107
+ }
108
+ }
109
+
110
+ export function assertEnvelopeHash(value, field, confirmation, prefix) {
111
+ const expected = hashWithout(value, field);
112
+ if (value?.[field] !== expected)
113
+ fail("HASH_MISMATCH", `${field} does not match the immutable body`);
114
+ if (confirmation !== `${prefix}:${expected}`)
115
+ fail("CONFIRMATION_REQUIRED", `confirmation must be ${prefix}:<hash>`);
116
+ }
117
+
118
+ export function assertState(actual, expected, code, step) {
119
+ if (statesEqual(actual, expected)) return;
120
+ fail(code, "semantic state changed or did not match the desired state", {
121
+ kind: step.kind,
122
+ endpoint: step.endpoint,
123
+ expected,
124
+ actual,
125
+ });
126
+ }
127
+
128
+ export function statesEqual(actual, expected) {
129
+ if (actual === null || expected === null) return actual === expected;
130
+ const normalizedActual = structuredClone(actual);
131
+ if (!("id" in expected)) delete normalizedActual.id;
132
+ return canonicalJson(normalizedActual) === canonicalJson(expected);
133
+ }
134
+
135
+ export function uniqueStates(states) {
136
+ const seen = new Set();
137
+ return states.filter((state) => {
138
+ const key = canonicalJson(state);
139
+ if (seen.has(key)) return false;
140
+ seen.add(key);
141
+ return true;
142
+ });
143
+ }
144
+
145
+ export function canonicalPlanResourceId(value, code) {
146
+ const text = typeof value === "string" ? value : String(value ?? "");
147
+ if (!/^[1-9]\d*$/u.test(text))
148
+ fail(code, "resource id must be a canonical positive integer");
149
+ const id = Number(text);
150
+ if (!Number.isSafeInteger(id) || String(id) !== text)
151
+ fail(code, "resource id must be a canonical positive integer");
152
+ return id;
153
+ }
154
+
155
+ export function validateMutationCaseIds(caseIds, code) {
156
+ if (!Array.isArray(caseIds) || caseIds.length === 0)
157
+ fail(code, "mutation step requires caseIds");
158
+ const seen = new Set();
159
+ for (const caseId of caseIds) {
160
+ if (
161
+ typeof caseId !== "string" ||
162
+ !caseId ||
163
+ caseId !== caseId.trim() ||
164
+ seen.has(caseId)
165
+ )
166
+ fail(code, "mutation step caseIds are invalid");
167
+ seen.add(caseId);
168
+ }
169
+ return [...seen];
170
+ }
171
+
172
+ export const READ_ONLY_FIELDS = {
173
+ dimension: new Set(["used", "models"]),
174
+ measure: new Set([
175
+ "used",
176
+ "models",
177
+ "isValid",
178
+ "formula_snapshot",
179
+ "formula_dependency",
180
+ ]),
181
+ };
182
+
183
+ export function hasCutAlternatives(value) {
184
+ return value !== undefined && (!Array.isArray(value) || value.length > 0);
185
+ }
186
+
187
+ export function canonicalSynonymId(value) {
188
+ const text = typeof value === "string" ? value : String(value ?? "");
189
+ if (!/^\d+$/.test(text))
190
+ fail("INVALID_SYNONYM_PLAN", "synonym id must be a positive integer");
191
+ const id = Number(text);
192
+ if (!Number.isSafeInteger(id) || id <= 0)
193
+ fail("INVALID_SYNONYM_PLAN", "synonym id must be a positive integer");
194
+ return id;
195
+ }
196
+
197
+ export function bindSummaryAuthorityTargets(plan) {
198
+ const authorities = new Map(
199
+ plan.authorities.map((authority) => [authority.caseId, authority]),
200
+ );
201
+ for (const summary of plan.summaries) {
202
+ summary.authorityTargets = summary.caseIds.map((caseId) => {
203
+ const authority = authorities.get(caseId);
204
+ if (!authority)
205
+ fail(
206
+ "INVALID_PLAN_STRUCTURE",
207
+ "plan summary references an unknown case authority",
208
+ );
209
+ return { caseId, target: structuredClone(authority.target) };
210
+ });
211
+ }
212
+ }
213
+
214
+ export function canonicalDatasetId(value) {
215
+ const text = typeof value === "string" ? value.trim() : String(value ?? "");
216
+ if (!/^\d+$/u.test(text))
217
+ fail("INVALID_DATASET_PLAN", "dataset id must be a positive integer");
218
+ const id = Number(text);
219
+ if (!Number.isSafeInteger(id) || id <= 0)
220
+ fail("INVALID_DATASET_PLAN", "dataset id must be a positive integer");
221
+ return id;
222
+ }
223
+
224
+ export function resolveCompletedStep(step, response) {
225
+ const responseId = response?.id;
226
+ if (
227
+ responseId === undefined ||
228
+ step.after?.id !== undefined ||
229
+ (step.before !== null && step.operation !== "REPLACE")
230
+ )
231
+ return structuredClone(step);
232
+ const after = { ...step.after, id: responseId };
233
+ let endpoint = step.endpoint;
234
+ if (endpoint.endsWith("/")) endpoint = `${endpoint}${responseId}/`;
235
+ return { ...structuredClone(step), endpoint, after };
236
+ }
237
+
238
+ export function assertPossibleState(actual, expectedStates, code, step) {
239
+ if (listOf(expectedStates).some((expected) => statesEqual(actual, expected)))
240
+ return;
241
+ fail(code, "semantic state is outside every recorded possible state", {
242
+ kind: step.kind,
243
+ endpoint: step.endpoint,
244
+ expectedStates,
245
+ actual,
246
+ });
247
+ }
248
+
249
+ export function authoritiesForCaseIds(authorities, caseIds, kind, code) {
250
+ return caseIds.map((caseId) => {
251
+ const authority = authorities.get(caseId);
252
+ if (authority?.kind !== kind)
253
+ fail(code, `${kind} step caseIds must match exact authorities`);
254
+ return authority;
255
+ });
256
+ }
257
+
258
+ export function matchesAuthority(authority, kind, predicate) {
259
+ return authority?.kind === kind && predicate(authority.target);
260
+ }
261
+
262
+ export function claimStepCaseIds(used, caseIds) {
263
+ for (const caseId of caseIds) {
264
+ if (used.has(caseId))
265
+ fail(
266
+ "INVALID_PLAN_STRUCTURE",
267
+ "one case authority cannot authorize multiple mutation steps",
268
+ );
269
+ used.add(caseId);
270
+ }
271
+ }
272
+
273
+ export function coalesceNamedOperation({
274
+ caseId,
275
+ operation,
276
+ groups,
277
+ names,
278
+ result,
279
+ conflictCode,
280
+ }) {
281
+ const kind = operation.kind;
282
+ const nameKey = normalizeText(operation.name);
283
+ const targetKey =
284
+ operation.id === undefined
285
+ ? `${kind}:name:${nameKey}`
286
+ : `${kind}:id:${operation.id}`;
287
+ const existingNameTarget = names.get(nameKey);
288
+ if (existingNameTarget !== undefined && existingNameTarget !== targetKey)
289
+ fail(conflictCode, `one ${kind} name cannot select different identities`);
290
+ names.set(nameKey, targetKey);
291
+
292
+ const desired = structuredClone(operation);
293
+ delete desired.caseId;
294
+ delete desired.caseIds;
295
+ const desiredKey = canonicalJson(desired);
296
+ let group = groups.get(targetKey);
297
+ if (!group) {
298
+ group = {
299
+ ...structuredClone(operation),
300
+ caseId,
301
+ caseIds: [],
302
+ desiredKey,
303
+ };
304
+ groups.set(targetKey, group);
305
+ result.push(group);
306
+ } else if (group.desiredKey !== desiredKey)
307
+ fail(
308
+ conflictCode,
309
+ `one ${kind} target cannot have different desired states`,
310
+ );
311
+ group.caseIds.push(caseId);
312
+ }