@arcticdata/dsh-datarc-assistant 0.0.0-stage → 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 (146) hide show
  1. package/README.md +46 -2
  2. package/api-operations.js +404 -0
  3. package/client.js +475 -0
  4. package/cordis.patch.yml +4 -0
  5. package/entry/SKILL.md +34 -0
  6. package/icon.png +0 -0
  7. package/index.js +69 -0
  8. package/locale/en.json +6 -0
  9. package/locale/zh.json +6 -0
  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 -6
  18. package/runtime/datarc-access-permissions/SKILL.md +30 -0
  19. package/runtime/datarc-access-permissions/references/api.md +31 -0
  20. package/runtime/datarc-access-permissions/references/write-order.md +16 -0
  21. package/runtime/datarc-analysis-report/SKILL.md +125 -0
  22. package/runtime/datarc-analysis-report/agents/openai.yaml +6 -0
  23. package/runtime/datarc-analysis-report/references/analyst-frameworks.md +215 -0
  24. package/runtime/datarc-analysis-report/references/api-contracts.md +478 -0
  25. package/runtime/datarc-analysis-report/references/direct-card-fallback-design.md +66 -0
  26. package/runtime/datarc-analysis-report/references/human-in-the-loop.md +142 -0
  27. package/runtime/datarc-analysis-report/references/loop-personalization-policy.md +138 -0
  28. package/runtime/datarc-analysis-report/references/manifest-example.json +779 -0
  29. package/runtime/datarc-analysis-report/references/narrative-schema.md +160 -0
  30. package/runtime/datarc-analysis-report/references/question-syntax.md +151 -0
  31. package/runtime/datarc-analysis-report/scripts/run_analysis_report.py +2225 -0
  32. package/runtime/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -0
  33. package/runtime/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -0
  34. package/runtime/datarc-data-search/SKILL.md +243 -0
  35. package/runtime/datarc-data-search/scripts/calculate.py +116 -0
  36. package/runtime/datarc-data-search/scripts/data-search.mjs +628 -0
  37. package/runtime/datarc-data-search/scripts/datarc-client.mjs +464 -0
  38. package/runtime/datarc-data-search/scripts/search-result.mjs +211 -0
  39. package/runtime/datarc-dataseek-batch-evaluation/SKILL.md +59 -0
  40. package/runtime/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -0
  41. package/runtime/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -0
  42. package/runtime/datarc-dataseek-batch-evaluation/scripts/datarc-client.mjs +464 -0
  43. package/runtime/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -0
  44. package/runtime/datarc-dataseek-search/SKILL.md +96 -0
  45. package/runtime/datarc-dataseek-search/scripts/datarc-client.mjs +464 -0
  46. package/runtime/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -0
  47. package/runtime/datarc-dataseek-semantic-debugging/SKILL.md +44 -0
  48. package/runtime/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -0
  49. package/runtime/datarc-dataseek-semantic-debugging/evals/evals.json +165 -0
  50. package/runtime/datarc-dataseek-semantic-debugging/references/dataset.md +77 -0
  51. package/runtime/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -0
  52. package/runtime/datarc-dataseek-semantic-debugging/references/interventions.md +64 -0
  53. package/runtime/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -0
  54. package/runtime/datarc-dataseek-semantic-debugging/references/rollback.md +11 -0
  55. package/runtime/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -0
  56. package/runtime/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -0
  57. package/runtime/datarc-dataseek-testset-generation/SKILL.md +47 -0
  58. package/runtime/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -0
  59. package/runtime/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -0
  60. package/runtime/datarc-datasource/SKILL.md +97 -0
  61. package/runtime/datarc-oauth/SKILL.md +50 -0
  62. package/runtime/datarc-oauth/scripts/auth.mjs +192 -0
  63. package/runtime/datarc-oauth/scripts/credentials.mjs +237 -0
  64. package/runtime/datarc-report-add-card/SKILL.md +90 -0
  65. package/runtime/datarc-report-add-card/agents/openai.yaml +4 -0
  66. package/runtime/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
  67. package/runtime/datarc-report-add-card/scripts/report-card.mjs +439 -0
  68. package/runtime/datarc-semantic-alias/SKILL.md +20 -0
  69. package/runtime/datarc-semantic-alias/scripts/alias-plan.mjs +422 -0
  70. package/runtime/datarc-semantic-alias/scripts/alias.mjs +11 -0
  71. package/runtime/datarc-semantic-calibration/SKILL.md +20 -0
  72. package/runtime/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -0
  73. package/runtime/datarc-semantic-calibration/scripts/calibration.mjs +11 -0
  74. package/runtime/datarc-semantic-core/SKILL.md +12 -0
  75. package/runtime/datarc-semantic-core/scripts/artifact-journal.mjs +853 -0
  76. package/runtime/datarc-semantic-core/scripts/canonical.mjs +48 -0
  77. package/runtime/datarc-semantic-core/scripts/case-model.mjs +608 -0
  78. package/runtime/datarc-semantic-core/scripts/cli.mjs +180 -0
  79. package/runtime/datarc-semantic-core/scripts/datarc-client.mjs +180 -0
  80. package/runtime/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -0
  81. package/runtime/datarc-semantic-core/scripts/interventions.mjs +693 -0
  82. package/runtime/datarc-semantic-core/scripts/live-resolution.mjs +305 -0
  83. package/runtime/datarc-semantic-core/scripts/model-scope.mjs +49 -0
  84. package/runtime/datarc-semantic-core/scripts/reproduction.mjs +330 -0
  85. package/runtime/datarc-semantic-core/scripts/semantic-cli.mjs +799 -0
  86. package/runtime/datarc-semantic-core/scripts/shared.mjs +312 -0
  87. package/runtime/datarc-semantic-core/scripts/verification.mjs +1111 -0
  88. package/runtime/datarc-semantic-dataset/SKILL.md +20 -0
  89. package/runtime/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -0
  90. package/runtime/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -0
  91. package/runtime/datarc-semantic-dataset/scripts/dataset.mjs +11 -0
  92. package/runtime/datarc-semantic-knowledge/SKILL.md +38 -0
  93. package/runtime/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -0
  94. package/runtime/datarc-semantic-knowledge/references/knowledge-generation.json +16 -0
  95. package/runtime/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -0
  96. package/runtime/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -0
  97. package/runtime/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -0
  98. package/runtime/datarc-semantic-prompt/SKILL.md +20 -0
  99. package/runtime/datarc-semantic-prompt/scripts/prompt-plan.mjs +598 -0
  100. package/runtime/datarc-semantic-prompt/scripts/prompt.mjs +15 -0
  101. package/runtime/datarc-semantic-synonym/SKILL.md +20 -0
  102. package/runtime/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -0
  103. package/runtime/datarc-semantic-synonym/scripts/synonym.mjs +11 -0
  104. package/runtime/datarc-viz-analysis-report/SKILL.md +108 -0
  105. package/runtime/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -0
  106. package/runtime/datarc-viz-analysis-report/assets/echarts.min.js +45 -0
  107. package/runtime/datarc-viz-analysis-report/references/api-contracts.md +163 -0
  108. package/runtime/datarc-viz-analysis-report/references/derivation-log.md +157 -0
  109. package/runtime/datarc-viz-analysis-report/references/evidence-framework.md +76 -0
  110. package/runtime/datarc-viz-analysis-report/references/html-template.md +92 -0
  111. package/runtime/datarc-viz-analysis-report/references/provenance-format.md +56 -0
  112. package/runtime/datarc-viz-analysis-report/references/question-syntax.md +151 -0
  113. package/runtime/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -0
  114. package/runtime/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -0
  115. package/runtime/datarc-workspace-configuration/SKILL.md +59 -0
  116. package/runtime/datarc-workspace-configuration/references/artifacts.md +75 -0
  117. package/runtime/datarc-workspace-configuration/references/verification.md +20 -0
  118. package/runtime/datarc-workspace-configuration/scripts/configuration.mjs +722 -0
  119. package/runtime/datarc-workspace-context/SKILL.md +43 -0
  120. package/runtime/datarc-workspace-context/agents/openai.yaml +4 -0
  121. package/runtime/datarc-workspace-context/scripts/datarc-client.mjs +31 -0
  122. package/runtime/datarc-workspace-context/scripts/query-display.mjs +114 -0
  123. package/runtime/datarc-workspace-context/scripts/workspace-context.mjs +58 -0
  124. package/runtime/datarc-workspace-custom-tables/SKILL.md +89 -0
  125. package/runtime/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -0
  126. package/runtime/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -0
  127. package/runtime/datarc-workspace-keywords/SKILL.md +197 -0
  128. package/runtime/datarc-workspace-keywords/agents/openai.yaml +4 -0
  129. package/runtime/datarc-workspace-keywords/references/api-fields.md +79 -0
  130. package/runtime/datarc-workspace-keywords/references/derived-measures.md +177 -0
  131. package/runtime/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -0
  132. package/runtime/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -0
  133. package/runtime/datarc-workspace-membership/SKILL.md +29 -0
  134. package/runtime/datarc-workspace-membership/references/api.md +19 -0
  135. package/runtime/datarc-workspace-modeling/SKILL.md +209 -0
  136. package/runtime/datarc-workspace-modeling/agents/openai.yaml +4 -0
  137. package/runtime/datarc-workspace-modeling/references/join-preview.md +38 -0
  138. package/runtime/datarc-workspace-modeling/references/model-plan.md +300 -0
  139. package/runtime/datarc-workspace-modeling/references/model-tags.md +95 -0
  140. package/runtime/datarc-workspace-modeling/references/modeling-contract.json +29 -0
  141. package/runtime/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -0
  142. package/runtime/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -0
  143. package/runtime/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -0
  144. package/runtime/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -0
  145. package/skills-provider.js +51 -0
  146. package/workflow-index.json +434 -0
@@ -0,0 +1,2421 @@
1
+ #!/usr/bin/env node
2
+ import { pathToFileURL } from "node:url";
3
+ import {
4
+ createClient,
5
+ DatarcError,
6
+ encryptSql,
7
+ parseArgs,
8
+ readJson,
9
+ required,
10
+ runCli,
11
+ } from "./datarc-client.mjs";
12
+
13
+ const RESOURCES = {
14
+ measure: {
15
+ path: "measures",
16
+ version: 2,
17
+ id: "id",
18
+ validation: "measure",
19
+ readonly: [
20
+ "used",
21
+ "models",
22
+ "isValid",
23
+ "formula_snapshot",
24
+ "formula_dependency",
25
+ ],
26
+ },
27
+ dimension: {
28
+ path: "dimensions",
29
+ version: 2,
30
+ id: "id",
31
+ validation: "dimension",
32
+ readonly: ["used", "models"],
33
+ patch: ["rating", "isKeyword"],
34
+ },
35
+ "time-series": {
36
+ path: "time-series",
37
+ version: 2,
38
+ id: "id",
39
+ validation: "timeSeries",
40
+ readonly: ["used", "models"],
41
+ },
42
+ "dimension-table": {
43
+ path: "dimension-tables",
44
+ version: 3,
45
+ id: "uid",
46
+ readonly: ["models"],
47
+ patch: ["mark", "table", "tableUid", "where"],
48
+ },
49
+ };
50
+ const TIME_UNITS = new Set([1, 2, 3, 4, 5, 6, 7, 8]);
51
+ const TIME_UNIT_LEVEL = new Map([
52
+ [8, 1],
53
+ [1, 2],
54
+ [2, 3],
55
+ [3, 4],
56
+ [4, 5],
57
+ [5, 6],
58
+ [6, 7],
59
+ [7, 8],
60
+ ]);
61
+ const DAY_OR_COARSER_TYPES = new Set([
62
+ "date",
63
+ "yyyymmdd_int",
64
+ "yyyymmdd_str",
65
+ "yyyy-mm-dd",
66
+ "yyyy/mm/dd",
67
+ ]);
68
+ const MONTH_OR_COARSER_TYPES = new Set([
69
+ "yyyymm_int",
70
+ "yyyymm_str",
71
+ "yyyy-mm",
72
+ "yyyy/mm",
73
+ ]);
74
+ const FULL_KEYWORD_SYNC_TASK = 0;
75
+ const GENERATE_DICTIONARY_TASK = 2;
76
+ const GENERATE_FUZZY_DICTIONARY_TASK = 19;
77
+ const INCREMENTAL_KEYWORD_SYNC_TASK = 31;
78
+ const SEARCH_COMPLETION_TASKS = [
79
+ FULL_KEYWORD_SYNC_TASK,
80
+ GENERATE_DICTIONARY_TASK,
81
+ GENERATE_FUZZY_DICTIONARY_TASK,
82
+ INCREMENTAL_KEYWORD_SYNC_TASK,
83
+ ];
84
+ const TASK_PENDING = 0;
85
+ const TASK_STARTED = 1;
86
+ const TASK_SUCCESS = 2;
87
+ const DEFAULT_SYNC_POLL_INTERVAL_MS = 5000;
88
+ const DEFAULT_SYNC_MAX_WAIT_MS = 600000;
89
+ const DEFAULT_SEARCH_CARDINALITY_LIMIT = 1000;
90
+
91
+ export async function execute(argv, options = {}) {
92
+ const args = parseArgs(argv);
93
+ const command = args._[0];
94
+ const client = options.client ?? createClient(options);
95
+ if (command === "workspaces")
96
+ return client.request("GET", "/api/v2/account-projects/", {
97
+ query: { admin: 1, q: args.query ?? "", offset: 0, limit: 20 },
98
+ });
99
+
100
+ const workspaceId = required(args, "workspace-id");
101
+ if (command === "search-settings")
102
+ return client.request("GET", `/api/v2/admin-projects/${workspaceId}/`, {
103
+ query: { type: 1 },
104
+ });
105
+ if (command === "sync-tasks")
106
+ return listKeywordSyncTasks(
107
+ client,
108
+ workspaceId,
109
+ Number(args.offset ?? 0),
110
+ Number(args.limit ?? 20),
111
+ );
112
+ if (command === "sync-task")
113
+ return client.request(
114
+ "GET",
115
+ `/api/v2/admin-projects/${workspaceId}/async-tasks/${required(args, "task-uid")}/`,
116
+ );
117
+ if (command === "apply-search-plan")
118
+ return applySearchPlan(client, workspaceId, args, options);
119
+ if (command === "list") return list(client, workspaceId, resourceOf(args));
120
+ if (command === "get")
121
+ return get(client, workspaceId, resourceOf(args), required(args, "id"));
122
+ if (command === "find")
123
+ return find(client, workspaceId, resourceOf(args), required(args, "name"));
124
+ if (command === "validate-name") {
125
+ const resource = resourceOf(args);
126
+ const config = RESOURCES[resource];
127
+ if (!config.validation)
128
+ throw new DatarcError(
129
+ "维度表不使用关键词名称校验接口",
130
+ "INVALID_ARGUMENT",
131
+ );
132
+ return client.request(
133
+ "POST",
134
+ `/api/v2/admin-projects/${workspaceId}/name-validation/`,
135
+ {
136
+ body: { names: namesOf(args), field: config.validation },
137
+ },
138
+ );
139
+ }
140
+ if (command === "create") {
141
+ const resource = resourceOf(args);
142
+ if (resource === "dimension-table")
143
+ throw new DatarcError(
144
+ "新维度表应随模型创建,请使用 datarc-workspace-modeling",
145
+ "UNSUPPORTED_OPERATION",
146
+ );
147
+ const input = cleanResource(
148
+ resource,
149
+ await readJson(required(args, "input")),
150
+ );
151
+ if (resource === "measure" && input.formula)
152
+ throw new DatarcError(
153
+ "衍生指标必须使用 upsert-derived,以执行查重、公式校验和回读",
154
+ "UNSAFE_DERIVED_CREATE",
155
+ );
156
+ validateResource(resource, input);
157
+ validateNewResourceClassification(resource, input);
158
+ await assertNamesValid(
159
+ client,
160
+ workspaceId,
161
+ input.names,
162
+ RESOURCES[resource].validation,
163
+ );
164
+ const plan = {
165
+ method: "POST",
166
+ path: collectionPath(workspaceId, resource),
167
+ body: input,
168
+ };
169
+ if (args["dry-run"]) return plan;
170
+ const result = await client.request(plan.method, plan.path, {
171
+ body: input,
172
+ });
173
+ const id = result?.[RESOURCES[resource].id];
174
+ if (id === undefined)
175
+ throw new DatarcError(
176
+ "创建响应缺少资源 ID,无法回读验证",
177
+ "WRITE_VERIFICATION_FAILED",
178
+ { result },
179
+ );
180
+ return {
181
+ ...plan,
182
+ result,
183
+ verified: await get(client, workspaceId, resource, id),
184
+ };
185
+ }
186
+ if (command === "upsert-derived")
187
+ return upsertDerived(client, workspaceId, args);
188
+ if (command === "check-formula")
189
+ return client.request(
190
+ "POST",
191
+ `/api/v2/admin-projects/${workspaceId}/measures/check-formula/`,
192
+ { body: { formula: required(args, "formula") } },
193
+ );
194
+ if (command === "custom-sort")
195
+ return client.request(
196
+ "GET",
197
+ `/api/v2/admin-projects/${workspaceId}/dimensions/${required(args, "id")}/custom-sort/`,
198
+ );
199
+ if (command === "set-custom-sort") {
200
+ const customSort = await readJson(required(args, "input"));
201
+ if (!Array.isArray(customSort))
202
+ throw new DatarcError("自定义排序输入必须是 JSON 数组", "INVALID_INPUT");
203
+ return client.request(
204
+ "POST",
205
+ `/api/v2/admin-projects/${workspaceId}/dimensions/${required(args, "id")}/custom-sort/`,
206
+ {
207
+ body: { customSort, overwrite: Boolean(args.overwrite) },
208
+ },
209
+ );
210
+ }
211
+ if (command === "update")
212
+ return update(
213
+ client,
214
+ workspaceId,
215
+ resourceOf(args),
216
+ required(args, "id"),
217
+ args,
218
+ );
219
+ if (command === "impact")
220
+ return impact(client, workspaceId, resourceOf(args), required(args, "id"));
221
+ if (command === "delete") {
222
+ const resource = resourceOf(args);
223
+ const id = required(args, "id");
224
+ if (args.confirm !== "DELETE")
225
+ throw new DatarcError(
226
+ "删除前先执行 impact,并显式传入 --confirm DELETE",
227
+ "CONFIRMATION_REQUIRED",
228
+ {
229
+ impact: await impact(client, workspaceId, resource, id),
230
+ },
231
+ );
232
+ return client.request("DELETE", itemPath(workspaceId, resource, id));
233
+ }
234
+ if (command === "add-dimension")
235
+ return addDimension(client, workspaceId, required(args, "id"), args);
236
+ if (command === "remove-dimension") {
237
+ if (args.confirm !== "DELETE")
238
+ throw new DatarcError(
239
+ "从维度表移除维度需要 --confirm DELETE",
240
+ "CONFIRMATION_REQUIRED",
241
+ );
242
+ return client.request(
243
+ "DELETE",
244
+ `${itemPath(workspaceId, "dimension-table", required(args, "id"))}delete-dimension/`,
245
+ {
246
+ body: { dimension: Number(required(args, "dimension-id")) },
247
+ },
248
+ );
249
+ }
250
+ throw new DatarcError(
251
+ "命令应为 workspaces、list、get、find、validate-name、check-formula、search-settings、sync-tasks、sync-task、apply-search-plan、custom-sort、set-custom-sort、create、upsert-derived、update、impact、delete、add-dimension 或 remove-dimension",
252
+ "INVALID_ARGUMENT",
253
+ );
254
+ }
255
+
256
+ export async function applySearchPlan(client, workspaceId, args, options = {}) {
257
+ const input = await readJson(required(args, "input"));
258
+ return applySearchPlanInput(client, workspaceId, input, args, options);
259
+ }
260
+
261
+ export async function applySearchPlanInput(
262
+ client,
263
+ workspaceId,
264
+ input,
265
+ args = {},
266
+ options = {},
267
+ ) {
268
+ if (args["require-fuzzy"] !== undefined)
269
+ throw new DatarcError(
270
+ "--require-fuzzy 缺少错字探针验收,不能作为可靠完成门槛;当前只报告模糊词典任务状态",
271
+ "UNSUPPORTED_ARGUMENT",
272
+ );
273
+ const maxCardinality = searchCardinalityLimit(
274
+ args["max-cardinality"],
275
+ "max-cardinality",
276
+ );
277
+ const entries = validatePendingSearchEntries(input, { maxCardinality });
278
+ const [dimensions, models] = await Promise.all([
279
+ list(client, workspaceId, "dimension"),
280
+ listWorkspaceModels(client, workspaceId),
281
+ ]);
282
+ const readyModelUidSet = new Set(
283
+ models
284
+ .filter((model) => model?.ready === true)
285
+ .map((model) => String(model?.uid ?? "").trim())
286
+ .filter(Boolean),
287
+ );
288
+ const targets = resolveSearchTargets(entries, dimensions).map((target) => ({
289
+ ...target,
290
+ readyModelUids: dimensionModelUids(target.models).filter((uid) =>
291
+ readyModelUidSet.has(uid),
292
+ ),
293
+ }));
294
+ if (!targets.length) return { status: "no_targets", targets: [] };
295
+
296
+ const pendingBinding = targets.filter(
297
+ (target) => target.used !== true || !target.readyModelUids.length,
298
+ );
299
+ if (pendingBinding.length)
300
+ throw new DatarcError(
301
+ "目标维度尚未被 ready 模型使用,不能开启后立即验证搜索同步",
302
+ "PENDING_MODEL_BINDING",
303
+ { targets: pendingBinding },
304
+ );
305
+
306
+ const evidence = validateResolvedSearchEvidence(targets, maxCardinality);
307
+ const changes = targets.filter((target) => target.isKeyword !== true);
308
+ const hasOptionBaseline = Array.isArray(options.baselineTaskUids);
309
+ const optionBaseline = hasOptionBaseline
310
+ ? options.baselineTaskUids.filter(Boolean)
311
+ : [];
312
+ const argumentBaseline = taskUids(args["baseline-task-uid"]);
313
+ const suppliedBaseline = hasOptionBaseline
314
+ ? optionBaseline
315
+ : argumentBaseline.length
316
+ ? argumentBaseline
317
+ : null;
318
+ if (!changes.length && !suppliedBaseline)
319
+ return {
320
+ status: "enabled_unverified",
321
+ complete: false,
322
+ searchable: null,
323
+ message: "维度配置已开启,但缺少本次开启对应的同步与词典任务证据",
324
+ targets: searchTargetSummary(targets),
325
+ };
326
+
327
+ const pollIntervalMs = nonNegativeNumber(
328
+ args["poll-interval-ms"],
329
+ "poll-interval-ms",
330
+ DEFAULT_SYNC_POLL_INTERVAL_MS,
331
+ );
332
+ const maxWaitMs = nonNegativeNumber(
333
+ args["max-wait-ms"],
334
+ "max-wait-ms",
335
+ DEFAULT_SYNC_MAX_WAIT_MS,
336
+ );
337
+ const baselineTaskUids = suppliedBaseline
338
+ ? [...new Set(suppliedBaseline)]
339
+ : await captureSearchTaskBaseline(client, workspaceId);
340
+ const updates = changes.map((target) => ({
341
+ method: "PATCH",
342
+ path: itemPath(workspaceId, "dimension", target.id),
343
+ body: { isKeyword: true },
344
+ }));
345
+ if (args["dry-run"])
346
+ return {
347
+ status: "dry_run",
348
+ targets: searchTargetSummary(targets),
349
+ evidence,
350
+ baselineTaskUids,
351
+ updates,
352
+ };
353
+
354
+ const changedTargets = [];
355
+ const attemptedTargets = [];
356
+ const now = options.now ?? (() => Date.now());
357
+ const waitOptions = {
358
+ baselineTaskUids,
359
+ pollIntervalMs,
360
+ deadlineAt: now() + maxWaitMs,
361
+ sleep:
362
+ options.sleep ??
363
+ ((milliseconds) =>
364
+ new Promise((resolve) => setTimeout(resolve, milliseconds))),
365
+ now,
366
+ };
367
+ let sync;
368
+ let dictionaries;
369
+ try {
370
+ for (const [index, target] of changes.entries()) {
371
+ const updatePlan = updates[index];
372
+ attemptedTargets.push(target);
373
+ await client.request(updatePlan.method, updatePlan.path, {
374
+ body: updatePlan.body,
375
+ });
376
+ const after = await get(client, workspaceId, "dimension", target.id);
377
+ if (after?.isKeyword !== true)
378
+ throw new DatarcError(
379
+ `维度 ${target.primaryName} 回读时 isKeyword 未开启`,
380
+ "WRITE_VERIFICATION_FAILED",
381
+ { target, after },
382
+ );
383
+ if (after?.used !== true)
384
+ throw new DatarcError(
385
+ `维度 ${target.primaryName} 回读时已不再被 ready 模型使用`,
386
+ "PENDING_MODEL_BINDING",
387
+ { target, after, writeCompleted: true },
388
+ );
389
+ changedTargets.push({ ...target, after });
390
+ }
391
+
392
+ const verificationTargets = targets;
393
+ sync = await waitForSearchSync(client, workspaceId, verificationTargets, {
394
+ ...waitOptions,
395
+ notBefore: options.notBefore,
396
+ });
397
+ dictionaries = await waitForSearchDictionaries(client, workspaceId, {
398
+ ...waitOptions,
399
+ notBefore: latestTaskTimestamp(sync.tasks, "updatedAt"),
400
+ });
401
+ dictionaries.probes = await waitForSearchProbes(
402
+ client,
403
+ workspaceId,
404
+ verificationTargets,
405
+ waitOptions,
406
+ );
407
+ } catch (error) {
408
+ if (!attemptedTargets.length) throw error;
409
+ const rollback = await rollbackSearchTargets(
410
+ client,
411
+ workspaceId,
412
+ attemptedTargets,
413
+ );
414
+ throw attachRollback(error, rollback);
415
+ }
416
+ const changedIds = new Set(changedTargets.map((target) => target.id));
417
+ return {
418
+ status: "searchable",
419
+ complete: true,
420
+ searchable: true,
421
+ targets: searchTargetSummary(
422
+ targets.map((target) =>
423
+ changedIds.has(target.id) ? { ...target, isKeyword: true } : target,
424
+ ),
425
+ ),
426
+ evidence,
427
+ baselineTaskUids,
428
+ updates,
429
+ sync,
430
+ dictionaries,
431
+ };
432
+ }
433
+
434
+ export function validatePendingSearchEntries(input, options = {}) {
435
+ const maxCardinality = searchCardinalityLimit(
436
+ options.maxCardinality,
437
+ "maxCardinality",
438
+ );
439
+ const entries = Array.isArray(input) ? input : input?.pendingSearchDimensions;
440
+ if (!Array.isArray(entries))
441
+ throw new DatarcError(
442
+ "搜索开启计划必须是数组,或包含 pendingSearchDimensions 数组",
443
+ "INVALID_INPUT",
444
+ );
445
+ for (const entry of entries) {
446
+ if (!entry || Array.isArray(entry) || typeof entry !== "object")
447
+ throw new DatarcError("搜索开启计划条目必须是对象", "INVALID_INPUT");
448
+ const hasId = entry.id !== undefined && entry.id !== null;
449
+ const hasName =
450
+ entry.name !== undefined && String(entry.name).trim().length > 0;
451
+ if (!hasId && !hasName)
452
+ throw new DatarcError(
453
+ "搜索开启计划条目必须提供 id 或 name",
454
+ "INVALID_INPUT",
455
+ );
456
+ if (!String(entry.reason ?? "").trim())
457
+ throw new DatarcError(
458
+ "搜索开启计划必须说明该维度值少、稳定、常用或易记的推荐理由",
459
+ "SEARCH_REASON_REQUIRED",
460
+ { entry },
461
+ );
462
+ validateSearchEvidenceShape(entry, maxCardinality);
463
+ }
464
+ return entries;
465
+ }
466
+
467
+ function validateSearchEvidenceShape(entry, maxCardinality) {
468
+ if (!String(entry.probeValue ?? "").trim())
469
+ throw new DatarcError(
470
+ "搜索开启计划必须提供可用于真实分词验收的 probeValue",
471
+ "SEARCH_PROBE_REQUIRED",
472
+ { entry },
473
+ );
474
+ const evidence = entry.cardinalityEvidence;
475
+ if (!evidence || Array.isArray(evidence) || typeof evidence !== "object")
476
+ throw new DatarcError(
477
+ "搜索开启计划缺少可信的 cardinalityEvidence",
478
+ "CARDINALITY_EVIDENCE_REQUIRED",
479
+ { entry },
480
+ );
481
+ const source = evidence.source;
482
+ if (source === "catalog-choice")
483
+ return { source, probeValue: String(entry.probeValue).trim() };
484
+ if (source === "database-distinct-count") {
485
+ const distinctCount = boundedCardinality(
486
+ evidence.distinctCount,
487
+ "distinctCount",
488
+ maxCardinality,
489
+ );
490
+ requireEvidenceText(evidence.scope, "scope", entry);
491
+ requireEvidenceText(evidence.basis, "basis", entry);
492
+ requireObservedAt(evidence.observedAt, entry);
493
+ return {
494
+ source,
495
+ distinctCount,
496
+ scope: evidence.scope,
497
+ basis: evidence.basis,
498
+ observedAt: evidence.observedAt,
499
+ probeValue: String(entry.probeValue).trim(),
500
+ };
501
+ }
502
+ if (source === "known-bounded-domain") {
503
+ const upperBound = boundedCardinality(
504
+ evidence.upperBound,
505
+ "upperBound",
506
+ maxCardinality,
507
+ );
508
+ requireEvidenceText(evidence.domain, "domain", entry);
509
+ requireEvidenceText(evidence.stability, "stability", entry);
510
+ requireEvidenceText(evidence.basis, "basis", entry);
511
+ requireObservedAt(evidence.observedAt, entry);
512
+ return {
513
+ source,
514
+ upperBound,
515
+ domain: evidence.domain,
516
+ stability: evidence.stability,
517
+ basis: evidence.basis,
518
+ observedAt: evidence.observedAt,
519
+ probeValue: String(entry.probeValue).trim(),
520
+ };
521
+ }
522
+ if (source === "user-confirmed") {
523
+ const upperBound = boundedCardinality(
524
+ evidence.upperBound,
525
+ "upperBound",
526
+ maxCardinality,
527
+ );
528
+ requireEvidenceText(evidence.basis, "basis", entry);
529
+ requireObservedAt(evidence.observedAt, entry);
530
+ return {
531
+ source,
532
+ upperBound,
533
+ basis: evidence.basis,
534
+ observedAt: evidence.observedAt,
535
+ probeValue: String(entry.probeValue).trim(),
536
+ };
537
+ }
538
+ throw new DatarcError(
539
+ "cardinalityEvidence.source 必须是 catalog-choice、database-distinct-count、known-bounded-domain 或 user-confirmed;抽样和 column-preview 不能证明基数",
540
+ "UNTRUSTWORTHY_CARDINALITY_EVIDENCE",
541
+ { entry },
542
+ );
543
+ }
544
+
545
+ function validateResolvedSearchEvidence(targets, maxCardinality) {
546
+ return targets.map((target) => {
547
+ const normalized = validateSearchEvidenceShape(
548
+ {
549
+ probeValue: target.probeValue,
550
+ cardinalityEvidence: target.cardinalityEvidence,
551
+ },
552
+ maxCardinality,
553
+ );
554
+ if (normalized.source !== "catalog-choice")
555
+ return { id: target.id, primaryName: target.primaryName, ...normalized };
556
+ const choice = target.baseField?.choice;
557
+ if (
558
+ target.dimensionType !== "choice" ||
559
+ !choice ||
560
+ Array.isArray(choice) ||
561
+ typeof choice !== "object"
562
+ )
563
+ throw new DatarcError(
564
+ `维度 ${target.primaryName} 不是带 choice 的目录维度,不能使用 catalog-choice 证据`,
565
+ "UNTRUSTWORTHY_CARDINALITY_EVIDENCE",
566
+ { target },
567
+ );
568
+ const values = Object.values(choice).map((value) => String(value));
569
+ const distinctCount = new Set(values).size;
570
+ boundedCardinality(distinctCount, "catalog choice count", maxCardinality);
571
+ if (!values.includes(target.probeValue))
572
+ throw new DatarcError(
573
+ `维度 ${target.primaryName} 的 probeValue 不在 catalog choice 中`,
574
+ "INVALID_SEARCH_PROBE",
575
+ { target, probeValue: target.probeValue },
576
+ );
577
+ return {
578
+ id: target.id,
579
+ primaryName: target.primaryName,
580
+ source: "catalog-choice",
581
+ distinctCount,
582
+ probeValue: target.probeValue,
583
+ };
584
+ });
585
+ }
586
+
587
+ function boundedCardinality(value, field, maxCardinality) {
588
+ const count = Number(value);
589
+ if (!Number.isInteger(count) || count <= 0)
590
+ throw new DatarcError(
591
+ `${field} 必须是正整数`,
592
+ "INVALID_CARDINALITY_EVIDENCE",
593
+ );
594
+ if (count > maxCardinality)
595
+ throw new DatarcError(
596
+ `${field}=${count} 超过推荐搜索维度上限 ${maxCardinality}`,
597
+ "SEARCH_CARDINALITY_TOO_HIGH",
598
+ { field, count, maxCardinality },
599
+ );
600
+ return count;
601
+ }
602
+
603
+ function requireEvidenceText(value, field, entry) {
604
+ if (!String(value ?? "").trim())
605
+ throw new DatarcError(
606
+ `cardinalityEvidence.${field} 不能为空`,
607
+ "INVALID_CARDINALITY_EVIDENCE",
608
+ { entry },
609
+ );
610
+ }
611
+
612
+ function requireObservedAt(value, entry) {
613
+ if (!String(value ?? "").trim() || !Number.isFinite(Date.parse(value)))
614
+ throw new DatarcError(
615
+ "cardinalityEvidence.observedAt 必须是合法时间",
616
+ "INVALID_CARDINALITY_EVIDENCE",
617
+ { entry },
618
+ );
619
+ }
620
+
621
+ function resolveSearchTargets(entries, dimensions) {
622
+ if (!Array.isArray(dimensions))
623
+ throw new DatarcError("维度目录不是数组", "INVALID_RESPONSE");
624
+ const resolved = [];
625
+ const seen = new Set();
626
+ for (const entry of entries) {
627
+ const requestedId =
628
+ entry.id === undefined || entry.id === null
629
+ ? null
630
+ : normalizePositiveId(entry.id);
631
+ const byId =
632
+ requestedId === null
633
+ ? null
634
+ : dimensions.filter(
635
+ (dimension) => Number(dimension?.id) === requestedId,
636
+ );
637
+ const byName =
638
+ entry.name === undefined || String(entry.name).trim() === ""
639
+ ? null
640
+ : dimensions.filter((dimension) =>
641
+ (dimension?.names ?? []).some(
642
+ (name) => normalizeName(name) === normalizeName(entry.name),
643
+ ),
644
+ );
645
+ for (const matches of [byId, byName].filter(Boolean)) {
646
+ if (matches.length === 0)
647
+ throw new DatarcError(
648
+ `无法定位搜索维度 ${entry.name ?? entry.id}`,
649
+ "SEARCH_DIMENSION_NOT_FOUND",
650
+ { entry },
651
+ );
652
+ if (matches.length > 1)
653
+ throw new DatarcError(
654
+ `搜索维度 ${entry.name ?? entry.id} 匹配不唯一`,
655
+ "AMBIGUOUS_SEARCH_DIMENSION",
656
+ { entry, ids: matches.map((item) => item.id) },
657
+ );
658
+ }
659
+ if (byId && byName && Number(byId[0].id) !== Number(byName[0].id))
660
+ throw new DatarcError(
661
+ "搜索开启计划的 id 与 name 指向不同维度",
662
+ "SEARCH_DIMENSION_MISMATCH",
663
+ { entry, idMatch: byId[0].id, nameMatch: byName[0].id },
664
+ );
665
+ const dimension = (byId ?? byName)[0];
666
+ const id = normalizePositiveId(dimension.id);
667
+ if (seen.has(id))
668
+ throw new DatarcError(
669
+ `搜索开启计划重复引用维度 ${id}`,
670
+ "DUPLICATE_SEARCH_DIMENSION",
671
+ );
672
+ const primaryName = dimension.names?.[0];
673
+ if (!primaryName)
674
+ throw new DatarcError(
675
+ `维度 ${id} 缺少主名称,无法核对同步结果`,
676
+ "INVALID_RESPONSE",
677
+ );
678
+ seen.add(id);
679
+ resolved.push({
680
+ id,
681
+ primaryName,
682
+ requestedName: entry.name,
683
+ reason: String(entry.reason).trim(),
684
+ probeValue: String(entry.probeValue).trim(),
685
+ cardinalityEvidence: structuredClone(entry.cardinalityEvidence),
686
+ dimensionType: dimension.type,
687
+ baseField: dimension.baseField,
688
+ used: dimension.used === true,
689
+ isKeyword: dimension.isKeyword === true,
690
+ models: dimension.models ?? [],
691
+ });
692
+ }
693
+ return resolved;
694
+ }
695
+
696
+ function searchTargetSummary(targets) {
697
+ return targets.map(
698
+ ({
699
+ id,
700
+ primaryName,
701
+ requestedName,
702
+ reason,
703
+ probeValue,
704
+ used,
705
+ isKeyword,
706
+ models,
707
+ readyModelUids,
708
+ }) => ({
709
+ id,
710
+ primaryName,
711
+ ...(requestedName === undefined ? {} : { requestedName }),
712
+ reason,
713
+ probeValue,
714
+ used,
715
+ isKeyword,
716
+ models,
717
+ readyModelUids,
718
+ }),
719
+ );
720
+ }
721
+
722
+ async function waitForSearchSync(
723
+ client,
724
+ workspaceId,
725
+ targets,
726
+ { baselineTaskUids, pollIntervalMs, deadlineAt, sleep, now, notBefore },
727
+ ) {
728
+ const baseline = new Set(baselineTaskUids);
729
+ const inspected = new Set();
730
+ const verifiedById = new Map();
731
+ const matchedTasks = [];
732
+ const failureCandidates = [];
733
+ const coverageCandidates = [];
734
+ while (true) {
735
+ const tasks = await listSearchCompletionTasks(client, workspaceId, 0, 100);
736
+ const candidates = tasks.filter(
737
+ (task) =>
738
+ task?.uid &&
739
+ !baseline.has(task.uid) &&
740
+ [FULL_KEYWORD_SYNC_TASK, INCREMENTAL_KEYWORD_SYNC_TASK].includes(
741
+ Number(task.taskType),
742
+ ) &&
743
+ taskAtOrAfter(task, notBefore),
744
+ );
745
+ for (const candidate of candidates) {
746
+ if (
747
+ inspected.has(candidate.uid) ||
748
+ [TASK_PENDING, TASK_STARTED].includes(Number(candidate.status))
749
+ )
750
+ continue;
751
+ const detail = await getSearchCompletionTask(
752
+ client,
753
+ workspaceId,
754
+ candidate.uid,
755
+ );
756
+ if ([TASK_PENDING, TASK_STARTED].includes(Number(detail?.status)))
757
+ continue;
758
+ inspected.add(candidate.uid);
759
+ const relatedResults = targetSyncResults(detail, targets);
760
+ if (Number(detail?.status) !== TASK_SUCCESS) {
761
+ if (relatedResults.length)
762
+ throw new DatarcError(
763
+ "覆盖目标维度的关键词同步任务失败",
764
+ "SYNC_FAILED",
765
+ {
766
+ task: safeTaskSummary(detail),
767
+ results: relatedResults.flatMap(({ matches }) =>
768
+ matches.map(safeSyncResult),
769
+ ),
770
+ },
771
+ );
772
+ failureCandidates.push(safeTaskSummary(detail));
773
+ continue;
774
+ }
775
+ const matched = verifySearchSyncResults(detail, targets, {
776
+ allowMissing: true,
777
+ });
778
+ coverageCandidates.push(...matched.coverageMissing);
779
+ if (!matched.verified.length) continue;
780
+ matchedTasks.push(safeTaskSummary(detail));
781
+ for (const item of matched.verified) verifiedById.set(item.id, item);
782
+ if (targets.every((target) => verifiedById.has(target.id)))
783
+ return {
784
+ tasks: matchedTasks,
785
+ verified: targets.map((target) => verifiedById.get(target.id)),
786
+ };
787
+ }
788
+ const remainingMs = deadlineAt - now();
789
+ if (remainingMs <= 0) {
790
+ const details = {
791
+ baselineTaskUids,
792
+ verifiedTargetIds: [...verifiedById.keys()],
793
+ failureCandidates,
794
+ coverageCandidates,
795
+ };
796
+ if (coverageCandidates.length)
797
+ throw new DatarcError(
798
+ "观察窗口内的关键词同步任务未覆盖全部 ready 模型",
799
+ "SYNC_MODEL_COVERAGE_MISSING",
800
+ details,
801
+ );
802
+ throw new DatarcError(
803
+ "观察窗口内未发现覆盖全部目标维度的成功关键词同步任务",
804
+ "NOT_OBSERVED",
805
+ details,
806
+ );
807
+ }
808
+ await sleep(Math.min(pollIntervalMs, remainingMs));
809
+ }
810
+ }
811
+
812
+ function verifySearchSyncResults(task, targets, options = {}) {
813
+ const results = task?.result?.results;
814
+ if (!Array.isArray(results))
815
+ return options.allowMissing
816
+ ? { verified: [], coverageMissing: [] }
817
+ : (() => {
818
+ throw new DatarcError(
819
+ "关键词同步任务缺少逐维度结果",
820
+ "SYNC_RESULT_MISSING",
821
+ { task: safeTaskSummary(task) },
822
+ );
823
+ })();
824
+ const verified = [];
825
+ const coverageMissing = [];
826
+ for (const target of targets) {
827
+ const matches = targetSyncResults(task, [target])[0]?.matches ?? [];
828
+ if (!matches.length) continue;
829
+ const failed = matches.filter((result) => Number(result.status) !== 0);
830
+ if (failed.some((result) => Number(result.status) === 1))
831
+ throw new DatarcError(
832
+ `维度 ${target.primaryName} 同步失败`,
833
+ "SYNC_FAILED",
834
+ {
835
+ target: searchTargetSummary([target])[0],
836
+ results: matches.map(safeSyncResult),
837
+ task: safeTaskSummary(task),
838
+ },
839
+ );
840
+ if (
841
+ failed.length ||
842
+ matches.some((result) => Object.keys(result?.skipped ?? {}).length > 0)
843
+ )
844
+ throw new DatarcError(
845
+ `维度 ${target.primaryName} 存在跳过的同步结果`,
846
+ "SYNC_SKIPPED",
847
+ {
848
+ target: searchTargetSummary([target])[0],
849
+ results: matches.map(safeSyncResult),
850
+ task: safeTaskSummary(task),
851
+ },
852
+ );
853
+ const expectedModelUids = target.readyModelUids;
854
+ const coveredModelUids = new Set(
855
+ matches.flatMap((result) => syncResultModelUids(result?.tuids)),
856
+ );
857
+ const missingModelUids = expectedModelUids.filter(
858
+ (uid) => !coveredModelUids.has(uid),
859
+ );
860
+ if (!expectedModelUids.length || missingModelUids.length) {
861
+ coverageMissing.push({
862
+ target: searchTargetSummary([target])[0],
863
+ expectedModelUids,
864
+ coveredModelUids: [...coveredModelUids],
865
+ missingModelUids,
866
+ results: matches.map(safeSyncResult),
867
+ task: safeTaskSummary(task),
868
+ });
869
+ continue;
870
+ }
871
+ verified.push({
872
+ id: target.id,
873
+ primaryName: target.primaryName,
874
+ results: matches.map(safeSyncResult),
875
+ });
876
+ }
877
+ return { task: safeTaskSummary(task), verified, coverageMissing };
878
+ }
879
+
880
+ function targetSyncResults(task, targets) {
881
+ const results = Array.isArray(task?.result?.results)
882
+ ? task.result.results
883
+ : [];
884
+ return targets
885
+ .map((target) => ({
886
+ target,
887
+ matches: results.filter(
888
+ (result) =>
889
+ normalizeName(result?.name) === normalizeName(target.primaryName),
890
+ ),
891
+ }))
892
+ .filter(({ matches }) => matches.length);
893
+ }
894
+
895
+ function safeSyncResult(result) {
896
+ const skipped =
897
+ result?.skipped &&
898
+ !Array.isArray(result.skipped) &&
899
+ typeof result.skipped === "object"
900
+ ? Object.fromEntries(
901
+ Object.entries(result.skipped).map(([key, value]) => [
902
+ key,
903
+ typeof value === "number" && Number.isFinite(value) ? value : true,
904
+ ]),
905
+ )
906
+ : {};
907
+ return {
908
+ name: result?.name,
909
+ tuids: result?.tuids,
910
+ status: Number(result?.status),
911
+ skipped,
912
+ };
913
+ }
914
+
915
+ function dimensionModelUids(models) {
916
+ return [
917
+ ...new Set(
918
+ (Array.isArray(models) ? models : [])
919
+ .filter(
920
+ (model) => model?.uid !== undefined || typeof model === "string",
921
+ )
922
+ .map((model) => String(model?.uid ?? model).trim())
923
+ .filter(Boolean),
924
+ ),
925
+ ];
926
+ }
927
+
928
+ async function listWorkspaceModels(client, workspaceId) {
929
+ const models = await client.request(
930
+ "GET",
931
+ `/api/v2/admin-projects/${workspaceId}/models/`,
932
+ );
933
+ if (!Array.isArray(models))
934
+ throw new DatarcError("模型目录不是数组", "INVALID_RESPONSE");
935
+ return models;
936
+ }
937
+
938
+ function syncResultModelUids(value) {
939
+ return [value]
940
+ .flat()
941
+ .flatMap((item) => String(item ?? "").split(/[\s,]+/u))
942
+ .map((item) => item.trim())
943
+ .filter(Boolean);
944
+ }
945
+
946
+ async function listKeywordSyncTasks(client, workspaceId, offset, limit) {
947
+ return listSearchCompletionTasks(client, workspaceId, offset, limit);
948
+ }
949
+
950
+ async function listSearchCompletionTasks(client, workspaceId, offset, limit) {
951
+ const tasks = await client.request(
952
+ "GET",
953
+ `/api/v2/admin-projects/${workspaceId}/async-tasks/`,
954
+ {
955
+ query: {
956
+ taskType: SEARCH_COMPLETION_TASKS.join(","),
957
+ offset,
958
+ limit,
959
+ },
960
+ },
961
+ );
962
+ if (!Array.isArray(tasks))
963
+ throw new DatarcError("关键词同步任务列表不是数组", "INVALID_RESPONSE");
964
+ return tasks;
965
+ }
966
+
967
+ async function getSearchCompletionTask(client, workspaceId, uid) {
968
+ return client.request(
969
+ "GET",
970
+ `/api/v2/admin-projects/${workspaceId}/async-tasks/${uid}/`,
971
+ );
972
+ }
973
+
974
+ export async function captureSearchTaskBaseline(client, workspaceId) {
975
+ const tasks = await listSearchCompletionTasks(client, workspaceId, 0, 100);
976
+ return tasks.map((task) => task?.uid).filter(Boolean);
977
+ }
978
+
979
+ async function waitForSearchDictionaries(
980
+ client,
981
+ workspaceId,
982
+ { baselineTaskUids, pollIntervalMs, deadlineAt, sleep, now, notBefore },
983
+ ) {
984
+ const baseline = new Set(baselineTaskUids);
985
+ const inspected = new Set();
986
+ const failures = [];
987
+ let exact;
988
+ let fuzzy;
989
+ let fuzzyObserved = false;
990
+ while (true) {
991
+ const tasks = await listSearchCompletionTasks(client, workspaceId, 0, 100);
992
+ const candidates = tasks.filter(
993
+ (task) =>
994
+ task?.uid &&
995
+ !baseline.has(task.uid) &&
996
+ [GENERATE_DICTIONARY_TASK, GENERATE_FUZZY_DICTIONARY_TASK].includes(
997
+ Number(task.taskType),
998
+ ) &&
999
+ taskAtOrAfter(task, notBefore),
1000
+ );
1001
+ for (const candidate of candidates) {
1002
+ if (Number(candidate.taskType) === GENERATE_FUZZY_DICTIONARY_TASK)
1003
+ fuzzyObserved = true;
1004
+ if (
1005
+ inspected.has(candidate.uid) ||
1006
+ [TASK_PENDING, TASK_STARTED].includes(Number(candidate.status))
1007
+ )
1008
+ continue;
1009
+ const detail = await getSearchCompletionTask(
1010
+ client,
1011
+ workspaceId,
1012
+ candidate.uid,
1013
+ );
1014
+ if ([TASK_PENDING, TASK_STARTED].includes(Number(detail?.status)))
1015
+ continue;
1016
+ inspected.add(candidate.uid);
1017
+ const taskType = Number(detail?.taskType ?? candidate.taskType);
1018
+ if (!taskAtOrAfter(detail, notBefore)) {
1019
+ failures.push({
1020
+ ...safeTaskSummary(detail),
1021
+ validation: "createdAt_not_at_or_after_target_sync",
1022
+ });
1023
+ continue;
1024
+ }
1025
+ if (Number(detail?.status) !== TASK_SUCCESS) {
1026
+ failures.push(safeTaskSummary(detail));
1027
+ continue;
1028
+ }
1029
+ if (taskType === GENERATE_DICTIONARY_TASK) {
1030
+ if (isFiniteCount(detail?.result?.keywordsNum))
1031
+ exact = safeTaskSummary(detail);
1032
+ else
1033
+ failures.push({
1034
+ ...safeTaskSummary(detail),
1035
+ validation: "keywordsNum_must_be_finite_number",
1036
+ });
1037
+ }
1038
+ if (taskType === GENERATE_FUZZY_DICTIONARY_TASK) {
1039
+ if (
1040
+ isFiniteCount(detail?.result?.count) &&
1041
+ !String(detail?.result?.message ?? "").trim()
1042
+ )
1043
+ fuzzy = safeTaskSummary(detail);
1044
+ else
1045
+ failures.push({
1046
+ ...safeTaskSummary(detail),
1047
+ validation: "count_must_be_finite_number_without_message",
1048
+ });
1049
+ }
1050
+ }
1051
+ if (exact)
1052
+ return {
1053
+ exact,
1054
+ fuzzy: fuzzy ?? null,
1055
+ fuzzyTaskStatus: fuzzy
1056
+ ? "task_succeeded_unverified"
1057
+ : fuzzyObserved
1058
+ ? "task_not_ready"
1059
+ : "not_observed",
1060
+ fuzzyFailures: failures.filter(
1061
+ (failure) =>
1062
+ Number(failure.taskType) === GENERATE_FUZZY_DICTIONARY_TASK,
1063
+ ),
1064
+ };
1065
+ const remainingMs = deadlineAt - now();
1066
+ if (remainingMs <= 0)
1067
+ throw new DatarcError(
1068
+ "普通搜索词典未在观察窗口内完成",
1069
+ "DICTIONARY_NOT_READY",
1070
+ { notBefore, exact, fuzzy, failures },
1071
+ );
1072
+ await sleep(Math.min(pollIntervalMs, remainingMs));
1073
+ }
1074
+ }
1075
+
1076
+ async function waitForSearchProbes(
1077
+ client,
1078
+ workspaceId,
1079
+ targets,
1080
+ { pollIntervalMs, deadlineAt, sleep, now },
1081
+ ) {
1082
+ const verified = new Map();
1083
+ const lastResponses = new Map();
1084
+ while (true) {
1085
+ for (const target of targets) {
1086
+ if (verified.has(target.id)) continue;
1087
+ try {
1088
+ const response = await client.request(
1089
+ "POST",
1090
+ `/api/v3/account-projects/${workspaceId}/cut/`,
1091
+ { body: { tokens: target.probeValue } },
1092
+ );
1093
+ const tokens = Array.isArray(response?.tokens) ? response.tokens : [];
1094
+ const expectedPropPrefix = `d${target.id}=`;
1095
+ const matched = tokens.find(
1096
+ (token) =>
1097
+ String(token?.word ?? "") === target.probeValue &&
1098
+ String(token?.prop ?? "").startsWith(expectedPropPrefix),
1099
+ );
1100
+ lastResponses.set(target.id, {
1101
+ tokenCount: tokens.length,
1102
+ matchedProp: matched?.prop ?? null,
1103
+ });
1104
+ if (matched)
1105
+ verified.set(target.id, {
1106
+ id: target.id,
1107
+ primaryName: target.primaryName,
1108
+ probeValue: target.probeValue,
1109
+ prop: matched.prop,
1110
+ });
1111
+ } catch (error) {
1112
+ if (
1113
+ [
1114
+ "AUTHENTICATION_FAILED",
1115
+ "PERMISSION_DENIED",
1116
+ "RATE_LIMITED",
1117
+ ].includes(error?.code)
1118
+ )
1119
+ throw error;
1120
+ lastResponses.set(target.id, {
1121
+ error: {
1122
+ code: error?.code ?? "CUT_FAILED",
1123
+ message: "分词验收请求失败",
1124
+ },
1125
+ });
1126
+ }
1127
+ }
1128
+ if (targets.every((target) => verified.has(target.id)))
1129
+ return targets.map((target) => verified.get(target.id));
1130
+ const remainingMs = deadlineAt - now();
1131
+ if (remainingMs <= 0)
1132
+ throw new DatarcError(
1133
+ "普通词典任务已完成,但目标维度值仍未通过真实分词验收",
1134
+ "SEARCH_PROBE_FAILED",
1135
+ {
1136
+ missingTargetIds: targets
1137
+ .filter((target) => !verified.has(target.id))
1138
+ .map((target) => target.id),
1139
+ lastResponses: Object.fromEntries(lastResponses),
1140
+ },
1141
+ );
1142
+ await sleep(Math.min(pollIntervalMs, remainingMs));
1143
+ }
1144
+ }
1145
+
1146
+ async function rollbackSearchTargets(client, workspaceId, targets) {
1147
+ const results = [];
1148
+ for (const target of targets) {
1149
+ try {
1150
+ const current = await get(client, workspaceId, "dimension", target.id);
1151
+ if (current?.isKeyword !== true) {
1152
+ results.push({
1153
+ id: target.id,
1154
+ primaryName: target.primaryName,
1155
+ restored: current?.isKeyword === false,
1156
+ action: "not_needed",
1157
+ });
1158
+ continue;
1159
+ }
1160
+ await client.request(
1161
+ "PATCH",
1162
+ itemPath(workspaceId, "dimension", target.id),
1163
+ { body: { isKeyword: false } },
1164
+ );
1165
+ const after = await get(client, workspaceId, "dimension", target.id);
1166
+ results.push({
1167
+ id: target.id,
1168
+ primaryName: target.primaryName,
1169
+ restored: after?.isKeyword === false,
1170
+ action: "disabled",
1171
+ });
1172
+ } catch (error) {
1173
+ results.push({
1174
+ id: target.id,
1175
+ primaryName: target.primaryName,
1176
+ restored: false,
1177
+ error: {
1178
+ code: error?.code ?? "ROLLBACK_FAILED",
1179
+ message: "搜索开关回退失败",
1180
+ },
1181
+ });
1182
+ }
1183
+ }
1184
+ return results;
1185
+ }
1186
+
1187
+ function attachRollback(error, rollback) {
1188
+ return new DatarcError(
1189
+ error?.message ?? "搜索开启后置验收失败",
1190
+ error?.code ?? "SEARCH_ACTIVATION_FAILED",
1191
+ {
1192
+ writeCompleted: true,
1193
+ rollback,
1194
+ cause: {
1195
+ code: error?.code ?? "SEARCH_ACTIVATION_FAILED",
1196
+ message: error?.message ?? "搜索开启后置验收失败",
1197
+ },
1198
+ },
1199
+ );
1200
+ }
1201
+
1202
+ function safeTaskSummary(task) {
1203
+ if (!task || typeof task !== "object") return task;
1204
+ const result = task.result;
1205
+ const safeResult =
1206
+ result && typeof result === "object" && !Array.isArray(result)
1207
+ ? Object.fromEntries(
1208
+ ["keywordsNum", "count"]
1209
+ .filter((key) => isFiniteCount(result[key]))
1210
+ .map((key) => [key, result[key]]),
1211
+ )
1212
+ : undefined;
1213
+ return {
1214
+ uid: task.uid,
1215
+ taskType: Number(task.taskType),
1216
+ status: Number(task.status),
1217
+ createdAt: task.createdAt,
1218
+ updatedAt: task.updatedAt,
1219
+ ...(safeResult === undefined ? {} : { result: safeResult }),
1220
+ };
1221
+ }
1222
+
1223
+ function latestTaskTimestamp(tasks, field) {
1224
+ if (!Array.isArray(tasks) || !tasks.length)
1225
+ throw new DatarcError(
1226
+ `缺少可用于词典任务归因的 ${field}`,
1227
+ "INVALID_TASK_TIMESTAMP",
1228
+ );
1229
+ const timestamps = tasks.map((task) => Date.parse(task?.[field]));
1230
+ if (timestamps.some((timestamp) => !Number.isFinite(timestamp)))
1231
+ throw new DatarcError(
1232
+ `关键词同步任务缺少合法的 ${field}`,
1233
+ "INVALID_TASK_TIMESTAMP",
1234
+ { tasks: tasks.map(safeTaskSummary) },
1235
+ );
1236
+ return new Date(Math.max(...timestamps)).toISOString();
1237
+ }
1238
+
1239
+ function taskAtOrAfter(task, notBefore) {
1240
+ if (!notBefore) return true;
1241
+ const threshold = Date.parse(notBefore);
1242
+ const createdAt = Date.parse(task?.createdAt);
1243
+ return (
1244
+ Number.isFinite(threshold) &&
1245
+ Number.isFinite(createdAt) &&
1246
+ createdAt >= threshold
1247
+ );
1248
+ }
1249
+
1250
+ function isFiniteCount(value) {
1251
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
1252
+ }
1253
+
1254
+ function taskUids(value) {
1255
+ if (value === undefined || value === null || value === true) return [];
1256
+ return [value]
1257
+ .flat()
1258
+ .flatMap((item) => String(item).split(","))
1259
+ .map((item) => item.trim())
1260
+ .filter(Boolean);
1261
+ }
1262
+
1263
+ function nonNegativeNumber(value, name, fallback) {
1264
+ const number = value === undefined ? fallback : Number(value);
1265
+ if (!Number.isFinite(number) || number < 0)
1266
+ throw new DatarcError(`${name} 必须是非负数`, "INVALID_ARGUMENT");
1267
+ return number;
1268
+ }
1269
+
1270
+ function positiveInteger(value, name, fallback) {
1271
+ const number = value === undefined ? fallback : Number(value);
1272
+ if (!Number.isInteger(number) || number <= 0)
1273
+ throw new DatarcError(`${name} 必须是正整数`, "INVALID_ARGUMENT");
1274
+ return number;
1275
+ }
1276
+
1277
+ function searchCardinalityLimit(value, name) {
1278
+ const limit = positiveInteger(value, name, DEFAULT_SEARCH_CARDINALITY_LIMIT);
1279
+ if (limit > DEFAULT_SEARCH_CARDINALITY_LIMIT)
1280
+ throw new DatarcError(
1281
+ `${name} 不能超过硬上限 ${DEFAULT_SEARCH_CARDINALITY_LIMIT}`,
1282
+ "SEARCH_CARDINALITY_LIMIT_TOO_HIGH",
1283
+ { limit, hardLimit: DEFAULT_SEARCH_CARDINALITY_LIMIT },
1284
+ );
1285
+ return limit;
1286
+ }
1287
+
1288
+ export async function update(client, workspaceId, resource, id, args) {
1289
+ const patch = await readJson(required(args, "input"));
1290
+ if (!patch || Array.isArray(patch) || typeof patch !== "object")
1291
+ throw new DatarcError("更新内容必须是 JSON 对象", "INVALID_INPUT");
1292
+ const config = RESOURCES[resource];
1293
+ const patchKeys = Object.keys(patch);
1294
+ if (resource === "dimension-table")
1295
+ return updateDimensionTable(client, workspaceId, id, patch, args);
1296
+ const canPatch =
1297
+ patchKeys.length > 0 &&
1298
+ patchKeys.every((key) => config.patch?.includes(key));
1299
+ const before = await get(client, workspaceId, resource, id);
1300
+ if (
1301
+ resource === "measure" &&
1302
+ (before.formula || Object.hasOwn(patch, "formula"))
1303
+ )
1304
+ throw new DatarcError(
1305
+ "衍生指标必须使用 upsert-derived 更新,以执行依赖和模型覆盖预检",
1306
+ "UNSAFE_DERIVED_UPDATE",
1307
+ );
1308
+ const normalizedPatch = normalizeUpdatePatch(resource, before, patch);
1309
+ const body = canPatch
1310
+ ? normalizedPatch
1311
+ : cleanResource(resource, {
1312
+ ...before,
1313
+ ...normalizedPatch,
1314
+ [config.id]: before[config.id] ?? normalizeId(config, id),
1315
+ });
1316
+ validateResource(
1317
+ resource,
1318
+ canPatch ? { ...before, ...normalizedPatch } : body,
1319
+ );
1320
+ if (resource === "dimension" && affectsDimensionDisplayName(patch))
1321
+ validateDimensionDisplayNameUpdate(body);
1322
+ if (Array.isArray(normalizedPatch.names)) {
1323
+ const addedNames = normalizedPatch.names.filter(
1324
+ (name) =>
1325
+ !(before.names ?? []).some(
1326
+ (current) => normalizeName(current) === normalizeName(name),
1327
+ ),
1328
+ );
1329
+ if (addedNames.length)
1330
+ await assertNamesValid(
1331
+ client,
1332
+ workspaceId,
1333
+ addedNames,
1334
+ config.validation,
1335
+ );
1336
+ }
1337
+ const plan = {
1338
+ method: canPatch ? "PATCH" : "PUT",
1339
+ path: itemPath(workspaceId, resource, id),
1340
+ before,
1341
+ body,
1342
+ };
1343
+ if (args["dry-run"]) return plan;
1344
+ await client.request(plan.method, plan.path, { body });
1345
+ const after = await get(client, workspaceId, resource, id);
1346
+ if (resource === "dimension" && affectsDimensionDisplayName(patch))
1347
+ verifyDimensionDisplayNameUpdate(after, body.displayName);
1348
+ return { ...plan, after };
1349
+ }
1350
+
1351
+ function normalizeUpdatePatch(resource, before, patch) {
1352
+ if (resource !== "dimension" || !Object.hasOwn(patch, "displayName"))
1353
+ return patch;
1354
+ // 顶层 displayName 非普通对象(如 null、数组)时同样必须在合并前拒绝,
1355
+ // 避免跳过校验后由服务端按 names 自动补齐中英文回显名。
1356
+ if (!isPlainObject(patch.displayName))
1357
+ throw new DatarcError(
1358
+ "维度 displayName 必须是 JSON 对象;不接受 null 或数组",
1359
+ "INVALID_INPUT",
1360
+ );
1361
+ let names = patch.names;
1362
+ if (!Object.hasOwn(patch, "names")) names = [...(before.names ?? [])];
1363
+ else if (Array.isArray(names)) names = [...names];
1364
+ const englishName = patch.displayName["en-US"];
1365
+ if (
1366
+ isEnglishDisplayNameUpdate(patch) &&
1367
+ Array.isArray(names) &&
1368
+ typeof englishName === "string" &&
1369
+ englishName.trim() &&
1370
+ !names.includes(englishName)
1371
+ )
1372
+ names.push(englishName);
1373
+ const displayName = {
1374
+ ...(isPlainObject(before.displayName) ? before.displayName : {}),
1375
+ ...patch.displayName,
1376
+ };
1377
+ return {
1378
+ ...patch,
1379
+ ...(isEnglishDisplayNameUpdate(patch) ? { names } : {}),
1380
+ displayName,
1381
+ };
1382
+ }
1383
+
1384
+ function validateDimensionDisplayNameUpdate(body) {
1385
+ const names = body.names ?? [];
1386
+ const merged = body.displayName;
1387
+ for (const [lang, value] of Object.entries(merged)) {
1388
+ if (value === null)
1389
+ throw new DatarcError(
1390
+ `维度 displayName["${lang}"] 不支持 null;请改为 names 中仍保留的名称`,
1391
+ "INVALID_INPUT",
1392
+ { language: lang },
1393
+ );
1394
+ }
1395
+ const englishName = merged["en-US"];
1396
+ if (typeof englishName !== "string" || !englishName.trim())
1397
+ throw new DatarcError(
1398
+ '维度 displayName["en-US"] 必须是非空字符串',
1399
+ "INVALID_INPUT",
1400
+ );
1401
+ for (const [lang, value] of Object.entries(merged)) {
1402
+ if (typeof value !== "string" || !names.includes(value))
1403
+ throw new DatarcError(
1404
+ `维度 displayName["${lang}"] 必须与 names 中的一个名称完全一致`,
1405
+ "DISPLAY_NAME_NOT_IN_NAMES",
1406
+ { displayName: value, names },
1407
+ );
1408
+ }
1409
+ }
1410
+
1411
+ function verifyDimensionDisplayNameUpdate(after, expectedDisplayName) {
1412
+ const actual = after.displayName;
1413
+ for (const [lang, expected] of Object.entries(expectedDisplayName)) {
1414
+ const got = actual?.[lang];
1415
+ if (got !== expected)
1416
+ throw new DatarcError(
1417
+ `维度 displayName["${lang}"] 写入后回读验证失败`,
1418
+ "UPDATE_VERIFICATION_FAILED",
1419
+ { expected, actual: got },
1420
+ );
1421
+ }
1422
+ const unexpected = Object.keys(actual ?? {}).filter(
1423
+ (lang) => !Object.hasOwn(expectedDisplayName, lang),
1424
+ );
1425
+ if (unexpected.length)
1426
+ throw new DatarcError(
1427
+ "维度 displayName 回读出现预期外的语言值",
1428
+ "UPDATE_VERIFICATION_FAILED",
1429
+ { unexpected, actual },
1430
+ );
1431
+ }
1432
+
1433
+ function isPlainObject(value) {
1434
+ return Boolean(value) && !Array.isArray(value) && typeof value === "object";
1435
+ }
1436
+
1437
+ function isEnglishDisplayNameUpdate(patch) {
1438
+ return (
1439
+ isPlainObject(patch.displayName) &&
1440
+ Object.hasOwn(patch.displayName, "en-US")
1441
+ );
1442
+ }
1443
+
1444
+ function affectsDimensionDisplayName(patch) {
1445
+ // 只要 patch 显式携带 displayName 就进入校验,即使值不是普通对象;
1446
+ // 否则 {"displayName": null} 会绕过写前与写后校验。
1447
+ return (
1448
+ Object.hasOwn(patch, "displayName") || Object.hasOwn(patch, "names")
1449
+ );
1450
+ }
1451
+
1452
+ export async function updateDimensionTable(
1453
+ client,
1454
+ workspaceId,
1455
+ id,
1456
+ patch,
1457
+ args,
1458
+ ) {
1459
+ const allowed = RESOURCES["dimension-table"].patch;
1460
+ const unsupported = Object.keys(patch).filter(
1461
+ (field) => !allowed.includes(field),
1462
+ );
1463
+ if (unsupported.length)
1464
+ throw new DatarcError(
1465
+ "维度表 update 只支持 mark、table、tableUid、where;维度结构请使用 add-dimension 或 remove-dimension",
1466
+ "INVALID_INPUT",
1467
+ {
1468
+ fields: unsupported,
1469
+ },
1470
+ );
1471
+ if (Object.hasOwn(patch, "table") && Object.hasOwn(patch, "tableUid"))
1472
+ throw new DatarcError(
1473
+ "table 与 tableUid 互斥,不能同时修改",
1474
+ "INVALID_INPUT",
1475
+ );
1476
+ const path = itemPath(workspaceId, "dimension-table", id);
1477
+ const before = await get(client, workspaceId, "dimension-table", id);
1478
+ const steps = ["mark", "table", "tableUid", "where"]
1479
+ .filter((field) => Object.hasOwn(patch, field))
1480
+ .map((field) => ({
1481
+ body: {
1482
+ [field]: field === "where" ? encryptSql(patch[field]) : patch[field],
1483
+ },
1484
+ }));
1485
+ if (!steps.length) throw new DatarcError("更新内容不能为空", "INVALID_INPUT");
1486
+ const plan = {
1487
+ method: "PATCH",
1488
+ path,
1489
+ before,
1490
+ steps,
1491
+ ...(steps.length === 1 ? { body: steps[0].body } : {}),
1492
+ };
1493
+ if (args["dry-run"]) return plan;
1494
+ let after = before;
1495
+ for (const step of steps) {
1496
+ await client.request("PATCH", path, { body: step.body });
1497
+ after = await get(client, workspaceId, "dimension-table", id);
1498
+ verifyDimensionTableStep(after, step.body);
1499
+ step.after = after;
1500
+ }
1501
+ return { ...plan, after };
1502
+ }
1503
+
1504
+ export async function addDimension(client, workspaceId, tableUid, args) {
1505
+ const definition = cleanResource(
1506
+ "dimension",
1507
+ await readJson(required(args, "input")),
1508
+ );
1509
+ validateResource("dimension", definition);
1510
+ validateNewResourceClassification("dimension", definition);
1511
+ await assertNamesValid(client, workspaceId, definition.names, "dimension");
1512
+ const table = await get(client, workspaceId, "dimension-table", tableUid);
1513
+ const uid = crypto.randomUUID().replaceAll("-", "");
1514
+ const binding = { uid, field: required(args, "field") };
1515
+ const dimensionTable = cleanResource("dimension-table", {
1516
+ ...table,
1517
+ dimensions: [...(table.dimensions ?? []), binding],
1518
+ });
1519
+ const body = { dimensionTable, dimensions: [{ ...definition, uid }] };
1520
+ const plan = {
1521
+ method: "PUT",
1522
+ path: itemPath(workspaceId, "dimension-table", tableUid),
1523
+ body,
1524
+ };
1525
+ if (args["dry-run"]) return plan;
1526
+ await client.request("PUT", plan.path, { body });
1527
+ return {
1528
+ ...plan,
1529
+ after: await get(client, workspaceId, "dimension-table", tableUid),
1530
+ };
1531
+ }
1532
+
1533
+ export async function upsertDerived(client, workspaceId, args) {
1534
+ const input = cleanResource(
1535
+ "measure",
1536
+ await readJson(required(args, "input")),
1537
+ );
1538
+ validateResource("measure", input);
1539
+ validateDerivedInput(input);
1540
+
1541
+ const measures = await list(client, workspaceId, "measure");
1542
+ const requestedId =
1543
+ args.id === undefined ? null : normalizePositiveId(args.id);
1544
+ const existingById =
1545
+ requestedId === null
1546
+ ? null
1547
+ : measures.find((measure) => Number(measure.id) === requestedId);
1548
+ if (requestedId !== null && !existingById)
1549
+ throw new DatarcError(
1550
+ `衍生指标 id ${requestedId} 不存在`,
1551
+ "RESOURCE_NOT_FOUND",
1552
+ );
1553
+ const existingByName = uniqueRequestedNameMatch(input.names, measures);
1554
+ if (
1555
+ existingById &&
1556
+ existingByName &&
1557
+ Number(existingById.id) !== Number(existingByName.id)
1558
+ )
1559
+ throw new DatarcError(
1560
+ "--id 与输入名称命中了不同指标",
1561
+ "AMBIGUOUS_RESOURCE",
1562
+ { requestedId, nameMatchedId: existingByName.id },
1563
+ );
1564
+ const existing = existingById ?? existingByName;
1565
+ if (existing && !existing.formula)
1566
+ throw new DatarcError(
1567
+ "同名资源是基础指标,不能原地转换为衍生指标",
1568
+ "RESOURCE_TYPE_CONFLICT",
1569
+ { id: existing.id, names: existing.names },
1570
+ );
1571
+ const dependencyResolution = resolveFormulaDependencies(
1572
+ input.formula,
1573
+ measures,
1574
+ existing?.id,
1575
+ );
1576
+ const dependencies = dependencyResolution.dependencies;
1577
+ const [formulaValid, settings, models] = await Promise.all([
1578
+ assertFormulaValid(client, workspaceId, input.formula),
1579
+ client.request("GET", `/api/v2/admin-projects/${workspaceId}/`, {
1580
+ query: { type: 1 },
1581
+ }),
1582
+ client.request("GET", `/api/v2/admin-projects/${workspaceId}/models/`),
1583
+ ]);
1584
+ const coverage = buildDerivedCoverage(
1585
+ measures,
1586
+ dependencies,
1587
+ settings,
1588
+ models,
1589
+ dependencyResolution.formulaReferences,
1590
+ );
1591
+ const common = {
1592
+ dependencies,
1593
+ coverage,
1594
+ formulaValid,
1595
+ dependentMeasures: existing
1596
+ ? dependentMeasureClosure(existing.id, measures)
1597
+ : [],
1598
+ };
1599
+
1600
+ if (existing && sameExplicitResource(input, existing, measures))
1601
+ return {
1602
+ action: "reuse",
1603
+ resource: existing,
1604
+ used: existing.used === true,
1605
+ queryability: derivedQueryability(coverage),
1606
+ ...common,
1607
+ };
1608
+
1609
+ let plan;
1610
+ if (existing) {
1611
+ const body = cleanResource("measure", {
1612
+ ...existing,
1613
+ ...input,
1614
+ id: Number(existing.id),
1615
+ });
1616
+ plan = {
1617
+ action: "update",
1618
+ method: "PUT",
1619
+ path: itemPath(workspaceId, "measure", existing.id),
1620
+ before: existing,
1621
+ body,
1622
+ confirmationRequired: "UPDATE",
1623
+ ...common,
1624
+ };
1625
+ const addedNames = input.names.filter(
1626
+ (name) =>
1627
+ !(existing.names ?? []).some(
1628
+ (current) => normalizeName(current) === normalizeName(name),
1629
+ ),
1630
+ );
1631
+ if (addedNames.length)
1632
+ await assertNamesValid(client, workspaceId, addedNames, "measure");
1633
+ if (args["dry-run"]) return plan;
1634
+ if (args.confirm !== "UPDATE")
1635
+ throw new DatarcError(
1636
+ "同名衍生指标已存在但定义不同;检查影响后传入 --confirm UPDATE",
1637
+ "CONFIRMATION_REQUIRED",
1638
+ { plan },
1639
+ );
1640
+ } else {
1641
+ await assertNamesValid(client, workspaceId, input.names, "measure");
1642
+ plan = {
1643
+ action: "create",
1644
+ method: "POST",
1645
+ path: collectionPath(workspaceId, "measure"),
1646
+ body: input,
1647
+ ...common,
1648
+ };
1649
+ if (args["dry-run"]) return plan;
1650
+ }
1651
+
1652
+ if (coverage.blockers.length)
1653
+ throw new DatarcError(
1654
+ "衍生指标依赖尚不具备可执行条件",
1655
+ "DERIVED_PREFLIGHT_FAILED",
1656
+ { plan, blockers: coverage.blockers },
1657
+ );
1658
+ const result = await client.request(plan.method, plan.path, {
1659
+ body: plan.body,
1660
+ });
1661
+ const id = result?.id ?? existing?.id;
1662
+ if (id === undefined)
1663
+ throw new DatarcError(
1664
+ "衍生指标写入响应缺少 id,无法回读验证",
1665
+ "WRITE_VERIFICATION_FAILED",
1666
+ { result },
1667
+ );
1668
+ const verified = await get(client, workspaceId, "measure", id);
1669
+ verifyDerivedWrite(verified, input, dependencies, measures);
1670
+ return {
1671
+ ...plan,
1672
+ action: existing ? "updated" : "created",
1673
+ result,
1674
+ verified,
1675
+ used: verified.used === true,
1676
+ queryability: derivedQueryability(coverage),
1677
+ };
1678
+ }
1679
+
1680
+ function validateDerivedInput(value) {
1681
+ if (typeof value.formula !== "string" || !value.formula.trim())
1682
+ throw new DatarcError("衍生指标必须提供非空 formula", "INVALID_INPUT");
1683
+ if (value.formula.length > 1024)
1684
+ throw new DatarcError(
1685
+ "衍生指标 formula 不能超过 1024 字符",
1686
+ "INVALID_INPUT",
1687
+ );
1688
+ if (!value.format)
1689
+ throw new DatarcError("衍生指标必须提供 format", "INVALID_INPUT");
1690
+ const bindingFields = ["model", "field", "sql", "calcType", "type"];
1691
+ const provided = bindingFields.filter((field) => value[field] !== undefined);
1692
+ if (provided.length)
1693
+ throw new DatarcError(
1694
+ "衍生指标是工作区级资源,不能包含模型绑定字段",
1695
+ "INVALID_INPUT",
1696
+ { fields: provided },
1697
+ );
1698
+ if (typeof value.cumulative !== "boolean")
1699
+ throw new DatarcError(
1700
+ "衍生指标必须显式提供布尔值 cumulative",
1701
+ "INVALID_INPUT",
1702
+ );
1703
+ const allowed = new Set([
1704
+ "names",
1705
+ "formula",
1706
+ "format",
1707
+ "cumulative",
1708
+ "description",
1709
+ "formatParams",
1710
+ "unique",
1711
+ "sort",
1712
+ "unitName",
1713
+ "currencyCode",
1714
+ "preferComparison",
1715
+ "hide",
1716
+ "displayName",
1717
+ ]);
1718
+ const unknown = Object.keys(value).filter((field) => !allowed.has(field));
1719
+ if (unknown.length)
1720
+ throw new DatarcError(
1721
+ "衍生指标输入包含不支持的字段;查询验收计划必须单独保存",
1722
+ "INVALID_INPUT",
1723
+ { fields: unknown },
1724
+ );
1725
+ }
1726
+
1727
+ async function assertFormulaValid(client, workspaceId, formula) {
1728
+ const result = await client.request(
1729
+ "POST",
1730
+ `/api/v2/admin-projects/${workspaceId}/measures/check-formula/`,
1731
+ { body: { formula } },
1732
+ );
1733
+ if (result !== true)
1734
+ throw new DatarcError("衍生指标公式校验未通过", "INVALID_FORMULA", {
1735
+ result,
1736
+ });
1737
+ return true;
1738
+ }
1739
+
1740
+ async function assertNamesValid(client, workspaceId, names, field) {
1741
+ const result = await client.request(
1742
+ "POST",
1743
+ `/api/v2/admin-projects/${workspaceId}/name-validation/`,
1744
+ { body: { names, field } },
1745
+ );
1746
+ if (result?.status !== "SUCCESS")
1747
+ throw new DatarcError("名称校验未通过", "INVALID_NAME", { result });
1748
+ }
1749
+
1750
+ function uniqueRequestedNameMatch(names, measures) {
1751
+ const matches = new Map();
1752
+ for (const name of names)
1753
+ for (const measure of measures)
1754
+ if (
1755
+ (measure.names ?? []).some(
1756
+ (candidate) => normalizeName(candidate) === normalizeName(name),
1757
+ )
1758
+ )
1759
+ matches.set(Number(measure.id), measure);
1760
+ if (matches.size > 1)
1761
+ throw new DatarcError(
1762
+ "计划名称分别匹配到多个指标,无法确定复用目标",
1763
+ "AMBIGUOUS_RESOURCE",
1764
+ { ids: [...matches.keys()] },
1765
+ );
1766
+ return matches.size ? [...matches.values()][0] : null;
1767
+ }
1768
+
1769
+ function resolveFormulaDependencies(formula, measures, targetId) {
1770
+ const byId = new Map(
1771
+ measures.map((measure) => [Number(measure.id), measure]),
1772
+ );
1773
+ const byName = new Map();
1774
+ for (const measure of measures)
1775
+ for (const name of measure.names ?? []) {
1776
+ const key = normalizeName(name);
1777
+ const matches = byName.get(key) ?? [];
1778
+ matches.push(measure);
1779
+ byName.set(key, matches);
1780
+ }
1781
+ const roots = formulaReferences(formula).map((name) => {
1782
+ const matches = byName.get(normalizeName(name)) ?? [];
1783
+ if (matches.length !== 1)
1784
+ throw new DatarcError(
1785
+ matches.length
1786
+ ? `公式引用 [${name}] 不唯一`
1787
+ : `公式引用 [${name}] 不存在`,
1788
+ matches.length ? "AMBIGUOUS_RESOURCE" : "UNKNOWN_RESOURCE",
1789
+ );
1790
+ return matches[0];
1791
+ });
1792
+ if (!roots.length)
1793
+ throw new DatarcError(
1794
+ "衍生指标公式至少引用一个已有指标",
1795
+ "INVALID_FORMULA",
1796
+ );
1797
+ const leaves = new Set();
1798
+ const visiting = new Set();
1799
+ const visit = (measure) => {
1800
+ const id = Number(measure.id);
1801
+ if (id === Number(targetId) || visiting.has(id))
1802
+ throw new DatarcError("衍生指标公式存在循环引用", "INVALID_FORMULA");
1803
+ if (!measure.formula) {
1804
+ leaves.add(id);
1805
+ return;
1806
+ }
1807
+ if (measure.isValid !== true)
1808
+ throw new DatarcError(
1809
+ `衍生指标 ${measure.names?.[0] ?? id} 已失效`,
1810
+ "INVALID_DERIVED_DEPENDENCY",
1811
+ { id },
1812
+ );
1813
+ visiting.add(id);
1814
+ if (
1815
+ Array.isArray(measure.formula_dependency) &&
1816
+ !measure.formula_dependency.length
1817
+ )
1818
+ throw new DatarcError(
1819
+ `衍生指标 ${measure.names?.[0] ?? id} 没有有效基础依赖`,
1820
+ "INVALID_DERIVED_DEPENDENCY",
1821
+ { id },
1822
+ );
1823
+ const references = formulaReferences(measure.formula);
1824
+ if (!references.length)
1825
+ throw new DatarcError(
1826
+ `衍生指标 ${measure.names?.[0] ?? id} 没有直接指标引用`,
1827
+ "INVALID_DERIVED_DEPENDENCY",
1828
+ { id },
1829
+ );
1830
+ for (const name of references) {
1831
+ const matches = byName.get(normalizeName(name)) ?? [];
1832
+ if (matches.length !== 1)
1833
+ throw new DatarcError(
1834
+ `无法解析嵌套衍生指标引用 [${name}]`,
1835
+ "UNKNOWN_RESOURCE",
1836
+ );
1837
+ visit(matches[0]);
1838
+ }
1839
+ visiting.delete(id);
1840
+ };
1841
+ for (const measure of roots) visit(measure);
1842
+ if (!leaves.size)
1843
+ throw new DatarcError(
1844
+ "衍生指标没有可执行的基础指标依赖",
1845
+ "INVALID_DERIVED_DEPENDENCY",
1846
+ );
1847
+ return {
1848
+ dependencies: [...leaves].sort((left, right) => left - right),
1849
+ formulaReferences: [
1850
+ ...new Set(roots.map((measure) => Number(measure.id))),
1851
+ ].sort((left, right) => left - right),
1852
+ };
1853
+ }
1854
+
1855
+ function formulaReferences(formula) {
1856
+ return [...String(formula).matchAll(/\[([^\[\]]+)\]/g)].map((match) =>
1857
+ match[1].trim(),
1858
+ );
1859
+ }
1860
+
1861
+ function buildDerivedCoverage(
1862
+ measures,
1863
+ dependencies,
1864
+ settings = {},
1865
+ models = [],
1866
+ formulaReferenceIds = dependencies,
1867
+ ) {
1868
+ const byId = new Map(
1869
+ measures.map((measure) => [Number(measure.id), measure]),
1870
+ );
1871
+ const readyModelUids = new Set(
1872
+ models
1873
+ .filter((model) => model?.ready === true)
1874
+ .map(modelUid)
1875
+ .filter(Boolean),
1876
+ );
1877
+ const dependencyModels = dependencies.map((id) => {
1878
+ const measure = byId.get(Number(id));
1879
+ const executableModels = [
1880
+ ...new Set(
1881
+ (measure?.models ?? [])
1882
+ .map(modelUid)
1883
+ .filter((uid) => readyModelUids.has(uid)),
1884
+ ),
1885
+ ];
1886
+ return {
1887
+ id,
1888
+ names: measure?.names ?? [],
1889
+ cumulative: measure?.cumulative === true,
1890
+ used: measure?.used === true,
1891
+ models: executableModels,
1892
+ };
1893
+ });
1894
+ const blockers = [];
1895
+ for (const dependency of dependencyModels)
1896
+ if (!dependency.used || !dependency.models.length)
1897
+ blockers.push(
1898
+ `指标 ${dependency.names[0] ?? dependency.id} 尚未进入 ready 模型`,
1899
+ );
1900
+
1901
+ const maxBlendModelNum = Number(settings.maxBlendModelNum ?? 3);
1902
+ const maxBlendRowNum = Number(settings.maxBlendRowNum ?? 100000);
1903
+ const cover = minimumModelCover(dependencyModels, maxBlendModelNum);
1904
+ const sourceModels = cover.models;
1905
+ const sharedModels = dependencyModels.length
1906
+ ? dependencyModels
1907
+ .map((dependency) => new Set(dependency.models))
1908
+ .reduce(
1909
+ (shared, current) =>
1910
+ new Set([...shared].filter((uid) => current.has(uid))),
1911
+ )
1912
+ : new Set();
1913
+ const requiresDataBlend = sharedModels.size === 0;
1914
+ if (requiresDataBlend && settings.enableDataBlend !== true)
1915
+ blockers.push("工作区未开启 enableDataBlend");
1916
+ if (requiresDataBlend && cover.exhausted)
1917
+ blockers.push("模型组合过多,无法在本地搜索预算内证明可执行覆盖");
1918
+ else if (
1919
+ requiresDataBlend &&
1920
+ !sourceModels.length &&
1921
+ dependencyModels.every((dependency) => dependency.models.length)
1922
+ )
1923
+ blockers.push(
1924
+ `无法在 maxBlendModelNum=${maxBlendModelNum} 内覆盖全部依赖指标`,
1925
+ );
1926
+ const formulaReferences = formulaReferenceIds.map((id) => {
1927
+ const measure = byId.get(Number(id));
1928
+ return {
1929
+ id,
1930
+ names: measure?.names ?? [],
1931
+ derived: Boolean(measure?.formula),
1932
+ cumulative: measure?.cumulative === true,
1933
+ };
1934
+ });
1935
+ const cumulativeCount = formulaReferences.filter(
1936
+ (dependency) => dependency.cumulative,
1937
+ ).length;
1938
+ const leafCumulativeCount = dependencyModels.filter(
1939
+ (dependency) => dependency.cumulative,
1940
+ ).length;
1941
+ const timeSemantics = classifyTimeSemantics(
1942
+ cumulativeCount,
1943
+ formulaReferences.length,
1944
+ );
1945
+ const leafTimeSemantics = classifyTimeSemantics(
1946
+ leafCumulativeCount,
1947
+ dependencyModels.length,
1948
+ );
1949
+ return {
1950
+ dependencyModels,
1951
+ formulaReferences,
1952
+ sourceModels,
1953
+ sharedModels: [...sharedModels].sort(),
1954
+ requiresDataBlend,
1955
+ enableDataBlend: settings.enableDataBlend === true,
1956
+ maxBlendModelNum,
1957
+ maxBlendRowNum,
1958
+ timeSemantics,
1959
+ leafTimeSemantics,
1960
+ queryVerificationRequired:
1961
+ requiresDataBlend ||
1962
+ cumulativeCount > 0 ||
1963
+ leafCumulativeCount > 0 ||
1964
+ timeSemantics !== leafTimeSemantics,
1965
+ blockers,
1966
+ };
1967
+ }
1968
+
1969
+ function classifyTimeSemantics(cumulativeCount, total) {
1970
+ if (cumulativeCount === 0) return "normal";
1971
+ return cumulativeCount === total ? "cumulative" : "mixed";
1972
+ }
1973
+
1974
+ function minimumModelCover(dependencies, maxModels, maxCombinations = 10000) {
1975
+ if (!dependencies.length || dependencies.some((item) => !item.models.length))
1976
+ return { models: [], exhausted: false };
1977
+ const candidates = [
1978
+ ...new Set(dependencies.flatMap((dependency) => dependency.models)),
1979
+ ].sort();
1980
+ let checked = 0;
1981
+ for (let size = 1; size <= Math.min(maxModels, candidates.length); size += 1)
1982
+ for (const combination of combinations(candidates, size)) {
1983
+ checked += 1;
1984
+ if (
1985
+ dependencies.every((dependency) =>
1986
+ dependency.models.some((uid) => combination.includes(uid)),
1987
+ )
1988
+ )
1989
+ return { models: combination, exhausted: false };
1990
+ if (checked >= maxCombinations) return { models: [], exhausted: true };
1991
+ }
1992
+ return { models: [], exhausted: false };
1993
+ }
1994
+
1995
+ function* combinations(values, size, start = 0, selected = []) {
1996
+ if (selected.length === size) {
1997
+ yield [...selected];
1998
+ return;
1999
+ }
2000
+ for (let index = start; index < values.length; index += 1) {
2001
+ selected.push(values[index]);
2002
+ yield* combinations(values, size, index + 1, selected);
2003
+ selected.pop();
2004
+ }
2005
+ }
2006
+
2007
+ function modelUid(model) {
2008
+ return typeof model === "string" ? model : model?.uid;
2009
+ }
2010
+
2011
+ function derivedQueryability(coverage) {
2012
+ if (coverage.blockers.length) return "BLOCKED";
2013
+ if (coverage.queryVerificationRequired) return "NEEDS_QUERY_VERIFICATION";
2014
+ return "READY_FOR_QUERY_VALIDATION";
2015
+ }
2016
+
2017
+ function sameExplicitResource(input, existing, measures = []) {
2018
+ for (const [field, value] of Object.entries(input)) {
2019
+ const actual =
2020
+ field === "cumulative" ? existing.cumulative === true : existing[field];
2021
+ if (field === "formula") {
2022
+ if (
2023
+ canonicalizeFormula(value, measures) !==
2024
+ canonicalizeFormula(actual, measures)
2025
+ )
2026
+ return false;
2027
+ } else if (field === "names") {
2028
+ const actualNames = new Set((actual ?? []).map(normalizeName));
2029
+ const requestedNames = new Set(value.map(normalizeName));
2030
+ if (
2031
+ requestedNames.size !== actualNames.size ||
2032
+ [...requestedNames].some((name) => !actualNames.has(name))
2033
+ )
2034
+ return false;
2035
+ } else if (stableValue(value) !== stableValue(actual)) return false;
2036
+ }
2037
+ return true;
2038
+ }
2039
+
2040
+ function verifyDerivedWrite(value, input, dependencies, measures) {
2041
+ const actualDependencies = [...(value.formula_dependency ?? [])]
2042
+ .map(Number)
2043
+ .sort((left, right) => left - right);
2044
+ if (
2045
+ value.isValid !== true ||
2046
+ stableValue(actualDependencies) !== stableValue(dependencies) ||
2047
+ !sameExplicitResource(input, value, measures) ||
2048
+ (Array.isArray(value.models) && value.models.length)
2049
+ )
2050
+ throw new DatarcError(
2051
+ "衍生指标写入后回读验证失败",
2052
+ "WRITE_VERIFICATION_FAILED",
2053
+ { expected: { input, dependencies }, actual: value },
2054
+ );
2055
+ }
2056
+
2057
+ function canonicalizeFormula(formula, measures) {
2058
+ const byName = new Map();
2059
+ const ids = new Set(measures.map((measure) => Number(measure.id)));
2060
+ for (const measure of measures)
2061
+ for (const name of measure.names ?? []) {
2062
+ const key = normalizeName(name);
2063
+ const matches = byName.get(key) ?? [];
2064
+ matches.push(Number(measure.id));
2065
+ byName.set(key, matches);
2066
+ }
2067
+ const canonical = String(formula ?? "").replace(
2068
+ /\[([^\[\]]+)\]/g,
2069
+ (_match, rawName) => {
2070
+ const prop = /^m(\d+)$/.exec(rawName.trim());
2071
+ const propId = prop ? Number(prop[1]) : null;
2072
+ const matches =
2073
+ propId !== null && ids.has(propId)
2074
+ ? [propId]
2075
+ : [...new Set(byName.get(normalizeName(rawName)) ?? [])];
2076
+ if (matches.length !== 1)
2077
+ throw new DatarcError(
2078
+ `无法唯一解析公式引用 [${rawName.trim()}]`,
2079
+ "INVALID_FORMULA_REFERENCE",
2080
+ { ids: matches },
2081
+ );
2082
+ return `[m${matches[0]}]`;
2083
+ },
2084
+ );
2085
+ return foldRedundantFormulaParentheses(normalizeFormula(canonical));
2086
+ }
2087
+
2088
+ function foldRedundantFormulaParentheses(value) {
2089
+ let result = "";
2090
+ for (let index = 0; index < value.length; index += 1) {
2091
+ if (value[index] !== "(") {
2092
+ result += value[index];
2093
+ continue;
2094
+ }
2095
+ const close = matchingParenthesis(value, index);
2096
+ if (close < 0) throw new DatarcError("公式圆括号未闭合", "INVALID_FORMULA");
2097
+ const inner = foldRedundantFormulaParentheses(
2098
+ value.slice(index + 1, close),
2099
+ );
2100
+ result += normalizedFormulaGroup(inner);
2101
+ index = close;
2102
+ }
2103
+ return result;
2104
+ }
2105
+
2106
+ function normalizedFormulaGroup(inner) {
2107
+ const numeric = inner !== "" && Number.isFinite(Number(inner));
2108
+ if (numeric) return Number(inner) < 0 ? `(${inner})` : inner;
2109
+ if (isSingleParenthesizedExpression(inner)) return inner;
2110
+ return hasTopLevelFormulaOperator(inner) ? `(${inner})` : inner;
2111
+ }
2112
+
2113
+ function matchingParenthesis(value, start) {
2114
+ let depth = 0;
2115
+ for (let index = start; index < value.length; index += 1) {
2116
+ if (value[index] === "(") depth += 1;
2117
+ else if (value[index] === ")") {
2118
+ depth -= 1;
2119
+ if (depth === 0) return index;
2120
+ }
2121
+ }
2122
+ return -1;
2123
+ }
2124
+
2125
+ function isSingleParenthesizedExpression(value) {
2126
+ return value[0] === "(" && matchingParenthesis(value, 0) === value.length - 1;
2127
+ }
2128
+
2129
+ function hasTopLevelFormulaOperator(value) {
2130
+ let parentheses = 0;
2131
+ let brackets = 0;
2132
+ for (let index = 0; index < value.length; index += 1) {
2133
+ const character = value[index];
2134
+ if (character === "(") parentheses += 1;
2135
+ else if (character === ")") parentheses -= 1;
2136
+ else if (character === "[") brackets += 1;
2137
+ else if (character === "]") brackets -= 1;
2138
+ else if (
2139
+ parentheses === 0 &&
2140
+ brackets === 0 &&
2141
+ (character === "*" ||
2142
+ character === "/" ||
2143
+ ((character === "+" || character === "-") && index > 0))
2144
+ )
2145
+ return true;
2146
+ }
2147
+ return false;
2148
+ }
2149
+
2150
+ function normalizeName(value) {
2151
+ return String(value).trim().toLocaleLowerCase();
2152
+ }
2153
+
2154
+ function normalizeFormula(value) {
2155
+ return String(value ?? "").replace(/\s+/g, "");
2156
+ }
2157
+
2158
+ function stableValue(value) {
2159
+ if (!value || typeof value !== "object") return JSON.stringify(value);
2160
+ if (Array.isArray(value)) return `[${value.map(stableValue).join(",")}]`;
2161
+ return `{${Object.keys(value)
2162
+ .sort()
2163
+ .map((key) => `${JSON.stringify(key)}:${stableValue(value[key])}`)
2164
+ .join(",")}}`;
2165
+ }
2166
+
2167
+ export function cleanResource(resource, value) {
2168
+ const result = structuredClone(value);
2169
+ for (const field of RESOURCES[resource].readonly ?? []) delete result[field];
2170
+ return result;
2171
+ }
2172
+
2173
+ export function validateResource(resource, value) {
2174
+ if (!value || Array.isArray(value) || typeof value !== "object")
2175
+ throw new DatarcError("资源定义必须是 JSON 对象", "INVALID_INPUT");
2176
+ if (["measure", "dimension", "time-series"].includes(resource)) {
2177
+ if (
2178
+ !Array.isArray(value.names) ||
2179
+ !value.names.length ||
2180
+ value.names.some((name) => !String(name).trim())
2181
+ )
2182
+ throw new DatarcError(
2183
+ "关键词 names 必须是非空字符串数组",
2184
+ "INVALID_INPUT",
2185
+ );
2186
+ }
2187
+ if (resource === "dimension" && value.type === "choice")
2188
+ validateChoice(value.baseField);
2189
+ if (
2190
+ resource === "dimension" &&
2191
+ value.isKeyword !== undefined &&
2192
+ typeof value.isKeyword !== "boolean"
2193
+ )
2194
+ throw new DatarcError("isKeyword 必须是布尔值", "INVALID_INPUT");
2195
+ if (resource === "time-series") {
2196
+ const timeUnit = Number(value.timeUnit);
2197
+ if (!TIME_UNITS.has(timeUnit))
2198
+ throw new DatarcError("时间维度必须提供合法 timeUnit", "INVALID_INPUT");
2199
+ const minTimeUnit = Number(value.minTimeUnit ?? timeUnit);
2200
+ if (!TIME_UNITS.has(minTimeUnit))
2201
+ throw new DatarcError("minTimeUnit 不合法", "INVALID_INPUT");
2202
+ if (TIME_UNIT_LEVEL.get(timeUnit) < TIME_UNIT_LEVEL.get(minTimeUnit))
2203
+ throw new DatarcError("timeUnit 不能细于 minTimeUnit", "INVALID_INPUT");
2204
+ if (
2205
+ DAY_OR_COARSER_TYPES.has(value.type) &&
2206
+ TIME_UNIT_LEVEL.get(minTimeUnit) < TIME_UNIT_LEVEL.get(3)
2207
+ )
2208
+ throw new DatarcError("日期编码时间维度不能细于日", "INVALID_INPUT");
2209
+ if (
2210
+ MONTH_OR_COARSER_TYPES.has(value.type) &&
2211
+ TIME_UNIT_LEVEL.get(minTimeUnit) < TIME_UNIT_LEVEL.get(5)
2212
+ )
2213
+ throw new DatarcError("年月编码时间维度不能细于月", "INVALID_INPUT");
2214
+ value.timeUnit = timeUnit;
2215
+ value.minTimeUnit = minTimeUnit;
2216
+ }
2217
+ if (
2218
+ value.format &&
2219
+ ![
2220
+ "text",
2221
+ "longText",
2222
+ "int",
2223
+ "float",
2224
+ "percentage",
2225
+ "date",
2226
+ "datetime",
2227
+ "imageSrc",
2228
+ ].includes(value.format)
2229
+ )
2230
+ throw new DatarcError("format 不在合法枚举中", "INVALID_INPUT");
2231
+ return value;
2232
+ }
2233
+
2234
+ function validateNewResourceClassification(resource, value) {
2235
+ if (resource === "measure" && typeof value.cumulative !== "boolean")
2236
+ throw new DatarcError(
2237
+ "基础指标必须显式提供布尔值 cumulative",
2238
+ "INVALID_INPUT",
2239
+ );
2240
+ if (resource === "dimension" && typeof value.isKeyword !== "boolean")
2241
+ throw new DatarcError(
2242
+ "新维度必须显式提供布尔值 isKeyword",
2243
+ "INVALID_INPUT",
2244
+ );
2245
+ }
2246
+
2247
+ function normalizePositiveId(value) {
2248
+ const id = Number(value);
2249
+ if (!Number.isInteger(id) || id <= 0)
2250
+ throw new DatarcError(`id 必须是正整数:${value}`, "INVALID_ARGUMENT");
2251
+ return id;
2252
+ }
2253
+
2254
+ async function list(client, workspaceId, resource) {
2255
+ return client.request("GET", collectionPath(workspaceId, resource));
2256
+ }
2257
+
2258
+ async function get(client, workspaceId, resource, id) {
2259
+ if (resource !== "dimension-table")
2260
+ return client.request("GET", itemPath(workspaceId, resource, id));
2261
+ const matches = (await list(client, workspaceId, resource)).filter(
2262
+ (item) => item.uid === id,
2263
+ );
2264
+ if (matches.length !== 1)
2265
+ throw new DatarcError("无法唯一定位维度表", "RESOURCE_NOT_FOUND");
2266
+ return matches[0];
2267
+ }
2268
+
2269
+ async function find(client, workspaceId, resource, name) {
2270
+ const values = await list(client, workspaceId, resource);
2271
+ const target = String(name).toLocaleLowerCase();
2272
+ return values.filter((item) =>
2273
+ resource === "dimension-table"
2274
+ ? [item.mark, item.table, item.tableUid]
2275
+ .filter(Boolean)
2276
+ .some((value) => String(value).toLocaleLowerCase() === target)
2277
+ : (item.names ?? []).some(
2278
+ (value) => String(value).toLocaleLowerCase() === target,
2279
+ ),
2280
+ );
2281
+ }
2282
+
2283
+ async function impact(client, workspaceId, resource, id) {
2284
+ const item = await get(client, workspaceId, resource, id);
2285
+ if (resource !== "measure")
2286
+ return { resource, id, item, models: item.models ?? [] };
2287
+ const measures = await list(client, workspaceId, "measure");
2288
+ return {
2289
+ resource,
2290
+ id,
2291
+ item,
2292
+ models: item.models ?? [],
2293
+ dependentMeasures: dependentMeasureClosure(id, measures),
2294
+ };
2295
+ }
2296
+
2297
+ function dependentMeasureClosure(targetId, measures) {
2298
+ const byName = new Map();
2299
+ for (const measure of measures)
2300
+ for (const name of measure.names ?? []) {
2301
+ const key = normalizeName(name);
2302
+ const ids = byName.get(key) ?? [];
2303
+ ids.push(Number(measure.id));
2304
+ byName.set(key, ids);
2305
+ }
2306
+ const dependencies = new Map();
2307
+ for (const measure of measures) {
2308
+ if (!measure.formula) continue;
2309
+ const ids = new Set((measure.formula_dependency ?? []).map(Number));
2310
+ for (const name of formulaReferences(measure.formula)) {
2311
+ const matches = [...new Set(byName.get(normalizeName(name)) ?? [])];
2312
+ if (matches.length === 1) ids.add(matches[0]);
2313
+ }
2314
+ dependencies.set(Number(measure.id), ids);
2315
+ }
2316
+ const affected = new Set();
2317
+ const queue = [Number(targetId)];
2318
+ while (queue.length) {
2319
+ const current = queue.shift();
2320
+ for (const [measureId, ids] of dependencies)
2321
+ if (!affected.has(measureId) && ids.has(current)) {
2322
+ affected.add(measureId);
2323
+ queue.push(measureId);
2324
+ }
2325
+ }
2326
+ return [...affected]
2327
+ .map((id) => measures.find((measure) => Number(measure.id) === id))
2328
+ .filter(Boolean)
2329
+ .map(({ id, names, formula, used, models }) => ({
2330
+ id,
2331
+ names,
2332
+ formula,
2333
+ used,
2334
+ models: models ?? [],
2335
+ }));
2336
+ }
2337
+
2338
+ function validateChoice(baseField) {
2339
+ const allowed = [
2340
+ "int",
2341
+ "float",
2342
+ "str",
2343
+ "province_str",
2344
+ "city_str",
2345
+ "county_str",
2346
+ "bool",
2347
+ ];
2348
+ if (
2349
+ !baseField ||
2350
+ !allowed.includes(baseField.typeBeforeMap) ||
2351
+ !allowed.includes(baseField.typeAfterMap)
2352
+ )
2353
+ throw new DatarcError(
2354
+ "choice 维度缺少合法的 baseField 类型",
2355
+ "INVALID_INPUT",
2356
+ );
2357
+ if (
2358
+ !baseField.choice ||
2359
+ Array.isArray(baseField.choice) ||
2360
+ typeof baseField.choice !== "object"
2361
+ )
2362
+ throw new DatarcError("choice 维度缺少映射对象", "INVALID_INPUT");
2363
+ if (baseField.typeBeforeMap === "bool") {
2364
+ const keys = Object.keys(baseField.choice).sort();
2365
+ if (baseField.typeAfterMap !== "str" || keys.join(",") !== "false,true")
2366
+ throw new DatarcError(
2367
+ "bool 映射必须恰好包含 true/false 且映射到 str",
2368
+ "INVALID_INPUT",
2369
+ );
2370
+ }
2371
+ }
2372
+
2373
+ function verifyDimensionTableStep(value, body) {
2374
+ const [field, expected] = Object.entries(body)[0];
2375
+ if (value[field] !== expected)
2376
+ throw new DatarcError(
2377
+ `维度表字段 ${field} 写入后回读不一致`,
2378
+ "UPDATE_VERIFICATION_FAILED",
2379
+ { field, expected, actual: value[field] },
2380
+ );
2381
+ if (field === "table" && Object.hasOwn(value, "tableUid"))
2382
+ throw new DatarcError(
2383
+ "切换到 table 后 tableUid 仍然存在",
2384
+ "UPDATE_VERIFICATION_FAILED",
2385
+ );
2386
+ if (field === "tableUid" && Object.hasOwn(value, "table"))
2387
+ throw new DatarcError(
2388
+ "切换到 tableUid 后 table 仍然存在",
2389
+ "UPDATE_VERIFICATION_FAILED",
2390
+ );
2391
+ }
2392
+
2393
+ function resourceOf(args) {
2394
+ const resource = required(args, "resource");
2395
+ if (!RESOURCES[resource])
2396
+ throw new DatarcError(`不支持的资源类型:${resource}`, "INVALID_ARGUMENT");
2397
+ return resource;
2398
+ }
2399
+
2400
+ function collectionPath(workspaceId, resource) {
2401
+ const config = RESOURCES[resource];
2402
+ return `/api/v${config.version}/admin-projects/${workspaceId}/${config.path}/`;
2403
+ }
2404
+
2405
+ function itemPath(workspaceId, resource, id) {
2406
+ return `${collectionPath(workspaceId, resource)}${id}/`;
2407
+ }
2408
+
2409
+ function normalizeId(config, id) {
2410
+ return config.id === "id" ? Number(id) : id;
2411
+ }
2412
+
2413
+ function namesOf(args) {
2414
+ return []
2415
+ .concat(required(args, "name"))
2416
+ .flatMap((value) => String(value).split(","))
2417
+ .filter(Boolean);
2418
+ }
2419
+
2420
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
2421
+ await runCli(() => execute(process.argv.slice(2)));