@arcticdata/dsh-datarc-skills 0.0.0-stage → 26.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +20 -2
  2. package/cordis.patch.yml +4 -0
  3. package/icon.svg +4 -0
  4. package/index.js +35 -0
  5. package/locale/en.json +6 -0
  6. package/locale/zh.json +6 -0
  7. package/package.json +37 -4
  8. package/skills/datarc-access-permissions/SKILL.md +30 -0
  9. package/skills/datarc-access-permissions/references/api.md +31 -0
  10. package/skills/datarc-access-permissions/references/write-order.md +16 -0
  11. package/skills/datarc-analysis-report/SKILL.md +125 -0
  12. package/skills/datarc-analysis-report/agents/openai.yaml +6 -0
  13. package/skills/datarc-analysis-report/references/analyst-frameworks.md +215 -0
  14. package/skills/datarc-analysis-report/references/api-contracts.md +478 -0
  15. package/skills/datarc-analysis-report/references/direct-card-fallback-design.md +66 -0
  16. package/skills/datarc-analysis-report/references/human-in-the-loop.md +142 -0
  17. package/skills/datarc-analysis-report/references/loop-personalization-policy.md +138 -0
  18. package/skills/datarc-analysis-report/references/manifest-example.json +779 -0
  19. package/skills/datarc-analysis-report/references/narrative-schema.md +160 -0
  20. package/skills/datarc-analysis-report/references/question-syntax.md +151 -0
  21. package/skills/datarc-analysis-report/scripts/run_analysis_report.py +2225 -0
  22. package/skills/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -0
  23. package/skills/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -0
  24. package/skills/datarc-data-search/SKILL.md +243 -0
  25. package/skills/datarc-data-search/scripts/calculate.py +116 -0
  26. package/skills/datarc-data-search/scripts/data-search.mjs +628 -0
  27. package/skills/datarc-data-search/scripts/datarc-client.mjs +464 -0
  28. package/skills/datarc-data-search/scripts/search-result.mjs +211 -0
  29. package/skills/datarc-dataseek-batch-evaluation/SKILL.md +59 -0
  30. package/skills/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -0
  31. package/skills/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -0
  32. package/skills/datarc-dataseek-batch-evaluation/scripts/datarc-client.mjs +464 -0
  33. package/skills/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -0
  34. package/skills/datarc-dataseek-search/SKILL.md +96 -0
  35. package/skills/datarc-dataseek-search/scripts/datarc-client.mjs +464 -0
  36. package/skills/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -0
  37. package/skills/datarc-dataseek-semantic-debugging/SKILL.md +44 -0
  38. package/skills/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -0
  39. package/skills/datarc-dataseek-semantic-debugging/evals/evals.json +165 -0
  40. package/skills/datarc-dataseek-semantic-debugging/references/dataset.md +77 -0
  41. package/skills/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -0
  42. package/skills/datarc-dataseek-semantic-debugging/references/interventions.md +64 -0
  43. package/skills/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -0
  44. package/skills/datarc-dataseek-semantic-debugging/references/rollback.md +11 -0
  45. package/skills/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -0
  46. package/skills/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -0
  47. package/skills/datarc-dataseek-testset-generation/SKILL.md +47 -0
  48. package/skills/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -0
  49. package/skills/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -0
  50. package/skills/datarc-datasource/SKILL.md +97 -0
  51. package/skills/datarc-oauth/SKILL.md +47 -0
  52. package/skills/datarc-oauth/scripts/auth.mjs +130 -0
  53. package/skills/datarc-oauth/scripts/credentials.mjs +237 -0
  54. package/skills/datarc-report-add-card/SKILL.md +90 -0
  55. package/skills/datarc-report-add-card/agents/openai.yaml +4 -0
  56. package/skills/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
  57. package/skills/datarc-report-add-card/scripts/report-card.mjs +439 -0
  58. package/skills/datarc-semantic-alias/SKILL.md +20 -0
  59. package/skills/datarc-semantic-alias/scripts/alias-plan.mjs +422 -0
  60. package/skills/datarc-semantic-alias/scripts/alias.mjs +11 -0
  61. package/skills/datarc-semantic-calibration/SKILL.md +20 -0
  62. package/skills/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -0
  63. package/skills/datarc-semantic-calibration/scripts/calibration.mjs +11 -0
  64. package/skills/datarc-semantic-core/SKILL.md +12 -0
  65. package/skills/datarc-semantic-core/scripts/artifact-journal.mjs +830 -0
  66. package/skills/datarc-semantic-core/scripts/canonical.mjs +48 -0
  67. package/skills/datarc-semantic-core/scripts/case-model.mjs +608 -0
  68. package/skills/datarc-semantic-core/scripts/cli.mjs +180 -0
  69. package/skills/datarc-semantic-core/scripts/datarc-client.mjs +180 -0
  70. package/skills/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -0
  71. package/skills/datarc-semantic-core/scripts/interventions.mjs +693 -0
  72. package/skills/datarc-semantic-core/scripts/live-resolution.mjs +305 -0
  73. package/skills/datarc-semantic-core/scripts/model-scope.mjs +49 -0
  74. package/skills/datarc-semantic-core/scripts/reproduction.mjs +330 -0
  75. package/skills/datarc-semantic-core/scripts/semantic-cli.mjs +740 -0
  76. package/skills/datarc-semantic-core/scripts/shared.mjs +312 -0
  77. package/skills/datarc-semantic-core/scripts/verification.mjs +1014 -0
  78. package/skills/datarc-semantic-dataset/SKILL.md +20 -0
  79. package/skills/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -0
  80. package/skills/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -0
  81. package/skills/datarc-semantic-dataset/scripts/dataset.mjs +11 -0
  82. package/skills/datarc-semantic-knowledge/SKILL.md +38 -0
  83. package/skills/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -0
  84. package/skills/datarc-semantic-knowledge/references/knowledge-generation.json +16 -0
  85. package/skills/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -0
  86. package/skills/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -0
  87. package/skills/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -0
  88. package/skills/datarc-semantic-prompt/SKILL.md +20 -0
  89. package/skills/datarc-semantic-prompt/scripts/prompt-plan.mjs +447 -0
  90. package/skills/datarc-semantic-prompt/scripts/prompt.mjs +15 -0
  91. package/skills/datarc-semantic-synonym/SKILL.md +20 -0
  92. package/skills/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -0
  93. package/skills/datarc-semantic-synonym/scripts/synonym.mjs +11 -0
  94. package/skills/datarc-viz-analysis-report/SKILL.md +108 -0
  95. package/skills/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -0
  96. package/skills/datarc-viz-analysis-report/assets/echarts.min.js +45 -0
  97. package/skills/datarc-viz-analysis-report/references/api-contracts.md +163 -0
  98. package/skills/datarc-viz-analysis-report/references/derivation-log.md +157 -0
  99. package/skills/datarc-viz-analysis-report/references/evidence-framework.md +76 -0
  100. package/skills/datarc-viz-analysis-report/references/html-template.md +92 -0
  101. package/skills/datarc-viz-analysis-report/references/provenance-format.md +56 -0
  102. package/skills/datarc-viz-analysis-report/references/question-syntax.md +151 -0
  103. package/skills/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -0
  104. package/skills/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -0
  105. package/skills/datarc-workspace-configuration/SKILL.md +59 -0
  106. package/skills/datarc-workspace-configuration/references/artifacts.md +75 -0
  107. package/skills/datarc-workspace-configuration/references/verification.md +20 -0
  108. package/skills/datarc-workspace-configuration/scripts/configuration.mjs +662 -0
  109. package/skills/datarc-workspace-context/SKILL.md +43 -0
  110. package/skills/datarc-workspace-context/agents/openai.yaml +4 -0
  111. package/skills/datarc-workspace-context/scripts/datarc-client.mjs +31 -0
  112. package/skills/datarc-workspace-context/scripts/query-display.mjs +114 -0
  113. package/skills/datarc-workspace-context/scripts/workspace-context.mjs +58 -0
  114. package/skills/datarc-workspace-custom-tables/SKILL.md +89 -0
  115. package/skills/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -0
  116. package/skills/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -0
  117. package/skills/datarc-workspace-keywords/SKILL.md +197 -0
  118. package/skills/datarc-workspace-keywords/agents/openai.yaml +4 -0
  119. package/skills/datarc-workspace-keywords/references/api-fields.md +79 -0
  120. package/skills/datarc-workspace-keywords/references/derived-measures.md +177 -0
  121. package/skills/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -0
  122. package/skills/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -0
  123. package/skills/datarc-workspace-membership/SKILL.md +29 -0
  124. package/skills/datarc-workspace-membership/references/api.md +19 -0
  125. package/skills/datarc-workspace-modeling/SKILL.md +209 -0
  126. package/skills/datarc-workspace-modeling/agents/openai.yaml +4 -0
  127. package/skills/datarc-workspace-modeling/references/join-preview.md +38 -0
  128. package/skills/datarc-workspace-modeling/references/model-plan.md +300 -0
  129. package/skills/datarc-workspace-modeling/references/model-tags.md +95 -0
  130. package/skills/datarc-workspace-modeling/references/modeling-contract.json +29 -0
  131. package/skills/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -0
  132. package/skills/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -0
  133. package/skills/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -0
  134. package/skills/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -0
  135. package/skills-index.json +194 -0
@@ -0,0 +1,1261 @@
1
+ #!/usr/bin/env node
2
+ import { resolve } from "node:path";
3
+ import { readFileSync } from "node:fs";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import {
6
+ createClient,
7
+ DatarcError,
8
+ decryptSql,
9
+ encryptSql,
10
+ parseArgs,
11
+ readJson,
12
+ required,
13
+ runCli,
14
+ } from "./datarc-client.mjs";
15
+ import {
16
+ applySearchPlanInput,
17
+ captureSearchTaskBaseline,
18
+ validatePendingSearchEntries,
19
+ } from "../../datarc-workspace-keywords/scripts/workspace-keywords.mjs";
20
+
21
+ import {
22
+ MODEL_TAG_COMMANDS,
23
+ executeModelTags,
24
+ } from "./workspace-model-tags.mjs";
25
+
26
+ export const MODELING_CONTRACT = JSON.parse(
27
+ readFileSync(
28
+ new URL("../references/modeling-contract.json", import.meta.url),
29
+ "utf8",
30
+ ),
31
+ );
32
+ const FORMATS = MODELING_CONTRACT.formats;
33
+ const CALC_TYPES = MODELING_CONTRACT.calcTypes;
34
+ const TIME_UNIT_LEVEL = new Map(
35
+ Object.entries(MODELING_CONTRACT.timeUnitLevels).map(([unit, level]) => [
36
+ Number(unit),
37
+ level,
38
+ ]),
39
+ );
40
+ const DAY_OR_COARSER_TYPES = new Set(MODELING_CONTRACT.dayOrCoarserTypes);
41
+ const MONTH_OR_COARSER_TYPES = new Set(MODELING_CONTRACT.monthOrCoarserTypes);
42
+ const DEFAULT_TABLE_PAGE_SIZE = 200;
43
+ const KEYWORDS_SCRIPT_PATH = fileURLToPath(
44
+ new URL(
45
+ "../../datarc-workspace-keywords/scripts/workspace-keywords.mjs",
46
+ import.meta.url,
47
+ ),
48
+ );
49
+
50
+ export async function execute(argv, options = {}) {
51
+ const args = parseArgs(argv);
52
+ const command = args._[0];
53
+ const client = options.client ?? createClient(options);
54
+ if (MODEL_TAG_COMMANDS.includes(command))
55
+ return executeModelTags(args, client);
56
+ if (command === "workspaces")
57
+ return client.request("GET", "/api/v2/account-projects/", {
58
+ query: { admin: 1, q: args.query ?? "", offset: 0, limit: 20 },
59
+ });
60
+ const workspaceId = required(args, "workspace-id");
61
+ const prefix = `/api/v2/admin-projects/${workspaceId}`;
62
+ if (command === "tables") {
63
+ if (args.count)
64
+ return client.request("GET", `${prefix}/schemas/`, {
65
+ query: { q: args.query ?? "", count: 1 },
66
+ });
67
+ if (args.all)
68
+ return listAllTables(client, prefix, {
69
+ query: args.query ?? "",
70
+ pageSize: Number(args["page-size"] ?? DEFAULT_TABLE_PAGE_SIZE),
71
+ });
72
+ return client.request("GET", `${prefix}/schemas/`, {
73
+ query: {
74
+ q: args.query ?? "",
75
+ offset: Number(args.offset ?? 0),
76
+ limit: Number(args.limit ?? 50),
77
+ },
78
+ });
79
+ }
80
+ if (command === "table-groups") {
81
+ const result = await listAllTables(client, prefix, {
82
+ query: args.query ?? "",
83
+ pageSize: Number(args["page-size"] ?? DEFAULT_TABLE_PAGE_SIZE),
84
+ });
85
+ const smallLimit = Number(args["small-limit"] ?? 50);
86
+ const largeLimit = Number(args["large-limit"] ?? 500);
87
+ const grouped = {
88
+ ...result,
89
+ strategy:
90
+ result.total <= smallLimit
91
+ ? "saturate"
92
+ : result.total <= largeLimit
93
+ ? "choose-series"
94
+ : "group-only",
95
+ groups: groupTables(result.tables, Number(args.samples ?? 5)),
96
+ };
97
+ if (grouped.strategy === "group-only") delete grouped.tables;
98
+ return grouped;
99
+ }
100
+ if (command === "columns")
101
+ return client.request("GET", `${prefix}/schemas/columns/`, {
102
+ query: { tableName: required(args, "table") },
103
+ });
104
+ if (command === "preview")
105
+ return client.request("GET", `${prefix}/schemas/table-data/`, {
106
+ query: { tableName: required(args, "table") },
107
+ });
108
+ if (command === "column-preview")
109
+ return client.request("GET", `${prefix}/schemas/column-preview/`, {
110
+ query: {
111
+ tableName: required(args, "table"),
112
+ columnName: required(args, "column"),
113
+ },
114
+ });
115
+ if (command === "catalog") return loadCatalog(client, workspaceId, prefix);
116
+ if (command === "validate-name")
117
+ return client.request("POST", `${prefix}/name-validation/`, {
118
+ body: { names: [required(args, "name")], field: required(args, "field") },
119
+ });
120
+ if (command === "build")
121
+ return buildPayload(await readJson(required(args, "input")));
122
+ if (command === "preflight") {
123
+ const inputPath = required(args, "input");
124
+ const plan = await readJson(inputPath);
125
+ const registry = buildReuseRegistry(
126
+ await loadCatalog(client, workspaceId, prefix),
127
+ );
128
+ const resolvedPlan = resolvePlanReuse(plan, registry);
129
+ const payload = buildPayload(resolvedPlan, { registry });
130
+ const nameValidation = await validatePlanNames(
131
+ client,
132
+ prefix,
133
+ resolvedPlan,
134
+ );
135
+ return {
136
+ resolvedPlan,
137
+ payload,
138
+ nameValidation,
139
+ searchAction: pendingSearchAction(resolvedPlan, undefined, {
140
+ workspaceId,
141
+ inputPath,
142
+ args,
143
+ }),
144
+ };
145
+ }
146
+ if (command === "get") {
147
+ const model = await client.request(
148
+ "GET",
149
+ `${prefix}/models/${required(args, "model-uid")}/`,
150
+ );
151
+ return { model, editablePlan: modelToPlan(model) };
152
+ }
153
+ if (["create", "update"].includes(command)) {
154
+ const uid = args["model-uid"];
155
+ if (command === "update" && !uid) required(args, "model-uid");
156
+ const inputPath = required(args, "input");
157
+ let plan = await readJson(inputPath);
158
+ const searchMode = resolveSearchMode(plan, args);
159
+ if (command === "create" && (plan.uid || plan.encodedLayout))
160
+ throw new DatarcError(
161
+ "create 计划不能包含已有模型 uid/encodedLayout;请改用 update",
162
+ "INVALID_PLAN",
163
+ );
164
+ if (command === "update" && plan.uid && String(plan.uid) !== String(uid))
165
+ throw new DatarcError("计划 uid 与 --model-uid 不一致", "INVALID_PLAN");
166
+ if (command === "update") plan.uid = uid;
167
+ const registry = buildReuseRegistry(
168
+ await loadCatalog(client, workspaceId, prefix),
169
+ );
170
+ plan = resolvePlanReuse(plan, registry);
171
+ const payload = buildPayload(plan, { registry });
172
+ const nameValidation = await validatePlanNames(client, prefix, plan);
173
+ const path =
174
+ command === "create" ? `${prefix}/models/` : `${prefix}/models/${uid}/`;
175
+ if (args["dry-run"])
176
+ return {
177
+ method: command === "create" ? "POST" : "PUT",
178
+ path,
179
+ resolvedPlan: plan,
180
+ payload,
181
+ nameValidation,
182
+ searchAction: pendingSearchAction(plan, searchMode, {
183
+ workspaceId,
184
+ inputPath,
185
+ args,
186
+ }),
187
+ };
188
+ const baselineTaskUids = searchMode
189
+ ? await captureSearchTaskBaseline(client, workspaceId)
190
+ : [];
191
+ const result = await client.request(
192
+ command === "create" ? "POST" : "PUT",
193
+ path,
194
+ { body: payload },
195
+ );
196
+ const resultUid = result?.uid ?? uid;
197
+ if (!resultUid)
198
+ throw new DatarcError(
199
+ "模型写入响应缺少 uid,无法回读验证",
200
+ "WRITE_VERIFICATION_FAILED",
201
+ { result },
202
+ );
203
+ const verified = await client.request(
204
+ "GET",
205
+ `${prefix}/models/${resultUid}/`,
206
+ );
207
+ if (payload.model.disable === true) {
208
+ if (verified?.disable !== true || verified?.ready !== false)
209
+ throw new DatarcError(
210
+ "禁用模型写入后的 disable/ready 状态与计划不一致",
211
+ "WRITE_VERIFICATION_FAILED",
212
+ { result, verified },
213
+ );
214
+ } else if (verified?.ready !== true)
215
+ throw new DatarcError("模型写入后未达到 ready 状态", "MODEL_NOT_READY", {
216
+ result,
217
+ verified,
218
+ });
219
+ if (!searchMode)
220
+ return { status: "complete", complete: true, result, verified };
221
+ if (searchMode === "defer")
222
+ return {
223
+ status: "SEARCH_PENDING",
224
+ complete: false,
225
+ result,
226
+ verified,
227
+ baselineTaskUids,
228
+ nextAction: pendingSearchAction(plan, searchMode, {
229
+ workspaceId,
230
+ inputPath,
231
+ baselineTaskUids,
232
+ args,
233
+ }),
234
+ };
235
+ try {
236
+ const search = await applySearchPlanInput(
237
+ client,
238
+ workspaceId,
239
+ plan,
240
+ searchArgs(args),
241
+ { ...options, baselineTaskUids },
242
+ );
243
+ return {
244
+ status: "complete",
245
+ complete: true,
246
+ result,
247
+ verified,
248
+ search,
249
+ };
250
+ } catch (error) {
251
+ throw new DatarcError(
252
+ "模型已成功写入并回读,但维度值搜索开启或验收失败;不要重试 create",
253
+ "POST_WRITE_SEARCH_FAILED",
254
+ {
255
+ modelWriteCompleted: true,
256
+ modelUid: resultUid,
257
+ searchError: {
258
+ code: error?.code ?? "SEARCH_ACTIVATION_FAILED",
259
+ message: error?.message ?? "搜索开启失败",
260
+ rollback: error?.details?.rollback,
261
+ },
262
+ },
263
+ );
264
+ }
265
+ }
266
+ throw new DatarcError(
267
+ "命令应为 workspaces、tables、table-groups、columns、preview、column-preview、catalog、validate-name、build、preflight、get、create 或 update",
268
+ "INVALID_ARGUMENT",
269
+ );
270
+ }
271
+
272
+ function resolveSearchMode(plan, args) {
273
+ if (args["require-fuzzy"] !== undefined)
274
+ throw new DatarcError(
275
+ "--require-fuzzy 缺少错字探针验收,不能作为可靠完成门槛",
276
+ "UNSUPPORTED_ARGUMENT",
277
+ );
278
+ const entries = plan?.pendingSearchDimensions;
279
+ if (entries === undefined) {
280
+ if (
281
+ args["apply-search"] !== undefined ||
282
+ args["defer-search"] !== undefined
283
+ )
284
+ throw new DatarcError(
285
+ "计划没有 pendingSearchDimensions,不能指定搜索后置动作",
286
+ "INVALID_ARGUMENT",
287
+ );
288
+ return null;
289
+ }
290
+ validatePendingSearchEntries(plan, {
291
+ maxCardinality: args["max-cardinality"],
292
+ });
293
+ if (!entries.length) return null;
294
+ const apply = cliFlag(args, "apply-search");
295
+ const defer = cliFlag(args, "defer-search");
296
+ if (apply === defer)
297
+ throw new DatarcError(
298
+ "存在 pendingSearchDimensions 时必须且只能选择 --apply-search 或 --defer-search;单模型直接 apply,多模型在全部 ready 前 defer",
299
+ "SEARCH_ACTION_REQUIRED",
300
+ );
301
+ return apply ? "apply" : "defer";
302
+ }
303
+
304
+ function cliFlag(args, name) {
305
+ const value = args[name];
306
+ if (value === undefined) return false;
307
+ if (value !== true)
308
+ throw new DatarcError(`--${name} 是无值开关`, "INVALID_ARGUMENT");
309
+ return true;
310
+ }
311
+
312
+ function searchArgs(args) {
313
+ return Object.fromEntries(
314
+ ["poll-interval-ms", "max-wait-ms", "max-cardinality"]
315
+ .filter((key) => args[key] !== undefined)
316
+ .map((key) => [key, args[key]]),
317
+ );
318
+ }
319
+
320
+ function pendingSearchAction(
321
+ plan,
322
+ mode,
323
+ { workspaceId, inputPath, baselineTaskUids = [], args = {} } = {},
324
+ ) {
325
+ const entries = plan?.pendingSearchDimensions;
326
+ if (!Array.isArray(entries) || !entries.length) return null;
327
+ const resolvedInputPath = inputPath === "-" ? "-" : resolve(inputPath);
328
+ const commonArgs = [
329
+ KEYWORDS_SCRIPT_PATH,
330
+ "apply-search-plan",
331
+ "--workspace-id",
332
+ String(workspaceId),
333
+ "--input",
334
+ resolvedInputPath,
335
+ ...(baselineTaskUids.length
336
+ ? ["--baseline-task-uid", baselineTaskUids.join(",")]
337
+ : []),
338
+ ...searchCliArguments(args),
339
+ ];
340
+ const command = (commandArgs) => ({
341
+ command: process.execPath,
342
+ args: commandArgs,
343
+ ...(inputPath === "-"
344
+ ? {
345
+ stdin: JSON.stringify({ pendingSearchDimensions: entries }),
346
+ }
347
+ : {}),
348
+ });
349
+ return {
350
+ gate: "ALL_MODELS_READY",
351
+ mode: mode ?? "choice_required",
352
+ pendingCount: entries.length,
353
+ pendingSearchDimensions: structuredClone(entries),
354
+ ...(baselineTaskUids.length ? { baselineTaskUids } : {}),
355
+ commands: [command([...commonArgs, "--dry-run"]), command(commonArgs)],
356
+ };
357
+ }
358
+
359
+ function searchCliArguments(args) {
360
+ const result = [];
361
+ for (const key of ["poll-interval-ms", "max-wait-ms", "max-cardinality"])
362
+ if (args[key] !== undefined) result.push(`--${key}`, String(args[key]));
363
+ return result;
364
+ }
365
+
366
+ export function buildPayload(plan, options = {}) {
367
+ if (!plan || Array.isArray(plan) || typeof plan !== "object")
368
+ throw new DatarcError("建模计划必须是 JSON 对象", "INVALID_PLAN");
369
+ if (plan.pendingSearchDimensions !== undefined)
370
+ validatePendingSearchEntries(plan);
371
+ const rawModelOptions = modelOptions(plan.modelOptions);
372
+ if (Boolean(plan.name) === Boolean(rawModelOptions.mark))
373
+ throw new DatarcError(
374
+ "建模计划的 name 与 modelOptions.mark 必须且只能提供一个",
375
+ "INVALID_PLAN",
376
+ );
377
+ if (plan.encodedLayout && !plan.uid)
378
+ throw new DatarcError(
379
+ "encodedLayout 只能来自已有模型 editablePlan 并用于 update",
380
+ "INVALID_PLAN",
381
+ );
382
+ const sourceCount = [plan.table, plan.tableUid, plan.sql].filter(
383
+ Boolean,
384
+ ).length;
385
+ if (sourceCount !== 1)
386
+ throw new DatarcError(
387
+ "table、tableUid、sql 必须且只能提供一个",
388
+ "INVALID_PLAN",
389
+ );
390
+ const uuid = options.uuid ?? (() => crypto.randomUUID().replaceAll("-", ""));
391
+ const definitions = {
392
+ timeSeries: [],
393
+ dimensions: [],
394
+ measures: [],
395
+ dimensionTables: [],
396
+ };
397
+ const legacyDefaultTimeSeries = rawModelOptions.defaultTimeSeries;
398
+ delete rawModelOptions.defaultTimeSeries;
399
+ const model = {
400
+ ...rawModelOptions,
401
+ ...(plan.encodedLayout?.nodes
402
+ ? { nodes: structuredClone(plan.encodedLayout.nodes) }
403
+ : {}),
404
+ ...(plan.encodedLayout?.edges
405
+ ? { edges: structuredClone(plan.encodedLayout.edges) }
406
+ : {}),
407
+ ...(plan.uid ? { uid: plan.uid } : {}),
408
+ ...(plan.name ? { name: plan.name } : {}),
409
+ ...(plan.table ? { table: plan.table } : {}),
410
+ ...(plan.tableUid ? { tableUid: plan.tableUid } : {}),
411
+ ...(plan.sql ? { sql: encryptSql(plan.sql) } : {}),
412
+ ...(plan.where ? { where: encryptSql(plan.where) } : {}),
413
+ timeSeries: bindAll(
414
+ "timeSeries",
415
+ plan.timeSeries ?? [],
416
+ definitions,
417
+ uuid,
418
+ options,
419
+ ),
420
+ dimensions: bindAll(
421
+ "dimensions",
422
+ plan.dimensions ?? [],
423
+ definitions,
424
+ uuid,
425
+ options,
426
+ ),
427
+ measures: bindAll(
428
+ "measures",
429
+ plan.measures ?? [],
430
+ definitions,
431
+ uuid,
432
+ options,
433
+ ),
434
+ dimensionTables: [],
435
+ };
436
+ if (!model.timeSeries.length)
437
+ throw new DatarcError("模型至少需要一个时间维度", "INVALID_PLAN");
438
+ if (!model.measures.length)
439
+ throw new DatarcError("模型至少需要一个指标", "INVALID_PLAN");
440
+ model.defaultTimeSeries = resolveDefaultTimeSeries(
441
+ plan.timeSeries ?? [],
442
+ model.timeSeries,
443
+ legacyDefaultTimeSeries,
444
+ );
445
+ for (const table of plan.dimensionTables ?? [])
446
+ model.dimensionTables.push(
447
+ bindDimensionTable(table, definitions, uuid, options),
448
+ );
449
+ validateUniqueFactFields(model);
450
+ validateUniqueBindings(model, definitions, options.registry);
451
+ return {
452
+ model,
453
+ ...Object.fromEntries(
454
+ Object.entries(definitions).filter(([, values]) => values.length),
455
+ ),
456
+ };
457
+ }
458
+
459
+ function bindAll(resource, items, definitions, uuid, options = {}) {
460
+ return items.map((item) => bind(resource, item, definitions, uuid, options));
461
+ }
462
+
463
+ function bind(resource, item, definitions, uuid, options = {}) {
464
+ if (!item || typeof item !== "object")
465
+ throw new DatarcError("绑定项必须是对象", "INVALID_PLAN");
466
+ if (Boolean(item.field) === Boolean(item.sql))
467
+ throw new DatarcError("绑定项必须且只能提供 field 或 sql", "INVALID_PLAN");
468
+ const hasId = item.id !== undefined && item.id !== null;
469
+ if (hasId && item.definition)
470
+ throw new DatarcError(
471
+ "复用已有关键词时不能同时提供 definition",
472
+ "INVALID_PLAN",
473
+ );
474
+ const identity = hasId
475
+ ? { id: normalizeResourceId(item.id) }
476
+ : { uid: uuid() };
477
+ if (hasId) validateRegistryBinding(resource, identity.id, options.registry);
478
+ else {
479
+ if (!item.definition)
480
+ throw new DatarcError("新关键词绑定缺少 definition", "INVALID_PLAN");
481
+ const definition = validateDefinition(resource, item.definition);
482
+ definitions[resource].push({ ...definition, ...identity });
483
+ }
484
+ const binding = {
485
+ ...identity,
486
+ ...(item.field ? { field: item.field } : { sql: encryptSql(item.sql) }),
487
+ };
488
+ if (resource === "measures") {
489
+ if (item.cumulative !== undefined)
490
+ throw new DatarcError(
491
+ "cumulative 是工作区级指标属性,请放入 definition",
492
+ "INVALID_PLAN",
493
+ );
494
+ if (item.formula)
495
+ throw new DatarcError(
496
+ "衍生指标不能绑定模型,请使用 datarc-workspace-keywords",
497
+ "INVALID_PLAN",
498
+ );
499
+ if (item.sql && item.calcType)
500
+ throw new DatarcError("SQL 指标不能再设置 calcType", "INVALID_PLAN");
501
+ if (item.field && !CALC_TYPES.includes(item.calcType))
502
+ throw new DatarcError("字段指标需要合法 calcType", "INVALID_PLAN");
503
+ if (!item.type || !FORMATS.includes(item.format))
504
+ throw new DatarcError("指标绑定需要合法 type、format", "INVALID_PLAN");
505
+ Object.assign(binding, {
506
+ ...(item.calcType ? { calcType: item.calcType } : {}),
507
+ ...(item.type ? { type: item.type } : {}),
508
+ ...(item.format ? { format: item.format } : {}),
509
+ });
510
+ }
511
+ if (resource === "dimensions" && item.joinFields !== undefined) {
512
+ binding.joinType = item.joinType ?? "left";
513
+ binding.joinFields = encodeJoinFields(item.joinFields);
514
+ }
515
+ return binding;
516
+ }
517
+
518
+ function modelOptions(value = {}) {
519
+ const allowed = MODELING_CONTRACT.modelOptions;
520
+ return Object.fromEntries(
521
+ Object.entries(value).filter(([key]) => allowed.includes(key)),
522
+ );
523
+ }
524
+
525
+ function bindDimensionTable(item, definitions, uuid, options = {}) {
526
+ if (!item.uid && !item.definition)
527
+ throw new DatarcError("维度表需要 uid 或 definition", "INVALID_PLAN");
528
+ if (item.uid && item.definition)
529
+ throw new DatarcError(
530
+ "复用维度表 uid 与新建 definition 互斥",
531
+ "INVALID_PLAN",
532
+ );
533
+ if (item.uid && options.registry) {
534
+ if (!options.registry.dimensionTables.byUid.has(item.uid))
535
+ throw new DatarcError(
536
+ `维度表 uid ${item.uid} 不在当前工作区目录中`,
537
+ "UNKNOWN_RESOURCE",
538
+ );
539
+ }
540
+ const uid = item.uid ?? uuid();
541
+ if (item.definition) {
542
+ const sourceCount = [
543
+ item.definition.table,
544
+ item.definition.tableUid,
545
+ ].filter(Boolean).length;
546
+ if (sourceCount !== 1)
547
+ throw new DatarcError(
548
+ "新维度表的 table、tableUid 必须且只能提供一个",
549
+ "INVALID_PLAN",
550
+ );
551
+ if (
552
+ Object.hasOwn(item.definition, "timeSeries") ||
553
+ Object.hasOwn(item.definition, "measures")
554
+ )
555
+ throw new DatarcError("维度表不能包含时间维度或指标", "INVALID_PLAN");
556
+ const { dimensions, ...metadata } = item.definition;
557
+ definitions.dimensionTables.push({
558
+ ...metadata,
559
+ ...(item.definition.where
560
+ ? { where: encryptSql(item.definition.where) }
561
+ : {}),
562
+ uid,
563
+ dimensions: (dimensions ?? []).map((dimension) => {
564
+ const binding = bind(
565
+ "dimensions",
566
+ dimension,
567
+ definitions,
568
+ uuid,
569
+ options,
570
+ );
571
+ if (binding.id !== undefined) binding.uid = dimension.uid ?? uuid();
572
+ return binding;
573
+ }),
574
+ });
575
+ }
576
+ if (!Array.isArray(item.joinFields) || !item.joinFields.length)
577
+ throw new DatarcError("维度表关联缺少 joinFields", "INVALID_PLAN");
578
+ return {
579
+ uid,
580
+ joinType: item.joinType ?? "left",
581
+ joinFields: encodeJoinFields(item.joinFields),
582
+ };
583
+ }
584
+
585
+ function encodeJoinFields(joinFields) {
586
+ if (!Array.isArray(joinFields) || !joinFields.length)
587
+ throw new DatarcError("关联缺少 joinFields", "INVALID_PLAN");
588
+ return joinFields.map(({ src, dst }) => {
589
+ if (!src || !dst)
590
+ throw new DatarcError("joinFields 需要 src 和 dst", "INVALID_PLAN");
591
+ return { src: encryptSql(src), dst: encryptSql(dst) };
592
+ });
593
+ }
594
+
595
+ async function loadCatalog(client, workspaceId, prefix) {
596
+ const [models, measures, dimensions, timeSeries, dimensionTables] =
597
+ await Promise.all([
598
+ client.request("GET", `${prefix}/models/`),
599
+ client.request("GET", `${prefix}/measures/`),
600
+ client.request("GET", `${prefix}/dimensions/`),
601
+ client.request("GET", `${prefix}/time-series/`),
602
+ listAllDimensionTables(client, workspaceId),
603
+ ]);
604
+ return { models, measures, dimensions, timeSeries, dimensionTables };
605
+ }
606
+
607
+ async function listAllDimensionTables(client, workspaceId, pageSize = 1000) {
608
+ const path = `/api/v3/admin-projects/${workspaceId}/dimension-tables/`;
609
+ const total = await client.request("GET", path, { query: { count: 1 } });
610
+ const tables = [];
611
+ const seen = new Set();
612
+ while (tables.length < total) {
613
+ const page = await client.request("GET", path, {
614
+ query: { offset: tables.length, limit: pageSize },
615
+ });
616
+ if (!Array.isArray(page) || !page.length) break;
617
+ const before = tables.length;
618
+ for (const item of page)
619
+ if (item?.uid && !seen.has(item.uid)) {
620
+ seen.add(item.uid);
621
+ tables.push(item);
622
+ }
623
+ if (tables.length === before) break;
624
+ }
625
+ if (tables.length !== total)
626
+ throw new DatarcError(
627
+ "维度表目录分页读取不完整,停止复用预检",
628
+ "INCOMPLETE_CATALOG",
629
+ { expected: total, actual: tables.length },
630
+ );
631
+ return tables;
632
+ }
633
+
634
+ async function validatePlanNames(client, prefix, plan) {
635
+ const requests = [
636
+ ...(plan.name
637
+ ? [
638
+ {
639
+ field: "model",
640
+ names: [plan.name],
641
+ ...(plan.uid ? { uid: plan.uid } : {}),
642
+ },
643
+ ]
644
+ : []),
645
+ {
646
+ field: "timeSeries",
647
+ names: (plan.timeSeries ?? []).flatMap(
648
+ (item) => item.definition?.names ?? [],
649
+ ),
650
+ },
651
+ {
652
+ field: "dimension",
653
+ names: [
654
+ ...(plan.dimensions ?? []).flatMap(
655
+ (item) => item.definition?.names ?? [],
656
+ ),
657
+ ...(plan.dimensionTables ?? []).flatMap(
658
+ (table) =>
659
+ table.definition?.dimensions?.flatMap(
660
+ (item) => item.definition?.names ?? [],
661
+ ) ?? [],
662
+ ),
663
+ ],
664
+ },
665
+ {
666
+ field: "measure",
667
+ names: (plan.measures ?? []).flatMap(
668
+ (item) => item.definition?.names ?? [],
669
+ ),
670
+ },
671
+ ].filter((item) => item.names.length);
672
+ const results = [];
673
+ for (const body of requests) {
674
+ const result = await client.request("POST", `${prefix}/name-validation/`, {
675
+ body,
676
+ });
677
+ if (result?.status !== "SUCCESS")
678
+ throw new DatarcError(`${body.field} 名称校验未通过`, "INVALID_NAME", {
679
+ body,
680
+ result,
681
+ });
682
+ results.push({ field: body.field, status: result.status });
683
+ }
684
+ return results;
685
+ }
686
+
687
+ export function modelToPlan(model) {
688
+ if (!model || Array.isArray(model) || typeof model !== "object")
689
+ throw new DatarcError("模型回读结果不是对象", "INVALID_MODEL");
690
+ const defaultIdentity = model.defaultTimeSeries;
691
+ const binding = (item, resource) => ({
692
+ ...(item.id !== undefined ? { id: item.id } : {}),
693
+ ...(item.uid !== undefined ? { uid: item.uid } : {}),
694
+ ...(item.field ? { field: item.field } : {}),
695
+ ...(item.sql ? { sql: decryptSql(item.sql) } : {}),
696
+ ...(resource === "measures" && item.calcType
697
+ ? { calcType: item.calcType }
698
+ : {}),
699
+ ...(resource === "measures" && item.type ? { type: item.type } : {}),
700
+ ...(resource === "measures" && item.format ? { format: item.format } : {}),
701
+ ...(resource === "dimensions" && item.joinType
702
+ ? { joinType: item.joinType }
703
+ : {}),
704
+ ...(resource === "dimensions" && item.joinFields
705
+ ? {
706
+ joinFields: item.joinFields.map(({ src, dst }) => ({
707
+ src: decryptSql(src),
708
+ dst: decryptSql(dst),
709
+ })),
710
+ }
711
+ : {}),
712
+ });
713
+ const timeSeries = (model.timeSeries ?? []).map((item) => ({
714
+ ...binding(item, "timeSeries"),
715
+ ...(sameIdentity(bindingIdentity(item), defaultIdentity)
716
+ ? { default: true }
717
+ : {}),
718
+ }));
719
+ return {
720
+ ...(model.uid ? { uid: model.uid } : {}),
721
+ ...(model.name ? { name: model.name } : {}),
722
+ ...(model.table ? { table: model.table } : {}),
723
+ ...(model.tableUid ? { tableUid: model.tableUid } : {}),
724
+ ...(model.sql ? { sql: decryptSql(model.sql) } : {}),
725
+ ...(model.where ? { where: decryptSql(model.where) } : {}),
726
+ timeSeries,
727
+ dimensions: (model.dimensions ?? []).map((item) =>
728
+ binding(item, "dimensions"),
729
+ ),
730
+ measures: (model.measures ?? []).map((item) => binding(item, "measures")),
731
+ dimensionTables: (model.dimensionTables ?? []).map((table) => ({
732
+ uid: table.uid,
733
+ joinType: table.joinType ?? "left",
734
+ joinFields: (table.joinFields ?? []).map(({ src, dst }) => ({
735
+ src: decryptSql(src),
736
+ dst: decryptSql(dst),
737
+ })),
738
+ })),
739
+ ...((model.nodes?.length || model.edges?.length) && {
740
+ encodedLayout: {
741
+ ...(model.nodes?.length ? { nodes: structuredClone(model.nodes) } : {}),
742
+ ...(model.edges?.length ? { edges: structuredClone(model.edges) } : {}),
743
+ },
744
+ }),
745
+ modelOptions: Object.fromEntries(
746
+ [
747
+ "mark",
748
+ "description",
749
+ "disable",
750
+ "disableDateRangeLimit",
751
+ "offsetType",
752
+ "baseOffset",
753
+ "timeOffset",
754
+ "weight",
755
+ ]
756
+ .filter((key) => model[key] !== undefined)
757
+ .map((key) => [key, model[key]]),
758
+ ),
759
+ };
760
+ }
761
+
762
+ async function listAllTables(client, prefix, { query = "", pageSize }) {
763
+ if (!Number.isInteger(pageSize) || pageSize <= 0)
764
+ throw new DatarcError("page-size 必须是正整数", "INVALID_ARGUMENT");
765
+ const total = await client.request("GET", `${prefix}/schemas/`, {
766
+ query: { q: query, count: 1 },
767
+ });
768
+ const tables = [];
769
+ while (tables.length < total) {
770
+ const page = await client.request("GET", `${prefix}/schemas/`, {
771
+ query: { q: query, offset: tables.length, limit: pageSize },
772
+ });
773
+ if (!Array.isArray(page) || !page.length) break;
774
+ const before = tables.length;
775
+ const seen = new Set(tables.map((item) => item.tableName));
776
+ for (const item of page)
777
+ if (item?.tableName && !seen.has(item.tableName)) {
778
+ seen.add(item.tableName);
779
+ tables.push(item);
780
+ }
781
+ if (tables.length === before) break;
782
+ }
783
+ return { total, tables, complete: tables.length === total };
784
+ }
785
+
786
+ export function groupTables(tables, sampleLimit = 5) {
787
+ if (!Array.isArray(tables))
788
+ throw new DatarcError("tables 必须是数组", "INVALID_ARGUMENT");
789
+ if (!Number.isInteger(sampleLimit) || sampleLimit <= 0)
790
+ throw new DatarcError("samples 必须是正整数", "INVALID_ARGUMENT");
791
+ const groups = new Map();
792
+ for (const table of tables) {
793
+ const name = table?.tableName;
794
+ if (!name) continue;
795
+ const separator = name.lastIndexOf(".");
796
+ const schema = separator >= 0 ? name.slice(0, separator) : "";
797
+ const base = separator >= 0 ? name.slice(separator + 1) : name;
798
+ const pattern = base.replace(/\d+/g, "#");
799
+ const series = schema ? `${schema}.${pattern}` : pattern;
800
+ const group = groups.get(series) ?? { series, count: 0, samples: [] };
801
+ group.count += 1;
802
+ if (group.samples.length < sampleLimit) group.samples.push(name);
803
+ groups.set(series, group);
804
+ }
805
+ return [...groups.values()].sort(
806
+ (left, right) =>
807
+ right.count - left.count || left.series.localeCompare(right.series),
808
+ );
809
+ }
810
+
811
+ export function buildReuseRegistry(catalog = {}) {
812
+ const registry = {
813
+ timeSeries: buildResourceIndex(catalog.timeSeries),
814
+ dimensions: buildResourceIndex(catalog.dimensions),
815
+ measures: buildResourceIndex(catalog.measures),
816
+ dimensionTables: {
817
+ byUid: new Map(
818
+ (catalog.dimensionTables ?? [])
819
+ .filter((item) => item?.uid)
820
+ .map((item) => [item.uid, item]),
821
+ ),
822
+ },
823
+ globalByName: new Map(),
824
+ };
825
+ for (const resource of ["timeSeries", "dimensions", "measures"])
826
+ for (const item of catalog[resource] ?? [])
827
+ addGlobalNames(registry.globalByName, resource, item, item.id);
828
+ for (const model of catalog.models ?? [])
829
+ if (model?.name)
830
+ addGlobalNames(
831
+ registry.globalByName,
832
+ "models",
833
+ { ...model, names: [model.name] },
834
+ model.uid,
835
+ );
836
+ return registry;
837
+ }
838
+
839
+ function addGlobalNames(index, resource, item, id) {
840
+ for (const name of item.names ?? []) {
841
+ const key = normalizeName(name);
842
+ const entries = index.get(key) ?? [];
843
+ entries.push({ resource, id, item });
844
+ index.set(key, entries);
845
+ }
846
+ }
847
+
848
+ export function resolvePlanReuse(plan, registry) {
849
+ const result = structuredClone(plan);
850
+ for (const resource of ["timeSeries", "dimensions", "measures"])
851
+ result[resource] = resolveResourceItems(
852
+ resource,
853
+ result[resource] ?? [],
854
+ registry,
855
+ );
856
+ result.dimensionTables = (result.dimensionTables ?? []).map((table) => {
857
+ if (table.uid) {
858
+ if (table.definition)
859
+ throw new DatarcError(
860
+ "复用维度表 uid 与新建 definition 互斥",
861
+ "INVALID_PLAN",
862
+ );
863
+ if (!registry.dimensionTables.byUid.has(table.uid))
864
+ throw new DatarcError(
865
+ `维度表 uid ${table.uid} 不在当前工作区目录中`,
866
+ "UNKNOWN_RESOURCE",
867
+ );
868
+ return table;
869
+ }
870
+ if (!table.definition) return table;
871
+ return {
872
+ ...table,
873
+ definition: {
874
+ ...table.definition,
875
+ dimensions: resolveResourceItems(
876
+ "dimensions",
877
+ table.definition.dimensions ?? [],
878
+ registry,
879
+ ),
880
+ },
881
+ };
882
+ });
883
+ return result;
884
+ }
885
+
886
+ function buildResourceIndex(values = []) {
887
+ const byId = new Map();
888
+ const byName = new Map();
889
+ for (const item of values ?? []) {
890
+ if (item?.id === undefined) continue;
891
+ byId.set(Number(item.id), item);
892
+ for (const name of item.names ?? []) {
893
+ const key = normalizeName(name);
894
+ const matches = byName.get(key) ?? [];
895
+ matches.push(item);
896
+ byName.set(key, matches);
897
+ }
898
+ }
899
+ return { byId, byName };
900
+ }
901
+
902
+ function resolveResourceItems(resource, items, registry) {
903
+ return items.map((item) => {
904
+ if (!item || typeof item !== "object")
905
+ throw new DatarcError("绑定项必须是对象", "INVALID_PLAN");
906
+ if (item.id !== undefined && item.id !== null) {
907
+ const id = normalizeResourceId(item.id);
908
+ validateRegistryBinding(resource, id, registry);
909
+ return { ...item, id };
910
+ }
911
+ if (!item.definition?.names?.length) return item;
912
+ const definition = validateDefinition(resource, item.definition);
913
+ for (const name of definition.names) {
914
+ const conflicts = (
915
+ registry.globalByName?.get(normalizeName(name)) ?? []
916
+ ).filter((entry) => entry.resource !== resource);
917
+ if (conflicts.length)
918
+ throw new DatarcError(
919
+ `名称 ${name} 已被其他类型资源使用`,
920
+ "INCOMPATIBLE_RESOURCE",
921
+ {
922
+ conflicts: conflicts.map(({ resource: type, id }) => ({
923
+ resource: type,
924
+ id,
925
+ })),
926
+ },
927
+ );
928
+ }
929
+ const matches = new Map();
930
+ for (const name of definition.names)
931
+ for (const candidate of registry[resource].byName.get(
932
+ normalizeName(name),
933
+ ) ?? [])
934
+ matches.set(Number(candidate.id), candidate);
935
+ if (!matches.size) return { ...item, definition };
936
+ if (matches.size !== 1)
937
+ throw new DatarcError(
938
+ `${definition.names.join("、")} 匹配到多个已有资源`,
939
+ "AMBIGUOUS_RESOURCE",
940
+ );
941
+ const existing = [...matches.values()][0];
942
+ const existingNames = new Set((existing.names ?? []).map(normalizeName));
943
+ if (
944
+ definition.names.some((name) => !existingNames.has(normalizeName(name)))
945
+ )
946
+ throw new DatarcError(
947
+ "已有资源缺少计划中的别名,请先使用 datarc-workspace-keywords 更新",
948
+ "REUSE_REQUIRES_UPDATE",
949
+ );
950
+ assertCompatibleDefinition(resource, definition, existing);
951
+ const { definition: _definition, ...binding } = item;
952
+ return { ...binding, id: Number(existing.id) };
953
+ });
954
+ }
955
+
956
+ function validateRegistryBinding(resource, id, registry) {
957
+ if (!registry) return;
958
+ const existing = registry[resource]?.byId.get(Number(id));
959
+ if (!existing)
960
+ throw new DatarcError(
961
+ `${resource} id ${id} 不在当前工作区目录中`,
962
+ "UNKNOWN_RESOURCE",
963
+ );
964
+ if (resource === "measures" && existing.formula)
965
+ throw new DatarcError(
966
+ "衍生指标不能绑定模型,请使用 datarc-workspace-keywords",
967
+ "INVALID_PLAN",
968
+ );
969
+ }
970
+
971
+ function assertCompatibleDefinition(resource, requested, existing) {
972
+ if (resource === "measures" && existing.formula)
973
+ throw new DatarcError(
974
+ "同名资源是衍生指标,不能绑定模型",
975
+ "INCOMPATIBLE_RESOURCE",
976
+ );
977
+ const fields = {
978
+ timeSeries: ["type", "format", "timeUnit", "minTimeUnit"],
979
+ dimensions: ["type", "format", "baseField"],
980
+ measures: ["cumulative"],
981
+ }[resource];
982
+ for (const field of fields) {
983
+ if (requested[field] === undefined) continue;
984
+ const expected =
985
+ resource === "timeSeries" && field === "minTimeUnit"
986
+ ? (requested.minTimeUnit ?? requested.timeUnit)
987
+ : requested[field];
988
+ const actual =
989
+ resource === "timeSeries" && field === "minTimeUnit"
990
+ ? (existing.minTimeUnit ?? existing.timeUnit)
991
+ : (existing[field] ??
992
+ (["cumulative", "isKeyword"].includes(field) ? false : undefined));
993
+ if (stableValue(expected) !== stableValue(actual))
994
+ throw new DatarcError(
995
+ `同名 ${resource} 的 ${field} 语义不兼容`,
996
+ "INCOMPATIBLE_RESOURCE",
997
+ );
998
+ }
999
+ }
1000
+
1001
+ function resolveDefaultTimeSeries(items, bindings, legacyDefault) {
1002
+ const marked = items
1003
+ .map((item, index) => (item.default === true ? index : -1))
1004
+ .filter((index) => index >= 0);
1005
+ if (marked.length > 1)
1006
+ throw new DatarcError("同一模型只能有一个默认时间维度", "INVALID_PLAN");
1007
+ let index;
1008
+ if (marked.length === 1) index = marked[0];
1009
+ else if (bindings.length === 1) index = 0;
1010
+ else if (legacyDefault !== undefined) {
1011
+ index = bindings.findIndex((binding) =>
1012
+ sameIdentity(bindingIdentity(binding), legacyDefault),
1013
+ );
1014
+ if (index < 0)
1015
+ throw new DatarcError(
1016
+ "defaultTimeSeries 必须属于当前模型",
1017
+ "INVALID_PLAN",
1018
+ );
1019
+ } else
1020
+ throw new DatarcError(
1021
+ "多个时间维度时必须标记一个默认时间维度",
1022
+ "INVALID_PLAN",
1023
+ );
1024
+ const selected = bindingIdentity(bindings[index]);
1025
+ if (legacyDefault !== undefined && !sameIdentity(selected, legacyDefault))
1026
+ throw new DatarcError(
1027
+ "default 标记与 modelOptions.defaultTimeSeries 冲突",
1028
+ "INVALID_PLAN",
1029
+ );
1030
+ return selected;
1031
+ }
1032
+
1033
+ function validateUniqueBindings(model, definitions, registry) {
1034
+ for (const [resource, bindings] of [
1035
+ ["timeSeries", model.timeSeries],
1036
+ ["measures", model.measures],
1037
+ ])
1038
+ assertUniqueIdentities(resource, bindings);
1039
+ const tableUids = model.dimensionTables.map((table) => table.uid);
1040
+ if (new Set(tableUids).size !== tableUids.length)
1041
+ throw new DatarcError(
1042
+ "同一模型不能重复引用同一维度表",
1043
+ "DUPLICATE_BINDING",
1044
+ );
1045
+ const dimensions = [...model.dimensions];
1046
+ for (const table of definitions.dimensionTables)
1047
+ dimensions.push(...(table.dimensions ?? []));
1048
+ if (registry)
1049
+ for (const table of model.dimensionTables) {
1050
+ const existing = registry.dimensionTables.byUid.get(table.uid);
1051
+ if (existing)
1052
+ dimensions.push(
1053
+ ...(existing.dimensions ?? []).filter((item) => item.id),
1054
+ );
1055
+ }
1056
+ assertUniqueIdentities("dimensions", dimensions);
1057
+ const names = [
1058
+ model.name,
1059
+ ...["timeSeries", "dimensions", "measures"].flatMap((resource) =>
1060
+ definitions[resource].flatMap((item) => item.names ?? []),
1061
+ ),
1062
+ ]
1063
+ .filter(Boolean)
1064
+ .map(normalizeName);
1065
+ if (new Set(names).size !== names.length)
1066
+ throw new DatarcError(
1067
+ "模型名与新建关键词名称不能跨类型重复",
1068
+ "DUPLICATE_BINDING",
1069
+ );
1070
+ const modelNameConflicts = model.name
1071
+ ? (registry?.globalByName?.get(normalizeName(model.name)) ?? []).filter(
1072
+ (entry) =>
1073
+ entry.resource !== "models" || String(entry.id) !== String(model.uid),
1074
+ )
1075
+ : [];
1076
+ if (modelNameConflicts.length)
1077
+ throw new DatarcError(
1078
+ `模型名 ${model.name} 已被工作区资源使用`,
1079
+ "INCOMPATIBLE_RESOURCE",
1080
+ );
1081
+ }
1082
+
1083
+ function validateUniqueFactFields(model) {
1084
+ const byField = new Map();
1085
+ for (const [resource, bindings] of [
1086
+ ["timeSeries", model.timeSeries],
1087
+ ["dimensions", model.dimensions],
1088
+ ["measures", model.measures],
1089
+ ])
1090
+ for (const [index, binding] of bindings.entries()) {
1091
+ if (!binding.field) continue;
1092
+ const entries = byField.get(binding.field) ?? [];
1093
+ entries.push({ resource, index });
1094
+ byField.set(binding.field, entries);
1095
+ }
1096
+ const duplicates = [...byField.entries()]
1097
+ .filter(([, bindings]) => bindings.length > 1)
1098
+ .map(([field, bindings]) => ({
1099
+ field,
1100
+ count: bindings.length,
1101
+ bindings,
1102
+ }));
1103
+ if (!duplicates.length) return;
1104
+ const summary = duplicates
1105
+ .map(({ field, count }) => `${field}(${count} 次)`)
1106
+ .join("、");
1107
+ const resources = new Set(
1108
+ duplicates.flatMap(({ bindings }) =>
1109
+ bindings.map(({ resource }) => resource),
1110
+ ),
1111
+ );
1112
+ const suggestions = ["请按绑定位置为每个重复字段保留一条直接绑定"];
1113
+ if (resources.has("timeSeries"))
1114
+ suggestions.push("重复的时间维度请核对业务含义后改绑其他字段或移除");
1115
+ if (resources.has("dimensions"))
1116
+ suggestions.push("重复的普通维度请核对业务含义后改绑其他字段或移除");
1117
+ if (resources.has("measures"))
1118
+ suggestions.push(
1119
+ "重复的指标可改用 sql 自定义指标,或在模型 ready 后创建衍生指标",
1120
+ );
1121
+ const suggestion = suggestions.join(";");
1122
+ throw new DatarcError(
1123
+ `事实表字段重复绑定:${summary}。一个物理字段只能绑定一次;${suggestion}`,
1124
+ "DUPLICATE_FACT_FIELD_BINDING",
1125
+ {
1126
+ duplicates,
1127
+ suggestion,
1128
+ },
1129
+ );
1130
+ }
1131
+
1132
+ function assertUniqueIdentities(resource, bindings) {
1133
+ const identities = bindings.map((binding) =>
1134
+ binding.id !== undefined ? `id:${binding.id}` : `uid:${binding.uid}`,
1135
+ );
1136
+ if (new Set(identities).size !== identities.length)
1137
+ throw new DatarcError(
1138
+ `同一模型不能重复绑定同一 ${resource}`,
1139
+ "DUPLICATE_BINDING",
1140
+ );
1141
+ }
1142
+
1143
+ function bindingIdentity(binding) {
1144
+ return binding.id !== undefined ? binding.id : binding.uid;
1145
+ }
1146
+
1147
+ function sameIdentity(left, right) {
1148
+ return String(left) === String(right);
1149
+ }
1150
+
1151
+ function normalizeResourceId(value) {
1152
+ const id = Number(value);
1153
+ if (!Number.isInteger(id) || id <= 0)
1154
+ throw new DatarcError(`关键词 id 必须是正整数:${value}`, "INVALID_PLAN");
1155
+ return id;
1156
+ }
1157
+
1158
+ function normalizeName(value) {
1159
+ return String(value).trim().toLocaleLowerCase();
1160
+ }
1161
+
1162
+ function stableValue(value) {
1163
+ if (!value || typeof value !== "object") return JSON.stringify(value);
1164
+ if (Array.isArray(value)) return `[${value.map(stableValue).join(",")}]`;
1165
+ return `{${Object.keys(value)
1166
+ .sort()
1167
+ .map((key) => `${JSON.stringify(key)}:${stableValue(value[key])}`)
1168
+ .join(",")}}`;
1169
+ }
1170
+
1171
+ function validateDefinition(resource, value) {
1172
+ if (!Array.isArray(value.names) || !value.names.length)
1173
+ throw new DatarcError("新关键词 definition.names 不能为空", "INVALID_PLAN");
1174
+ if (["dimensions", "timeSeries"].includes(resource)) {
1175
+ if (!value.type || !FORMATS.includes(value.format))
1176
+ throw new DatarcError(
1177
+ "新维度和时间维度需要合法 type、format",
1178
+ "INVALID_PLAN",
1179
+ );
1180
+ }
1181
+ const result = structuredClone(value);
1182
+ if (resource === "timeSeries") {
1183
+ const timeUnit = Number(value.timeUnit);
1184
+ if (!TIME_UNIT_LEVEL.has(timeUnit))
1185
+ throw new DatarcError(
1186
+ "新时间维度 definition.timeUnit 必须是合法时间单位",
1187
+ "INVALID_PLAN",
1188
+ );
1189
+ const minTimeUnit = Number(value.minTimeUnit ?? timeUnit);
1190
+ if (!TIME_UNIT_LEVEL.has(minTimeUnit))
1191
+ throw new DatarcError("minTimeUnit 必须是合法时间单位", "INVALID_PLAN");
1192
+ if (TIME_UNIT_LEVEL.get(timeUnit) < TIME_UNIT_LEVEL.get(minTimeUnit))
1193
+ throw new DatarcError("timeUnit 不能细于 minTimeUnit", "INVALID_PLAN");
1194
+ if (
1195
+ DAY_OR_COARSER_TYPES.has(value.type) &&
1196
+ TIME_UNIT_LEVEL.get(minTimeUnit) < TIME_UNIT_LEVEL.get(3)
1197
+ )
1198
+ throw new DatarcError("日期编码时间维度不能细于日", "INVALID_PLAN");
1199
+ if (
1200
+ MONTH_OR_COARSER_TYPES.has(value.type) &&
1201
+ TIME_UNIT_LEVEL.get(minTimeUnit) < TIME_UNIT_LEVEL.get(5)
1202
+ )
1203
+ throw new DatarcError("年月编码时间维度不能细于月", "INVALID_PLAN");
1204
+ result.timeUnit = timeUnit;
1205
+ result.minTimeUnit = minTimeUnit;
1206
+ }
1207
+ if (resource === "measures") {
1208
+ if (value.formula)
1209
+ throw new DatarcError(
1210
+ "衍生指标不能绑定模型,请使用 datarc-workspace-keywords",
1211
+ "INVALID_PLAN",
1212
+ );
1213
+ if (typeof value.cumulative !== "boolean")
1214
+ throw new DatarcError(
1215
+ "指标 definition.cumulative 必须显式为布尔值",
1216
+ "INVALID_PLAN",
1217
+ );
1218
+ result.cumulative = value.cumulative;
1219
+ }
1220
+ if (resource === "dimensions") {
1221
+ if (typeof value.isKeyword !== "boolean")
1222
+ throw new DatarcError(
1223
+ "维度 definition.isKeyword 必须显式为布尔值",
1224
+ "INVALID_PLAN",
1225
+ );
1226
+ if (value.isKeyword === true)
1227
+ throw new DatarcError(
1228
+ "基础建模阶段维度搜索必须关闭,请将开启请求放入后置搜索计划",
1229
+ "SEARCH_ACTION_REQUIRED",
1230
+ );
1231
+ result.isKeyword = false;
1232
+ if (value.type === "choice") {
1233
+ const base = value.baseField ?? {};
1234
+ if (
1235
+ !base.choice ||
1236
+ typeof base.choice !== "object" ||
1237
+ Array.isArray(base.choice) ||
1238
+ !Object.keys(base.choice).length ||
1239
+ base.typeAfterMap !== "str"
1240
+ )
1241
+ throw new DatarcError(
1242
+ "choice 维度需要非空映射并映射到 str,请核对维度定义",
1243
+ "INVALID_PLAN",
1244
+ );
1245
+ if (
1246
+ base.typeBeforeMap === "bool" &&
1247
+ Object.keys(base.choice).sort().join(",") !== "false,true"
1248
+ )
1249
+ throw new DatarcError(
1250
+ "bool choice 必须恰好映射 true 和 false,请核对枚举值",
1251
+ "INVALID_PLAN",
1252
+ );
1253
+ }
1254
+ }
1255
+ if (value.format && !FORMATS.includes(value.format))
1256
+ throw new DatarcError("format 不在合法枚举中", "INVALID_PLAN");
1257
+ return result;
1258
+ }
1259
+
1260
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
1261
+ await runCli(() => execute(process.argv.slice(2)));