@boringparts/lioni 0.0.0-stage → 0.4.2

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.
package/dist/index.js ADDED
@@ -0,0 +1,3862 @@
1
+ import { A as defineChecker, B as validateQaSuppressions, C as validateComparisonResult, D as TranslationIdentityContractError, E as writeTranslationRequests, F as QaSuppressionFormatError, H as MemoScopeClosedError, I as createQaSuppression, L as upsertQaSuppressionFromReport, N as StandardSchemaContractError, O as QualityCheckerContractError, P as assertJsonValue, R as validateQaSuppression, S as validateComparisonInput, T as validateTranslationWriteRequest, U as createMemoScope, W as createQualityProfiler, _ as replaceComparisonBaseline, a as readSourceSnapshot, b as compareSnapshots, c as applyUpdatePlan, d as defaultUpdatePolicy, f as previewUpdate, g as recordComparisonBaseline, h as ComparisonBaselineIncompleteSnapshotError, i as readProjectSnapshot, k as QualityDataReaderContractError, l as update, m as ComparisonBaselineFormatError, n as defineConfig, o as runQa, p as validateUpdatePlan, r as readComparisonSnapshot, t as DuplicateTranslationUnitKeyError, u as createUpdatePlan, v as validateComparisonBaseline, w as validateTranslationCandidate, x as defaultCompare, y as ComparisonContractError, z as validateQaSuppressionFile } from "./dist-BjI3h4o3.js";
2
+ import { n as formatQualityReport, r as isQualityReportPassing, t as decideQualityReport } from "./report-EsWS84c0.js";
3
+ import { a as contractIssue, c as createTermbase, d as selectTerms, i as assertUsageConflicts, l as jsonValueSchema, n as parseTermbaseYaml, o as contractIssues, r as TermContractError, s as copyJson, t as TermbaseYamlError, u as nonemptyTextSchema } from "./yaml-DX1EEaWD.js";
4
+ import { z } from "zod";
5
+ import { baseCompile } from "@intlify/message-compiler";
6
+ // ../../packages/checks/dist/translation.js
7
+ const subjectSchema = z.object({
8
+ key: z.string(),
9
+ language: z.string()
10
+ });
11
+ const sameTextInputSchema = subjectSchema.extend({
12
+ source: z.string(),
13
+ target: z.string(),
14
+ sourceRange: z.unknown(),
15
+ targetRange: z.unknown()
16
+ }).nullable();
17
+ /** 只检查是否提供了候选正文。空字符串也是已提供的译文。 */
18
+ function createMissingTranslationChecker() {
19
+ return defineChecker.withTypes()({
20
+ id: "missing-translation",
21
+ version: "checks.missing-translation/v1",
22
+ inputSchema: subjectSchema.nullable(),
23
+ prepare({ candidate, association }) {
24
+ if (candidate !== null) return null;
25
+ if (association.status !== "missing") throw new Error("缺少可靠的译文读取依据,无法判断是否缺译。");
26
+ return {
27
+ key: association.sourceKey,
28
+ language: association.language
29
+ };
30
+ },
31
+ check(subject) {
32
+ if (subject === null) return [];
33
+ return [{
34
+ severity: "error",
35
+ object: {
36
+ kind: "translation-unit",
37
+ ...subject
38
+ },
39
+ location: {
40
+ ...subject,
41
+ range: null
42
+ },
43
+ message: "尚未提供译文。",
44
+ evidence: []
45
+ }];
46
+ }
47
+ });
48
+ }
49
+ /** 仅对字符串正文执行精确比较,保留空格、大小写和 Unicode 表示差异。 */
50
+ function createSameTextChecker() {
51
+ return defineChecker.withTypes()({
52
+ id: "same-text",
53
+ version: "checks.same-text/v1",
54
+ inputSchema: sameTextInputSchema,
55
+ prepare({ snapshot, sourceUnit, translation, candidate, association }) {
56
+ if (candidate === null) {
57
+ if (association.status !== "missing") throw new Error("无法读取候选正文以检查同文。");
58
+ return null;
59
+ }
60
+ if (sourceUnit.bodyAvailability !== "available") throw new Error("无法读取原文正文以检查同文。");
61
+ const source = sourceUnit.unit.source;
62
+ const target = candidate.content;
63
+ if (typeof source !== "string" || typeof target !== "string") throw new Error("无法取得原文或候选译文的字符串正文。");
64
+ return {
65
+ key: association.sourceKey,
66
+ language: association.language,
67
+ source,
68
+ target,
69
+ sourceRange: snapshot.source.read.scopes[sourceUnit.scopeIndex]?.range ?? null,
70
+ targetRange: translation?.range ?? null
71
+ };
72
+ },
73
+ check(input) {
74
+ if (input === null || input.source !== input.target) return [];
75
+ const object = {
76
+ kind: "translation-unit",
77
+ key: input.key,
78
+ language: input.language
79
+ };
80
+ const sourceLocation = {
81
+ language: null,
82
+ range: input.sourceRange,
83
+ key: input.key
84
+ };
85
+ const location = {
86
+ key: input.key,
87
+ language: input.language,
88
+ range: input.targetRange
89
+ };
90
+ return [{
91
+ severity: "error",
92
+ object,
93
+ location,
94
+ message: "译文与原文完全相同。",
95
+ evidence: [{
96
+ role: "source",
97
+ object: {
98
+ kind: "source-unit",
99
+ key: input.key
100
+ },
101
+ location: sourceLocation,
102
+ value: input.source
103
+ }, {
104
+ role: "target",
105
+ object,
106
+ location,
107
+ value: input.target
108
+ }]
109
+ }];
110
+ }
111
+ });
112
+ }
113
+ // ../../packages/checks/dist/numbers.js
114
+ const qualityLocationSchema$2 = z.object({
115
+ language: z.string().nullable(),
116
+ range: z.unknown(),
117
+ key: z.string().optional()
118
+ }).passthrough();
119
+ const numberTextInputSchema = z.object({
120
+ source: z.string(),
121
+ target: z.string(),
122
+ subject: z.object({
123
+ key: z.string(),
124
+ language: z.string()
125
+ }),
126
+ sourceLocation: qualityLocationSchema$2,
127
+ targetLocation: qualityLocationSchema$2,
128
+ targetContent: z.unknown()
129
+ });
130
+ /** 默认比较字符串正文;结构化正文可通过 prepare 明确提供适配。 */
131
+ function createNumberCheckerImplementation(options = {}) {
132
+ if (options === null || typeof options !== "object" || Array.isArray(options)) throw new TypeError("数字检查器选项必须是对象。");
133
+ if (options.prepare !== void 0 && typeof options.prepare !== "function") throw new TypeError("数字检查器 prepare 必须是函数。");
134
+ return defineChecker.withTypes()({
135
+ id: "number-correspondence",
136
+ version: "checks.number-correspondence/v3",
137
+ inputSchema: numberTextInputSchema.nullable(),
138
+ async prepare(input) {
139
+ if (input.candidate === null) {
140
+ if (input.association.status !== "missing") throw new Error("候选正文不可用。");
141
+ return null;
142
+ }
143
+ const preparation = options.prepare === void 0 ? defaultNumberPreparation(input) : await options.prepare(input);
144
+ if (preparation === null) return null;
145
+ if (typeof preparation !== "object" || Array.isArray(preparation)) throw new QualityCheckerContractError("number-correspondence", "prepare", "的 prepare 返回了无效结果。");
146
+ if (input.sourceUnit.bodyAvailability !== "available") throw new Error("原文正文不可用,无法核对数字。");
147
+ const sourceLocation = {
148
+ language: null,
149
+ range: input.snapshot.source.read.scopes[input.sourceUnit.scopeIndex]?.range ?? null
150
+ };
151
+ const targetLocation = {
152
+ language: input.candidate.language,
153
+ range: input.translation?.range ?? null,
154
+ key: input.candidate.sourceKey
155
+ };
156
+ return {
157
+ source: preparation.source,
158
+ target: preparation.target,
159
+ subject: {
160
+ key: input.candidate.sourceKey,
161
+ language: input.candidate.language
162
+ },
163
+ sourceLocation: preparation.sourceLocation ?? sourceLocation,
164
+ targetLocation: preparation.targetLocation ?? targetLocation,
165
+ targetContent: input.candidate.content
166
+ };
167
+ },
168
+ check: (input) => input === null ? [] : compareNumberText(input)
169
+ });
170
+ }
171
+ function createNumberCheckerWithTypes() {
172
+ return (options = {}) => createNumberCheckerImplementation(options);
173
+ }
174
+ /** 内置版本、默认文本提取和定位由本包维护。 */
175
+ const createNumberChecker = Object.assign(createNumberCheckerImplementation, { withTypes: createNumberCheckerWithTypes });
176
+ function defaultNumberPreparation(input) {
177
+ const source = input.sourceUnit.unit.source;
178
+ const target = input.candidate?.content;
179
+ if (typeof source !== "string" || typeof target !== "string") throw new Error("无法取得原文或候选译文的字符串正文。");
180
+ return {
181
+ source,
182
+ target
183
+ };
184
+ }
185
+ function compareNumberText(input) {
186
+ const sourceNumbers = numbersIn(input.source);
187
+ const targetNumbers = numbersIn(input.target);
188
+ const missing = difference(sourceNumbers, targetNumbers);
189
+ const extra = difference(targetNumbers, sourceNumbers);
190
+ const object = {
191
+ kind: "translation-unit",
192
+ key: input.subject.key,
193
+ language: input.subject.language
194
+ };
195
+ const evidence = [{
196
+ role: "source",
197
+ object: {
198
+ kind: "translation-unit",
199
+ key: input.subject.key
200
+ },
201
+ location: input.sourceLocation,
202
+ value: input.source
203
+ }, {
204
+ role: "target",
205
+ object,
206
+ location: input.targetLocation,
207
+ value: input.targetContent
208
+ }];
209
+ return missing.length === 0 && extra.length === 0 ? [] : [{
210
+ severity: "error",
211
+ object,
212
+ location: input.targetLocation,
213
+ message: [...missing.length === 0 ? [] : [`译文缺少数字:${missing.join("、")}。`], ...extra.length === 0 ? [] : [`译文多出数字:${extra.join("、")}。`]].join(""),
214
+ evidence
215
+ }];
216
+ }
217
+ function numbersIn(text) {
218
+ const counts = /* @__PURE__ */ new Map();
219
+ for (const [number] of text.matchAll(/[+-]?[0-9]+(?:\.[0-9]+)?/gu)) counts.set(number, (counts.get(number) ?? 0) + 1);
220
+ return counts;
221
+ }
222
+ function difference(left, right) {
223
+ return [...left.entries()].flatMap(([number, count]) => Array(Math.max(0, count - (right.get(number) ?? 0))).fill(number));
224
+ }
225
+ // ../../packages/terminology/dist/input.js
226
+ const termRangeSchema = z.compile(z.object({
227
+ start: z.int().nonnegative(),
228
+ end: z.int().nonnegative()
229
+ }));
230
+ function splitsSurrogatePair(text, boundary) {
231
+ if (boundary <= 0 || boundary >= text.length) return false;
232
+ const before = text.charCodeAt(boundary - 1);
233
+ const after = text.charCodeAt(boundary);
234
+ return before >= 55296 && before <= 56319 && after >= 56320 && after <= 57343;
235
+ }
236
+ function validTermRange(text, range) {
237
+ return range.end > range.start && range.end <= text.length && !splitsSurrogatePair(text, range.start) && !splitsSurrogatePair(text, range.end);
238
+ }
239
+ const termFragmentSchema = z.object({
240
+ ref: jsonValueSchema,
241
+ text: z.string(),
242
+ protectedRanges: z.array(termRangeSchema).exactOptional()
243
+ }).superRefine((fragment, context) => {
244
+ fragment.protectedRanges?.forEach((range, index) => {
245
+ if (!validTermRange(fragment.text, range)) context.addIssue({
246
+ code: "custom",
247
+ message: "保护区间必须是正文内非空的 UTF-16 半开区间。",
248
+ path: ["protectedRanges", index]
249
+ });
250
+ });
251
+ });
252
+ const termTextInputSchema = z.compile(z.object({
253
+ language: nonemptyTextSchema,
254
+ fragments: z.array(termFragmentSchema),
255
+ /** 省略表示宿主已提供此侧完整的比较范围。 */
256
+ complete: z.boolean().exactOptional()
257
+ }));
258
+ const comparisonGroupSchema = z.object({
259
+ ref: jsonValueSchema.exactOptional(),
260
+ source: termTextInputSchema,
261
+ target: termTextInputSchema
262
+ });
263
+ const comparisonContract = z.compile(z.object({ groups: z.array(comparisonGroupSchema) }));
264
+ function validateTextInput(value) {
265
+ if (!termTextInputSchema.validate(value)) throw new TermContractError("input", contractIssues(termTextInputSchema.safeParse(value).error));
266
+ }
267
+ const termComparisonInputSchema = { "~standard": {
268
+ version: 1,
269
+ vendor: "lioni-terminology",
270
+ validate(value) {
271
+ try {
272
+ const snapshot = copyJson(value, "input");
273
+ return comparisonContract.validate(snapshot) ? { value: snapshot } : { issues: contractIssues(comparisonContract.safeParse(snapshot).error) };
274
+ } catch (error) {
275
+ if (error instanceof TermContractError) return { issues: error.issues };
276
+ throw error;
277
+ }
278
+ }
279
+ } };
280
+ function comparisonSnapshot(value) {
281
+ const snapshot = copyJson(value, "input");
282
+ if (!comparisonContract.validate(snapshot)) throw new TermContractError("input", contractIssues(comparisonContract.safeParse(snapshot).error));
283
+ return snapshot;
284
+ }
285
+ function sameJson(left, right) {
286
+ if (Object.is(left, right)) return true;
287
+ if (typeof left !== "object" || left === null || typeof right !== "object" || right === null) return false;
288
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
289
+ const leftKeys = Object.keys(left);
290
+ const rightKeys = Object.keys(right);
291
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.hasOwn(right, key) && sameJson(left[key], right[key]));
292
+ }
293
+ // ../../packages/text-analysis/dist/types.js
294
+ var TextAnalysisContractError = class extends Error {
295
+ code;
296
+ constructor(code, message) {
297
+ super(message);
298
+ this.name = "TextAnalysisContractError";
299
+ this.code = code;
300
+ }
301
+ };
302
+ const textRangeSchema = z.compile(z.object({
303
+ start: z.int().nonnegative(),
304
+ end: z.int().nonnegative()
305
+ }));
306
+ const textInputSchema = z.compile(z.object({
307
+ text: z.string(),
308
+ language: z.string().min(1),
309
+ protectedRanges: z.array(textRangeSchema).exactOptional()
310
+ }));
311
+ const analysisIssueSchema = z.object({
312
+ code: z.string().min(1),
313
+ message: z.string(),
314
+ range: textRangeSchema.exactOptional()
315
+ });
316
+ const textTokenSchema = textRangeSchema.extend({
317
+ kind: z.string().min(1),
318
+ identity: z.string().min(1).exactOptional(),
319
+ value: z.unknown().exactOptional(),
320
+ /** 显式保护该区间;种类名称不隐式决定保护行为。 */
321
+ protect: z.boolean().exactOptional()
322
+ });
323
+ const recognitionSchema = z.object({
324
+ tokens: z.array(textTokenSchema),
325
+ complete: z.boolean(),
326
+ issues: z.array(analysisIssueSchema)
327
+ });
328
+ const wordTokenSchema = textRangeSchema.extend({ text: z.string() });
329
+ const wordAnalysisSchema = z.compile(z.object({
330
+ words: z.array(wordTokenSchema),
331
+ boundaries: z.array(z.int().nonnegative()),
332
+ /** 结构和词界阶段均完整时为 true;两阶段的问题按顺序合并。 */
333
+ complete: z.boolean(),
334
+ issues: z.array(analysisIssueSchema)
335
+ }));
336
+ function analysisError(code, error) {
337
+ return new TextAnalysisContractError(code, error.issues.map((issue) => `${issue.path.map(String).join(".") || "输入"}:${issue.message}`).join(";"));
338
+ }
339
+ // ../../packages/text-analysis/dist/ranges.js
340
+ const emptyRanges = Object.freeze([]);
341
+ function isCodePointBoundary$1(text, offset) {
342
+ if (offset <= 0 || offset >= text.length) return true;
343
+ const previous = text.charCodeAt(offset - 1);
344
+ const next = text.charCodeAt(offset);
345
+ return !(previous >= 55296 && previous <= 56319 && next >= 56320 && next <= 57343);
346
+ }
347
+ function validateInput(input) {
348
+ if (!textInputSchema.validate(input)) throw analysisError("invalid-input", textInputSchema.safeParse(input).error);
349
+ }
350
+ function validateRange(text, range, allowEmpty = false) {
351
+ if (!textRangeSchema.validate(range)) throw analysisError("invalid-range", textRangeSchema.safeParse(range).error);
352
+ validateRangeBounds(text, range, allowEmpty);
353
+ }
354
+ /** 在形状已经通过 schema 后,只检查区间与当前原文的关系。 */
355
+ function validateRangeBounds(text, range, allowEmpty = false) {
356
+ if (range.end > text.length || (allowEmpty ? range.start > range.end : range.start >= range.end) || !isCodePointBoundary$1(text, range.start) || !isCodePointBoundary$1(text, range.end)) throw new TextAnalysisContractError("invalid-range", "区间必须是原文内不切开代理对的 UTF-16 半开区间。");
357
+ }
358
+ function mergeRanges(text, ranges) {
359
+ const sorted = ranges.map((range) => {
360
+ validateRange(text, range);
361
+ return {
362
+ start: range.start,
363
+ end: range.end
364
+ };
365
+ });
366
+ sorted.sort((a, b) => a.start - b.start || a.end - b.end);
367
+ const merged = [];
368
+ for (const range of sorted) {
369
+ const previous = merged.at(-1);
370
+ if (previous !== void 0 && range.start <= previous.end) previous.end = Math.max(previous.end, range.end);
371
+ else merged.push(range);
372
+ }
373
+ return Object.freeze(merged.map((range) => Object.freeze(range)));
374
+ }
375
+ function complementRanges(text, excluded) {
376
+ const ranges = [];
377
+ let start = 0;
378
+ for (const range of excluded) {
379
+ if (start < range.start) ranges.push(Object.freeze({
380
+ start,
381
+ end: range.start
382
+ }));
383
+ start = range.end;
384
+ }
385
+ if (start < text.length) ranges.push(Object.freeze({
386
+ start,
387
+ end: text.length
388
+ }));
389
+ return Object.freeze(ranges);
390
+ }
391
+ function fitsRange(range, available) {
392
+ return available.some((gap) => gap.start <= range.start && range.end <= gap.end);
393
+ }
394
+ // ../../packages/text-analysis/dist/templates.js
395
+ const slotIdentitySchema = z.object({
396
+ kind: z.string().min(1),
397
+ identity: z.string().min(1)
398
+ });
399
+ /** 只抽象明确选中的 token;保护区间和未抽象内容仍作为原样文本参与比较。 */
400
+ function createTemplateSignature(analysis, options) {
401
+ if (!analysis.complete) throw new TextAnalysisContractError("incomplete-structure", "结构分析不完整,不能生成完整模板签名。");
402
+ const parts = [];
403
+ const slots = [];
404
+ let cursor = 0;
405
+ let previousEnd = -1;
406
+ for (const token of analysis.tokens) {
407
+ validateRange(analysis.text, token);
408
+ if (token.start < previousEnd) throw new TextAnalysisContractError("overlapping-token", "模板 token 必须按原文顺序且不重叠。");
409
+ previousEnd = token.end;
410
+ const identity = options.abstract(token);
411
+ if (identity === void 0) continue;
412
+ if (!slotIdentitySchema.safeParse(identity).success) throw new TextAnalysisContractError("invalid-slot", "槽位种类与身份必须非空。");
413
+ if (token.start > cursor) parts.push(Object.freeze({
414
+ type: "text",
415
+ text: analysis.text.slice(cursor, token.start)
416
+ }));
417
+ parts.push(Object.freeze({
418
+ type: "slot",
419
+ kind: identity.kind,
420
+ identity: identity.identity
421
+ }));
422
+ slots.push(Object.freeze({
423
+ start: token.start,
424
+ end: token.end,
425
+ kind: identity.kind,
426
+ identity: identity.identity,
427
+ raw: analysis.text.slice(token.start, token.end),
428
+ ...token.value === void 0 ? {} : { value: token.value }
429
+ }));
430
+ cursor = token.end;
431
+ }
432
+ if (cursor < analysis.text.length) parts.push(Object.freeze({
433
+ type: "text",
434
+ text: analysis.text.slice(cursor)
435
+ }));
436
+ return Object.freeze({
437
+ parts: Object.freeze(parts),
438
+ slots: Object.freeze(slots)
439
+ });
440
+ }
441
+ /** 结构编码不会把原值、原文长度或来源位置当作模板等价条件。 */
442
+ function signatureKey(signature) {
443
+ return JSON.stringify(signature.parts.map((part) => part.type === "text" ? ["text", part.text] : [
444
+ "slot",
445
+ part.kind,
446
+ part.identity
447
+ ]));
448
+ }
449
+ /** 声明等价关系;未声明的签名保留自身类别,不构成白名单失败。 */
450
+ function createSignatureEquivalence(groups) {
451
+ const parents = /* @__PURE__ */ new Map();
452
+ function root(key) {
453
+ const parent = parents.get(key);
454
+ if (parent === void 0 || parent === key) return key;
455
+ const result = root(parent);
456
+ parents.set(key, result);
457
+ return result;
458
+ }
459
+ for (const group of groups) {
460
+ const keys = group.map(signatureKey);
461
+ const first = keys[0];
462
+ if (first === void 0) continue;
463
+ for (const key of keys) {
464
+ const left = root(first);
465
+ const right = root(key);
466
+ if (left < right) parents.set(right, left);
467
+ else if (right < left) parents.set(left, right);
468
+ }
469
+ }
470
+ const canonical = new Map([...parents.keys()].map((key) => [key, root(key)]));
471
+ return (signature) => {
472
+ const key = signatureKey(signature);
473
+ return canonical.get(key) ?? key;
474
+ };
475
+ }
476
+ // ../../packages/text-analysis/dist/words.js
477
+ /** 基础词界只承诺 en/zh/ja;其他语言由调用方明确替换。 */
478
+ function segmentWords(input) {
479
+ validateInput(input);
480
+ const protectedRanges = mergeRanges(input.text, input.protectedRanges ?? emptyRanges);
481
+ let language;
482
+ try {
483
+ language = new Intl.Locale(input.language).language;
484
+ } catch {
485
+ language = void 0;
486
+ }
487
+ if (language === void 0 || ![
488
+ "en",
489
+ "zh",
490
+ "ja"
491
+ ].includes(language)) return Object.freeze({
492
+ words: Object.freeze([]),
493
+ boundaries: Object.freeze([]),
494
+ complete: false,
495
+ issues: Object.freeze([Object.freeze({
496
+ code: "unsupported-language",
497
+ message: `内置分词不支持语言 ${input.language}。`
498
+ })])
499
+ });
500
+ const segmenter = new Intl.Segmenter(input.language, { granularity: "word" });
501
+ const words = [];
502
+ const boundaries = /* @__PURE__ */ new Set();
503
+ for (const range of complementRanges(input.text, protectedRanges)) {
504
+ boundaries.add(range.start);
505
+ boundaries.add(range.end);
506
+ for (const segment of segmenter.segment(input.text.slice(range.start, range.end))) {
507
+ const start = range.start + segment.index;
508
+ const end = start + segment.segment.length;
509
+ boundaries.add(start);
510
+ boundaries.add(end);
511
+ if (segment.isWordLike) words.push(Object.freeze({
512
+ start,
513
+ end,
514
+ text: segment.segment
515
+ }));
516
+ }
517
+ }
518
+ return Object.freeze({
519
+ words: Object.freeze(words),
520
+ boundaries: Object.freeze([...boundaries].sort((a, b) => a - b)),
521
+ complete: true,
522
+ issues: Object.freeze([])
523
+ });
524
+ }
525
+ // ../../packages/text-analysis/dist/analysis.js
526
+ function copyIssues(text, value) {
527
+ return Object.freeze(value.map((issue) => {
528
+ if (issue.range !== void 0) validateRangeBounds(text, issue.range);
529
+ return Object.freeze({
530
+ code: issue.code,
531
+ message: issue.message,
532
+ ...issue.range === void 0 ? {} : { range: Object.freeze({ ...issue.range }) }
533
+ });
534
+ }));
535
+ }
536
+ const recognizedSchema = z.compile(z.union([z.array(textTokenSchema), recognitionSchema]));
537
+ function recognitionResult(value) {
538
+ if (!recognizedSchema.validate(value)) throw analysisError("invalid-recognition", recognizedSchema.safeParse(value).error);
539
+ return Array.isArray(value) ? {
540
+ tokens: value,
541
+ complete: true,
542
+ issues: []
543
+ } : value;
544
+ }
545
+ /** 配置只固定函数和政策;调用时才计算,借入的 memo 生命周期由调用方管理。 */
546
+ function createTextAnalysis(options = {}) {
547
+ const recognizers = [...options.recognizers ?? []];
548
+ const segmenter = options.segmenter ?? segmentWords;
549
+ async function computeStructures(text, language, inputProtectedRanges) {
550
+ const protectedRanges = mergeRanges(text, inputProtectedRanges);
551
+ const tokens = [];
552
+ const issues = [];
553
+ let complete = true;
554
+ for (const recognizer of recognizers) {
555
+ const availableRanges = complementRanges(text, mergeRanges(text, [...protectedRanges, ...tokens]));
556
+ const recognized = recognitionResult(await recognizer({
557
+ text,
558
+ language,
559
+ protectedRanges,
560
+ availableRanges
561
+ }));
562
+ complete = complete && recognized.complete;
563
+ issues.push(...copyIssues(text, recognized.issues));
564
+ const sorted = [...recognized.tokens].sort((a, b) => a.start - b.start || a.end - b.end);
565
+ let previousEnd = -1;
566
+ for (const token of sorted) {
567
+ validateRangeBounds(text, token);
568
+ if (!fitsRange(token, availableRanges) || token.start < previousEnd) throw new TextAnalysisContractError("overlapping-token", "识别结果必须位于可用范围内且互不重叠。");
569
+ tokens.push(Object.freeze({ ...token }));
570
+ previousEnd = token.end;
571
+ }
572
+ }
573
+ tokens.sort((a, b) => a.start - b.start);
574
+ const effectiveProtectedRanges = mergeRanges(text, [...protectedRanges, ...tokens.filter((token) => token.protect === true)]);
575
+ return Object.freeze({
576
+ text,
577
+ language,
578
+ tokens: Object.freeze(tokens),
579
+ protectedRanges: effectiveProtectedRanges,
580
+ availableRanges: complementRanges(text, effectiveProtectedRanges),
581
+ complete,
582
+ issues: Object.freeze(issues)
583
+ });
584
+ }
585
+ async function computeWords(analysis) {
586
+ const result = await segmenter({
587
+ text: analysis.text,
588
+ language: analysis.language,
589
+ protectedRanges: analysis.protectedRanges
590
+ });
591
+ if (!wordAnalysisSchema.validate(result)) throw analysisError("invalid-segmentation", wordAnalysisSchema.safeParse(result).error);
592
+ let previousEnd = -1;
593
+ for (const word of result.words) {
594
+ validateRangeBounds(analysis.text, word);
595
+ if (!fitsRange(word, analysis.availableRanges) || word.start < previousEnd || word.text !== analysis.text.slice(word.start, word.end)) throw new TextAnalysisContractError("invalid-segmentation", "词必须按原文顺序定位于可用范围,文本须与原文一致。");
596
+ previousEnd = word.end;
597
+ }
598
+ for (const boundary of result.boundaries) {
599
+ validateRangeBounds(analysis.text, {
600
+ start: boundary,
601
+ end: boundary
602
+ }, true);
603
+ if (analysis.protectedRanges.some((range) => range.start < boundary && boundary < range.end)) throw new TextAnalysisContractError("invalid-segmentation", "词界不能位于受保护区间内部。");
604
+ }
605
+ const issues = copyIssues(analysis.text, result.issues);
606
+ return Object.freeze({
607
+ words: Object.freeze(result.words.map((word) => Object.freeze({ ...word }))),
608
+ boundaries: Object.freeze([...new Set(result.boundaries)].sort((a, b) => a - b)),
609
+ complete: analysis.complete && result.complete,
610
+ issues: Object.freeze([...analysis.issues, ...issues])
611
+ });
612
+ }
613
+ function computeSignature(analysis, policy) {
614
+ return createTemplateSignature(analysis, policy);
615
+ }
616
+ function structureKey(text, language, protectedRanges) {
617
+ return [
618
+ text,
619
+ language,
620
+ ...protectedRanges.flatMap((range) => [range.start, range.end])
621
+ ];
622
+ }
623
+ function signatureInputKey(analysis, policy) {
624
+ return [analysis, policy.abstract];
625
+ }
626
+ function structures(input, runtime = {}) {
627
+ validateInput(input);
628
+ return (runtime.memo?.memo(computeStructures, { key: structureKey }) ?? computeStructures)(input.text, input.language, input.protectedRanges ?? emptyRanges);
629
+ }
630
+ return Object.freeze({
631
+ structures,
632
+ words: async (input, runtime = {}) => {
633
+ const structure = await structures(input, runtime);
634
+ return (runtime.memo?.memo(computeWords) ?? computeWords)(structure);
635
+ },
636
+ signature: async (input, policy, runtime = {}) => {
637
+ const structure = await structures(input, runtime);
638
+ return (runtime.memo?.memo(computeSignature, { key: signatureInputKey }) ?? computeSignature)(structure, policy);
639
+ }
640
+ });
641
+ }
642
+ // ../../packages/text-analysis/dist/normalize.js
643
+ /** NFC 比较视图;分解字符保留来源,再验证选中原文的规范化结果。 */
644
+ function normalizeText(original) {
645
+ const text = original.normalize("NFC");
646
+ if (text === original) return Object.freeze({
647
+ original,
648
+ text,
649
+ mapRange: (range) => {
650
+ validateRange(text, range, true);
651
+ return Object.freeze({
652
+ start: range.start,
653
+ end: range.end
654
+ });
655
+ }
656
+ });
657
+ const origins = /* @__PURE__ */ new Map();
658
+ let offset = 0;
659
+ for (const character of original) {
660
+ const range = {
661
+ start: offset,
662
+ end: offset + character.length
663
+ };
664
+ for (const decomposed of character.normalize("NFD")) {
665
+ let queue = origins.get(decomposed);
666
+ if (queue === void 0) {
667
+ queue = {
668
+ values: [],
669
+ next: 0
670
+ };
671
+ origins.set(decomposed, queue);
672
+ }
673
+ queue.values.push(range);
674
+ }
675
+ offset = range.end;
676
+ }
677
+ const units = [];
678
+ const unitIndexes = /* @__PURE__ */ new Map();
679
+ offset = 0;
680
+ for (const character of text) {
681
+ const source = [];
682
+ for (const decomposed of character.normalize("NFD")) {
683
+ const queue = origins.get(decomposed);
684
+ const origin = queue?.values[queue.next];
685
+ if (queue === void 0 || origin === void 0) throw new Error("NFC 分解的来源映射不完整。");
686
+ queue.next += 1;
687
+ source.push(origin);
688
+ }
689
+ unitIndexes.set(offset, units.length);
690
+ units.push({
691
+ start: offset,
692
+ end: offset + character.length,
693
+ origins: source
694
+ });
695
+ offset += character.length;
696
+ }
697
+ return Object.freeze({
698
+ original,
699
+ text,
700
+ mapRange: (range) => {
701
+ validateRange(text, range, true);
702
+ if (range.start === range.end) {
703
+ if (range.start === 0) return Object.freeze({
704
+ start: 0,
705
+ end: 0
706
+ });
707
+ if (range.end === text.length) return Object.freeze({
708
+ start: original.length,
709
+ end: original.length
710
+ });
711
+ const index = unitIndexes.get(range.start);
712
+ const left = index === void 0 ? void 0 : units[index - 1];
713
+ const right = index === void 0 ? void 0 : units[index];
714
+ const end = Math.max(...left?.origins.map((origin) => origin.end) ?? []);
715
+ const start = Math.min(...right?.origins.map((origin) => origin.start) ?? []);
716
+ return start === end ? Object.freeze({
717
+ start,
718
+ end
719
+ }) : null;
720
+ }
721
+ let start = original.length;
722
+ let end = 0;
723
+ const first = unitIndexes.get(range.start);
724
+ if (first === void 0) return null;
725
+ for (let index = first; index < units.length; index += 1) {
726
+ const unit = units[index];
727
+ if (unit === void 0 || unit.start >= range.end) break;
728
+ for (const origin of unit.origins) {
729
+ start = Math.min(start, origin.start);
730
+ end = Math.max(end, origin.end);
731
+ }
732
+ }
733
+ if (!isCodePointBoundary$1(original, start) || !isCodePointBoundary$1(original, end) || original.slice(start, end).normalize("NFC") !== text.slice(range.start, range.end)) return null;
734
+ return Object.freeze({
735
+ start,
736
+ end
737
+ });
738
+ }
739
+ });
740
+ }
741
+ // ../../packages/text-analysis/dist/recognizers.js
742
+ const tokenKindSchema = z.string().min(1);
743
+ const markersSchema = z.array(z.string().min(1));
744
+ /** 每个可用原文区间独立扫描,不共享 RegExp.lastIndex。 */
745
+ function regexTokens(options) {
746
+ const { kind, identity, value, protect } = options;
747
+ if (!tokenKindSchema.safeParse(kind).success) throw new TextAnalysisContractError("invalid-kind", "token 种类必须非空。");
748
+ const source = options.pattern.source;
749
+ const flags = options.pattern.flags.includes("g") ? options.pattern.flags : `${options.pattern.flags}g`;
750
+ return (input) => {
751
+ const tokens = [];
752
+ for (const range of input.availableRanges) {
753
+ const pattern = new RegExp(source, flags);
754
+ const fragment = input.text.slice(range.start, range.end);
755
+ for (const match of fragment.matchAll(pattern)) {
756
+ if (match[0].length === 0) throw new TextAnalysisContractError("empty-token", "识别器不能返回空匹配。");
757
+ const start = range.start + match.index;
758
+ tokens.push({
759
+ kind,
760
+ start,
761
+ end: start + match[0].length,
762
+ ...identity === void 0 ? {} : { identity: identity(match) },
763
+ ...value === void 0 ? {} : { value: value(match) },
764
+ ...protect === void 0 ? {} : { protect }
765
+ });
766
+ }
767
+ }
768
+ return tokens;
769
+ };
770
+ }
771
+ /** ASCII 整数与小数,保留符号、前导零及全部原始数字,不解析为浮点数。 */
772
+ function asciiNumbers() {
773
+ return regexTokens({
774
+ kind: "number",
775
+ pattern: /[+-]?[0-9]+(?:\.[0-9]+)?/gu,
776
+ value: (match) => match[0]
777
+ });
778
+ }
779
+ /** 仅为显式选择的示例语法;不包含数字索引、嵌套或字面转义。 */
780
+ function braceVariables(options = {}) {
781
+ return regexTokens({
782
+ kind: "variable",
783
+ pattern: /\{([A-Za-z_][A-Za-z0-9_]*)\}/gu,
784
+ identity: (match) => match[1],
785
+ value: (match) => match[1],
786
+ ...options.protect === void 0 ? {} : { protect: options.protect }
787
+ });
788
+ }
789
+ function literalMarkers(markers, options = {}) {
790
+ if (!markersSchema.safeParse(markers).success) throw new TextAnalysisContractError("empty-marker", "字面标记不能是空串。");
791
+ const literals = [...new Set(markers)].sort((a, b) => b.length - a.length || a.localeCompare(b));
792
+ const { kind = "marker", protect } = options;
793
+ return (input) => {
794
+ const tokens = [];
795
+ for (const range of input.availableRanges) {
796
+ let offset = range.start;
797
+ while (offset < range.end) {
798
+ const marker = literals.find((literal) => offset + literal.length <= range.end && input.text.startsWith(literal, offset));
799
+ if (marker !== void 0) {
800
+ tokens.push({
801
+ start: offset,
802
+ end: offset + marker.length,
803
+ kind,
804
+ identity: marker,
805
+ value: marker,
806
+ ...protect === void 0 ? {} : { protect }
807
+ });
808
+ offset += marker.length;
809
+ } else {
810
+ const point = input.text.codePointAt(offset);
811
+ offset += point !== void 0 && point > 65535 ? 2 : 1;
812
+ }
813
+ }
814
+ }
815
+ return tokens;
816
+ };
817
+ }
818
+ // ../../packages/text-analysis/dist/quantities/common.js
819
+ const technicalTimeUnits = {
820
+ ms: .001,
821
+ s: 1
822
+ };
823
+ const technicalDataUnits = {
824
+ b: 1,
825
+ byte: 1,
826
+ bytes: 1,
827
+ kb: 1e3,
828
+ kib: 1024,
829
+ mb: 1e6,
830
+ mib: 1024 ** 2,
831
+ gb: 1e9,
832
+ gib: 1024 ** 3,
833
+ tb: 0xe8d4a51000,
834
+ tib: 1024 ** 4
835
+ };
836
+ /** 只在选定语言的词表中识别单位;别名来自对应资源的声明。 */
837
+ function quantityLexicon(settings) {
838
+ const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
839
+ const normalizeUnit = (unit, options) => (options.aliases?.[unit] ?? unit).toLowerCase();
840
+ const unitPattern = (options) => [.../* @__PURE__ */ new Set([
841
+ ...Object.keys(settings.timeUnits),
842
+ ...Object.keys(settings.dataUnits),
843
+ ...Object.keys(options.aliases ?? {})
844
+ ])].sort((a, b) => b.length - a.length).map(escape).join("|");
845
+ function unitFact(unit, options) {
846
+ const canonical = normalizeUnit(unit, options);
847
+ if (canonical in settings.timeUnits) return `时间秒:${settings.timeUnits[canonical]}`;
848
+ if (canonical in settings.dataUnits) return `数据字节:${settings.dataUnits[canonical]}`;
849
+ }
850
+ return {
851
+ facts(text, options) {
852
+ const result = /* @__PURE__ */ new Set();
853
+ let normalized = text;
854
+ for (const literal of options.ignoredLiterals ?? []) if (literal) normalized = normalized.replaceAll(literal, " ");
855
+ normalized = settings.normalize(normalized, result);
856
+ normalized = normalized.replace(/(?<![A-Za-z_\d,])[+-]?\d{1,3}(?:,\d{3})+(?:\.\d+)?(?![\d,])/gu, (value) => value.replaceAll(",", ""));
857
+ normalized = normalized.replace(new RegExp(`(?<![A-Za-z_\\d.])([+-]?\\d+(?:\\.\\d+)?)\\s*(${unitPattern(options)})(?![A-Za-z])`, "giu"), (all, value, unit) => {
858
+ const canonical = normalizeUnit(unit, options);
859
+ if (canonical in settings.timeUnits) result.add(`时间秒:${Number((Number(value) * settings.timeUnits[canonical]).toPrecision(12))}`);
860
+ else if (canonical in settings.dataUnits) result.add(`数据字节:${Number(value) * settings.dataUnits[canonical]}`);
861
+ else return all;
862
+ return " ";
863
+ });
864
+ const defaultUnit = options.defaultUnit === void 0 ? void 0 : normalizeUnit(options.defaultUnit, options);
865
+ for (const match of normalized.matchAll(/(?<![A-Za-z_\d.])[+-]?\d+(?:\.\d+)?(?![A-Za-z_\d]|\.\d)/gu)) {
866
+ const value = Number(match[0]);
867
+ if (defaultUnit && defaultUnit in settings.timeUnits) result.add(`时间秒:${Number((value * settings.timeUnits[defaultUnit]).toPrecision(12))}`);
868
+ else if (defaultUnit && defaultUnit in settings.dataUnits) result.add(`数据字节:${value * settings.dataUnits[defaultUnit]}`);
869
+ else result.add(`数值:${value}`);
870
+ }
871
+ return result;
872
+ },
873
+ unitAfter(text, options) {
874
+ const match = text.match(new RegExp(`^\\s*(${unitPattern(options)})(?![A-Za-z])`, "iu"));
875
+ return match ? unitFact(match[1], options) : void 0;
876
+ }
877
+ };
878
+ }
879
+ /** 中日文共用的汉字位值转换;支持到万位,不推断约数。 */
880
+ function kanjiNumber(text) {
881
+ const digits = {
882
+ 零: 0,
883
+ 〇: 0,
884
+ 一: 1,
885
+ 二: 2,
886
+ 两: 2,
887
+ 三: 3,
888
+ 四: 4,
889
+ 五: 5,
890
+ 六: 6,
891
+ 七: 7,
892
+ 八: 8,
893
+ 九: 9
894
+ };
895
+ if (!/[十百千万]/u.test(text)) return Number(Array.from(text, (char) => digits[char]).join(""));
896
+ let total = 0, section = 0, current = 0;
897
+ for (const char of text) {
898
+ if (char in digits) {
899
+ current = digits[char];
900
+ continue;
901
+ }
902
+ if (char === "万") {
903
+ total += (section + current) * 1e4;
904
+ section = 0;
905
+ current = 0;
906
+ } else {
907
+ section += (current || 1) * {
908
+ 十: 10,
909
+ 百: 100,
910
+ 千: 1e3
911
+ }[char];
912
+ current = 0;
913
+ }
914
+ }
915
+ return total + section + current;
916
+ }
917
+ // ../../packages/text-analysis/dist/quantities/en.js
918
+ const timeUnits$2 = {
919
+ ...technicalTimeUnits,
920
+ millisecond: .001,
921
+ milliseconds: .001,
922
+ second: 1,
923
+ seconds: 1,
924
+ sec: 1,
925
+ secs: 1,
926
+ minute: 60,
927
+ minutes: 60,
928
+ min: 60,
929
+ mins: 60,
930
+ hour: 3600,
931
+ hours: 3600,
932
+ hr: 3600,
933
+ hrs: 3600,
934
+ day: 86400,
935
+ days: 86400
936
+ };
937
+ const englishQuantities = {
938
+ id: "en",
939
+ supports: (language) => /^en(?:-|$)/iu.test(language),
940
+ ...quantityLexicon({
941
+ timeUnits: timeUnits$2,
942
+ dataUnits: {
943
+ ...technicalDataUnits,
944
+ byte: 1,
945
+ bytes: 1
946
+ },
947
+ normalize(text, facts) {
948
+ return text.replace(/\b(\d+)(?:st|nd|rd|th)\b/giu, (_all, value) => {
949
+ facts.add(`序数:${Number(value)}`);
950
+ return " ";
951
+ }).replace(/\bper\s+(second|minute|hour|day)\b/giu, (_all, unit) => {
952
+ facts.add(`频率基准秒:${timeUnits$2[unit.toLowerCase()]}`);
953
+ return " ";
954
+ });
955
+ }
956
+ })
957
+ };
958
+ // ../../packages/text-analysis/dist/quantities/ja.js
959
+ const timeUnits$1 = {
960
+ ...technicalTimeUnits,
961
+ ミリ秒: .001,
962
+ 秒: 1,
963
+ 秒間: 1,
964
+ 分: 60,
965
+ 分間: 60,
966
+ 時間: 3600,
967
+ 時: 3600,
968
+ 日: 86400,
969
+ 日間: 86400
970
+ };
971
+ const japaneseQuantities = {
972
+ id: "ja",
973
+ supports: (language) => /^ja(?:-|$)/iu.test(language),
974
+ ...quantityLexicon({
975
+ timeUnits: timeUnits$1,
976
+ dataUnits: {
977
+ ...technicalDataUnits,
978
+ バイト: 1
979
+ },
980
+ normalize(text, facts) {
981
+ return text.normalize("NFKC").replace(/((?:毎\s*[零〇一二三四五六七八九十百千万0-9.\s]*(?:ミリ秒|秒|分|時間|日)|[零〇一二三四五六七八九十百千万0-9.\s]*(?:ミリ秒|秒|分|時間|日)(?:ごと|毎))[^。;;]{0,20})(?:1|一)回/gu, "$1").replace(/第([零〇一二三四五六七八九十百千万]+|\d+)|([零〇一二三四五六七八九十百千万]+|\d+)番目/gu, (_all, prefix, suffix) => {
982
+ const value = prefix ?? suffix;
983
+ facts.add(`序数:${/^[0-9]/u.test(value) ? Number(value) : kanjiNumber(value)}`);
984
+ return " ";
985
+ }).replace(/(?:[零〇一二三四五六七八九][零〇一二三四五六七八九十百千万]*|十[一二三四五六七八九]?)(?=\s*(?:ミリ秒|秒|分|時間|日|バイト|回|段|件|個))/gu, (value) => String(kanjiNumber(value))).replace(/(?<![\d.])(?:1\s*)?(ミリ秒|秒|分|時間|日)(?:あたり|当たり)/gu, (_all, unit) => {
986
+ facts.add(`频率基准秒:${timeUnits$1[unit]}`);
987
+ return " ";
988
+ }).replace(/毎(ミリ秒|秒|分|時|日)/gu, (_all, unit) => {
989
+ facts.add(`频率基准秒:${timeUnits$1[unit]}`);
990
+ return " ";
991
+ });
992
+ }
993
+ })
994
+ };
995
+ // ../../packages/text-analysis/dist/quantities/zh-CN.js
996
+ const timeUnits = {
997
+ ...technicalTimeUnits,
998
+ 毫秒: .001,
999
+ 秒: 1,
1000
+ 秒钟: 1,
1001
+ 分钟: 60,
1002
+ 小时: 3600,
1003
+ 天: 86400,
1004
+ 日: 86400
1005
+ };
1006
+ // ../../packages/text-analysis/dist/quantities/index.js
1007
+ const profiles = [
1008
+ englishQuantities,
1009
+ {
1010
+ id: "zh-CN",
1011
+ supports: (language) => language === "zh-CN" || language === "zh-Hans",
1012
+ ...quantityLexicon({
1013
+ timeUnits,
1014
+ dataUnits: {
1015
+ ...technicalDataUnits,
1016
+ 字节: 1
1017
+ },
1018
+ normalize(text, facts) {
1019
+ return text.replace(/(每(?:隔)?\s*[零〇一二两三四五六七八九十百千万0-9.\s]*(?:毫秒|秒|分钟|小时)[^,。;;]{0,20})一次/gu, "$1").replace(/第([零〇一二两三四五六七八九十百千万]+|\d+)/gu, (_all, value) => {
1020
+ facts.add(`序数:${/^[0-9]/u.test(value) ? Number(value) : kanjiNumber(value)}`);
1021
+ return " ";
1022
+ }).replace(/(?:[零〇一二两三四五六七八九][零〇一二两三四五六七八九十百千万]*|十[一二三四五六七八九]?)(?=\s*(?:毫秒|秒|分钟|小时|天|日|字节|次|段|个))/gu, (value) => String(kanjiNumber(value))).replace(/每(毫秒|秒|分钟|小时|天)/gu, (_all, unit) => {
1023
+ facts.add(`频率基准秒:${timeUnits[unit]}`);
1024
+ return " ";
1025
+ });
1026
+ }
1027
+ })
1028
+ },
1029
+ japaneseQuantities
1030
+ ];
1031
+ /** 显式选择能力;不会把未知语言悄悄交给另一种语言的词法。 */
1032
+ function quantityProfile(id, language) {
1033
+ return profiles.find((profile) => profile.id === id && profile.supports(language));
1034
+ }
1035
+ // ../../packages/terminology/dist/matching.js
1036
+ const basicTermTextAnalysis = createTextAnalysis();
1037
+ const compiledIndexes = /* @__PURE__ */ new WeakMap();
1038
+ const literalPolicy = Object.freeze({
1039
+ id: "nfc-literal",
1040
+ boundary: "literal"
1041
+ });
1042
+ const englishPolicy = Object.freeze({
1043
+ id: "nfc-english-word-boundary",
1044
+ boundary: "word"
1045
+ });
1046
+ function defaultTermMatchingPolicy(language) {
1047
+ if (/^en(?:-|$)/iu.test(language)) return englishPolicy;
1048
+ if (/^(?:zh|ja)(?:-|$)/iu.test(language)) return literalPolicy;
1049
+ }
1050
+ const matchingPolicySchema = z.object({
1051
+ id: z.string().min(1),
1052
+ boundary: z.union([z.enum(["literal", "word"]), z.function()]),
1053
+ normalize: z.function().exactOptional(),
1054
+ forms: z.function().exactOptional()
1055
+ });
1056
+ const normalizedTextSchema = z.object({
1057
+ original: z.string(),
1058
+ text: z.string(),
1059
+ mapRange: z.function()
1060
+ });
1061
+ const boundaryResultSchema = z.boolean();
1062
+ function compileTerms(termbase, options = {}) {
1063
+ const selected = selectTerms(termbase);
1064
+ const forms = [];
1065
+ for (const entry of selected.expressions) {
1066
+ const selectedPolicy = options.policyFor?.(entry) ?? options.policy ?? defaultTermMatchingPolicy(entry.language);
1067
+ if (!selectedPolicy) continue;
1068
+ if (!matchingPolicySchema.safeParse(selectedPolicy).success) throw new TermContractError("compile", [contractIssue("invalid-policy", "匹配政策需要身份及有效边界政策。")]);
1069
+ const policy = Object.freeze({ ...selectedPolicy });
1070
+ const normalize = policy.normalize ?? normalizeText;
1071
+ const candidates = [entry.expression.text, ...policy.forms?.(entry) ?? []];
1072
+ const seen = /* @__PURE__ */ new Set();
1073
+ for (const form of candidates) {
1074
+ if (!nonemptyTextSchema.safeParse(form).success) throw new TermContractError("compile", [contractIssue("invalid-form", "额外识别形式不得为空。", [entry.conceptId, entry.expressionId])]);
1075
+ const normalized = normalize(form);
1076
+ validateNormalized(normalized, form, "compile");
1077
+ if (normalized.text === "") throw new TermContractError("compile", [contractIssue("empty-normalized-form", "规范化后的识别形式不得为空。", [entry.conceptId, entry.expressionId])]);
1078
+ if (seen.has(normalized.text)) continue;
1079
+ seen.add(normalized.text);
1080
+ forms.push(Object.freeze({
1081
+ entry,
1082
+ form,
1083
+ key: normalized.text,
1084
+ policy
1085
+ }));
1086
+ }
1087
+ }
1088
+ assertUsageConflicts(forms.map(({ entry, key }) => ({
1089
+ entry,
1090
+ key
1091
+ })), "compile");
1092
+ const result = Object.freeze({
1093
+ termbase: selected,
1094
+ languages: Object.freeze([...new Set(selected.expressions.map((entry) => entry.language))]),
1095
+ analysis: options.analysis ?? basicTermTextAnalysis
1096
+ });
1097
+ compiledIndexes.set(result, Object.freeze(forms));
1098
+ return result;
1099
+ }
1100
+ function findTermsMemoKey(terms, input, options) {
1101
+ return [terms, JSON.stringify([
1102
+ input.language,
1103
+ input.complete === false,
1104
+ input.fragments.map(({ ref, text, protectedRanges }) => [
1105
+ ref,
1106
+ text,
1107
+ protectedRanges ?? null
1108
+ ]),
1109
+ options.conceptIds === void 0 ? null : [...new Set(options.conceptIds)].sort()
1110
+ ])];
1111
+ }
1112
+ function validateNormalized(value, original, stage) {
1113
+ if (!normalizedTextSchema.safeParse(value).success || value.original !== original) throw new TermContractError(stage, [contractIssue("invalid-normalization", "规范化策略必须保留原文并提供区间回映。")]);
1114
+ }
1115
+ function intersects$1(left, right) {
1116
+ return left.start < right.end && right.start < left.end;
1117
+ }
1118
+ function contains(outer, inner) {
1119
+ return outer.start <= inner.start && outer.end >= inner.end && (outer.start < inner.start || outer.end > inner.end);
1120
+ }
1121
+ function appendWordIssues(target, words, fragmentIndex) {
1122
+ for (const issue of words.issues) if (!target.some((existing) => existing.fragmentIndex === fragmentIndex && existing.code === issue.code && existing.message === issue.message)) target.push({
1123
+ ...issue,
1124
+ fragmentIndex
1125
+ });
1126
+ if (!words.complete && words.issues.length === 0 && !target.some((issue) => issue.fragmentIndex === fragmentIndex && issue.code === "incomplete-word-boundaries")) target.push({
1127
+ code: "incomplete-word-boundaries",
1128
+ message: "词界分析未完整处理片段。",
1129
+ fragmentIndex
1130
+ });
1131
+ }
1132
+ function resolveTermMatches(matches, issues = []) {
1133
+ const suppressed = [];
1134
+ const active = matches.filter((match) => {
1135
+ const by = matches.filter((other) => other.fragmentIndex === match.fragmentIndex && contains(other.range, match.range));
1136
+ if (by.length) suppressed.push(Object.freeze({
1137
+ match,
1138
+ by: Object.freeze(by)
1139
+ }));
1140
+ return by.length === 0;
1141
+ });
1142
+ const ambiguities = [];
1143
+ const ambiguous = /* @__PURE__ */ new Set();
1144
+ for (let li = 0; li < active.length; li += 1) {
1145
+ const left = active[li];
1146
+ for (let ri = li + 1; ri < active.length; ri += 1) {
1147
+ const right = active[ri];
1148
+ if (left.fragmentIndex !== right.fragmentIndex || !intersects$1(left.range, right.range)) continue;
1149
+ const equal = left.range.start === right.range.start && left.range.end === right.range.end;
1150
+ const usageConflict = equal && left.conceptId === right.conceptId && left.usage === "forbidden" !== (right.usage === "forbidden");
1151
+ if (equal && left.conceptId === right.conceptId && !usageConflict) continue;
1152
+ ambiguous.add(left);
1153
+ ambiguous.add(right);
1154
+ ambiguities.push(Object.freeze({
1155
+ reason: usageConflict ? "conflicting-usage" : equal ? "same-span-concepts" : "crossing-overlap",
1156
+ matches: Object.freeze([left, right])
1157
+ }));
1158
+ }
1159
+ }
1160
+ return Object.freeze({
1161
+ status: issues.length || ambiguities.length ? "incomplete" : "complete",
1162
+ matches: Object.freeze([...matches]),
1163
+ active: Object.freeze(active),
1164
+ certain: Object.freeze(active.filter((match) => !ambiguous.has(match))),
1165
+ suppressed: Object.freeze(suppressed),
1166
+ ambiguities: Object.freeze(ambiguities),
1167
+ issues: Object.freeze([...issues])
1168
+ });
1169
+ }
1170
+ /** 分片查找;严格包含只在全部边界和保护政策通过后处理。 */
1171
+ async function findTermsUncached(terms, input, options = {}) {
1172
+ const index = compiledIndexes.get(terms);
1173
+ if (!index) throw new TermContractError("input", [contractIssue("uncompiled-terms", "必须使用 compileTerms 创建的匹配器。")]);
1174
+ const applicable = options.conceptIds === void 0 ? void 0 : new Set(options.conceptIds);
1175
+ const entries = terms.termbase.expressions.filter((entry) => entry.language === input.language && (!applicable || applicable.has(entry.conceptId)));
1176
+ const forms = index.filter(({ entry }) => entry.language === input.language && (!applicable || applicable.has(entry.conceptId)));
1177
+ const issues = [];
1178
+ const matches = [];
1179
+ if (input.complete === false) issues.push({
1180
+ code: "incomplete-scope",
1181
+ message: "文本输入范围不完整,可能仍有未提供的片段。"
1182
+ });
1183
+ if (!input.fragments.length || applicable?.size === 0 || terms.termbase.expressions.length === 0) return resolveTermMatches(matches, issues);
1184
+ const available = new Set(forms.map(({ entry }) => entry));
1185
+ for (const entry of entries) if (!available.has(entry)) issues.push({
1186
+ code: "unsupported-language",
1187
+ message: `未声明 ${input.language} 的术语匹配能力。`,
1188
+ conceptId: entry.conceptId,
1189
+ expressionId: entry.expressionId
1190
+ });
1191
+ if (!entries.length && applicable === void 0) issues.push({
1192
+ code: "missing-language-data",
1193
+ message: `有效术语库没有 ${input.language} 的表达资料。`
1194
+ });
1195
+ for (const [fragmentIndex, fragment] of input.fragments.entries()) {
1196
+ if (!forms.length) continue;
1197
+ const textInput = {
1198
+ text: fragment.text,
1199
+ language: input.language,
1200
+ ...fragment.protectedRanges === void 0 ? {} : { protectedRanges: fragment.protectedRanges }
1201
+ };
1202
+ const structure = await terms.analysis.structures(textInput, options);
1203
+ if (!structure.complete) {
1204
+ issues.push(...structure.issues.map((issue) => ({
1205
+ code: issue.code,
1206
+ message: issue.message,
1207
+ fragmentIndex
1208
+ })));
1209
+ if (!structure.issues.length) issues.push({
1210
+ code: "incomplete-structure",
1211
+ message: "结构分析未完整处理片段。",
1212
+ fragmentIndex
1213
+ });
1214
+ }
1215
+ const normalizedCache = /* @__PURE__ */ new Map();
1216
+ let words;
1217
+ let boundaries;
1218
+ const seen = /* @__PURE__ */ new Set();
1219
+ for (const { entry, form, key, policy } of forms) {
1220
+ const normalizer = policy.normalize ?? normalizeText;
1221
+ let normalized = normalizedCache.get(normalizer);
1222
+ if (!normalized) {
1223
+ normalized = options.memo ? options.memo.memo(normalizer)(fragment.text) : normalizer(fragment.text);
1224
+ validateNormalized(normalized, fragment.text, "input");
1225
+ normalizedCache.set(normalizer, normalized);
1226
+ }
1227
+ for (let position = normalized.text.indexOf(key); position !== -1; position = normalized.text.indexOf(key, position + 1)) {
1228
+ const range = normalized.mapRange({
1229
+ start: position,
1230
+ end: position + key.length
1231
+ });
1232
+ if (!range) {
1233
+ issues.push({
1234
+ code: "unmappable-match",
1235
+ message: "命中无法精确回映到原文区间。",
1236
+ fragmentIndex,
1237
+ conceptId: entry.conceptId,
1238
+ expressionId: entry.expressionId
1239
+ });
1240
+ continue;
1241
+ }
1242
+ if (!termRangeSchema.safeParse(range).success || range.end <= range.start || range.end > fragment.text.length) throw new TermContractError("input", [contractIssue("invalid-mapped-range", "规范化策略返回了无效原文区间。")]);
1243
+ if (splitsSurrogatePair(fragment.text, range.start) || splitsSurrogatePair(fragment.text, range.end)) throw new TermContractError("input", [contractIssue("split-surrogate-range", "规范化策略不能将原文区间映射到代理对内部。")]);
1244
+ if (structure.protectedRanges.some((protectedRange) => intersects$1(range, protectedRange))) continue;
1245
+ if (policy.boundary === "word") {
1246
+ words ??= await terms.analysis.words(textInput, options);
1247
+ appendWordIssues(issues, words, fragmentIndex);
1248
+ boundaries ??= new Set(words.boundaries);
1249
+ if (!boundaries.has(range.start) || !boundaries.has(range.end)) continue;
1250
+ } else if (typeof policy.boundary === "function") {
1251
+ const accepted = await policy.boundary({
1252
+ text: fragment.text,
1253
+ range,
1254
+ entry
1255
+ });
1256
+ if (!boundaryResultSchema.safeParse(accepted).success) throw new TermContractError("input", [contractIssue("invalid-boundary-result", "自定义词界政策必须返回布尔值。")]);
1257
+ if (!accepted) continue;
1258
+ }
1259
+ const identity = JSON.stringify([
1260
+ entry.conceptId,
1261
+ entry.expressionId,
1262
+ range.start,
1263
+ range.end
1264
+ ]);
1265
+ if (seen.has(identity)) continue;
1266
+ seen.add(identity);
1267
+ matches.push(Object.freeze({
1268
+ conceptId: entry.conceptId,
1269
+ expressionId: entry.expressionId,
1270
+ language: input.language,
1271
+ usage: entry.expression.usage,
1272
+ fragmentIndex,
1273
+ ref: fragment.ref,
1274
+ range: Object.freeze({ ...range }),
1275
+ text: fragment.text.slice(range.start, range.end),
1276
+ expressionText: entry.expression.text,
1277
+ form,
1278
+ policyId: policy.id,
1279
+ entry
1280
+ }));
1281
+ }
1282
+ }
1283
+ }
1284
+ matches.sort((left, right) => left.fragmentIndex - right.fragmentIndex || left.range.start - right.range.start || right.range.end - left.range.end || left.conceptId.localeCompare(right.conceptId) || left.expressionId.localeCompare(right.expressionId));
1285
+ return resolveTermMatches(matches, issues);
1286
+ }
1287
+ /** 同一 memo 范围内,按完整识别依赖复用术语匹配与解释。 */
1288
+ function findTerms(terms, input, options = {}) {
1289
+ validateTextInput(input);
1290
+ if (!options.memo) return findTermsUncached(terms, input, options);
1291
+ return options.memo.memo(findTermsUncached, { key: findTermsMemoKey })(terms, input, options);
1292
+ }
1293
+ // ../../packages/terminology/dist/assessment.js
1294
+ const termRuleIdSchema = z.enum(["require-allowed-translation", "reject-forbidden-translation"]);
1295
+ const termRuleSchema = z.object({ id: termRuleIdSchema }).readonly();
1296
+ const termRulesSchema = z.array(termRuleSchema);
1297
+ const allowedRule = Object.freeze({ id: "require-allowed-translation" });
1298
+ const forbiddenRule = Object.freeze({ id: "reject-forbidden-translation" });
1299
+ const defaultRules = Object.freeze([allowedRule, forbiddenRule]);
1300
+ function requireAllowedTranslation() {
1301
+ return allowedRule;
1302
+ }
1303
+ function rejectForbiddenTranslation() {
1304
+ return forbiddenRule;
1305
+ }
1306
+ const termRulesConfigurationSchema = { "~standard": z.object({ rules: z.array(termRuleIdSchema).readonly() }).readonly()["~standard"] };
1307
+ /** 识别信息独立于规则;目标端只解释源端确定适用的概念。 */
1308
+ async function analyzeTermUse(terms, input, runtime = {}) {
1309
+ const snapshot = comparisonSnapshot(input);
1310
+ const groups = [];
1311
+ for (const group of snapshot.groups) {
1312
+ const source = await findTerms(terms, group.source, runtime);
1313
+ const ids = [...new Set(source.certain.map((match) => match.conceptId))];
1314
+ const target = ids.length ? await findTerms(terms, group.target, {
1315
+ ...runtime,
1316
+ conceptIds: ids
1317
+ }) : resolveTermMatches([]);
1318
+ groups.push(Object.freeze({
1319
+ source,
1320
+ target,
1321
+ applicableConcepts: Object.freeze(ids.map((id) => terms.termbase.getConcept(id)))
1322
+ }));
1323
+ }
1324
+ return Object.freeze({
1325
+ input: snapshot,
1326
+ groups: Object.freeze(groups)
1327
+ });
1328
+ }
1329
+ function selectedRules(options) {
1330
+ const rules = options.rules ?? defaultRules;
1331
+ const result = termRulesSchema.safeParse(rules);
1332
+ if (!result.success) throw new TermContractError("input", contractIssues(result.error));
1333
+ return [...new Map(rules.map((rule) => [rule.id, rule])).values()];
1334
+ }
1335
+ /** 只消费已有信息,不分词、查缓存或访问外部资料。 */
1336
+ function assessTermUse(input, analysis, options = {}) {
1337
+ if (!sameJson(input, analysis.input) || input.groups.length !== analysis.groups.length) throw new TermContractError("input", [contractIssue("analysis-input-mismatch", "术语分析与本次比较输入不一致。")]);
1338
+ const rules = selectedRules(options);
1339
+ if (!rules.length) return Object.freeze({
1340
+ status: "complete",
1341
+ problems: Object.freeze([]),
1342
+ issues: Object.freeze([])
1343
+ });
1344
+ const problems = [];
1345
+ const issues = [];
1346
+ const issueKeys = /* @__PURE__ */ new Set();
1347
+ const addIssue = (issue) => {
1348
+ const key = JSON.stringify([
1349
+ issue.groupIndex,
1350
+ issue.conceptId,
1351
+ issue.ruleId,
1352
+ issue.code
1353
+ ]);
1354
+ if (!issueKeys.has(key)) {
1355
+ issueKeys.add(key);
1356
+ issues.push(Object.freeze(issue));
1357
+ }
1358
+ };
1359
+ for (const [groupIndex, group] of input.groups.entries()) {
1360
+ const evidence = analysis.groups[groupIndex];
1361
+ if (group.source.complete === false) addIssue({
1362
+ code: "incomplete-source-scope",
1363
+ message: "原文比较范围不完整,可能还有未识别的适用概念。",
1364
+ groupIndex
1365
+ });
1366
+ for (const issue of evidence.source.issues.filter(({ code }) => code !== "incomplete-scope")) addIssue({
1367
+ code: issue.code,
1368
+ message: issue.message,
1369
+ groupIndex,
1370
+ ...issue.conceptId === void 0 ? {} : { conceptId: issue.conceptId }
1371
+ });
1372
+ if (evidence.source.ambiguities.length) addIssue({
1373
+ code: "ambiguous-source",
1374
+ message: "部分原文术语归属不确定,未据此强行触发概念约束。",
1375
+ groupIndex
1376
+ });
1377
+ for (const concept of evidence.applicableConcepts) {
1378
+ const sourceMatches = evidence.source.certain.filter((match) => match.conceptId === concept.id);
1379
+ const certain = evidence.target.certain.filter((match) => match.conceptId === concept.id);
1380
+ const uncertain = evidence.target.ambiguities.flatMap((ambiguity) => ambiguity.matches).filter((match) => match.conceptId === concept.id);
1381
+ const expressions = concept.languages.find((language) => language.language === group.target.language)?.expressions ?? [];
1382
+ const targetIssues = evidence.target.issues.filter((issue) => issue.code !== "incomplete-scope" && (issue.conceptId === void 0 || issue.conceptId === concept.id));
1383
+ for (const rule of rules) {
1384
+ const context = {
1385
+ groupIndex,
1386
+ conceptId: concept.id,
1387
+ ruleId: rule.id
1388
+ };
1389
+ if (rule.id === "require-allowed-translation") {
1390
+ if (!expressions.some((expression) => expression.usage !== "forbidden")) {
1391
+ addIssue({
1392
+ ...context,
1393
+ code: "missing-allowed-expressions",
1394
+ message: `概念 ${concept.id} 缺少 ${group.target.language} 的允许表达资料。`
1395
+ });
1396
+ continue;
1397
+ }
1398
+ if (certain.some((match) => match.usage !== "forbidden")) continue;
1399
+ let incomplete = false;
1400
+ if (group.target.complete === false) {
1401
+ incomplete = true;
1402
+ addIssue({
1403
+ ...context,
1404
+ code: "incomplete-target-scope",
1405
+ message: "目标范围不完整,不能根据未命中判定缺少允许表达。"
1406
+ });
1407
+ }
1408
+ for (const issue of targetIssues) {
1409
+ incomplete = true;
1410
+ addIssue({
1411
+ ...context,
1412
+ code: issue.code,
1413
+ message: issue.message
1414
+ });
1415
+ }
1416
+ if (uncertain.some((match) => match.usage !== "forbidden")) {
1417
+ incomplete = true;
1418
+ addIssue({
1419
+ ...context,
1420
+ code: "ambiguous-target",
1421
+ message: "目标表达的概念归属不确定,无法判定允许表达是否满足。"
1422
+ });
1423
+ }
1424
+ if (!incomplete) problems.push(Object.freeze({
1425
+ ...context,
1426
+ code: "missing-allowed-translation",
1427
+ message: `目标内容缺少概念 ${concept.id} 的允许表达。`,
1428
+ sourceMatches: Object.freeze(sourceMatches),
1429
+ targetMatches: Object.freeze(certain)
1430
+ }));
1431
+ } else {
1432
+ const forbidden = certain.filter((match) => match.usage === "forbidden");
1433
+ if (forbidden.length) problems.push(Object.freeze({
1434
+ ...context,
1435
+ code: "forbidden-translation",
1436
+ message: `目标内容使用了概念 ${concept.id} 的禁用表达。`,
1437
+ sourceMatches: Object.freeze(sourceMatches),
1438
+ targetMatches: Object.freeze(forbidden)
1439
+ }));
1440
+ if (!expressions.some((expression) => expression.usage === "forbidden")) continue;
1441
+ if (group.target.complete === false) addIssue({
1442
+ ...context,
1443
+ code: "incomplete-target-scope",
1444
+ message: "目标范围不完整,已识别的禁用表达仍单独报告。"
1445
+ });
1446
+ for (const issue of targetIssues) addIssue({
1447
+ ...context,
1448
+ code: issue.code,
1449
+ message: issue.message
1450
+ });
1451
+ if (uncertain.some((match) => match.usage === "forbidden")) addIssue({
1452
+ ...context,
1453
+ code: "ambiguous-target",
1454
+ message: "目标表达可能属于多个概念,未将不确定的禁用地位判为违规。"
1455
+ });
1456
+ }
1457
+ }
1458
+ }
1459
+ }
1460
+ return Object.freeze({
1461
+ status: issues.length ? "incomplete" : "complete",
1462
+ problems: Object.freeze(problems),
1463
+ issues: Object.freeze(issues)
1464
+ });
1465
+ }
1466
+ /** 完整入口复用同一分析与判断实现;关闭全部规则时不进行分析。 */
1467
+ async function evaluateTerms(terms, input, options = {}) {
1468
+ const rules = selectedRules(options);
1469
+ if (!rules.length) {
1470
+ comparisonSnapshot(input);
1471
+ return Object.freeze({
1472
+ status: "complete",
1473
+ problems: Object.freeze([]),
1474
+ issues: Object.freeze([])
1475
+ });
1476
+ }
1477
+ return assessTermUse(input, await analyzeTermUse(terms, input, options), { rules });
1478
+ }
1479
+ // ../../packages/terminology/dist/discovery-languages.js
1480
+ /** 功能词仅用于默认发现的短语边缘;不用于匹配已有术语或跨语言推断。 */
1481
+ const functionWords = {
1482
+ en: new Set("a an the this that these those i me my we us our you your he him his she her it its they them their who which what whose am is are was were be been being do does did have has had and or but if then than as at by for from in into of on onto to with without not".split(" ")),
1483
+ zh: new Set("的 地 得 了 着 过 和 与 及 或 而 但 在 从 对 把 被 向 于 是 为 我 你 他 她 它 我们 你们 他们 这 那 这些 那些".split(" ")),
1484
+ ja: new Set("の は が を に へ と で や も から まで より です ます する した して いる ある これ それ あれ この その あの".split(" "))
1485
+ };
1486
+ const emptyWords = /* @__PURE__ */ new Set();
1487
+ /** 未配置的语言保留全部词,由调用方的分词及候选生成政策提供语言能力。 */
1488
+ function discoveryFunctionWords(language) {
1489
+ try {
1490
+ return functionWords[new Intl.Locale(language).language] ?? emptyWords;
1491
+ } catch {
1492
+ return emptyWords;
1493
+ }
1494
+ }
1495
+ // ../../packages/terminology/dist/discovery-generation.js
1496
+ /** 紧连的短横线和词间连接符可属于词组;句读与破折号仍终止词组。 */
1497
+ function connectsWords(gap) {
1498
+ return /^\s*$/u.test(gap) || /^[-‐‑]$/u.test(gap) || /^\s*[/&·]\s*$/u.test(gap);
1499
+ }
1500
+ function createDefaultCandidateGenerator(language) {
1501
+ const functionWords = discoveryFunctionWords(language);
1502
+ return (input) => {
1503
+ const ranges = [];
1504
+ const gaps = input.words.map((word, index) => index === 0 ? "" : input.text.slice(input.words[index - 1].end, word.start));
1505
+ const connected = gaps.map(connectsWords);
1506
+ const compound = gaps.map((gap) => /^[-‐‑/&·]$/u.test(gap));
1507
+ const firstContent = input.words.map(({ text }, index) => functionWords.has(text.toLowerCase()) ? Infinity : index);
1508
+ const lastContent = firstContent.map((index) => index === Infinity ? -1 : index);
1509
+ for (let index = input.words.length - 2; index >= 0; index -= 1) if (firstContent[index] === Infinity && compound[index + 1]) firstContent[index] = firstContent[index + 1];
1510
+ for (let index = 1; index < input.words.length; index += 1) if (lastContent[index] === -1 && compound[index]) lastContent[index] = lastContent[index - 1];
1511
+ for (let start = 0; start < input.words.length; start += 1) {
1512
+ if (firstContent[start] >= start + input.maxWords) continue;
1513
+ const first = input.words[start];
1514
+ for (let end = start; end < Math.min(input.words.length, start + input.maxWords); end += 1) {
1515
+ const last = input.words[end];
1516
+ if (end > start && !connected[end]) break;
1517
+ if (input.protectedRanges.some((range) => first.start < range.end && range.start < last.end)) break;
1518
+ const text = input.text.slice(first.start, last.end);
1519
+ if (text.length > input.maxCharacters && Array.from(text).length > input.maxCharacters) break;
1520
+ if (firstContent[start] <= end && lastContent[end] >= start) ranges.push(Object.freeze({
1521
+ start: first.start,
1522
+ end: last.end
1523
+ }));
1524
+ }
1525
+ }
1526
+ return Object.freeze(ranges);
1527
+ };
1528
+ }
1529
+ // ../../packages/terminology/dist/discovery.js
1530
+ const corpusEntrySchema = z.object({
1531
+ ref: jsonValueSchema,
1532
+ fragments: z.array(termFragmentSchema)
1533
+ });
1534
+ const discoveryCorpusSchema = z.compile(z.object({
1535
+ language: nonemptyTextSchema,
1536
+ entries: z.array(corpusEntrySchema),
1537
+ complete: z.boolean().exactOptional()
1538
+ }));
1539
+ const discoveryParametersSchema = z.compile(z.object({
1540
+ maxWords: z.int().min(1).max(8).default(3),
1541
+ maxCharacters: z.int().positive().default(80),
1542
+ minOccurrences: z.int().positive().default(1),
1543
+ limit: z.int().nonnegative().default(100),
1544
+ maxExamples: z.int().positive().default(3)
1545
+ }));
1546
+ const candidateRangesSchema = z.compile(z.array(termRangeSchema));
1547
+ const candidateRankSchema = z.compile(z.object({
1548
+ method: nonemptyTextSchema,
1549
+ score: z.number()
1550
+ }));
1551
+ function discoverySnapshot(value) {
1552
+ const snapshot = copyJson(value, "input");
1553
+ if (!discoveryCorpusSchema.validate(snapshot)) throw new TermContractError("input", contractIssues(discoveryCorpusSchema.safeParse(snapshot).error));
1554
+ return snapshot;
1555
+ }
1556
+ function intersects(left, right) {
1557
+ return left.start < right.end && right.start < left.end;
1558
+ }
1559
+ /**
1560
+ * 有界词组发现,默认允许词间连接符并按语言过滤功能词首尾。
1561
+ * 低频候选仍由 minOccurrences 决定,排名只表示审阅顺序,不证明候选是术语。
1562
+ */
1563
+ async function discoverTerms(corpus, options = {}) {
1564
+ const input = discoverySnapshot(corpus);
1565
+ const parameters = discoveryParametersSchema.safeParse(options);
1566
+ if (!parameters.success) throw new TermContractError("input", contractIssues(parameters.error));
1567
+ const { maxWords, maxCharacters, minOccurrences, limit, maxExamples } = parameters.data;
1568
+ const issues = [];
1569
+ const issueKeys = /* @__PURE__ */ new Set();
1570
+ const addIssue = (issue) => {
1571
+ const key = JSON.stringify([
1572
+ issue.entryIndex,
1573
+ issue.fragmentIndex,
1574
+ issue.code,
1575
+ issue.message,
1576
+ issue.range?.start,
1577
+ issue.range?.end
1578
+ ]);
1579
+ if (issueKeys.has(key)) return;
1580
+ issueKeys.add(key);
1581
+ issues.push(Object.freeze({
1582
+ ...issue,
1583
+ ...issue.range === void 0 ? {} : { range: Object.freeze({ ...issue.range }) }
1584
+ }));
1585
+ };
1586
+ if (input.complete === false) addIssue({
1587
+ code: "incomplete-corpus",
1588
+ message: "输入语料范围不完整,统计仅覆盖实际提供的条目。"
1589
+ });
1590
+ const accumulated = /* @__PURE__ */ new Map();
1591
+ const textAnalysis = options.analysis ?? basicTermTextAnalysis;
1592
+ const generateCandidates = options.candidateGenerator ?? createDefaultCandidateGenerator(input.language);
1593
+ for (const [entryIndex, entry] of input.entries.entries()) for (const [fragmentIndex, fragment] of entry.fragments.entries()) {
1594
+ const textInput = {
1595
+ text: fragment.text,
1596
+ language: input.language,
1597
+ ...fragment.protectedRanges === void 0 ? {} : { protectedRanges: fragment.protectedRanges }
1598
+ };
1599
+ const structure = await textAnalysis.structures(textInput, options);
1600
+ const analysis = await textAnalysis.words(textInput, options);
1601
+ for (const issue of structure.issues) addIssue({
1602
+ ...issue,
1603
+ entryIndex,
1604
+ fragmentIndex
1605
+ });
1606
+ if (!structure.complete && structure.issues.length === 0) addIssue({
1607
+ code: "incomplete-structure",
1608
+ message: "结构分析未完整处理该片段。",
1609
+ entryIndex,
1610
+ fragmentIndex
1611
+ });
1612
+ for (const issue of analysis.issues) addIssue({
1613
+ ...issue,
1614
+ entryIndex,
1615
+ fragmentIndex
1616
+ });
1617
+ if (!analysis.complete) {
1618
+ if (structure.complete && analysis.issues.length === 0) addIssue({
1619
+ code: "incomplete-segmentation",
1620
+ message: "分词能力未完整处理该片段。",
1621
+ entryIndex,
1622
+ fragmentIndex
1623
+ });
1624
+ }
1625
+ if (!candidateRangesSchema.validate(analysis.words)) throw new TermContractError("input", contractIssues(candidateRangesSchema.safeParse(analysis.words).error));
1626
+ const words = Object.freeze(analysis.words.map((word) => Object.freeze({ ...word })));
1627
+ let previousEnd = 0;
1628
+ for (const word of words) {
1629
+ if (word.start < previousEnd || !validTermRange(fragment.text, word) || fragment.text.slice(word.start, word.end) !== word.text) throw new TermContractError("input", [contractIssue("invalid-word-analysis", "分词结果必须按序返回精确的原文区间。", [
1630
+ "entries",
1631
+ entryIndex,
1632
+ "fragments",
1633
+ fragmentIndex
1634
+ ])]);
1635
+ previousEnd = word.end;
1636
+ }
1637
+ const protectedRanges = Object.freeze(structure.protectedRanges.map((range) => Object.freeze({ ...range })));
1638
+ const generatedRanges = generateCandidates(Object.freeze({
1639
+ language: input.language,
1640
+ text: fragment.text,
1641
+ words,
1642
+ protectedRanges,
1643
+ maxWords,
1644
+ maxCharacters
1645
+ }));
1646
+ if (!candidateRangesSchema.validate(generatedRanges)) throw new TermContractError("input", [contractIssue("invalid-candidate-generation", "候选生成政策必须返回区间数组。", [
1647
+ "entries",
1648
+ entryIndex,
1649
+ "fragments",
1650
+ fragmentIndex
1651
+ ])]);
1652
+ const wordStarts = new Map(words.map((word, index) => [word.start, index]));
1653
+ const wordEnds = new Map(words.map((word, index) => [word.end, index]));
1654
+ const seenRanges = /* @__PURE__ */ new Set();
1655
+ for (const [rangeIndex, candidateRange] of generatedRanges.entries()) {
1656
+ if (!validTermRange(fragment.text, candidateRange)) throw new TermContractError("input", [contractIssue("invalid-candidate-range", "候选政策必须返回正文内不切开代理对的非空区间。", [
1657
+ "entries",
1658
+ entryIndex,
1659
+ "fragments",
1660
+ fragmentIndex,
1661
+ "candidates",
1662
+ rangeIndex
1663
+ ])]);
1664
+ const range = {
1665
+ start: candidateRange.start,
1666
+ end: candidateRange.end
1667
+ };
1668
+ const firstWord = wordStarts.get(range.start);
1669
+ const lastWord = wordEnds.get(range.end);
1670
+ if (firstWord === void 0 || lastWord === void 0 || lastWord < firstWord) throw new TermContractError("input", [contractIssue("unaligned-candidate-range", "候选区间必须与完整词项边界对齐。", [
1671
+ "entries",
1672
+ entryIndex,
1673
+ "fragments",
1674
+ fragmentIndex,
1675
+ "candidates",
1676
+ rangeIndex
1677
+ ])]);
1678
+ const wordCount = lastWord - firstWord + 1;
1679
+ if (wordCount > maxWords) continue;
1680
+ if (protectedRanges.some((protectedRange) => intersects(range, protectedRange))) continue;
1681
+ const text = fragment.text.slice(range.start, range.end);
1682
+ if (Array.from(text).length > maxCharacters) continue;
1683
+ if (!/[\p{L}\p{M}]/u.test(text)) continue;
1684
+ const rangeKey = `${range.start}:${range.end}`;
1685
+ if (seenRanges.has(rangeKey)) throw new TermContractError("input", [contractIssue("duplicate-candidate-range", "候选政策不能重复返回同一原文区间。", [
1686
+ "entries",
1687
+ entryIndex,
1688
+ "fragments",
1689
+ fragmentIndex,
1690
+ "candidates",
1691
+ rangeIndex
1692
+ ])]);
1693
+ seenRanges.add(rangeKey);
1694
+ const key = (options.memo ? options.memo.memo(normalizeText)(text) : normalizeText(text)).text;
1695
+ let record = accumulated.get(key);
1696
+ if (!record) {
1697
+ record = {
1698
+ count: 0,
1699
+ entries: /* @__PURE__ */ new Set(),
1700
+ examples: [],
1701
+ maxWordCount: 0
1702
+ };
1703
+ accumulated.set(key, record);
1704
+ }
1705
+ record.count += 1;
1706
+ record.entries.add(entryIndex);
1707
+ record.maxWordCount = Math.max(record.maxWordCount, wordCount);
1708
+ if (record.examples.length < maxExamples) record.examples.push(Object.freeze({
1709
+ entryIndex,
1710
+ entryRef: entry.ref,
1711
+ fragmentIndex,
1712
+ ref: fragment.ref,
1713
+ range: Object.freeze(range),
1714
+ text,
1715
+ context: fragment.text
1716
+ }));
1717
+ }
1718
+ }
1719
+ const candidates = [...accumulated].flatMap(([text, record]) => {
1720
+ if (record.count < minOccurrences) return [];
1721
+ const draft = Object.freeze({
1722
+ text,
1723
+ language: input.language,
1724
+ occurrences: record.count,
1725
+ entryCount: record.entries.size,
1726
+ examples: Object.freeze(record.examples),
1727
+ examplesTruncated: record.count > record.examples.length,
1728
+ ranking: Object.freeze({
1729
+ method: "frequency-times-word-count",
1730
+ maxWordCount: record.maxWordCount,
1731
+ score: record.count * record.maxWordCount
1732
+ })
1733
+ });
1734
+ const ranking = options.candidateRanker === void 0 ? draft.ranking : options.candidateRanker(draft);
1735
+ if (!candidateRankSchema.validate(ranking)) throw new TermContractError("input", [contractIssue("invalid-candidate-ranking", "候选排序政策必须返回非空方法名称和有限分值。", ["candidates", text])]);
1736
+ const candidate = Object.freeze({
1737
+ ...draft,
1738
+ ranking: Object.freeze({
1739
+ method: ranking.method,
1740
+ maxWordCount: record.maxWordCount,
1741
+ score: ranking.score
1742
+ })
1743
+ });
1744
+ return options.include && !options.include(candidate) ? [] : [candidate];
1745
+ });
1746
+ candidates.sort((left, right) => right.ranking.score - left.ranking.score || right.entryCount - left.entryCount || (left.text < right.text ? -1 : left.text > right.text ? 1 : 0));
1747
+ return Object.freeze({
1748
+ status: issues.length ? "incomplete" : "complete",
1749
+ candidates: Object.freeze(candidates.slice(0, limit)),
1750
+ issues: Object.freeze(issues),
1751
+ statistics: Object.freeze({
1752
+ entries: input.entries.length,
1753
+ distinctCandidates: accumulated.size,
1754
+ eligibleCandidates: candidates.length,
1755
+ omittedCandidates: Math.max(0, candidates.length - limit)
1756
+ })
1757
+ });
1758
+ }
1759
+ // ../../packages/checks/dist/terms.js
1760
+ const termCheckerVersion = "checks.terminology-rule/v3";
1761
+ function createTermCheckerImplementation(options) {
1762
+ validateTermCheckerOptions(options);
1763
+ const ruleId = options.rule.id;
1764
+ const checkerId = options.id ?? `terminology/${ruleId}`;
1765
+ const load = async (input) => {
1766
+ try {
1767
+ const [terms, context] = await Promise.all([typeof options.terms === "function" ? options.terms(input) : options.terms, options.load?.(input)]);
1768
+ return {
1769
+ terms,
1770
+ context
1771
+ };
1772
+ } catch (error) {
1773
+ if (error instanceof TermContractError) throw new StandardSchemaContractError("术语检查资料", "schema-mismatch", "术语检查资料不符合术语 schema。", void 0, { cause: error });
1774
+ throw error;
1775
+ }
1776
+ };
1777
+ const prepare = async (input) => {
1778
+ if (input.candidate === null) {
1779
+ if (input.association.status !== "missing") throw new Error("候选正文不可用。");
1780
+ return null;
1781
+ }
1782
+ const prepared = await options.prepare(input);
1783
+ if (prepared === null) return null;
1784
+ if (!isRecord(prepared) || !Object.hasOwn(prepared, "comparison") || !Object.hasOwn(prepared, "subject")) throw new QualityCheckerContractError(checkerId, "prepare", "的 prepare 返回了无效结果。");
1785
+ const comparison = await validateComparisonInput$1(prepared.comparison);
1786
+ const analysis = await analyzeTermUse(input.loaded.terms, comparison, { memo: input.memo });
1787
+ const sourceRange = input.snapshot.source.read.scopes[input.sourceUnit.scopeIndex]?.range ?? null;
1788
+ const targetRange = input.translation?.range ?? null;
1789
+ const locations = comparison.groups.map((group, groupIndex) => {
1790
+ const mapLocation = (ref, language, side, fragmentIndex) => options.location?.({
1791
+ ref,
1792
+ language,
1793
+ side,
1794
+ sourceKey: input.association.sourceKey,
1795
+ subject: prepared.subject,
1796
+ groupIndex,
1797
+ ...fragmentIndex === void 0 ? {} : { fragmentIndex }
1798
+ }) ?? {
1799
+ language: side === "source" ? null : language,
1800
+ range: side === "source" ? sourceRange : targetRange,
1801
+ key: input.association.sourceKey
1802
+ };
1803
+ const source = group.source.fragments.map((fragment, fragmentIndex) => mapLocation(fragment.ref, group.source.language, "source", fragmentIndex));
1804
+ const target = group.target.fragments.map((fragment, fragmentIndex) => mapLocation(fragment.ref, group.target.language, "target", fragmentIndex));
1805
+ return {
1806
+ source,
1807
+ target,
1808
+ targetFallback: target[0] ?? mapLocation(group.ref ?? null, group.target.language, "target")
1809
+ };
1810
+ });
1811
+ return {
1812
+ sourceKey: input.association.sourceKey,
1813
+ language: input.association.language,
1814
+ ruleId,
1815
+ analysis,
1816
+ locations
1817
+ };
1818
+ };
1819
+ const definition = {
1820
+ id: checkerId,
1821
+ version: termCheckerVersion,
1822
+ inputSchema: termCheckerInputSchema,
1823
+ load,
1824
+ prepare,
1825
+ check: checkTermUse
1826
+ };
1827
+ return defineChecker.withTypes()(definition);
1828
+ }
1829
+ function createTermCheckerWithTypes() {
1830
+ function create(options) {
1831
+ return createTermCheckerImplementation(options);
1832
+ }
1833
+ return create;
1834
+ }
1835
+ /**
1836
+ * 术语规则工厂;显式宿主泛型先经 withTypes 绑定,规则与覆盖 ID 由调用推断。
1837
+ * 规则识别分析由工厂完成;prepare 只适配当前候选的术语比较及宿主上下文。
1838
+ */
1839
+ const createTermChecker = Object.assign(createTermCheckerImplementation, { withTypes: createTermCheckerWithTypes });
1840
+ function validateTermCheckerOptions(options) {
1841
+ const ruleId = isRecord(options.rule) ? options.rule.id : void 0;
1842
+ if (ruleId !== "require-allowed-translation" && ruleId !== "reject-forbidden-translation") throw new TypeError("术语检查器 rule 必须是受支持的术语规则。");
1843
+ if (typeof options.prepare !== "function") throw new TypeError("术语检查器必须提供 prepare 函数。");
1844
+ if (options.load !== void 0 && typeof options.load !== "function") throw new TypeError("术语检查器 load 必须是函数。");
1845
+ if (options.location !== void 0 && typeof options.location !== "function") throw new TypeError("术语检查器 location 必须是函数。");
1846
+ if (typeof options.terms !== "function" && !isCompiledTermsShape(options.terms)) throw new TypeError("术语检查器 terms 必须是编译结果或加载函数。");
1847
+ }
1848
+ function isCompiledTermsShape(value) {
1849
+ return isRecord(value) && isRecord(value.termbase) && Array.isArray(value.languages) && isRecord(value.analysis);
1850
+ }
1851
+ async function validateComparisonInput$1(value) {
1852
+ assertJsonValue(value, "术语投影输入");
1853
+ let result;
1854
+ try {
1855
+ result = await termComparisonInputSchema["~standard"].validate(value);
1856
+ } catch (error) {
1857
+ throw new StandardSchemaContractError("术语投影输入", "schema-threw", "术语投影输入的 Standard Schema 执行失败。", void 0, { cause: error });
1858
+ }
1859
+ if ("issues" in result) {
1860
+ const issues = result.issues ?? [];
1861
+ throw new StandardSchemaContractError("术语投影输入", "schema-mismatch", `术语投影输入不符合 Standard Schema:${issues.map(({ message }) => message).join(";")}`, issues);
1862
+ }
1863
+ if (!Object.hasOwn(result, "value")) throw new StandardSchemaContractError("术语投影输入", "invalid-schema-result", "术语投影输入的 Standard Schema 返回了无效结果。");
1864
+ assertJsonValue(result.value, "术语分析输入");
1865
+ return result.value;
1866
+ }
1867
+ function checkTermUse(input) {
1868
+ if (input === null) return [];
1869
+ const analysis = input.analysis;
1870
+ const assessment = assessTermUse(analysis.input, analysis, { rules: [ruleFromId(input.ruleId)] });
1871
+ if (assessment.status === "incomplete") throw new Error(assessment.issues.map(({ message }) => message).join(" ") || "缺少完整的术语判断依据。");
1872
+ const object = {
1873
+ kind: "translation",
1874
+ key: input.sourceKey,
1875
+ language: input.language
1876
+ };
1877
+ const location = (groupIndex, side, fragmentIndex) => input.locations[groupIndex][side][fragmentIndex];
1878
+ const evidence = (match, groupIndex, side) => ({
1879
+ role: side === "source" ? "source-term" : "target-term",
1880
+ object: {
1881
+ ...object,
1882
+ kind: side === "source" ? "source" : "translation",
1883
+ language: match.language
1884
+ },
1885
+ location: {
1886
+ ...location(groupIndex, side, match.fragmentIndex),
1887
+ span: match.range
1888
+ },
1889
+ value: match
1890
+ });
1891
+ return assessment.problems.map((problem) => {
1892
+ const target = problem.targetMatches[0];
1893
+ const targetLocation = target === void 0 ? input.locations[problem.groupIndex].targetFallback : location(problem.groupIndex, "target", target.fragmentIndex);
1894
+ return {
1895
+ severity: "error",
1896
+ object: {
1897
+ ...object,
1898
+ conceptId: problem.conceptId,
1899
+ groupIndex: problem.groupIndex,
1900
+ code: problem.code
1901
+ },
1902
+ location: {
1903
+ ...targetLocation,
1904
+ ...target === void 0 ? {} : { span: target.range }
1905
+ },
1906
+ message: problem.message,
1907
+ evidence: [...problem.sourceMatches.map((match) => evidence(match, problem.groupIndex, "source")), ...problem.targetMatches.map((match) => evidence(match, problem.groupIndex, "target"))]
1908
+ };
1909
+ });
1910
+ }
1911
+ function ruleFromId(ruleId) {
1912
+ return ruleId === "require-allowed-translation" ? requireAllowedTranslation() : rejectForbiddenTranslation();
1913
+ }
1914
+ function isTermCheckerInput(value) {
1915
+ if (!isRecord(value)) return false;
1916
+ const analysis = value.analysis;
1917
+ const locations = value.locations;
1918
+ const analysisInput = isRecord(analysis) ? analysis.input : void 0;
1919
+ const groups = isRecord(analysisInput) ? analysisInput.groups : void 0;
1920
+ if (typeof value.sourceKey !== "string" || typeof value.language !== "string" || value.ruleId !== "require-allowed-translation" && value.ruleId !== "reject-forbidden-translation" || !Array.isArray(groups) || !Array.isArray(locations) || locations.length !== groups.length) return false;
1921
+ return locations.every((entry, groupIndex) => {
1922
+ const group = groups[groupIndex];
1923
+ if (!isRecord(group)) return false;
1924
+ const source = isRecord(group.source) ? group.source.fragments : void 0;
1925
+ const target = isRecord(group.target) ? group.target.fragments : void 0;
1926
+ return Array.isArray(source) && Array.isArray(target) && isRecord(entry) && Array.isArray(entry.source) && entry.source.length === source.length && entry.source.every(isQualityLocation) && Array.isArray(entry.target) && entry.target.length === target.length && entry.target.every(isQualityLocation) && isQualityLocation(entry.targetFallback);
1927
+ });
1928
+ }
1929
+ function isQualityLocation(value) {
1930
+ return isRecord(value) && (value.language === null || typeof value.language === "string") && Object.hasOwn(value, "range");
1931
+ }
1932
+ function isRecord(value) {
1933
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1934
+ }
1935
+ const termCheckerInputSchema = { "~standard": {
1936
+ version: 1,
1937
+ vendor: "lioni-checks-terminology",
1938
+ validate(value) {
1939
+ return value === null || isTermCheckerInput(value) ? { value } : { issues: [{ message: "术语检查输入必须包含固定分析和对应宿主位置。" }] };
1940
+ }
1941
+ } };
1942
+ // ../../packages/checks/dist/message-families.js
1943
+ const referenceSchema = z.custom((value) => {
1944
+ try {
1945
+ assertJsonValue(value, "消息族投影引用");
1946
+ return true;
1947
+ } catch {
1948
+ return false;
1949
+ }
1950
+ }, "消息族投影引用必须是无损 JSON 值。");
1951
+ const rangeSchema = z.object({
1952
+ start: z.number().int().nonnegative(),
1953
+ end: z.number().int().nonnegative()
1954
+ }).refine(({ start, end }) => end >= start, "范围终点不得早于起点。").readonly();
1955
+ const messageFamilyIssueSchema = z.object({
1956
+ code: z.string().min(1),
1957
+ message: z.string(),
1958
+ language: z.string().optional(),
1959
+ sourceKey: z.string().optional(),
1960
+ ref: referenceSchema.optional(),
1961
+ range: rangeSchema.optional()
1962
+ }).readonly();
1963
+ const messageFragmentSchema = z.object({
1964
+ ref: referenceSchema,
1965
+ text: z.string(),
1966
+ protectedRanges: z.array(rangeSchema).readonly().optional()
1967
+ }).refine(({ text, protectedRanges }) => protectedRanges === void 0 || protectedRanges.every((range) => isTextRange(text, range)), "保护范围必须落在文本中的完整 Unicode 字符边界上。").readonly();
1968
+ const messageTextSchema = z.object({
1969
+ language: z.string().min(1),
1970
+ fragments: z.array(messageFragmentSchema).readonly(),
1971
+ complete: z.boolean().optional(),
1972
+ issues: z.array(messageFamilyIssueSchema).readonly().optional()
1973
+ }).readonly();
1974
+ const messageFamilyGroupSchema = z.object({
1975
+ ref: referenceSchema,
1976
+ /** 宿主明确声明可相互参照的业务范围。 */
1977
+ scope: z.string().min(1),
1978
+ source: messageTextSchema,
1979
+ target: messageTextSchema
1980
+ }).readonly();
1981
+ const qualityLocationSchema$1 = z.custom((value) => {
1982
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1983
+ const location = value;
1984
+ return (location.language === null || typeof location.language === "string") && Object.hasOwn(location, "range") && (!Object.hasOwn(location, "key") || typeof location.key === "string");
1985
+ });
1986
+ const messageFamilyInputShapeSchema = z.object({
1987
+ groups: z.array(messageFamilyGroupSchema).readonly(),
1988
+ /** 与投影文本一起固定的候选位置;通用参照仍从事实回退。 */
1989
+ location: qualityLocationSchema$1.optional(),
1990
+ /** false 表示仍有未投影的消息组;单个目标正文缺失由 target.complete 表达。 */
1991
+ complete: z.boolean().optional(),
1992
+ issues: z.array(messageFamilyIssueSchema).readonly().optional()
1993
+ }).readonly();
1994
+ /** 投影包含宿主引用与扩展属性;验证契约后保留原值,不让对象解析裁剪它们。 */
1995
+ const messageFamilyInputSchema = z.unknown().transform((value, context) => {
1996
+ const parsed = messageFamilyInputShapeSchema.safeParse(value);
1997
+ if (!parsed.success) {
1998
+ for (const issue of parsed.error.issues) context.issues.push({
1999
+ code: "custom",
2000
+ message: issue.message,
2001
+ path: issue.path,
2002
+ input: value
2003
+ });
2004
+ return z.NEVER;
2005
+ }
2006
+ return value;
2007
+ });
2008
+ const messageFamilyLimitsSchema = z.object({
2009
+ maxCategories: z.number().int().positive(),
2010
+ maxSourcesPerCategory: z.number().int().positive()
2011
+ }).readonly();
2012
+ function isTextRange(text, range) {
2013
+ if (range.end > text.length) return false;
2014
+ return isCodePointBoundary(text, range.start) && isCodePointBoundary(text, range.end);
2015
+ }
2016
+ function isCodePointBoundary(text, index) {
2017
+ if (index === 0 || index === text.length) return true;
2018
+ const before = text.charCodeAt(index - 1);
2019
+ const after = text.charCodeAt(index);
2020
+ return !(before >= 55296 && before <= 56319 && after >= 56320 && after <= 57343);
2021
+ }
2022
+ /** 固定证据只索引一次;同一物理记录在同一类别中的别名不重复计数。 */
2023
+ function indexMessageFamilies(references) {
2024
+ const families = /* @__PURE__ */ new Map();
2025
+ const ordered = references.map((reference) => ({
2026
+ reference,
2027
+ key: messageFamilyEvidenceKey([
2028
+ reference.targetKey,
2029
+ reference.translationIdentity,
2030
+ reference.sourceKey,
2031
+ reference.group.ref,
2032
+ reference.group.scope,
2033
+ reference.group.source,
2034
+ reference.group.target,
2035
+ reference.sourceSignatures.map(messageFamilySignatureEvidence),
2036
+ reference.targetSignatures.map(messageFamilySignatureEvidence),
2037
+ reference.translationLocation ?? null
2038
+ ])
2039
+ })).sort((left, right) => left.key < right.key ? -1 : left.key > right.key ? 1 : 0).map(({ reference }) => reference);
2040
+ for (const reference of ordered) {
2041
+ let family = families.get(reference.familyKey);
2042
+ if (family === void 0) {
2043
+ family = {
2044
+ categories: /* @__PURE__ */ new Map(),
2045
+ categoriesByRecord: /* @__PURE__ */ new Map(),
2046
+ referenceCount: 0
2047
+ };
2048
+ families.set(reference.familyKey, family);
2049
+ }
2050
+ let category = family.categories.get(reference.targetKey);
2051
+ if (category === void 0) {
2052
+ category = {
2053
+ key: reference.targetKey,
2054
+ references: /* @__PURE__ */ new Map()
2055
+ };
2056
+ family.categories.set(reference.targetKey, category);
2057
+ }
2058
+ if (category.references.has(reference.translationIndex)) continue;
2059
+ category.references.set(reference.translationIndex, reference);
2060
+ family.referenceCount++;
2061
+ let keys = family.categoriesByRecord.get(reference.translationIndex);
2062
+ if (keys === void 0) {
2063
+ keys = /* @__PURE__ */ new Set();
2064
+ family.categoriesByRecord.set(reference.translationIndex, keys);
2065
+ }
2066
+ keys.add(reference.targetKey);
2067
+ }
2068
+ return { families };
2069
+ }
2070
+ /** 按候选替代的物理索引减去旧值;判断使用全量统计,输出只取有界代表。 */
2071
+ function compareMessageFamily(index, candidate, excludedRecordIndexes, limits) {
2072
+ if (!messageFamilyLimitsSchema.safeParse(limits).success) throw new TypeError("消息族展示上限必须为正整数。");
2073
+ const family = index.families.get(candidate.familyKey);
2074
+ if (family === void 0) return {
2075
+ status: "no-comparison",
2076
+ categoryCount: 0,
2077
+ referenceCount: 0,
2078
+ omittedCategories: 0,
2079
+ omittedReferences: 0,
2080
+ categories: []
2081
+ };
2082
+ const removed = /* @__PURE__ */ new Map();
2083
+ let referenceCount = family.referenceCount;
2084
+ let categoryCount = family.categories.size;
2085
+ for (const recordIndex of excludedRecordIndexes) for (const key of family.categoriesByRecord.get(recordIndex) ?? []) {
2086
+ removed.set(key, (removed.get(key) ?? 0) + 1);
2087
+ referenceCount--;
2088
+ }
2089
+ for (const [key, count] of removed) if (family.categories.get(key).references.size === count) categoryCount--;
2090
+ const ownCategory = family.categories.get(candidate.targetKey);
2091
+ const ownCount = (ownCategory?.references.size ?? 0) - (removed.get(candidate.targetKey) ?? 0);
2092
+ const different = referenceCount > ownCount;
2093
+ const categories = [];
2094
+ let shownReferences = 0;
2095
+ const append = (category) => {
2096
+ const count = category.references.size - (removed.get(category.key) ?? 0);
2097
+ if (count === 0 || categories.length >= limits.maxCategories) return;
2098
+ const references = [];
2099
+ for (const [recordIndex, reference] of category.references) {
2100
+ if (excludedRecordIndexes.has(recordIndex)) continue;
2101
+ references.push(reference);
2102
+ if (references.length >= limits.maxSourcesPerCategory) break;
2103
+ }
2104
+ shownReferences += references.length;
2105
+ categories.push({
2106
+ key: category.key,
2107
+ referenceCount: count,
2108
+ references
2109
+ });
2110
+ };
2111
+ if (different) for (const category of family.categories.values()) {
2112
+ if (category.key !== candidate.targetKey) append(category);
2113
+ if (categories.length >= limits.maxCategories) break;
2114
+ }
2115
+ if (ownCategory !== void 0) append(ownCategory);
2116
+ return {
2117
+ status: referenceCount === 0 ? "no-comparison" : different ? "different" : "consistent",
2118
+ categoryCount,
2119
+ referenceCount,
2120
+ omittedCategories: categoryCount - categories.length,
2121
+ omittedReferences: referenceCount - shownReferences,
2122
+ categories
2123
+ };
2124
+ }
2125
+ /** 指纹准备、代表选择和报告共同使用的签名证据,省略识别器私有值。 */
2126
+ function messageFamilySignatureEvidence(signature) {
2127
+ return {
2128
+ parts: signature.parts,
2129
+ slots: signature.slots.map(({ start, end, kind, identity, raw }) => ({
2130
+ start,
2131
+ end,
2132
+ kind,
2133
+ identity,
2134
+ raw
2135
+ }))
2136
+ };
2137
+ }
2138
+ /** JSON 对象属性顺序不参与消息族证据排序,数组顺序仍表达业务内容。 */
2139
+ function messageFamilyEvidenceKey(value) {
2140
+ return JSON.stringify(value, (_key, item) => item !== null && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)) : item);
2141
+ }
2142
+ // ../../packages/checks/dist/message-family-checker.js
2143
+ const checkInputSchema = z.custom((value) => {
2144
+ assertJsonValue(value, "消息族完整检查输入");
2145
+ return typeof value === "object" && value !== null;
2146
+ });
2147
+ const defaultLimits = {
2148
+ maxCategories: 6,
2149
+ maxSourcesPerCategory: 3
2150
+ };
2151
+ const projectionSchema = messageFamilyInputSchema;
2152
+ const defaultTemplate = { abstract: () => void 0 };
2153
+ function messageFamilyCheckerFor() {
2154
+ function create(options) {
2155
+ return messageFamilyChecker(options);
2156
+ }
2157
+ return create;
2158
+ }
2159
+ /** 显式宿主类型后继续推导加载资料与检查项 ID。 */
2160
+ const createMessageFamilyChecker = Object.assign(messageFamilyChecker, { withTypes: messageFamilyCheckerFor });
2161
+ function messageFamilyChecker(options) {
2162
+ const checkId = options.id ?? "message-family-consistency";
2163
+ const analysis = options.analysis ?? createTextAnalysis();
2164
+ const sourceTemplate = options.sourceTemplate ?? defaultTemplate;
2165
+ const targetTemplate = options.targetTemplate ?? defaultTemplate;
2166
+ const limits = {
2167
+ maxCategories: options.limits?.maxCategories ?? defaultLimits.maxCategories,
2168
+ maxSourcesPerCategory: options.limits?.maxSourcesPerCategory ?? defaultLimits.maxSourcesPerCategory
2169
+ };
2170
+ if (!messageFamilyLimitsSchema.safeParse(limits).success) throw new TypeError("消息族展示上限必须为正整数。");
2171
+ if (typeof options.prepare !== "function" || typeof options.reference !== "function") throw new TypeError("消息族检查必须提供 prepare 与 reference 函数。");
2172
+ if (options.load !== void 0 && typeof options.load !== "function") throw new TypeError("消息族 load 必须为函数。");
2173
+ if (typeof sourceTemplate.abstract !== "function" || typeof targetTemplate.abstract !== "function") throw new TypeError("消息族模板必须提供 abstract 函数。");
2174
+ if (options.targetEquivalence !== void 0 && typeof options.targetEquivalence !== "function") throw new TypeError("消息族目标等价策略必须为函数。");
2175
+ async function projectSavedReference(reference, context) {
2176
+ const { sourceKey, language } = reference;
2177
+ const projected = validateProjection(await options.reference(reference, context), sourceKey, language, checkId);
2178
+ const projectionIssues = withSource(projected.issues ?? [], sourceKey, language);
2179
+ if (projected.complete === false && projectionIssues.length === 0) projectionIssues.push(issue("referenceProjectionIncomplete", "保存参照投影仍有未提供的消息组。", {
2180
+ language,
2181
+ sourceKey
2182
+ }));
2183
+ return {
2184
+ projected,
2185
+ projectionIssues,
2186
+ signedGroups: (await Promise.all(projected.groups.map(async (group) => {
2187
+ assertProjectedLanguage(group, language, checkId);
2188
+ return signGroup(group, analysis, sourceTemplate, targetTemplate, options.targetEquivalence, language, { sourceKey }, context.memo, context);
2189
+ }))).map((signed) => ({
2190
+ ...signed,
2191
+ sourceSignatures: signed.sourceSignatures.map(messageFamilySignatureEvidence),
2192
+ ...signed.targetSignatures === void 0 ? {} : { targetSignatures: signed.targetSignatures.map(messageFamilySignatureEvidence) }
2193
+ }))
2194
+ };
2195
+ }
2196
+ async function prepareSavedReference(records, reference) {
2197
+ const prepared = records.get(reference.association)?.get(reference.translation);
2198
+ if (prepared === void 0) throw new TypeError("消息族参照目录缺少现存记录。");
2199
+ if ("error" in prepared) throw prepared.error;
2200
+ return prepared;
2201
+ }
2202
+ async function evaluateReferences(input, language, replacedIndex, familyKeys, associations, sourceByKey, readEvidence, records) {
2203
+ const snapshot = input.snapshot;
2204
+ const issues = [];
2205
+ let incomplete = false;
2206
+ if (readEvidence) {
2207
+ if (snapshot.source.read.status !== "complete" || snapshot.source.read.scopes.some(({ enumeration }) => enumeration !== "complete")) {
2208
+ incomplete = true;
2209
+ issues.push(issue("sourceEvidenceIncomplete", "原文读取不完整,可能缺少消息族参照。"));
2210
+ }
2211
+ const translationRead = snapshot.translations.reads.find((read) => read.language === language);
2212
+ if (translationRead === void 0 || translationRead.error !== void 0 || translationRead.scopes.some((scope) => scope.enumeration !== "complete" && scope.covers.length === 0)) {
2213
+ incomplete = true;
2214
+ issues.push(issue("translationEvidenceIncomplete", `目标语言 ${language} 的译文读取不完整,可能缺少消息族参照。`, { language }));
2215
+ }
2216
+ }
2217
+ for (const association of associations) {
2218
+ if (association.language !== language) continue;
2219
+ const sourceKey = association.sourceKey;
2220
+ const sourceUnit = sourceByKey.get(sourceKey);
2221
+ if (sourceUnit === void 0) {
2222
+ incomplete = true;
2223
+ issues.push(issue("sourceAssociationUnavailable", "消息族关联缺少对应原文单元。", {
2224
+ language,
2225
+ sourceKey
2226
+ }));
2227
+ continue;
2228
+ }
2229
+ const associationIssues = [];
2230
+ let associationIncomplete = sourceUnit.bodyAvailability !== "available" || association.coverageStatus !== "complete" || ["unknown", "unavailable"].includes(association.status);
2231
+ if (sourceUnit.bodyAvailability !== "available") associationIssues.push(issue("sourceBodyUnavailable", "原文正文不可用,无法完整投影消息族。", {
2232
+ language,
2233
+ sourceKey
2234
+ }));
2235
+ if (association.coverageStatus !== "complete" || ["unknown", "unavailable"].includes(association.status)) associationIssues.push(issue(association.status === "unknown" ? "translationAssociationUnknown" : association.status === "unavailable" ? "translationBodyUnavailable" : "translationAssociationIncomplete", `原文 ${sourceKey} 的目标译文关联不完整(${association.status})。`, {
2236
+ language,
2237
+ sourceKey
2238
+ }));
2239
+ let knownFamilies = association.translationIndexes.length > 0;
2240
+ const preparedRecords = /* @__PURE__ */ new Map();
2241
+ for (const translationIndex of association.translationIndexes) {
2242
+ if (translationIndex === replacedIndex) continue;
2243
+ const translation = snapshot.translations.records[translationIndex];
2244
+ if (translation === void 0 || translation.language !== language) {
2245
+ knownFamilies = false;
2246
+ continue;
2247
+ }
2248
+ const prepared = await prepareSavedReference(records, {
2249
+ kind: "reference",
2250
+ sourceUnit,
2251
+ sourceKey,
2252
+ language,
2253
+ association,
2254
+ translation
2255
+ });
2256
+ preparedRecords.set(translationIndex, prepared);
2257
+ if (prepared.projected.complete === false || prepared.signedGroups.some(({ familyKey }) => familyKey === "")) knownFamilies = false;
2258
+ }
2259
+ let relevant = false;
2260
+ for (const translationIndex of association.translationIndexes) {
2261
+ if (translationIndex === replacedIndex) continue;
2262
+ const translation = snapshot.translations.records[translationIndex];
2263
+ if (translation === void 0 || translation.language !== language) {
2264
+ associationIncomplete = true;
2265
+ associationIssues.push(issue("translationRecordUnavailable", `目标语言 ${language} 的关联译文记录不可用。`, {
2266
+ language,
2267
+ sourceKey
2268
+ }));
2269
+ continue;
2270
+ }
2271
+ const { projected, projectionIssues, signedGroups } = preparedRecords.get(translationIndex);
2272
+ if (projected.complete === false) associationIncomplete = true;
2273
+ const projectionRelevant = signedGroups.some(({ familyKey }) => familyKeys.has(familyKey));
2274
+ relevant ||= projectionRelevant;
2275
+ if (!knownFamilies || projectionRelevant) associationIssues.push(...projectionIssues);
2276
+ for (const signed of signedGroups) {
2277
+ if (signed.familyKey !== "" && !familyKeys.has(signed.familyKey)) continue;
2278
+ issues.push(...signed.issues);
2279
+ if (signed.familyKey === "" || signed.targetKey === void 0 || signed.targetSignatures === void 0) {
2280
+ incomplete = true;
2281
+ continue;
2282
+ }
2283
+ }
2284
+ }
2285
+ if (relevant || !knownFamilies && (associationIssues.length > 0 || preparedRecords.size > 0)) {
2286
+ issues.push(...associationIssues);
2287
+ incomplete ||= associationIncomplete;
2288
+ }
2289
+ }
2290
+ return {
2291
+ incomplete,
2292
+ issues: issues.sort(stableCompare)
2293
+ };
2294
+ }
2295
+ async function prepareDirectory(input, language) {
2296
+ const preparedRecords = /* @__PURE__ */ new WeakMap();
2297
+ const snapshot = input.snapshot;
2298
+ const sourceByKey = new Map(snapshot.source.units.map((unit) => [unit.key, unit]));
2299
+ const associations = snapshot.associations.filter((item) => item.language === language);
2300
+ const reads = await evaluateReferences(input, language, void 0, /* @__PURE__ */ new Set(), [], sourceByKey, true, preparedRecords);
2301
+ const byFamily = /* @__PURE__ */ new Map();
2302
+ const unknown = /* @__PURE__ */ new Set();
2303
+ const references = [];
2304
+ for (const association of associations) {
2305
+ const { sourceKey } = association;
2306
+ const sourceUnit = sourceByKey.get(sourceKey);
2307
+ if (sourceUnit === void 0) {
2308
+ unknown.add(association);
2309
+ continue;
2310
+ }
2311
+ if (association.translationIndexes.length === 0 && (sourceUnit.bodyAvailability !== "available" || association.coverageStatus !== "complete" || ["unknown", "unavailable"].includes(association.status))) unknown.add(association);
2312
+ for (const translationIndex of association.translationIndexes) {
2313
+ const translation = snapshot.translations.records[translationIndex];
2314
+ if (translation === void 0 || translation.language !== language) {
2315
+ unknown.add(association);
2316
+ continue;
2317
+ }
2318
+ let records = preparedRecords.get(association);
2319
+ if (records === void 0) {
2320
+ records = /* @__PURE__ */ new Map();
2321
+ preparedRecords.set(association, records);
2322
+ }
2323
+ let prepared;
2324
+ try {
2325
+ prepared = await projectSavedReference({
2326
+ kind: "reference",
2327
+ sourceUnit,
2328
+ sourceKey,
2329
+ language,
2330
+ association,
2331
+ translation
2332
+ }, input);
2333
+ records.set(translation, prepared);
2334
+ } catch (error) {
2335
+ records.set(translation, { error });
2336
+ unknown.add(association);
2337
+ continue;
2338
+ }
2339
+ if (prepared.projected.complete === false) unknown.add(association);
2340
+ for (const signed of prepared.signedGroups) {
2341
+ if (signed.familyKey === "") {
2342
+ unknown.add(association);
2343
+ continue;
2344
+ }
2345
+ let members = byFamily.get(signed.familyKey);
2346
+ if (members === void 0) {
2347
+ members = /* @__PURE__ */ new Set();
2348
+ byFamily.set(signed.familyKey, members);
2349
+ }
2350
+ members.add(association);
2351
+ if (signed.targetKey === void 0 || signed.targetSignatures === void 0) continue;
2352
+ references.push({
2353
+ familyKey: signed.familyKey,
2354
+ targetKey: signed.targetKey,
2355
+ translationIndex,
2356
+ translationIdentity: translation.identity,
2357
+ sourceKey,
2358
+ group: signed.group,
2359
+ sourceSignatures: signed.sourceSignatures,
2360
+ targetSignatures: signed.targetSignatures,
2361
+ translationLocation: prepared.projected.location ?? {
2362
+ language,
2363
+ range: translation.range,
2364
+ key: sourceKey
2365
+ }
2366
+ });
2367
+ }
2368
+ }
2369
+ }
2370
+ const index = indexMessageFamilies(references);
2371
+ const orderedFamilies = new Map([...index.families].map(([familyKey, family]) => [familyKey, [...family.categories.values()].flatMap((category) => [...category.references.values()]).map((reference) => {
2372
+ const { translationIndex: _translationIndex, ...evidence } = reference;
2373
+ return {
2374
+ translationIndex: reference.translationIndex,
2375
+ reference: evidence,
2376
+ key: messageFamilyEvidenceKey(evidence)
2377
+ };
2378
+ }).sort((left, right) => left.key < right.key ? -1 : left.key > right.key ? 1 : 0).map(({ translationIndex, reference }) => ({
2379
+ translationIndex,
2380
+ reference
2381
+ }))]));
2382
+ return async (excluded, familyKeys) => {
2383
+ const relevant = new Set([...familyKeys].flatMap((familyKey) => [...byFamily.get(familyKey) ?? []]));
2384
+ for (const association of unknown) relevant.add(association);
2385
+ const evidence = await evaluateReferences(input, language, excluded, familyKeys, [...relevant], sourceByKey, false, preparedRecords);
2386
+ return {
2387
+ references: [...familyKeys].sort().flatMap((familyKey) => orderedFamilies.get(familyKey) ?? []).filter(({ translationIndex }) => translationIndex !== excluded).map(({ reference }) => reference),
2388
+ incomplete: reads.incomplete || evidence.incomplete,
2389
+ issues: [...reads.issues, ...evidence.issues].sort(stableCompare)
2390
+ };
2391
+ };
2392
+ }
2393
+ return defineChecker.withTypes()({
2394
+ id: checkId,
2395
+ version: "checks.message-family-consistency/v6",
2396
+ inputSchema: checkInputSchema.nullable(),
2397
+ load: async (input) => {
2398
+ const loaded = await options.load?.(input);
2399
+ const context = fixedContext({
2400
+ ...input,
2401
+ loaded
2402
+ });
2403
+ const directories = /* @__PURE__ */ new Map();
2404
+ for (const language of new Set(input.candidates.map((candidate) => candidate.language))) directories.set(language, await prepareDirectory(context, language));
2405
+ return {
2406
+ loaded,
2407
+ directories
2408
+ };
2409
+ },
2410
+ prepare: async (input) => {
2411
+ if (input.candidate === null) {
2412
+ if (input.association.status !== "missing") throw new Error("候选正文不可用。");
2413
+ return null;
2414
+ }
2415
+ const context = fixedContext({
2416
+ ...input,
2417
+ loaded: input.loaded.loaded
2418
+ });
2419
+ const preparation = await options.prepare({
2420
+ ...input,
2421
+ loaded: input.loaded.loaded
2422
+ });
2423
+ if (preparation === null) return null;
2424
+ if (typeof preparation !== "object" || Array.isArray(preparation)) throw new QualityCheckerContractError(checkId, "prepare", "的 prepare 返回了无效结果。");
2425
+ const { sourceKey, language } = input.candidate;
2426
+ const projected = validateProjection(preparation, sourceKey, language, checkId);
2427
+ if (input.sourceUnit.bodyAvailability !== "available") throw new Error("候选对应的原文正文不可用。");
2428
+ if (projected.complete === false) throw new Error(projected.issues?.map(({ message }) => message).join(" ") || "候选投影仍有未提供的消息组。");
2429
+ const groups = await Promise.all(projected.groups.map(async (group) => {
2430
+ assertProjectedLanguage(group, language, checkId);
2431
+ const signed = await signGroup(group, analysis, sourceTemplate, targetTemplate, options.targetEquivalence, language, { sourceKey }, input.memo, context);
2432
+ if (signed.familyKey === "" || signed.targetKey === void 0) throw new Error(signed.issues.map(({ message }) => message).join(" ") || "无法确定候选签名。");
2433
+ return {
2434
+ ...signed,
2435
+ targetKey: signed.targetKey,
2436
+ sourceSignatures: signed.sourceSignatures.map(messageFamilySignatureEvidence),
2437
+ ...signed.targetSignatures === void 0 ? {} : { targetSignatures: signed.targetSignatures.map(messageFamilySignatureEvidence) }
2438
+ };
2439
+ }));
2440
+ const excluded = candidateRecordIndex(input.snapshot, sourceKey, language, input.memo);
2441
+ if (excluded === void 0 && (input.association.coverageStatus !== "complete" || input.association.status === "unknown" || input.association.status === "unavailable")) throw new Error("无法唯一确认候选替代的已保存译文。");
2442
+ const references = await input.loaded.directories.get(language)(excluded, new Set(groups.map(({ familyKey }) => familyKey)));
2443
+ if (references.incomplete) throw new Error(references.issues.map(({ message }) => message).join(" ") || "缺少完整的同族参照。");
2444
+ return {
2445
+ sourceKey,
2446
+ language,
2447
+ groups,
2448
+ savedReferences: references.references,
2449
+ location: projected.location ?? translationLocation(input.snapshot, sourceKey, language, excluded),
2450
+ limits
2451
+ };
2452
+ },
2453
+ check: (preparedInput) => {
2454
+ if (preparedInput === null) return [];
2455
+ const input = preparedInput;
2456
+ const object = {
2457
+ kind: "translation-unit",
2458
+ key: input.sourceKey,
2459
+ language: input.language
2460
+ };
2461
+ const candidateLocation = input.location;
2462
+ const diagnostics = [];
2463
+ const recordIndexes = /* @__PURE__ */ new Map();
2464
+ const referenceIndex = indexMessageFamilies(input.savedReferences.map((reference) => {
2465
+ const identity = messageFamilyEvidenceKey(reference.translationIdentity);
2466
+ if (!recordIndexes.has(identity)) recordIndexes.set(identity, recordIndexes.size);
2467
+ return {
2468
+ ...reference,
2469
+ translationIndex: recordIndexes.get(identity)
2470
+ };
2471
+ }));
2472
+ for (const signed of input.groups) {
2473
+ const comparison = compareMessageFamily(referenceIndex, {
2474
+ familyKey: signed.familyKey,
2475
+ targetKey: signed.targetKey
2476
+ }, /* @__PURE__ */ new Set(), input.limits);
2477
+ if (comparison.status === "different") diagnostics.push(createDiagnostic(object, candidateLocation, "同一消息族的已保存译文存在不同表达;此发现不裁定当前候选错误。", comparison, signed, input));
2478
+ }
2479
+ return diagnostics;
2480
+ }
2481
+ });
2482
+ }
2483
+ async function signGroup(group, analysis, sourceTemplate, targetTemplate, targetEquivalence, language, context, memo, input) {
2484
+ const issues = [];
2485
+ const source = await signText(group.source.fragments, group.source.language, group.source.complete, group.source.issues, sourceTemplate, analysis, group.ref, context.sourceKey, memo);
2486
+ issues.push(...source.issues);
2487
+ if (source.signatures === void 0) return {
2488
+ group,
2489
+ familyKey: "",
2490
+ sourceSignatures: [],
2491
+ issues
2492
+ };
2493
+ const familyKey = JSON.stringify([
2494
+ group.scope,
2495
+ group.source.language,
2496
+ group.target.language,
2497
+ source.signatures.map(signatureKey)
2498
+ ]);
2499
+ const target = await signText(group.target.fragments, group.target.language, group.target.complete, group.target.issues, targetTemplate, analysis, group.ref, context.sourceKey, memo);
2500
+ issues.push(...target.issues);
2501
+ if (target.signatures === void 0) return {
2502
+ group,
2503
+ familyKey,
2504
+ sourceSignatures: source.signatures,
2505
+ issues
2506
+ };
2507
+ const targetParts = target.signatures.map((signature) => {
2508
+ const key = targetEquivalence?.(signature, language, fixedContext(input)) ?? signatureKey(signature);
2509
+ if (typeof key !== "string" || key.length === 0) throw new TypeError("目标签名等价键必须为非空字符串。");
2510
+ return key;
2511
+ });
2512
+ return {
2513
+ group,
2514
+ familyKey,
2515
+ sourceSignatures: source.signatures,
2516
+ targetSignatures: target.signatures,
2517
+ targetKey: JSON.stringify([group.target.language, targetParts]),
2518
+ issues
2519
+ };
2520
+ }
2521
+ async function signText(fragments, language, declaredComplete, inputIssues, policy, analysis, ref, sourceKey, memo) {
2522
+ const issues = (inputIssues ?? []).map((item) => ({
2523
+ ...item,
2524
+ language: item.language ?? language,
2525
+ ...item.sourceKey !== void 0 || sourceKey === void 0 ? {} : { sourceKey },
2526
+ ref: item.ref ?? ref
2527
+ }));
2528
+ if (declaredComplete === false) {
2529
+ if (issues.length === 0) issues.push(issue("messageTextIncomplete", "消息文本投影不完整,不能形成完整签名。", {
2530
+ language,
2531
+ ...sourceKey === void 0 ? {} : { sourceKey },
2532
+ ref
2533
+ }));
2534
+ return { issues };
2535
+ }
2536
+ const signatures = [];
2537
+ for (const fragment of fragments) {
2538
+ const input = {
2539
+ text: fragment.text,
2540
+ language,
2541
+ ...fragment.protectedRanges === void 0 ? {} : { protectedRanges: fragment.protectedRanges }
2542
+ };
2543
+ const structure = await analysis.structures(input, { memo });
2544
+ if (!structure.complete) {
2545
+ issues.push(...structure.issues.map((item) => ({
2546
+ ...item,
2547
+ language,
2548
+ ...sourceKey === void 0 ? {} : { sourceKey },
2549
+ ref: fragment.ref
2550
+ })));
2551
+ if (structure.issues.length === 0) issues.push(issue("structureIncomplete", "消息结构分析不完整,不能形成完整签名。", {
2552
+ language,
2553
+ ...sourceKey === void 0 ? {} : { sourceKey },
2554
+ ref: fragment.ref
2555
+ }));
2556
+ return { issues };
2557
+ }
2558
+ signatures.push(await analysis.signature(input, policy, { memo }));
2559
+ }
2560
+ return {
2561
+ signatures,
2562
+ issues
2563
+ };
2564
+ }
2565
+ function createDiagnostic(object, location, message, comparison, signed, subject) {
2566
+ return {
2567
+ severity: "warning",
2568
+ object,
2569
+ location,
2570
+ message,
2571
+ evidence: [
2572
+ {
2573
+ role: "candidate",
2574
+ object,
2575
+ location,
2576
+ value: {
2577
+ sourceKey: subject.sourceKey,
2578
+ language: subject.language,
2579
+ groupRef: signed.group.ref,
2580
+ scope: signed.group.scope,
2581
+ source: signed.group.source,
2582
+ target: signed.group.target,
2583
+ signatures: signed.targetSignatures?.map(messageFamilySignatureEvidence) ?? null
2584
+ }
2585
+ },
2586
+ ...comparison.categories.flatMap(({ references }) => references.map((reference) => ({
2587
+ role: "saved-reference",
2588
+ object: {
2589
+ kind: "translation-unit",
2590
+ key: reference.sourceKey,
2591
+ language: reference.group.target.language
2592
+ },
2593
+ location: reference.translationLocation ?? {
2594
+ language: reference.group.target.language,
2595
+ range: null,
2596
+ key: reference.sourceKey
2597
+ },
2598
+ value: {
2599
+ translationIdentity: reference.translationIdentity,
2600
+ sourceKey: reference.sourceKey,
2601
+ groupRef: reference.group.ref,
2602
+ scope: reference.group.scope,
2603
+ source: reference.group.source,
2604
+ target: reference.group.target,
2605
+ sourceSignatures: reference.sourceSignatures.map(messageFamilySignatureEvidence),
2606
+ targetSignatures: reference.targetSignatures.map(messageFamilySignatureEvidence),
2607
+ category: reference.targetKey
2608
+ }
2609
+ }))),
2610
+ {
2611
+ role: "comparison-summary",
2612
+ object,
2613
+ location,
2614
+ value: {
2615
+ categoryCount: comparison.categoryCount,
2616
+ referenceCount: comparison.referenceCount,
2617
+ omittedCategories: comparison.omittedCategories,
2618
+ omittedReferences: comparison.omittedReferences,
2619
+ categories: comparison.categories.map(({ key, referenceCount }) => ({
2620
+ key,
2621
+ referenceCount
2622
+ }))
2623
+ }
2624
+ }
2625
+ ]
2626
+ };
2627
+ }
2628
+ function stableCompare(left, right) {
2629
+ const leftKey = messageFamilyEvidenceKey(left);
2630
+ const rightKey = messageFamilyEvidenceKey(right);
2631
+ return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0;
2632
+ }
2633
+ function candidateRecordIndex(snapshot, sourceKey, language, memo) {
2634
+ const association = findAssociation(snapshot, sourceKey, language, memo);
2635
+ if (association?.coverageStatus === "complete" && (association.status === "matched" || association.status === "unavailable") && association.translationIndexes.length === 1) return association.translationIndexes[0];
2636
+ }
2637
+ function findAssociation(snapshot, sourceKey, language, memo) {
2638
+ return memo.memo(indexAssociations)(snapshot).get(language)?.get(sourceKey);
2639
+ }
2640
+ /** 同次事实的关联定位只建一次,避免候选替换和指纹阶段反复线性查找。 */
2641
+ function indexAssociations(snapshot) {
2642
+ const languages = /* @__PURE__ */ new Map();
2643
+ for (const association of snapshot.associations) {
2644
+ let sources = languages.get(association.language);
2645
+ if (sources === void 0) {
2646
+ sources = /* @__PURE__ */ new Map();
2647
+ languages.set(association.language, sources);
2648
+ }
2649
+ if (!sources.has(association.sourceKey)) sources.set(association.sourceKey, association);
2650
+ }
2651
+ return languages;
2652
+ }
2653
+ function translationLocation(snapshot, sourceKey, language, translationIndex) {
2654
+ return {
2655
+ language,
2656
+ range: (translationIndex === void 0 ? void 0 : snapshot.translations.records[translationIndex])?.range ?? null,
2657
+ key: sourceKey
2658
+ };
2659
+ }
2660
+ function withSource(issues, sourceKey, language) {
2661
+ return issues.map((item) => ({
2662
+ ...item,
2663
+ ...item.sourceKey === void 0 && sourceKey !== void 0 ? { sourceKey } : {},
2664
+ language: item.language ?? language
2665
+ }));
2666
+ }
2667
+ function issue(code, message, details = {}) {
2668
+ return {
2669
+ code,
2670
+ message,
2671
+ ...details
2672
+ };
2673
+ }
2674
+ function assertProjectedLanguage(group, language, checkId) {
2675
+ if (group.target.language !== language) throw new StandardSchemaContractError(`QA 检查项 ${checkId} 消息族投影`, "schema-mismatch", `消息族投影的目标语言 ${group.target.language} 与适配器语言 ${language} 不一致。`);
2676
+ }
2677
+ function validateProjection(value, sourceKey, language, checkId) {
2678
+ const result = projectionSchema["~standard"].validate(value);
2679
+ if ("then" in result) throw new StandardSchemaContractError(`QA 检查项 ${checkId} 消息族投影`, "invalid-schema-result", "消息族投影 schema 必须同步验证。");
2680
+ if (result.issues !== void 0) throw new StandardSchemaContractError(`消息族投影 ${sourceKey}/${language}`, "schema-mismatch", result.issues.map(({ message }) => message).join(";"), result.issues);
2681
+ return result.value;
2682
+ }
2683
+ function fixedContext(input) {
2684
+ const { snapshot, loaded, relationships, memo } = input;
2685
+ return {
2686
+ snapshot,
2687
+ loaded,
2688
+ relationships,
2689
+ memo
2690
+ };
2691
+ }
2692
+ // ../../packages/checks/dist/quantities.js
2693
+ /** 按集合比较数量事实,并为每个目标分支选择差异最少的源分支。 */
2694
+ function compareQuantityBranches(input) {
2695
+ const issues = [];
2696
+ for (const [targetBranchIndex, targetBranch] of input.target.entries()) {
2697
+ const targetValues = new Set(targetBranch.values);
2698
+ let best;
2699
+ for (const sourceBranch of input.source) {
2700
+ const sourceValues = new Set(sourceBranch.values);
2701
+ const missing = [...sourceValues].filter((value) => !targetValues.has(value));
2702
+ const extra = sourceValues.size ? [...targetValues].filter((value) => !sourceValues.has(value)) : [];
2703
+ const score = missing.length + extra.length;
2704
+ if (best === void 0 || score < best.score) best = {
2705
+ missing,
2706
+ extra,
2707
+ score
2708
+ };
2709
+ }
2710
+ if (best && (best.missing.length || best.extra.length)) issues.push({
2711
+ targetBranchIndex,
2712
+ missing: best.missing,
2713
+ extra: best.extra
2714
+ });
2715
+ }
2716
+ return issues;
2717
+ }
2718
+ // ../../packages/checks/dist/protected-literals.js
2719
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
2720
+ /** 原文实际含有的字面值必须在译文中按 ASCII 标识符边界保留。 */
2721
+ function compareProtectedLiterals(input) {
2722
+ return input.literals.filter((literal) => input.source.includes(literal) && !new RegExp(`(?<![A-Za-z0-9_])${escapeRegExp(literal)}(?![A-Za-z0-9_])`, "u").test(input.target)).map((literal) => ({ literal }));
2723
+ }
2724
+ // ../../packages/checks/dist/vue-i18n/vue-i18n-messages.js
2725
+ const VUE_I18N_MESSAGE_COMPILER_VERSION = "11.4.17";
2726
+ /** 使用固定版本的 Vue I18n 编译器提取消息分支、变量和关联。 */
2727
+ function parseVueI18nMessage(text) {
2728
+ const errors = [];
2729
+ const { ast } = baseCompile(text, {
2730
+ jit: true,
2731
+ optimize: false,
2732
+ onError: (error) => errors.push(syntaxError(error))
2733
+ });
2734
+ const cases = "cases" in ast.body ? ast.body.cases : [ast.body];
2735
+ const tokens = [];
2736
+ const links = [];
2737
+ return {
2738
+ errors,
2739
+ branches: cases.map((branch) => analyzeBranch(branch, text.length, tokens, links)),
2740
+ tokens,
2741
+ links
2742
+ };
2743
+ }
2744
+ function analyzeBranch(branch, textLength, tokens, links) {
2745
+ const variables = [];
2746
+ let projectedText = "";
2747
+ for (const item of branch.items) if (item.type === 3 || item.type === 9) projectedText += item.value ?? "";
2748
+ else if (item.type === 4 || item.type === 5) {
2749
+ addVariable(item, variables, tokens);
2750
+ projectedText += " ";
2751
+ } else if (item.type === 6) {
2752
+ projectedText += " ";
2753
+ const link = analyzeLink(item, variables, tokens, textLength);
2754
+ links.push(link);
2755
+ }
2756
+ return {
2757
+ range: nodeRange(branch, textLength),
2758
+ text: projectedText,
2759
+ variables
2760
+ };
2761
+ }
2762
+ function analyzeLink(item, variables, tokens, textLength) {
2763
+ const range = nodeRange(item, textLength);
2764
+ const key = item.key;
2765
+ if (key.type === 7) return {
2766
+ kind: "static",
2767
+ key: key.value,
2768
+ range
2769
+ };
2770
+ if (key.type === 9) return {
2771
+ kind: "static",
2772
+ key: key.value ?? "",
2773
+ range
2774
+ };
2775
+ if (key.type === 4 || key.type === 5) return {
2776
+ kind: "dynamic",
2777
+ variables: [addVariable(key, variables, tokens)],
2778
+ range
2779
+ };
2780
+ return {
2781
+ kind: "dynamic",
2782
+ variables: [],
2783
+ range
2784
+ };
2785
+ }
2786
+ function addVariable(node, variables, tokens) {
2787
+ const identity = node.type === 4 ? `named:${node.key}` : `list:${node.index}`;
2788
+ variables.push(identity);
2789
+ const range = nodeRange(node, node.end ?? 0);
2790
+ tokens.push({
2791
+ kind: "variable",
2792
+ identity,
2793
+ ...range,
2794
+ protect: true
2795
+ });
2796
+ return identity;
2797
+ }
2798
+ function nodeRange(node, textLength) {
2799
+ return {
2800
+ start: node.loc?.start.offset ?? node.start ?? 0,
2801
+ end: node.loc?.end.offset ?? node.end ?? textLength
2802
+ };
2803
+ }
2804
+ function syntaxError(error) {
2805
+ const { location } = error;
2806
+ return {
2807
+ code: error.code,
2808
+ ...error.domain === void 0 ? {} : { domain: error.domain },
2809
+ message: error.message,
2810
+ ...location === void 0 ? {} : { range: {
2811
+ start: location.start.offset,
2812
+ end: location.end.offset
2813
+ } }
2814
+ };
2815
+ }
2816
+ // ../../packages/checks/dist/vue-i18n/analysis.js
2817
+ /** 将固定的 Vue I18n 解析结果接入共享文本分析能力。 */
2818
+ function createVueI18nTextRecognizer() {
2819
+ return (input) => {
2820
+ const result = parseVueI18nMessage(input.text);
2821
+ return {
2822
+ tokens: result.tokens.filter((token) => input.availableRanges.some((range) => token.start >= range.start && token.end <= range.end)),
2823
+ complete: result.errors.length === 0,
2824
+ issues: result.errors.map(({ code, message }) => ({
2825
+ code: "vue-message-syntax",
2826
+ message: `${code}: ${message}`
2827
+ }))
2828
+ };
2829
+ };
2830
+ }
2831
+ /** 创建使用 Vue I18n 消息变量语法的文本分析器。 */
2832
+ function createVueI18nAnalysis() {
2833
+ return createTextAnalysis({ recognizers: [createVueI18nTextRecognizer()] });
2834
+ }
2835
+ // ../../packages/checks/dist/vue-i18n/message-memo.js
2836
+ const keyByText = (text) => [text];
2837
+ /** 同一次 QA 运行共享相同消息正文的解析结果。 */
2838
+ function memoizedVueI18nMessage(text, memo) {
2839
+ return memo.memo(parseVueI18nMessage, { key: keyByText })(text);
2840
+ }
2841
+ // ../../packages/checks/dist/vue-i18n/scope.js
2842
+ /** 按显式键或正则选择消息族;未声明的键各自单独成组。 */
2843
+ function createVueI18nScopeResolver(policy) {
2844
+ const scopes = policy.messageFamilies.scopes.map((rule) => ({
2845
+ ...rule,
2846
+ pattern: rule.keyPattern === void 0 ? void 0 : new RegExp(rule.keyPattern, rule.flags)
2847
+ }));
2848
+ return (key) => {
2849
+ for (const rule of scopes) if (rule.keys?.includes(key) || rule.pattern?.test(key)) return rule.scope;
2850
+ return `unclassified:${key}`;
2851
+ };
2852
+ }
2853
+ /** 仅将声明的完整纯文本签名折叠到同一等价键。 */
2854
+ function createVueI18nTargetEquivalence(groups) {
2855
+ const equivalentKey = createSignatureEquivalence(groups.map((group) => group.map((text) => ({
2856
+ parts: [{
2857
+ type: "text",
2858
+ text
2859
+ }],
2860
+ slots: []
2861
+ }))));
2862
+ return (signature) => signature.parts.every((part) => part.type === "text") ? equivalentKey(signature) : signatureKey(signature);
2863
+ }
2864
+ // ../../packages/checks/dist/vue-i18n/dependencies.js
2865
+ /** 回调形状属于装配契约,读取资料仍留到 load 阶段。 */
2866
+ function assertVueI18nCallback(value, name) {
2867
+ if (value !== void 0 && typeof value !== "function") throw new TypeError(`Vue I18n ${name} 必须是函数。`);
2868
+ }
2869
+ /** 将缺少必需读取器报告为宿主契约错误,且只在依赖它的检查项被选中时触发。 */
2870
+ function missingVueI18nData(description) {
2871
+ return () => {
2872
+ throw new StandardSchemaContractError(description, "schema-mismatch", `${description}未提供。`);
2873
+ };
2874
+ }
2875
+ /** 按字典自有条目验证消息资源,避免对象键处理跳过 __proto__ 对应的值。 */
2876
+ function dictionarySchema(valueSchema) {
2877
+ return z.preprocess((value) => value !== null && typeof value === "object" && !Array.isArray(value) ? new Map(Object.entries(value)) : value, z.map(z.string(), valueSchema));
2878
+ }
2879
+ const languagePoliciesSchema = z.array(z.object({
2880
+ sourceLanguage: z.string(),
2881
+ targetLanguage: z.string()
2882
+ })).superRefine((policies, context) => {
2883
+ const languages = /* @__PURE__ */ new Set();
2884
+ policies.forEach((policy, index) => {
2885
+ if (languages.has(policy.targetLanguage)) context.addIssue({
2886
+ code: "custom",
2887
+ path: [index, "targetLanguage"],
2888
+ message: "Vue I18n 策略的目标语言必须唯一。"
2889
+ });
2890
+ languages.add(policy.targetLanguage);
2891
+ });
2892
+ });
2893
+ const quantityOptionsSchema = z.object({
2894
+ aliases: dictionarySchema(z.string()).optional(),
2895
+ defaultUnit: z.string().optional(),
2896
+ ignoredLiterals: z.array(z.string()).optional()
2897
+ });
2898
+ const quantityPolicySchema = quantityOptionsSchema.extend({
2899
+ profile: z.string().optional(),
2900
+ byKey: dictionarySchema(quantityOptionsSchema).optional()
2901
+ });
2902
+ const resourceSchema = z.object({
2903
+ messages: dictionarySchema(z.string()),
2904
+ range: z.unknown()
2905
+ });
2906
+ const resourcesSchema = z.object({
2907
+ source: resourceSchema,
2908
+ target: resourceSchema
2909
+ });
2910
+ const quantitiesSchema = z.object({
2911
+ source: quantityPolicySchema,
2912
+ target: quantityPolicySchema
2913
+ });
2914
+ const protectedLiteralsSchema = dictionarySchema(z.array(z.string()));
2915
+ const messageFamiliesSchema = z.object({
2916
+ scopes: z.array(z.object({
2917
+ scope: z.string(),
2918
+ keys: z.array(z.string()).optional(),
2919
+ keyPattern: z.string().optional(),
2920
+ flags: z.string().optional()
2921
+ })),
2922
+ targetEquivalences: z.array(z.array(z.string()))
2923
+ });
2924
+ function validate(schema, value, description, pathPrefix = []) {
2925
+ const parsed = schema.safeParse(value);
2926
+ if (parsed.success) return parsed.data;
2927
+ const issues = parsed.error.issues.map((issue) => ({
2928
+ message: issue.message,
2929
+ path: [...pathPrefix, ...issue.path]
2930
+ }));
2931
+ const details = issues.map(({ path, message }) => `${path.join(".")}: ${message}`).join(";");
2932
+ throw new StandardSchemaContractError(description, "schema-mismatch", `${description}格式无效:${details}`, issues);
2933
+ }
2934
+ /** 语法、变量和术语只读取语言范围,不要求其余策略或术语容器。 */
2935
+ function readVueI18nLanguagePolicies(value) {
2936
+ const policies = validate(languagePoliciesSchema, value, "Vue I18n 语言策略");
2937
+ return new Map(policies.map((policy) => [policy.targetLanguage, policy]));
2938
+ }
2939
+ /** 校验策略公共身份和所选消费者声明的策略片段。 */
2940
+ function readVueI18nPolicies(value, requirements) {
2941
+ validate(languagePoliciesSchema, value, "Vue I18n 策略语言范围");
2942
+ const policies = value;
2943
+ policies.forEach((policy, index) => {
2944
+ const prefix = `Vue I18n 策略 ${index + 1}`;
2945
+ if (requirements.includes("resources")) validate(resourcesSchema, policy.resources, `${prefix} 消息资源`, ["resources"]);
2946
+ if (requirements.includes("quantities") && policy.quantities !== void 0) validate(quantitiesSchema, policy.quantities, `${prefix} 数量策略`, ["quantities"]);
2947
+ if (requirements.includes("protectedLiterals") && policy.protectedLiterals !== void 0) validate(protectedLiteralsSchema, policy.protectedLiterals, `${prefix} 受保护字面值策略`, ["protectedLiterals"]);
2948
+ if (requirements.includes("messageFamilies")) validate(messageFamiliesSchema, policy.messageFamilies, `${prefix} 消息族策略`, ["messageFamilies"]);
2949
+ });
2950
+ return new Map(policies.map((policy) => [policy.targetLanguage, {
2951
+ ...policy,
2952
+ protectedLiterals: policy.protectedLiterals ?? {}
2953
+ }]));
2954
+ }
2955
+ /** 只为消息族消费者构造目标等价索引。 */
2956
+ function readVueI18nFamilyPolicies(value) {
2957
+ const policies = readVueI18nPolicies(value, ["messageFamilies"]);
2958
+ const targetEquivalences = /* @__PURE__ */ new Map();
2959
+ for (const policy of policies.values()) targetEquivalences.set(policy.targetLanguage, createVueI18nTargetEquivalence(policy.messageFamilies.targetEquivalences));
2960
+ return {
2961
+ policies,
2962
+ targetEquivalences
2963
+ };
2964
+ }
2965
+ // ../../packages/checks/dist/vue-i18n/quality-projection.js
2966
+ const sourceMessageSchema = z.discriminatedUnion("status", [
2967
+ z.looseObject({
2968
+ status: z.literal("available"),
2969
+ text: z.string()
2970
+ }),
2971
+ z.looseObject({ status: z.literal("unavailable") }),
2972
+ z.looseObject({ status: z.literal("absent") })
2973
+ ]);
2974
+ const targetMessageSchema = z.discriminatedUnion("status", [
2975
+ z.looseObject({
2976
+ status: z.literal("available"),
2977
+ text: z.string()
2978
+ }),
2979
+ z.looseObject({ status: z.literal("unavailable") }),
2980
+ z.looseObject({ status: z.literal("missing") })
2981
+ ]);
2982
+ const qualityLocationSchema = z.looseObject({
2983
+ language: z.string().nullable(),
2984
+ range: z.unknown(),
2985
+ key: z.string().optional()
2986
+ }).refine((value) => Object.hasOwn(value, "range"), {
2987
+ path: ["range"],
2988
+ message: "Vue I18n 消息位置必须显式提供 range。"
2989
+ });
2990
+ const projectionShape = z.looseObject({
2991
+ key: z.string(),
2992
+ language: z.string(),
2993
+ source: sourceMessageSchema,
2994
+ target: targetMessageSchema,
2995
+ locations: z.looseObject({
2996
+ source: qualityLocationSchema,
2997
+ target: qualityLocationSchema
2998
+ })
2999
+ });
3000
+ /** Zod 负责结构验证;保留原投影,避免对象复制丢失位置上的特殊扩展键。 */
3001
+ const vueI18nMessageProjectionSchema = { "~standard": {
3002
+ version: 1,
3003
+ vendor: "lioni-vue-i18n",
3004
+ validate(value) {
3005
+ if (value === null) return { value: null };
3006
+ const result = projectionShape.safeParse(value);
3007
+ return result.success ? { value } : { issues: result.error.issues.map((issue) => ({
3008
+ message: issue.message,
3009
+ path: issue.path.map((key) => typeof key === "symbol" ? String(key) : key)
3010
+ })) };
3011
+ }
3012
+ } };
3013
+ const projectionKey = (input) => [
3014
+ input.snapshot,
3015
+ input.association,
3016
+ input.candidate,
3017
+ input.sourceUnit,
3018
+ input.relationships
3019
+ ];
3020
+ /** 默认只提取字符串;各项检查自行判断所需一侧的正文可用性。 */
3021
+ function prepareVueI18nMessage(input, adapter) {
3022
+ if (adapter) {
3023
+ const { loaded: _loaded, ...context } = input;
3024
+ return (async () => {
3025
+ const prepared = await input.memo.memo(adapter, { key: projectionKey })(context);
3026
+ if (prepared === null) return null;
3027
+ assertVueI18nMessageProjection(prepared);
3028
+ if (prepared.key !== input.association.sourceKey || prepared.language !== input.association.language) throw new Error("消息准备结果的键或语言与本次检查对象不一致。");
3029
+ return prepared;
3030
+ })();
3031
+ }
3032
+ const source = input.sourceUnit.unit.source;
3033
+ return {
3034
+ key: input.association.sourceKey,
3035
+ language: input.association.language,
3036
+ source: input.sourceUnit.bodyAvailability === "available" && typeof source === "string" ? {
3037
+ status: "available",
3038
+ text: source
3039
+ } : { status: "unavailable" },
3040
+ target: input.candidate === null ? input.association.status === "missing" ? { status: "missing" } : { status: "unavailable" } : typeof input.candidate.content === "string" ? {
3041
+ status: "available",
3042
+ text: input.candidate.content
3043
+ } : { status: "unavailable" },
3044
+ locations: {
3045
+ source: {
3046
+ language: null,
3047
+ key: input.association.sourceKey,
3048
+ range: input.snapshot.source.read.scopes[input.sourceUnit.scopeIndex]?.range ?? null
3049
+ },
3050
+ target: {
3051
+ language: input.association.language,
3052
+ key: input.association.sourceKey,
3053
+ range: input.translation?.range ?? null
3054
+ }
3055
+ }
3056
+ };
3057
+ }
3058
+ /** 普通参数在装配时校验,检查项筛选不能推迟这些错误。 */
3059
+ function assertVueI18nPreparer(adapter) {
3060
+ if (adapter !== void 0 && typeof adapter !== "function") throw new TypeError("Vue I18n 准备适配必须是函数。");
3061
+ }
3062
+ /** 消费投影字段前验证宿主返回值,避免提前解引用掩盖契约错误。 */
3063
+ function assertVueI18nMessageProjection(value) {
3064
+ assertJsonValue(value, "Vue I18n 消息投影");
3065
+ const result = projectionShape.safeParse(value);
3066
+ if (!result.success) throw new StandardSchemaContractError("Vue I18n 消息投影", "schema-mismatch", "Vue I18n 消息投影格式无效。", result.error.issues.map((issue) => ({
3067
+ message: issue.message,
3068
+ path: issue.path.map((key) => typeof key === "symbol" ? String(key) : key)
3069
+ })));
3070
+ }
3071
+ // ../../packages/checks/dist/vue-i18n/checks/common.js
3072
+ /** 策略和运行时工具仅在准备阶段使用;规则只接收消息及所需依据。 */
3073
+ function createVueI18nMessageCheck(options) {
3074
+ assertVueI18nPreparer(options.adapter);
3075
+ return defineChecker.withTypes()({
3076
+ id: options.id,
3077
+ version: options.version,
3078
+ inputSchema: { "~standard": {
3079
+ version: 1,
3080
+ vendor: "lioni-vue-i18n",
3081
+ async validate(value) {
3082
+ if (value === null) return { value: null };
3083
+ if (!value || typeof value !== "object" || !("projection" in value) || value.projection === null || !("prepared" in value)) return { issues: [{ message: "Vue I18n 检查输入缺少消息或依据。" }] };
3084
+ const result = await vueI18nMessageProjectionSchema["~standard"].validate(value.projection);
3085
+ return result.issues ? { issues: result.issues } : { value };
3086
+ }
3087
+ } },
3088
+ load: async ({ snapshot, memo, qualityData }) => readVueI18nPolicies(await qualityData.read(options.loadPolicies, snapshot, memo), options.policyRequirements),
3089
+ prepare: async (input) => {
3090
+ const policy = input.loaded.get(input.association.language);
3091
+ if (!policy) return null;
3092
+ const projection = await prepareVueI18nMessage(input, options.adapter);
3093
+ if (projection === null) return null;
3094
+ if (options.requiresTarget) {
3095
+ if (projection.target.status === "missing") return null;
3096
+ if (projection.target.status === "unavailable") throw new Error("目标消息正文不可用,检查未执行。");
3097
+ }
3098
+ if (options.requiresSource) {
3099
+ if (projection.source.status === "absent") return null;
3100
+ if (projection.source.status === "unavailable" || input.sourceUnit.bodyAvailability !== "available") throw new Error("原文正文不可用,检查未执行。");
3101
+ }
3102
+ if (options.targetMustContainText && (projection.target.status !== "available" || !projection.target.text.trim())) return null;
3103
+ if (options.applies && !options.applies(projection, policy)) return null;
3104
+ return {
3105
+ projection,
3106
+ prepared: options.prepare(projection, policy, input.memo)
3107
+ };
3108
+ },
3109
+ check: (input) => input === null ? [] : options.check(input.projection, input.prepared)
3110
+ });
3111
+ }
3112
+ function sourceObject(key) {
3113
+ return {
3114
+ kind: "source-unit",
3115
+ key
3116
+ };
3117
+ }
3118
+ function translationObject(projection, code) {
3119
+ return {
3120
+ kind: "translation-unit",
3121
+ key: projection.key,
3122
+ language: projection.language,
3123
+ ...code === void 0 ? {} : { code }
3124
+ };
3125
+ }
3126
+ function messageLocation(projection, span) {
3127
+ return {
3128
+ ...projection.locations.target,
3129
+ ...span === void 0 ? {} : { span }
3130
+ };
3131
+ }
3132
+ function finding(projection, code, message, span, evidence) {
3133
+ return {
3134
+ severity: "error",
3135
+ object: translationObject(projection, code),
3136
+ location: messageLocation(projection, span),
3137
+ message,
3138
+ evidence
3139
+ };
3140
+ }
3141
+ // ../../packages/checks/dist/vue-i18n/checks/links.js
3142
+ function createLinkTargetExistsCheck(options) {
3143
+ return createVueI18nMessageCheck({
3144
+ id: options.identity.id,
3145
+ version: version("link-target-exists", 2),
3146
+ adapter: options.prepare,
3147
+ loadPolicies: options.loadPolicies,
3148
+ policyRequirements: ["resources"],
3149
+ requiresSource: false,
3150
+ requiresTarget: true,
3151
+ prepare: (projection, policy, memo) => {
3152
+ if (projection.target.status !== "available") return [];
3153
+ return memoizedVueI18nMessage(projection.target.text, memo).links.flatMap((link) => link.kind === "static" ? [{
3154
+ key: link.key,
3155
+ exists: hasOwn(policy.resources.source.messages, link.key) || hasOwn(policy.resources.target.messages, link.key)
3156
+ }] : []);
3157
+ },
3158
+ check: (input, targets) => {
3159
+ const projection = input;
3160
+ if (projection.target.status !== "available") throw new Error("目标消息正文不可用。");
3161
+ const targetText = projection.target.text;
3162
+ const message = parseVueI18nMessage(targetText);
3163
+ if (message.errors.length > 0) throw new Error("译文语法无效,关联目标检查未执行。");
3164
+ return message.links.flatMap((link) => link.kind === "static" && !targets.some((target) => target.key === link.key && target.exists) ? [finding(projection, "missing-linked-message", `译文关联的消息键 ${link.key} 不存在。`, link.range, [{
3165
+ role: "target-message",
3166
+ object: translationObject(projection),
3167
+ location: messageLocation(projection, link.range),
3168
+ value: targetText
3169
+ }, {
3170
+ role: "linked-key",
3171
+ object: translationObject(projection),
3172
+ location: messageLocation(projection, link.range),
3173
+ value: link.key
3174
+ }])] : []);
3175
+ }
3176
+ });
3177
+ }
3178
+ function createLinkCycleCheck(options) {
3179
+ return createVueI18nMessageCheck({
3180
+ id: options.identity.id,
3181
+ version: version("link-cycle", 3),
3182
+ adapter: options.prepare,
3183
+ loadPolicies: options.loadPolicies,
3184
+ policyRequirements: ["resources"],
3185
+ requiresSource: false,
3186
+ requiresTarget: true,
3187
+ prepare: reachableMessages,
3188
+ check: (input, messages) => {
3189
+ if (input.target.status !== "available") throw new Error("目标消息正文不可用。");
3190
+ const search = findCycle(input, messages);
3191
+ const targetText = input.target.text;
3192
+ const fallbackRange = fullRange$1(input.target.text);
3193
+ return search.path === void 0 ? [] : [finding(input, "linked-message-cycle", `关联消息形成循环:${search.path.join(" → ")}。`, search.range ?? fallbackRange, [{
3194
+ role: "target-message",
3195
+ object: translationObject(input),
3196
+ location: messageLocation(input, search.range ?? fallbackRange),
3197
+ value: targetText
3198
+ }, {
3199
+ role: "link-cycle",
3200
+ object: translationObject(input),
3201
+ location: messageLocation(input, search.range ?? fallbackRange),
3202
+ value: search.path
3203
+ }])];
3204
+ }
3205
+ });
3206
+ }
3207
+ /** 先准备完整可达闭包,包括缺失键,避免首次发现循环后漏掉后续依赖。 */
3208
+ function reachableMessages(projection, policy, memo) {
3209
+ const messages = /* @__PURE__ */ new Map();
3210
+ function visit(key) {
3211
+ if (messages.has(key)) return;
3212
+ const origin = key === projection.key ? "candidate" : hasOwn(policy.resources.target.messages, key) ? "target" : hasOwn(policy.resources.source.messages, key) ? "source" : "missing";
3213
+ const text = origin === "candidate" ? projection.target.status === "available" ? projection.target.text : null : origin === "missing" ? null : policy.resources[origin].messages[key];
3214
+ const message = text === null ? void 0 : memoizedVueI18nMessage(text, memo);
3215
+ if (message && message.errors.length > 0) throw new Error(`关联消息 ${key} 语法无效,无法完整判断循环。`);
3216
+ const links = message?.links.filter((link) => link.kind === "static") ?? [];
3217
+ messages.set(key, {
3218
+ key,
3219
+ origin,
3220
+ text,
3221
+ links
3222
+ });
3223
+ for (const link of links) visit(link.key);
3224
+ }
3225
+ visit(projection.key);
3226
+ return [...messages.values()];
3227
+ }
3228
+ function findCycle(projection, messages) {
3229
+ const byKey = new Map(messages.map((message) => [message.key, message.links]));
3230
+ const active = /* @__PURE__ */ new Map();
3231
+ const done = /* @__PURE__ */ new Set();
3232
+ const stack = [];
3233
+ let path;
3234
+ let range;
3235
+ function visit(key) {
3236
+ const activeIndex = active.get(key);
3237
+ if (activeIndex !== void 0) {
3238
+ path = [...stack.slice(activeIndex), key];
3239
+ return true;
3240
+ }
3241
+ if (done.has(key)) return false;
3242
+ active.set(key, stack.length);
3243
+ stack.push(key);
3244
+ for (const link of byKey.get(key) ?? []) if (visit(link.key)) {
3245
+ if (key === projection.key) range = link.range;
3246
+ return true;
3247
+ }
3248
+ stack.pop();
3249
+ active.delete(key);
3250
+ done.add(key);
3251
+ return false;
3252
+ }
3253
+ visit(projection.key);
3254
+ return {
3255
+ ...path === void 0 ? {} : { path },
3256
+ ...range === void 0 ? {} : { range }
3257
+ };
3258
+ }
3259
+ function version(kind, major) {
3260
+ return `vue-i18n-suite/${kind}/v${major}+@intlify/message-compiler@${VUE_I18N_MESSAGE_COMPILER_VERSION}`;
3261
+ }
3262
+ function hasOwn(record, key) {
3263
+ return Object.hasOwn(record, key);
3264
+ }
3265
+ function fullRange$1(text) {
3266
+ return {
3267
+ start: 0,
3268
+ end: text.length
3269
+ };
3270
+ }
3271
+ // ../../packages/checks/dist/vue-i18n/versions.js
3272
+ const VUE_I18N_QUANTITY_COMPARISON_VERSION = "checks.quantity-branches/v1+text-analysis.quantity-profiles/v1";
3273
+ const VUE_I18N_PROTECTED_LITERAL_COMPARISON_VERSION = "checks.protected-literals/v1";
3274
+ // ../../packages/checks/dist/vue-i18n/checks/quantities-and-literals.js
3275
+ function createProtectedLiteralCheck(options) {
3276
+ const version = ["vue-i18n-suite/protected-literals/v2", VUE_I18N_PROTECTED_LITERAL_COMPARISON_VERSION].join("+");
3277
+ return createVueI18nMessageCheck({
3278
+ id: options.identity.id,
3279
+ version,
3280
+ adapter: options.prepare,
3281
+ loadPolicies: options.loadPolicies,
3282
+ policyRequirements: ["protectedLiterals"],
3283
+ requiresSource: true,
3284
+ requiresTarget: true,
3285
+ targetMustContainText: true,
3286
+ applies: (projection, policy) => Object.hasOwn(policy.protectedLiterals, projection.key) && (policy.protectedLiterals[projection.key]?.length ?? 0) > 0,
3287
+ prepare: (projection, policy) => Object.hasOwn(policy.protectedLiterals, projection.key) ? policy.protectedLiterals[projection.key] : [],
3288
+ check: (input, literals) => evaluateProtectedLiterals(input, literals)
3289
+ });
3290
+ }
3291
+ function createQuantityCheck(options) {
3292
+ const version = [
3293
+ "vue-i18n-suite/quantities/v2",
3294
+ `@intlify/message-compiler@${VUE_I18N_MESSAGE_COMPILER_VERSION}`,
3295
+ VUE_I18N_QUANTITY_COMPARISON_VERSION
3296
+ ].join("+");
3297
+ return createVueI18nMessageCheck({
3298
+ id: options.identity.id,
3299
+ version,
3300
+ adapter: options.prepare,
3301
+ loadPolicies: options.loadPolicies,
3302
+ policyRequirements: ["quantities"],
3303
+ requiresSource: true,
3304
+ requiresTarget: true,
3305
+ targetMustContainText: true,
3306
+ prepare: (projection, policy) => ({
3307
+ sourceLanguage: policy.sourceLanguage,
3308
+ targetLanguage: policy.targetLanguage,
3309
+ quantities: {
3310
+ source: {
3311
+ profile: policy.quantities?.source.profile ?? null,
3312
+ ...quantityOptions(policy.quantities?.source ?? {}, projection.key)
3313
+ },
3314
+ target: {
3315
+ profile: policy.quantities?.target.profile ?? null,
3316
+ ...quantityOptions(policy.quantities?.target ?? {}, projection.key)
3317
+ }
3318
+ }
3319
+ }),
3320
+ check: (input, prepared) => evaluateQuantities(input, prepared)
3321
+ });
3322
+ }
3323
+ function evaluateProtectedLiterals(projection, literals) {
3324
+ if (projection.source.status !== "available" || projection.target.status !== "available") throw new Error("原文或目标消息正文不可用。");
3325
+ const issues = compareProtectedLiterals({
3326
+ source: projection.source.text,
3327
+ target: projection.target.text,
3328
+ literals
3329
+ });
3330
+ const span = fullRange(projection.target.text);
3331
+ const evidence = [{
3332
+ role: "source-message",
3333
+ object: sourceObject(projection.key),
3334
+ location: projection.locations.source,
3335
+ value: projection.source.text
3336
+ }, {
3337
+ role: "target-message",
3338
+ object: translationObject(projection),
3339
+ location: projection.locations.target,
3340
+ value: projection.target.text
3341
+ }];
3342
+ return issues.map(({ literal }) => finding(projection, "protected-literal-missing", `译文没有保留技术字面值 ${literal}。`, span, [...evidence, {
3343
+ role: "protected-literal",
3344
+ object: translationObject(projection),
3345
+ location: projection.locations.target,
3346
+ value: literal
3347
+ }]));
3348
+ }
3349
+ function evaluateQuantities(projection, policy) {
3350
+ if (projection.source.status !== "available" || projection.target.status !== "available") throw new Error("原文或目标消息正文不可用。");
3351
+ const quantityPolicy = policy.quantities;
3352
+ const sourceId = quantityPolicy?.source.profile;
3353
+ const targetId = quantityPolicy?.target.profile;
3354
+ const sourceProfile = quantityProfile(sourceId ?? void 0, policy.sourceLanguage);
3355
+ const targetProfile = quantityProfile(targetId ?? void 0, policy.targetLanguage);
3356
+ if (!sourceProfile) throw new Error(`源语言 ${policy.sourceLanguage} 没有已声明的数值分析能力。`);
3357
+ if (!targetProfile) throw new Error(`目标语言 ${policy.targetLanguage} 没有已声明的数值分析能力。`);
3358
+ const source = parseVueI18nMessage(projection.source.text);
3359
+ const target = parseVueI18nMessage(projection.target.text);
3360
+ if (source.errors.length > 0 || target.errors.length > 0) throw new Error("原文或译文消息语法无效,数量检查未执行。");
3361
+ const sourceOptions = quantityPolicy.source;
3362
+ const targetOptions = quantityPolicy.target;
3363
+ const sourceText = projection.source.text;
3364
+ const targetText = projection.target.text;
3365
+ const sourceBranches = source.branches.map((branch) => ({ values: [...branchQuantities(sourceProfile, source, sourceText, branch, sourceOptions)] }));
3366
+ const targetBranches = target.branches.map((branch) => ({ values: [...branchQuantities(targetProfile, target, targetText, branch, targetOptions)] }));
3367
+ const differences = compareQuantityBranches({
3368
+ source: sourceBranches,
3369
+ target: targetBranches
3370
+ });
3371
+ const sourceObjectValue = sourceObject(projection.key);
3372
+ const targetObjectValue = translationObject(projection);
3373
+ return differences.map((difference) => {
3374
+ const targetBranch = target.branches[difference.targetBranchIndex];
3375
+ const targetLocation = {
3376
+ ...projection.locations.target,
3377
+ span: targetBranch.range
3378
+ };
3379
+ return {
3380
+ severity: "error",
3381
+ object: translationObject(projection, "quantity-mismatch"),
3382
+ location: targetLocation,
3383
+ message: `译文分支 ${difference.targetBranchIndex + 1} 的数值或时间单位与原文不对应。`,
3384
+ evidence: [
3385
+ {
3386
+ role: "source-quantity-branches",
3387
+ object: sourceObjectValue,
3388
+ location: projection.locations.source,
3389
+ value: {
3390
+ text: sourceText,
3391
+ branches: sourceBranches
3392
+ }
3393
+ },
3394
+ {
3395
+ role: "target-quantity-branches",
3396
+ object: targetObjectValue,
3397
+ location: targetLocation,
3398
+ value: {
3399
+ text: targetText,
3400
+ branches: targetBranches
3401
+ }
3402
+ },
3403
+ {
3404
+ role: "quantity-difference",
3405
+ object: targetObjectValue,
3406
+ location: targetLocation,
3407
+ value: difference
3408
+ }
3409
+ ]
3410
+ };
3411
+ });
3412
+ }
3413
+ function quantityOptions(policy, key) {
3414
+ const specific = policy.byKey !== void 0 && Object.hasOwn(policy.byKey, key) ? policy.byKey[key] : void 0;
3415
+ return {
3416
+ ...policy.aliases === void 0 && specific?.aliases === void 0 ? {} : { aliases: {
3417
+ ...policy.aliases,
3418
+ ...specific?.aliases
3419
+ } },
3420
+ ...(specific?.defaultUnit ?? policy.defaultUnit) === void 0 ? {} : { defaultUnit: specific?.defaultUnit ?? policy.defaultUnit },
3421
+ ...(policy.ignoredLiterals?.length ?? 0) === 0 && (specific?.ignoredLiterals?.length ?? 0) === 0 ? {} : { ignoredLiterals: [...policy.ignoredLiterals ?? [], ...specific?.ignoredLiterals ?? []] }
3422
+ };
3423
+ }
3424
+ function branchQuantities(profile, message, text, branch, options) {
3425
+ const values = profile.facts(branch.text, options);
3426
+ for (const token of message.tokens) {
3427
+ if (token.start < branch.range.start || token.end > branch.range.end) continue;
3428
+ const unit = profile.unitAfter(text.slice(token.end), options);
3429
+ if (unit) values.add(`变量单位:${token.identity}:${unit}`);
3430
+ }
3431
+ return values;
3432
+ }
3433
+ function fullRange(text) {
3434
+ return {
3435
+ start: 0,
3436
+ end: text.length
3437
+ };
3438
+ }
3439
+ // ../../packages/checks/dist/vue-i18n/checks/terminology-families.js
3440
+ function createVueI18nTerminologyChecks(options) {
3441
+ const rules = [{
3442
+ rule: requireAllowedTranslation(),
3443
+ identity: options.identities.allowedTerminology
3444
+ }, {
3445
+ rule: rejectForbiddenTranslation(),
3446
+ identity: options.identities.forbiddenTerminology
3447
+ }];
3448
+ const compile = (data) => compileTerms(createTermbase(data), { analysis: options.analysis });
3449
+ const loadLanguages = async ({ snapshot, memo, qualityData }) => {
3450
+ return readVueI18nLanguagePolicies(await qualityData.read(options.loadLanguages, snapshot, memo));
3451
+ };
3452
+ const loadTerms = async ({ snapshot, memo, qualityData }) => {
3453
+ const data = await qualityData.read(options.loadTerms, snapshot, memo);
3454
+ return memo.memo(compile)(data);
3455
+ };
3456
+ return rules.map(({ rule, identity }) => createTermChecker.withTypes()({
3457
+ id: identity.id,
3458
+ terms: loadTerms,
3459
+ load: loadLanguages,
3460
+ rule,
3461
+ prepare: async (input) => {
3462
+ const policy = input.loaded.context.get(input.association.language);
3463
+ if (policy === void 0) return null;
3464
+ const { loaded: _loaded, ...messageInput } = input;
3465
+ const projection = await prepareVueI18nMessage(messageInput, options.prepare);
3466
+ if (projection === null) return null;
3467
+ if (projection.target.status === "missing") return null;
3468
+ if (projection.target.status === "unavailable") throw new Error("目标消息正文不可用,术语检查未执行。");
3469
+ if (projection.source.status === "absent") return null;
3470
+ if (projection.source.status === "unavailable" || input.sourceUnit.bodyAvailability !== "available") throw new Error("原文正文不可用,术语检查未执行。");
3471
+ if (!projection.target.text.trim()) return null;
3472
+ return {
3473
+ subject: projection,
3474
+ comparison: { groups: [{
3475
+ ref: projection.key,
3476
+ source: {
3477
+ language: policy.sourceLanguage,
3478
+ fragments: [{
3479
+ ref: projection.key,
3480
+ text: projection.source.text
3481
+ }]
3482
+ },
3483
+ target: {
3484
+ language: policy.targetLanguage,
3485
+ fragments: [{
3486
+ ref: projection.key,
3487
+ text: projection.target.text
3488
+ }]
3489
+ }
3490
+ }] }
3491
+ };
3492
+ },
3493
+ location: ({ side, subject }) => subject.locations[side]
3494
+ }));
3495
+ }
3496
+ function createVueI18nMessageFamilyCheck(options) {
3497
+ const sourceTemplate = { abstract: (token) => token.kind === "variable" && token.identity ? {
3498
+ kind: token.kind,
3499
+ identity: token.identity
3500
+ } : void 0 };
3501
+ const targetTemplate = { ...sourceTemplate };
3502
+ const resolvePolicies = (dependencies) => readVueI18nFamilyPolicies(dependencies);
3503
+ const loadDependencies = ({ snapshot, memo, qualityData }) => qualityData.read(options.loadPolicies, snapshot, memo);
3504
+ return createMessageFamilyChecker({
3505
+ id: options.identity.id,
3506
+ load: loadDependencies,
3507
+ analysis: options.analysis,
3508
+ sourceTemplate,
3509
+ targetTemplate,
3510
+ targetEquivalence: (signature, language, input) => input.memo.memo(resolvePolicies)(input.loaded).targetEquivalences.get(language)?.(signature) ?? signatureKey(signature),
3511
+ prepare: async (input) => {
3512
+ if (input.memo.memo(resolvePolicies)(input.loaded).policies.get(input.association.language) === void 0 || input.sourceUnit === null) return null;
3513
+ const projection = await prepareVueI18nMessage(input, options.prepare);
3514
+ if (projection === null) return null;
3515
+ if (projection.source.status === "absent" || projection.target.status === "missing") return null;
3516
+ if (projection.target.status === "unavailable" || projection.source.status === "unavailable") throw new Error("原文或目标消息正文不可用,无法比较消息族。");
3517
+ if (input.sourceUnit.bodyAvailability !== "available") throw new Error("原文正文不可用,消息族检查未执行。");
3518
+ if (projection.source.status !== "available" || projection.target.status !== "available" || !projection.target.text.trim()) return null;
3519
+ if (memoizedVueI18nMessage(projection.source.text, input.memo).errors.length > 0 || memoizedVueI18nMessage(projection.target.text, input.memo).errors.length > 0) throw new Error("原文或译文语法无效,无法确定消息族。");
3520
+ return familyInput(projection, input.memo.memo(resolvePolicies)(input.loaded).policies);
3521
+ },
3522
+ reference: (reference, context) => familyInput(options.reference(reference, context), context.memo.memo(resolvePolicies)(context.loaded).policies)
3523
+ });
3524
+ }
3525
+ function familyInput(projection, policies) {
3526
+ assertVueI18nMessageProjection(projection);
3527
+ const location = projection.locations.target;
3528
+ const policy = policies.get(projection.language);
3529
+ if (policy === void 0) return {
3530
+ complete: false,
3531
+ groups: [],
3532
+ location,
3533
+ issues: [{
3534
+ code: "missing-language-policy",
3535
+ message: `未声明 ${projection.language} 的消息族策略。`,
3536
+ language: projection.language
3537
+ }]
3538
+ };
3539
+ if (projection.source.status !== "available") return {
3540
+ complete: false,
3541
+ groups: [],
3542
+ location,
3543
+ issues: [{
3544
+ code: "sourceBodyUnavailable",
3545
+ message: "原文正文不可用,无法完整投影消息族。",
3546
+ language: projection.language,
3547
+ sourceKey: projection.key
3548
+ }]
3549
+ };
3550
+ if (parseVueI18nMessage(projection.source.text).errors.length > 0) return {
3551
+ complete: false,
3552
+ groups: [],
3553
+ location,
3554
+ issues: [{
3555
+ code: "sourceMessageSyntaxInvalid",
3556
+ message: "原文语法无效,无法确定消息族。",
3557
+ language: projection.language,
3558
+ sourceKey: projection.key
3559
+ }]
3560
+ };
3561
+ const targetIssue = projection.target.status !== "available" ? {
3562
+ code: projection.target.status === "missing" ? "targetMissing" : "targetBodyUnavailable",
3563
+ message: "已保存译文正文不可用,无法完整投影消息族。",
3564
+ language: projection.language,
3565
+ sourceKey: projection.key
3566
+ } : parseVueI18nMessage(projection.target.text).errors.length > 0 ? {
3567
+ code: "targetMessageSyntaxInvalid",
3568
+ message: "已保存译文语法无效,无法完整投影消息族。",
3569
+ language: projection.language,
3570
+ sourceKey: projection.key
3571
+ } : void 0;
3572
+ const scope = createVueI18nScopeResolver(policy)(projection.key);
3573
+ return {
3574
+ location,
3575
+ groups: [{
3576
+ ref: projection.key,
3577
+ scope,
3578
+ source: {
3579
+ language: policy.sourceLanguage,
3580
+ fragments: [{
3581
+ ref: projection.key,
3582
+ text: projection.source.text
3583
+ }]
3584
+ },
3585
+ target: {
3586
+ language: policy.targetLanguage,
3587
+ fragments: projection.target.status === "available" && targetIssue === void 0 ? [{
3588
+ ref: projection.key,
3589
+ text: projection.target.text
3590
+ }] : [],
3591
+ ...targetIssue === void 0 ? {} : {
3592
+ complete: false,
3593
+ issues: [targetIssue]
3594
+ }
3595
+ }
3596
+ }]
3597
+ };
3598
+ }
3599
+ // ../../packages/checks/dist/vue-i18n/vue-i18n-syntax-checkers.js
3600
+ function createVueI18nSourceSyntaxChecker(options) {
3601
+ assertVueI18nPreparer(options?.prepare);
3602
+ assertVueI18nCallback(options?.loadLanguages, "loadLanguages");
3603
+ return defineChecker.withTypes()({
3604
+ id: options?.id ?? "vue-i18n/source-syntax",
3605
+ version: `checks.vue-i18n/source-syntax/v3+@intlify/message-compiler@${VUE_I18N_MESSAGE_COMPILER_VERSION}`,
3606
+ inputSchema: vueI18nMessageProjectionSchema,
3607
+ load: async ({ snapshot, memo, qualityData }) => options?.loadLanguages ? readVueI18nLanguagePolicies(await qualityData.read(options?.loadLanguages, snapshot, memo)) : null,
3608
+ prepare: async (input) => {
3609
+ if (input.loaded !== null && !input.loaded.has(input.association.language)) return null;
3610
+ const projection = await prepareVueI18nMessage(input, options?.prepare);
3611
+ if (projection === null) return null;
3612
+ if (projection.source.status === "absent") return null;
3613
+ if (projection.source.status === "unavailable" || input.sourceUnit.bodyAvailability !== "available") throw new Error("原文正文不可用,无法检查 Vue I18n 语法。");
3614
+ return projection;
3615
+ },
3616
+ check: (input) => {
3617
+ if (input === null) return [];
3618
+ const text = input.source;
3619
+ if (text.status !== "available") throw new Error("原文正文不可用。");
3620
+ return syntaxOutcome("source", input, text.text);
3621
+ }
3622
+ });
3623
+ }
3624
+ function createVueI18nTargetSyntaxChecker(options) {
3625
+ assertVueI18nPreparer(options?.prepare);
3626
+ assertVueI18nCallback(options?.loadLanguages, "loadLanguages");
3627
+ return defineChecker.withTypes()({
3628
+ id: options?.id ?? "vue-i18n/target-syntax",
3629
+ version: `checks.vue-i18n/target-syntax/v2+@intlify/message-compiler@${VUE_I18N_MESSAGE_COMPILER_VERSION}`,
3630
+ inputSchema: vueI18nMessageProjectionSchema,
3631
+ load: async ({ snapshot, memo, qualityData }) => options?.loadLanguages ? readVueI18nLanguagePolicies(await qualityData.read(options?.loadLanguages, snapshot, memo)) : null,
3632
+ prepare: async (input) => {
3633
+ if (input.loaded !== null && !input.loaded.has(input.association.language)) return null;
3634
+ const projection = await prepareVueI18nMessage(input, options?.prepare);
3635
+ if (projection === null) return null;
3636
+ if (projection.target.status === "missing") return null;
3637
+ if (projection.target.status === "unavailable") throw new Error("目标消息正文不可用,Vue I18n 检查未执行。");
3638
+ return projection;
3639
+ },
3640
+ check: (input) => {
3641
+ if (input === null) return [];
3642
+ const text = input.target;
3643
+ if (text.status !== "available") throw new Error("目标消息正文不可用。");
3644
+ return syntaxOutcome("target", input, text.text);
3645
+ }
3646
+ });
3647
+ }
3648
+ function syntaxOutcome(side, projection, text) {
3649
+ const parsed = parseVueI18nMessage(text);
3650
+ const location = projection.locations[side];
3651
+ const object = {
3652
+ kind: side === "source" ? "source-unit" : "translation-unit",
3653
+ key: projection.key,
3654
+ ...side === "target" ? { language: projection.language } : {}
3655
+ };
3656
+ return parsed.errors.map((error) => {
3657
+ const range = error.range ?? {
3658
+ start: 0,
3659
+ end: 0
3660
+ };
3661
+ const findingLocation = {
3662
+ ...location,
3663
+ span: range
3664
+ };
3665
+ const evidence = [{
3666
+ role: `${side}-message`,
3667
+ object,
3668
+ location: findingLocation,
3669
+ value: text
3670
+ }, {
3671
+ role: "syntax-error",
3672
+ object,
3673
+ location: findingLocation,
3674
+ value: error
3675
+ }];
3676
+ return {
3677
+ severity: "error",
3678
+ object,
3679
+ location: findingLocation,
3680
+ message: `${side === "source" ? "原文" : "译文"}不符合 Vue I18n 消息语法:${error.message}。`,
3681
+ evidence
3682
+ };
3683
+ });
3684
+ }
3685
+ // ../../packages/checks/dist/vue-i18n/vue-i18n-variable-checker.js
3686
+ function createVueI18nVariableCorrespondenceChecker(options) {
3687
+ assertVueI18nPreparer(options?.prepare);
3688
+ assertVueI18nCallback(options?.loadLanguages, "loadLanguages");
3689
+ return defineChecker.withTypes()({
3690
+ id: options?.id ?? "vue-i18n/variable-correspondence",
3691
+ version: `checks.vue-i18n/variable-correspondence/v2+@intlify/message-compiler@${VUE_I18N_MESSAGE_COMPILER_VERSION}`,
3692
+ inputSchema: vueI18nMessageProjectionSchema,
3693
+ load: async ({ snapshot, memo, qualityData }) => options?.loadLanguages ? readVueI18nLanguagePolicies(await qualityData.read(options?.loadLanguages, snapshot, memo)) : null,
3694
+ prepare: async (input) => {
3695
+ if (input.loaded !== null && !input.loaded.has(input.association.language)) return null;
3696
+ const projection = await prepareVueI18nMessage(input, options?.prepare);
3697
+ if (projection === null) return null;
3698
+ if (projection.target.status === "missing") return null;
3699
+ if (projection.target.status === "unavailable") throw new Error("目标消息正文不可用,Vue I18n 检查未执行。");
3700
+ if (projection.source.status === "absent") return null;
3701
+ if (projection.source.status === "unavailable" || input.sourceUnit.bodyAvailability !== "available") throw new Error("原文正文不可用,无法检查变量对应。");
3702
+ return projection;
3703
+ },
3704
+ check: (input) => input === null ? [] : compareVariables(input)
3705
+ });
3706
+ }
3707
+ function compareVariables(projection) {
3708
+ if (projection.source.status !== "available" || projection.target.status !== "available") throw new Error("变量对应检查所需的原文或译文正文不可用。");
3709
+ const source = parseVueI18nMessage(projection.source.text);
3710
+ const target = parseVueI18nMessage(projection.target.text);
3711
+ if (source.errors.length > 0 || target.errors.length > 0) throw new Error("原文或译文语法无效,无法核对变量。");
3712
+ const sourcePatterns = variablePatterns(source);
3713
+ const targetPatterns = variablePatterns(target);
3714
+ const sourcePatternKeys = new Set(sourcePatterns.map(({ key }) => key));
3715
+ const targetPatternKeys = new Set(targetPatterns.map(({ key }) => key));
3716
+ const missing = sourcePatterns.filter(({ key }) => !targetPatternKeys.has(key));
3717
+ const extra = targetPatterns.filter(({ key }) => !sourcePatternKeys.has(key));
3718
+ if (missing.length === 0 && extra.length === 0) return [];
3719
+ const sourceObject = {
3720
+ kind: "source-unit",
3721
+ key: projection.key
3722
+ };
3723
+ const targetObject = {
3724
+ kind: "translation-unit",
3725
+ key: projection.key,
3726
+ language: projection.language
3727
+ };
3728
+ const sourceLocation = { ...projection.locations.source };
3729
+ const targetLocation = { ...projection.locations.target };
3730
+ const evidence = [
3731
+ {
3732
+ role: "source-variable-patterns",
3733
+ object: sourceObject,
3734
+ location: sourceLocation,
3735
+ value: {
3736
+ text: projection.source.text,
3737
+ patterns: sourcePatterns
3738
+ }
3739
+ },
3740
+ {
3741
+ role: "target-variable-patterns",
3742
+ object: targetObject,
3743
+ location: targetLocation,
3744
+ value: {
3745
+ text: projection.target.text,
3746
+ patterns: targetPatterns
3747
+ }
3748
+ },
3749
+ {
3750
+ role: "variable-pattern-difference",
3751
+ object: targetObject,
3752
+ location: targetLocation,
3753
+ value: {
3754
+ missing,
3755
+ extra
3756
+ }
3757
+ }
3758
+ ];
3759
+ return [{
3760
+ severity: "error",
3761
+ object: targetObject,
3762
+ location: targetLocation,
3763
+ message: describeDifference(missing, extra),
3764
+ evidence
3765
+ }];
3766
+ }
3767
+ function variablePatterns(message) {
3768
+ const patterns = /* @__PURE__ */ new Map();
3769
+ for (const branch of message.branches) {
3770
+ const counts = /* @__PURE__ */ new Map();
3771
+ for (const variable of branch.variables) counts.set(variable, (counts.get(variable) ?? 0) + 1);
3772
+ const variables = [...counts].map(([identity, count]) => ({
3773
+ identity,
3774
+ count
3775
+ })).sort((left, right) => compareText(left.identity, right.identity));
3776
+ const key = JSON.stringify(variables);
3777
+ patterns.set(key, {
3778
+ key,
3779
+ variables
3780
+ });
3781
+ }
3782
+ return [...patterns.values()].sort((left, right) => compareText(left.key, right.key));
3783
+ }
3784
+ function describeDifference(missing, extra) {
3785
+ return [...missing.length === 0 ? [] : [`译文缺少变量模式:${missing.map(describePattern).join(";")}。`], ...extra.length === 0 ? [] : [`译文多出变量模式:${extra.map(describePattern).join(";")}。`]].join("");
3786
+ }
3787
+ function describePattern(pattern) {
3788
+ return pattern.variables.length === 0 ? "无变量" : pattern.variables.map(({ identity, count }) => `${identity} × ${count}`).join("、");
3789
+ }
3790
+ function compareText(left, right) {
3791
+ return left < right ? -1 : left > right ? 1 : 0;
3792
+ }
3793
+ // ../../packages/checks/dist/vue-i18n/quality-checks.js
3794
+ /** 创建可直接放入 quality.checks 的 Vue I18n 消息检查集合。 */
3795
+ function createVueI18nChecks(options) {
3796
+ assertVueI18nPreparer(options.prepare);
3797
+ assertVueI18nCallback(options.loadLanguages, "loadLanguages");
3798
+ assertVueI18nCallback(options.loadPolicies, "loadPolicies");
3799
+ assertVueI18nCallback(options.loadTerms, "loadTerms");
3800
+ if (typeof options.reference !== "function") throw new TypeError("Vue I18n reference 必须是函数。");
3801
+ const loadLanguages = options.loadLanguages ?? missingVueI18nData("Vue I18n 语言策略读取器");
3802
+ const loadPolicies = options.loadPolicies ?? missingVueI18nData("Vue I18n 检查策略读取器");
3803
+ const messagePreparation = options.prepare === void 0 ? {} : { prepare: options.prepare };
3804
+ const loadTerms = options.loadTerms ?? missingVueI18nData("Vue I18n 术语库读取器");
3805
+ const identity = (id) => ({ id });
3806
+ const analysis = createVueI18nAnalysis();
3807
+ return [
3808
+ createVueI18nSourceSyntaxChecker({
3809
+ id: "vue-i18n/source-syntax",
3810
+ ...messagePreparation,
3811
+ loadLanguages
3812
+ }),
3813
+ createVueI18nTargetSyntaxChecker({
3814
+ id: "vue-i18n/target-syntax",
3815
+ ...messagePreparation,
3816
+ loadLanguages
3817
+ }),
3818
+ createVueI18nVariableCorrespondenceChecker({
3819
+ id: "vue-i18n/variable-correspondence",
3820
+ ...messagePreparation,
3821
+ loadLanguages
3822
+ }),
3823
+ createLinkTargetExistsCheck({
3824
+ identity: identity("vue-i18n/link-target-exists"),
3825
+ ...messagePreparation,
3826
+ loadPolicies
3827
+ }),
3828
+ createLinkCycleCheck({
3829
+ identity: identity("vue-i18n/link-cycle"),
3830
+ ...messagePreparation,
3831
+ loadPolicies
3832
+ }),
3833
+ createProtectedLiteralCheck({
3834
+ identity: identity("vue-i18n/protected-literals"),
3835
+ ...messagePreparation,
3836
+ loadPolicies
3837
+ }),
3838
+ createQuantityCheck({
3839
+ identity: identity("vue-i18n/quantities"),
3840
+ ...messagePreparation,
3841
+ loadPolicies
3842
+ }),
3843
+ ...createVueI18nTerminologyChecks({
3844
+ ...messagePreparation,
3845
+ analysis,
3846
+ loadLanguages,
3847
+ loadTerms,
3848
+ identities: {
3849
+ allowedTerminology: identity("terminology/require-allowed-translation"),
3850
+ forbiddenTerminology: identity("terminology/reject-forbidden-translation")
3851
+ }
3852
+ }),
3853
+ createVueI18nMessageFamilyCheck({
3854
+ ...messagePreparation,
3855
+ loadPolicies,
3856
+ reference: options.reference,
3857
+ analysis,
3858
+ identity: identity("message-family-consistency")
3859
+ })
3860
+ ];
3861
+ }
3862
+ export { ComparisonBaselineFormatError, ComparisonBaselineIncompleteSnapshotError, ComparisonContractError, DuplicateTranslationUnitKeyError, MemoScopeClosedError, QaSuppressionFormatError, QualityCheckerContractError, QualityDataReaderContractError, StandardSchemaContractError, TermContractError, TermbaseYamlError, TextAnalysisContractError, TranslationIdentityContractError, analyzeTermUse, applyUpdatePlan, asciiNumbers, assessTermUse, braceVariables, compareNumberText, compareProtectedLiterals, compareQuantityBranches, compareSnapshots, compileTerms, createMemoScope, createMessageFamilyChecker, createMissingTranslationChecker, createNumberChecker, createQaSuppression, createQualityProfiler, createSameTextChecker, createSignatureEquivalence, createTemplateSignature, createTermChecker, createTermbase, createTextAnalysis, createUpdatePlan, createVueI18nChecks, createVueI18nSourceSyntaxChecker, createVueI18nTargetSyntaxChecker, createVueI18nVariableCorrespondenceChecker, decideQualityReport, defaultCompare, defaultTermMatchingPolicy, defaultUpdatePolicy, defineChecker, defineConfig, discoverTerms, evaluateTerms, findTerms, formatQualityReport, isQualityReportPassing, literalMarkers, normalizeText, parseTermbaseYaml, prepareVueI18nMessage, previewUpdate, quantityProfile, readComparisonSnapshot, readProjectSnapshot, readSourceSnapshot, recordComparisonBaseline, regexTokens, rejectForbiddenTranslation, replaceComparisonBaseline, requireAllowedTranslation, runQa, segmentWords, selectTerms, signatureKey, termRulesConfigurationSchema, update, upsertQaSuppressionFromReport, validateComparisonBaseline, validateComparisonInput, validateComparisonResult, validateQaSuppression, validateQaSuppressionFile, validateQaSuppressions, validateTranslationCandidate, validateTranslationWriteRequest, validateUpdatePlan, writeTranslationRequests };