js-opencc 1.4.1 → 1.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.
Files changed (134) hide show
  1. package/README.md +111 -129
  2. package/README.zh-Hant.md +222 -0
  3. package/data/custom/CNTWPhrases.txt +6 -0
  4. package/dist/bundles/cn2t.d.ts +2 -3
  5. package/dist/bundles/cn2t.js +36 -11
  6. package/dist/bundles/full.d.ts +2 -3
  7. package/dist/bundles/full.js +22 -8
  8. package/dist/bundles/t2cn.d.ts +2 -3
  9. package/dist/bundles/t2cn.js +28 -9
  10. package/dist/converter.d.ts +6 -1
  11. package/dist/converter.js +43 -10
  12. package/dist/core.d.ts +107 -17
  13. package/dist/core.js +377 -51
  14. package/dist/dict/CNTWPhrases.d.ts +2 -3
  15. package/dist/dict/CNTWPhrases.js +2 -2
  16. package/dist/dict/HKPhrases.d.ts +2 -3
  17. package/dist/dict/HKPhrases.js +2 -2
  18. package/dist/dict/HKPhrasesRev.d.ts +2 -3
  19. package/dist/dict/HKPhrasesRev.js +2 -2
  20. package/dist/dict/HKVariants.d.ts +2 -3
  21. package/dist/dict/HKVariants.js +2 -2
  22. package/dist/dict/HKVariantsPhrases.d.ts +2 -3
  23. package/dist/dict/HKVariantsPhrases.js +2 -2
  24. package/dist/dict/HKVariantsRev.d.ts +2 -3
  25. package/dist/dict/HKVariantsRev.js +2 -2
  26. package/dist/dict/HKVariantsRevPhrases.d.ts +2 -3
  27. package/dist/dict/HKVariantsRevPhrases.js +2 -2
  28. package/dist/dict/JPShinjitaiCharacters.d.ts +2 -3
  29. package/dist/dict/JPShinjitaiCharacters.js +2 -2
  30. package/dist/dict/JPShinjitaiCharactersRev.d.ts +2 -3
  31. package/dist/dict/JPShinjitaiCharactersRev.js +2 -2
  32. package/dist/dict/JPShinjitaiPhrases.d.ts +2 -3
  33. package/dist/dict/JPShinjitaiPhrases.js +2 -2
  34. package/dist/dict/STCharacters.d.ts +2 -3
  35. package/dist/dict/STCharacters.js +2 -2
  36. package/dist/dict/STPhrases.d.ts +2 -3
  37. package/dist/dict/STPhrases.js +2 -2
  38. package/dist/dict/STPhrases_GeneratedFromRegionalPhrases.d.ts +2 -0
  39. package/dist/dict/STPhrases_GeneratedFromRegionalPhrases.js +2 -0
  40. package/dist/dict/TSCharacters.d.ts +2 -3
  41. package/dist/dict/TSCharacters.js +2 -2
  42. package/dist/dict/TSPhrases.d.ts +2 -3
  43. package/dist/dict/TSPhrases.js +2 -2
  44. package/dist/dict/TWPhrases.d.ts +2 -3
  45. package/dist/dict/TWPhrases.js +2 -2
  46. package/dist/dict/TWPhrasesRev.d.ts +2 -3
  47. package/dist/dict/TWPhrasesRev.js +2 -2
  48. package/dist/dict/TWVariants.d.ts +2 -3
  49. package/dist/dict/TWVariants.js +2 -2
  50. package/dist/dict/TWVariantsPhrases.d.ts +2 -3
  51. package/dist/dict/TWVariantsPhrases.js +2 -2
  52. package/dist/dict/TWVariantsRev.d.ts +2 -3
  53. package/dist/dict/TWVariantsRev.js +2 -2
  54. package/dist/dict/TWVariantsRevPhrases.d.ts +2 -3
  55. package/dist/dict/TWVariantsRevPhrases.js +2 -2
  56. package/dist/dict/index.d.ts +0 -1
  57. package/dist/dict/index.js +1 -1
  58. package/dist/html-converter.d.ts +0 -1
  59. package/dist/html-converter.js +65 -26
  60. package/dist/index.d.ts +2 -3
  61. package/dist/index.js +14 -5
  62. package/dist/presets.d.ts +44 -1
  63. package/dist/presets.js +58 -2
  64. package/dist/umd/cn2t.js +554 -102
  65. package/dist/umd/cn2t.js.map +1 -1
  66. package/dist/umd/cn2t.min.js +1 -1
  67. package/dist/umd/cn2t.min.js.map +1 -1
  68. package/dist/umd/full.js +560 -119
  69. package/dist/umd/full.js.map +1 -1
  70. package/dist/umd/full.min.js +1 -1
  71. package/dist/umd/full.min.js.map +1 -1
  72. package/dist/umd/t2cn.js +548 -103
  73. package/dist/umd/t2cn.js.map +1 -1
  74. package/dist/umd/t2cn.min.js +1 -1
  75. package/dist/umd/t2cn.min.js.map +1 -1
  76. package/package.json +2 -1
  77. package/dist/bundles/cn2t.d.ts.map +0 -1
  78. package/dist/bundles/cn2t.js.map +0 -1
  79. package/dist/bundles/full.d.ts.map +0 -1
  80. package/dist/bundles/full.js.map +0 -1
  81. package/dist/bundles/t2cn.d.ts.map +0 -1
  82. package/dist/bundles/t2cn.js.map +0 -1
  83. package/dist/converter.d.ts.map +0 -1
  84. package/dist/converter.js.map +0 -1
  85. package/dist/core.d.ts.map +0 -1
  86. package/dist/core.js.map +0 -1
  87. package/dist/dict/CNTWPhrases.d.ts.map +0 -1
  88. package/dist/dict/CNTWPhrases.js.map +0 -1
  89. package/dist/dict/HKPhrases.d.ts.map +0 -1
  90. package/dist/dict/HKPhrases.js.map +0 -1
  91. package/dist/dict/HKPhrasesRev.d.ts.map +0 -1
  92. package/dist/dict/HKPhrasesRev.js.map +0 -1
  93. package/dist/dict/HKVariants.d.ts.map +0 -1
  94. package/dist/dict/HKVariants.js.map +0 -1
  95. package/dist/dict/HKVariantsPhrases.d.ts.map +0 -1
  96. package/dist/dict/HKVariantsPhrases.js.map +0 -1
  97. package/dist/dict/HKVariantsRev.d.ts.map +0 -1
  98. package/dist/dict/HKVariantsRev.js.map +0 -1
  99. package/dist/dict/HKVariantsRevPhrases.d.ts.map +0 -1
  100. package/dist/dict/HKVariantsRevPhrases.js.map +0 -1
  101. package/dist/dict/JPShinjitaiCharacters.d.ts.map +0 -1
  102. package/dist/dict/JPShinjitaiCharacters.js.map +0 -1
  103. package/dist/dict/JPShinjitaiCharactersRev.d.ts.map +0 -1
  104. package/dist/dict/JPShinjitaiCharactersRev.js.map +0 -1
  105. package/dist/dict/JPShinjitaiPhrases.d.ts.map +0 -1
  106. package/dist/dict/JPShinjitaiPhrases.js.map +0 -1
  107. package/dist/dict/STCharacters.d.ts.map +0 -1
  108. package/dist/dict/STCharacters.js.map +0 -1
  109. package/dist/dict/STPhrases.d.ts.map +0 -1
  110. package/dist/dict/STPhrases.js.map +0 -1
  111. package/dist/dict/TSCharacters.d.ts.map +0 -1
  112. package/dist/dict/TSCharacters.js.map +0 -1
  113. package/dist/dict/TSPhrases.d.ts.map +0 -1
  114. package/dist/dict/TSPhrases.js.map +0 -1
  115. package/dist/dict/TWPhrases.d.ts.map +0 -1
  116. package/dist/dict/TWPhrases.js.map +0 -1
  117. package/dist/dict/TWPhrasesRev.d.ts.map +0 -1
  118. package/dist/dict/TWPhrasesRev.js.map +0 -1
  119. package/dist/dict/TWVariants.d.ts.map +0 -1
  120. package/dist/dict/TWVariants.js.map +0 -1
  121. package/dist/dict/TWVariantsPhrases.d.ts.map +0 -1
  122. package/dist/dict/TWVariantsPhrases.js.map +0 -1
  123. package/dist/dict/TWVariantsRev.d.ts.map +0 -1
  124. package/dist/dict/TWVariantsRev.js.map +0 -1
  125. package/dist/dict/TWVariantsRevPhrases.d.ts.map +0 -1
  126. package/dist/dict/TWVariantsRevPhrases.js.map +0 -1
  127. package/dist/dict/index.d.ts.map +0 -1
  128. package/dist/dict/index.js.map +0 -1
  129. package/dist/html-converter.d.ts.map +0 -1
  130. package/dist/html-converter.js.map +0 -1
  131. package/dist/index.d.ts.map +0 -1
  132. package/dist/index.js.map +0 -1
  133. package/dist/presets.d.ts.map +0 -1
  134. package/dist/presets.js.map +0 -1
@@ -2,12 +2,13 @@
2
2
  * cn2t bundle - Simplified Chinese to Traditional Chinese only
3
3
  * Smaller bundle size for one-way conversion
4
4
  */
5
- import { Trie, ConverterFactory, CustomConverter, ProtectedConverter, parseOpenCCDict } from "../core.js";
5
+ import { Trie, ConverterFactory, ConverterFactoryWithSegmentation, CustomConverter, ProtectedConverter, parseOpenCCDict, normalizeCompatibilityIdeographs } from "../core.js";
6
6
  import { HTMLConverter } from "../html-converter.js";
7
- import { standard2variants, phraseDictDirection } from "../presets.js";
7
+ import { standard2variants, phraseDictDirection, segmentationDictsFor } from "../presets.js";
8
8
  // Import only the dictionaries needed for cn -> t/tw/twp/hk
9
9
  import STCharacters from "../dict/STCharacters.js";
10
10
  import STPhrases from "../dict/STPhrases.js";
11
+ import STPhrases_GeneratedFromRegionalPhrases from "../dict/STPhrases_GeneratedFromRegionalPhrases.js";
11
12
  import TWVariants from "../dict/TWVariants.js";
12
13
  import TWVariantsPhrases from "../dict/TWVariantsPhrases.js";
13
14
  import TWPhrases from "../dict/TWPhrases.js";
@@ -19,6 +20,7 @@ import CNTWPhrases from "../dict/CNTWPhrases.js";
19
20
  const dictMap = {
20
21
  STCharacters,
21
22
  STPhrases,
23
+ STPhrases_GeneratedFromRegionalPhrases,
22
24
  TWVariants,
23
25
  TWVariantsPhrases,
24
26
  TWPhrases,
@@ -49,8 +51,10 @@ function Converter(options, protectedDict) {
49
51
  throw new Error(`cn2t bundle cannot convert to 'cn' — use the t2cn bundle`);
50
52
  }
51
53
  const dictGroups = [];
52
- // From cn to standard (always needed)
53
- dictGroups.push([STCharacters, STPhrases]);
54
+ // From cn to standard (always needed). Order = last-write-wins priority;
55
+ // the generated dict pins regional terms (出租车→出租車) so segmentation can
56
+ // keep them whole — see presets.ts segmentationDictsFor.
57
+ dictGroups.push([STCharacters, STPhrases_GeneratedFromRegionalPhrases, STPhrases]);
54
58
  // From standard to target variant. Unknown locales and preset files missing
55
59
  // from dictMap throw loudly — silently skipping a step would return
56
60
  // partially-converted text (JS callers bypass the TS type check).
@@ -70,17 +74,38 @@ function Converter(options, protectedDict) {
70
74
  return d;
71
75
  }));
72
76
  }
73
- // CNTWPhrases (custom vocabulary dict) — whether it applies comes from the
74
- // shared rule, so UMD output matches the npm main entry (幼儿园→幼稚園). The
75
- // direction can only be "forward" here: `from` is always cn, never Taiwanese.
77
+ // Cut the input before converting: without it the second step's regional
78
+ // vocabulary table matches across word boundaries the first step set, and
79
+ // 他优化了 comes out 他最佳化了 where OpenCC gives 他優化了. Only the
80
+ // cn <-> tw/hk directions segment; segmentationDictsFor decides.
81
+ const segmentation = segmentationDictsFor("cn", options.to).length
82
+ ? [STPhrases, STPhrases_GeneratedFromRegionalPhrases]
83
+ : null;
84
+ let convert = ConverterFactoryWithSegmentation(segmentation, ...dictGroups);
85
+ // CNTWPhrases used to be unshifted as an ordinary FIRST trie group. That
86
+ // shape had two failure modes, both found by probing every entry in context:
87
+ //
88
+ // 1. Its keys were not segmentation boundaries, so the cut could land
89
+ // inside one (人脸识别 → [人脸][识别]) and the entry never matched.
90
+ // 2. Its OUTPUT was re-fed through the built-in steps, which re-converted
91
+ // pieces of it: 调制解调器 → 數據機 → TWPhrases hits 數據→資料 → 資料機.
92
+ // This one predates segmentation — it shipped wrong from the start.
93
+ //
94
+ // ProtectedConverter's masking already implements the semantics this dict
95
+ // actually wants — match key, hide the span behind a PUA placeholder so the
96
+ // whole inner pipeline (segmentation included) cannot see it, restore the
97
+ // TARGET VALUE afterwards. Vocabulary override means override: nothing
98
+ // downstream may re-chew the result. The user's own protectedDict still
99
+ // wraps outermost, so its priority stays above this layer (inner masking
100
+ // passes pre-existing PUA through untouched).
101
+ // Direction can only be "forward" here: `from` is always cn, never Taiwanese.
76
102
  if (phraseDictDirection("cn", options.to, options.loadCustomPhrases)) {
77
- dictGroups.unshift([CNTWPhrases]);
103
+ convert = ProtectedConverter(CNTWPhrases, convert);
78
104
  }
79
- let convert = ConverterFactory(...dictGroups);
80
105
  if (protectedDict) {
81
106
  convert = ProtectedConverter(protectedDict, convert);
82
107
  }
83
108
  return convert;
84
109
  }
85
- export { Converter, CustomConverter, ConverterFactory, ProtectedConverter, parseOpenCCDict, HTMLConverter, Trie };
86
- //# sourceMappingURL=cn2t.js.map
110
+ // // 带切段的工厂也导出:只给不带切段的那个,自己拼链的人会静默丢掉地区词边界处理
111
+ export { Converter, CustomConverter, ConverterFactory, ConverterFactoryWithSegmentation, ProtectedConverter, normalizeCompatibilityIdeographs, parseOpenCCDict, HTMLConverter, Trie, };
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Full bundle - includes all locales and converters
3
3
  */
4
- import { Trie, ConverterFactory, CustomConverter, ProtectedConverter, parseOpenCCDict, DictLike } from "../core.js";
4
+ import { Trie, ConverterFactory, ConverterFactoryWithSegmentation, CustomConverter, ProtectedConverter, parseOpenCCDict, DictLike, normalizeCompatibilityIdeographs } from "../core.js";
5
5
  import { HTMLConverter, HTMLConverterOptions } from "../html-converter.js";
6
6
  import { LocaleCode } from "../presets.js";
7
7
  type DictGroup = DictLike[];
@@ -36,6 +36,5 @@ declare const Locale: {
36
36
  [k: string]: string[];
37
37
  };
38
38
  };
39
- export { Converter, CustomConverter, ConverterFactory, ProtectedConverter, parseOpenCCDict, HTMLConverter, Locale, Trie };
39
+ export { Converter, CustomConverter, ConverterFactory, ConverterFactoryWithSegmentation, ProtectedConverter, normalizeCompatibilityIdeographs, parseOpenCCDict, HTMLConverter, Locale, Trie, };
40
40
  export type { ConverterOptions, HTMLConverterOptions, LocaleCode, DictLike, DictGroup };
41
- //# sourceMappingURL=full.d.ts.map
@@ -1,13 +1,14 @@
1
1
  /**
2
2
  * Full bundle - includes all locales and converters
3
3
  */
4
- import { Trie, ConverterFactory, CustomConverter, ProtectedConverter, parseOpenCCDict, reverseDictString } from "../core.js";
4
+ import { Trie, ConverterFactory, ConverterFactoryWithSegmentation, CustomConverter, ProtectedConverter, parseOpenCCDict, reverseDictString, normalizeCompatibilityIdeographs } from "../core.js";
5
5
  import { HTMLConverter } from "../html-converter.js";
6
- import { variants2standard, standard2variants, phraseDictDirection } from "../presets.js";
6
+ import { variants2standard, standard2variants, phraseDictDirection, segmentationDictsFor } from "../presets.js";
7
7
  // Import all preset dictionaries eagerly — UMD bundles are single-file by
8
8
  // design, so they bypass the lazy dictLoaders map in dict/index.js.
9
9
  import STCharacters from "../dict/STCharacters.js";
10
10
  import STPhrases from "../dict/STPhrases.js";
11
+ import STPhrases_GeneratedFromRegionalPhrases from "../dict/STPhrases_GeneratedFromRegionalPhrases.js";
11
12
  import TSCharacters from "../dict/TSCharacters.js";
12
13
  import TSPhrases from "../dict/TSPhrases.js";
13
14
  import HKVariants from "../dict/HKVariants.js";
@@ -29,6 +30,7 @@ import CNTWPhrases from "../dict/CNTWPhrases.js";
29
30
  const dict = {
30
31
  STCharacters,
31
32
  STPhrases,
33
+ STPhrases_GeneratedFromRegionalPhrases,
32
34
  TSCharacters,
33
35
  TSPhrases,
34
36
  HKVariants,
@@ -79,13 +81,25 @@ function Converter(options, protectedDict) {
79
81
  if (options.to !== "t") {
80
82
  dictGroups.push(standard2variants[options.to].map((name) => dict[name]));
81
83
  }
82
- // CNTWPhrases (custom vocabulary dict) — direction and default come from the
83
- // shared rule, so UMD output matches the npm main entry.
84
+ // Cut the input before converting: without it the second step's regional
85
+ // vocabulary table matches across word boundaries the first step set, and
86
+ // 他优化了 comes out 他最佳化了 where OpenCC gives 他優化了. Only the
87
+ // cn <-> tw/hk directions segment; segmentationDictsFor decides which dict.
88
+ const segmentationFiles = segmentationDictsFor(options.from, options.to);
89
+ const segmentation = segmentationFiles.length ? segmentationFiles.map((name) => dict[name]) : null;
90
+ let convert = ConverterFactoryWithSegmentation(segmentation, ...dictGroups);
91
+ // CNTWPhrases as a masking override, not a first trie group — the group
92
+ // shape let segmentation cut its keys (人脸识别 → [人脸][识别], entry dead)
93
+ // and let later steps re-chew its output (调制解调器 → 數據機 → 資料機 via
94
+ // TWPhrases 數據→資料). Masking hides the span from the whole inner pipeline
95
+ // and restores the TARGET VALUE at the end; the user's protectedDict still
96
+ // wraps outermost, keeping its priority above this layer. Direction and
97
+ // default come from the shared rule (presets.phraseDictDirection);
98
+ // "reverse" flips the dict for Taiwanese→cn conversions.
84
99
  const phraseDir = phraseDictDirection(options.from, options.to, options.loadCustomPhrases);
85
100
  if (phraseDir) {
86
- dictGroups.unshift([phraseDir === "reverse" ? reverseDictString(CNTWPhrases) : CNTWPhrases]);
101
+ convert = ProtectedConverter(phraseDir === "reverse" ? reverseDictString(CNTWPhrases) : CNTWPhrases, convert);
87
102
  }
88
- let convert = ConverterFactory(...dictGroups);
89
103
  if (protectedDict) {
90
104
  convert = ProtectedConverter(protectedDict, convert);
91
105
  }
@@ -96,5 +110,5 @@ const Locale = {
96
110
  from: Object.fromEntries(Object.entries(variants2standard).map(([locale, files]) => [locale, files.map((name) => dict[name])])),
97
111
  to: Object.fromEntries(Object.entries(standard2variants).map(([locale, files]) => [locale, files.map((name) => dict[name])])),
98
112
  };
99
- export { Converter, CustomConverter, ConverterFactory, ProtectedConverter, parseOpenCCDict, HTMLConverter, Locale, Trie };
100
- //# sourceMappingURL=full.js.map
113
+ // // 带切段的工厂也导出:只给不带切段的那个,自己拼链的人会静默丢掉地区词边界处理
114
+ export { Converter, CustomConverter, ConverterFactory, ConverterFactoryWithSegmentation, ProtectedConverter, normalizeCompatibilityIdeographs, parseOpenCCDict, HTMLConverter, Locale, Trie, };
@@ -2,7 +2,7 @@
2
2
  * t2cn bundle - Traditional Chinese to Simplified Chinese only
3
3
  * Smaller bundle size for one-way conversion
4
4
  */
5
- import { Trie, ConverterFactory, CustomConverter, ProtectedConverter, parseOpenCCDict, DictLike } from "../core.js";
5
+ import { Trie, ConverterFactory, ConverterFactoryWithSegmentation, CustomConverter, ProtectedConverter, parseOpenCCDict, DictLike, normalizeCompatibilityIdeographs } from "../core.js";
6
6
  import { HTMLConverter, HTMLConverterOptions } from "../html-converter.js";
7
7
  type DictGroup = DictLike[];
8
8
  type SourceLocale = "t" | "tw" | "twp" | "hk" | "hkp" | "jp";
@@ -21,6 +21,5 @@ interface ConverterOptions {
21
21
  * pass the dict explicitly (use `parseOpenCCDict` for OpenCC-format text).
22
22
  */
23
23
  declare function Converter(options: ConverterOptions, protectedDict?: DictLike): (input: string) => string;
24
- export { Converter, CustomConverter, ConverterFactory, ProtectedConverter, parseOpenCCDict, HTMLConverter, Trie };
24
+ export { Converter, CustomConverter, ConverterFactory, ConverterFactoryWithSegmentation, ProtectedConverter, normalizeCompatibilityIdeographs, parseOpenCCDict, HTMLConverter, Trie, };
25
25
  export type { ConverterOptions, HTMLConverterOptions, DictLike, DictGroup };
26
- //# sourceMappingURL=t2cn.d.ts.map
@@ -2,9 +2,9 @@
2
2
  * t2cn bundle - Traditional Chinese to Simplified Chinese only
3
3
  * Smaller bundle size for one-way conversion
4
4
  */
5
- import { Trie, ConverterFactory, CustomConverter, ProtectedConverter, parseOpenCCDict, reverseDictString } from "../core.js";
5
+ import { Trie, ConverterFactory, ConverterFactoryWithSegmentation, CustomConverter, ProtectedConverter, parseOpenCCDict, reverseDictString, normalizeCompatibilityIdeographs } from "../core.js";
6
6
  import { HTMLConverter } from "../html-converter.js";
7
- import { variants2standard, phraseDictDirection } from "../presets.js";
7
+ import { variants2standard, phraseDictDirection, segmentationDictsFor } from "../presets.js";
8
8
  // Import only the dictionaries needed for t/tw/twp/hk -> cn
9
9
  import TSCharacters from "../dict/TSCharacters.js";
10
10
  import TSPhrases from "../dict/TSPhrases.js";
@@ -68,17 +68,36 @@ function Converter(options, protectedDict) {
68
68
  }
69
69
  // From standard to cn (always needed)
70
70
  dictGroups.push([TSCharacters, TSPhrases]);
71
- // CNTWPhrases (custom vocabulary dict) — whether it applies comes from the
72
- // shared rule, so UMD output matches the npm main entry (幼稚園→幼儿园). The
73
- // direction can only be "reverse" here: `to` is always cn, never Taiwanese.
71
+ // Cut the input before converting: without it the second step's regional
72
+ // vocabulary table matches across word boundaries the first step set, and
73
+ // 他优化了 comes out 他最佳化了 where OpenCC gives 他優化了. Only the
74
+ // cn <-> tw/hk directions segment; segmentationDictsFor decides.
75
+ const segmentation = segmentationDictsFor(options.from ?? "t", "cn").length ? [TSPhrases] : null;
76
+ let convert = ConverterFactoryWithSegmentation(segmentation, ...dictGroups);
77
+ // CNTWPhrases used to be unshifted as an ordinary FIRST trie group. That
78
+ // shape had two failure modes, both found by probing every entry in context:
79
+ //
80
+ // 1. Its keys were not segmentation boundaries, so the cut could land
81
+ // inside one (人脸识别 → [人脸][识别]) and the entry never matched.
82
+ // 2. Its OUTPUT was re-fed through the built-in steps, which re-converted
83
+ // pieces of it: 调制解调器 → 數據機 → TWPhrases hits 數據→資料 → 資料機.
84
+ // This one predates segmentation — it shipped wrong from the start.
85
+ //
86
+ // ProtectedConverter's masking already implements the semantics this dict
87
+ // actually wants — match key, hide the span behind a PUA placeholder so the
88
+ // whole inner pipeline (segmentation included) cannot see it, restore the
89
+ // TARGET VALUE afterwards. Vocabulary override means override: nothing
90
+ // downstream may re-chew the result. The user's own protectedDict still
91
+ // wraps outermost, so its priority stays above this layer (inner masking
92
+ // passes pre-existing PUA through untouched).
93
+ // Only the "reverse" direction can occur here (`to` is always cn): flip the dict.
74
94
  if (phraseDictDirection(options.from, "cn", options.loadCustomPhrases)) {
75
- dictGroups.unshift([reverseDictString(CNTWPhrases)]);
95
+ convert = ProtectedConverter(reverseDictString(CNTWPhrases), convert);
76
96
  }
77
- let convert = ConverterFactory(...dictGroups);
78
97
  if (protectedDict) {
79
98
  convert = ProtectedConverter(protectedDict, convert);
80
99
  }
81
100
  return convert;
82
101
  }
83
- export { Converter, CustomConverter, ConverterFactory, ProtectedConverter, parseOpenCCDict, HTMLConverter, Trie };
84
- //# sourceMappingURL=t2cn.js.map
102
+ // // 带切段的工厂也导出:只给不带切段的那个,自己拼链的人会静默丢掉地区词边界处理
103
+ export { Converter, CustomConverter, ConverterFactory, ConverterFactoryWithSegmentation, ProtectedConverter, normalizeCompatibilityIdeographs, parseOpenCCDict, HTMLConverter, Trie, };
@@ -25,6 +25,12 @@ export interface ConverterOptions {
25
25
  export interface LocalePreset {
26
26
  from: Record<string, DictGroup>;
27
27
  to: Record<string, DictGroup>;
28
+ /**
29
+ * Dictionaries available to cut the input on, keyed by dict file name (the
30
+ * names `segmentationDictsFor` returns, e.g. `STPhrases` / `TSPhrases`).
31
+ * Optional: a preset without it simply does not segment.
32
+ */
33
+ segmentation?: Record<string, DictLike>;
28
34
  }
29
35
  /**
30
36
  * Create a Converter factory with locale preset
@@ -72,4 +78,3 @@ export declare function getDictFiles(from: LocaleCode, to: LocaleCode): string[]
72
78
  export declare function createConverter(options: ConverterOptions, protectedDict?: DictLike): Promise<(input: string) => string>;
73
79
  export type { LocaleCode } from "./presets.js";
74
80
  export type { DictLike, DictGroup } from "./core.js";
75
- //# sourceMappingURL=converter.d.ts.map
package/dist/converter.js CHANGED
@@ -3,8 +3,8 @@
3
3
  * High-level API for creating converters
4
4
  */
5
5
  // Imports removed
6
- import { ConverterFactory, ProtectedConverter, parseOpenCCDict, reverseDictString } from "./core.js";
7
- import { variants2standard, standard2variants, phraseDictDirection } from "./presets.js";
6
+ import { ConverterFactoryWithSegmentation, ProtectedConverter, parseOpenCCDict, reverseDictString } from "./core.js";
7
+ import { variants2standard, standard2variants, phraseDictDirection, segmentationDictsFor } from "./presets.js";
8
8
  // Loader map only (a few hundred bytes) — the dict payloads behind each thunk
9
9
  // stay in their own lazily-imported chunks so bundlers fetch per-file on demand.
10
10
  import { dictLoaders } from "./dict/index.js";
@@ -24,7 +24,13 @@ export function ConverterBuilder(localePreset) {
24
24
  if (options.to !== "t" && localePreset.to[options.to]) {
25
25
  dictGroups.push(localePreset.to[options.to]);
26
26
  }
27
- return ConverterFactory(...dictGroups);
27
+ // Segmentation needs a dictionary keyed in the INPUT's script, which a
28
+ // caller-supplied preset may not carry. Cut only when the preset actually
29
+ // has it; a preset without it keeps the old, unsegmented behaviour rather
30
+ // than silently cutting on the wrong script.
31
+ const segmentationFiles = segmentationDictsFor(options.from, options.to);
32
+ const segmentation = segmentationFiles.map((name) => localePreset.segmentation?.[name]).filter((d) => d !== undefined);
33
+ return ConverterFactoryWithSegmentation(segmentation.length ? segmentation : null, ...dictGroups);
28
34
  };
29
35
  }
30
36
  /**
@@ -116,7 +122,13 @@ export async function createConverter(options, protectedDict) {
116
122
  // Memoized like innerConverterCache: the file ships with the package and never
117
123
  // changes at runtime, and re-reading it dominates everything else in a batch
118
124
  // (200 cached calls: 82ms re-reading vs 0.1ms with the read hoisted out).
119
- if (!protectedDict) {
125
+ //
126
+ // `=== undefined`, NOT a falsy check: the documented contract is "any explicit
127
+ // second argument (including []) bypasses auto-load", and "" is an explicit
128
+ // argument too (DictLike admits strings). A falsy check made "" auto-load while
129
+ // [] bypassed — invisible while the shipped file is all-commented (auto-load
130
+ // yields zero entries either way), diverging the moment a user edits the file.
131
+ if (protectedDict === undefined) {
120
132
  if (!packageProtectedDict)
121
133
  packageProtectedDict = tryLoadPackageProtectedDict();
122
134
  protectedDict = await packageProtectedDict;
@@ -168,15 +180,36 @@ async function buildInnerConverter(from, to, phraseDir) {
168
180
  if (group.length)
169
181
  dictGroups.push(group);
170
182
  }
171
- // (b) CNTWPhrases (ordinary vocabulary dict, stays in main chain). Loaded only
172
- // when the direction rule says it applies, so other directions don't fetch it.
183
+ // (b) Segmentation dictionary. Cutting the input first keeps a later
184
+ // conversion step from matching across a word boundary an earlier step set —
185
+ // without it the regional vocabulary tables over-fire in context
186
+ // (他优化了 → 他最佳化了 where OpenCC gives 他優化了). Empty for single-step
187
+ // chains, which then take ConverterFactory's cheaper path.
188
+ const segmentationFiles = segmentationDictsFor(from, to);
189
+ const segmentation = segmentationFiles.length ? (await Promise.all(segmentationFiles.map(loadDict))).filter((d) => d !== null) : [];
190
+ // (c) Build the inner converter chain
191
+ let convert = ConverterFactoryWithSegmentation(segmentation.length ? segmentation : null, ...dictGroups);
192
+ // CNTWPhrases used to be unshifted as an ordinary FIRST trie group. That
193
+ // shape had two failure modes, both found by probing every entry in context:
194
+ //
195
+ // 1. Its keys were not segmentation boundaries, so the cut could land
196
+ // inside one (人脸识别 → [人脸][识别]) and the entry never matched.
197
+ // 2. Its OUTPUT was re-fed through the built-in steps, which re-converted
198
+ // pieces of it: 调制解调器 → 數據機 → TWPhrases hits 數據→資料 → 資料機.
199
+ // This one predates segmentation — it shipped wrong from the start.
200
+ //
201
+ // ProtectedConverter's masking already implements the semantics this dict
202
+ // actually wants — match key, hide the span behind a PUA placeholder so the
203
+ // whole inner pipeline (segmentation included) cannot see it, restore the
204
+ // TARGET VALUE afterwards. Vocabulary override means override: nothing
205
+ // downstream may re-chew the result. The user's own protectedDict still
206
+ // wraps outermost, so its priority stays above this layer (inner masking
207
+ // passes pre-existing PUA through untouched).
173
208
  if (phraseDir) {
174
209
  const phrases = await loadDict("CNTWPhrases");
175
210
  if (phrases) {
176
- dictGroups.unshift([phraseDir === "reverse" ? reverseDictString(phrases) : phrases]);
211
+ convert = ProtectedConverter(phraseDir === "reverse" ? reverseDictString(phrases) : phrases, convert);
177
212
  }
178
213
  }
179
- // (c) Build the inner converter chain
180
- return ConverterFactory(...dictGroups);
214
+ return convert;
181
215
  }
182
- //# sourceMappingURL=converter.js.map
package/dist/core.d.ts CHANGED
@@ -14,9 +14,18 @@ export type DictGroup = DictLike[];
14
14
  * Trie tree for efficient string matching and conversion
15
15
  */
16
16
  export declare class Trie {
17
- private map;
17
+ /**
18
+ * Children, allocated on first insert.
19
+ *
20
+ * Half the nodes in a real dictionary trie are leaves (measured on
21
+ * STPhrases: 42 950 of 86 388, 49.7%), and an eagerly-constructed `new Map()`
22
+ * on every one of them is pure overhead — an empty Map is not free. Leaving
23
+ * this `undefined` until a child is actually added drops a Map allocation
24
+ * for every leaf. Read sites must therefore go through `?.get(...)`, which
25
+ * returns `undefined` for a leaf exactly as an empty Map's `get` would.
26
+ */
27
+ private map?;
18
28
  private value?;
19
- constructor();
20
29
  /**
21
30
  * Add a word to the trie
22
31
  * @param key - The string to match
@@ -42,11 +51,23 @@ export declare class Trie {
42
51
  * not relative to `start`. Callers should check `end > start`.
43
52
  * @param input - The string to search
44
53
  * @param start - The index to start matching from
54
+ *
55
+ * 热路径请用 {@link matchLongestInto}(免分配变体,语义一致)——两边改其一必同步另一个。
45
56
  */
46
57
  findLongestMatch(input: string, start: number): {
47
58
  end: number;
48
59
  value: string | undefined;
49
60
  };
61
+ /**
62
+ * findLongestMatch 的免分配变体:结果写进调用方复用的 `out`,不造对象。
63
+ * 给每个位置都要探一次的热调用方用(maskWithTrie 一个位置一次——对象版
64
+ * 在 4 万字语料上就是 4 万次 {end,value} 分配)。语义与 findLongestMatch
65
+ * 完全一致,改其一必同步另一个。
66
+ */
67
+ matchLongestInto(input: string, start: number, out: {
68
+ end: number;
69
+ value: string | undefined;
70
+ }): void;
50
71
  /**
51
72
  * Convert a string using the trie
52
73
  * Uses longest match algorithm for optimal conversion
@@ -54,7 +75,48 @@ export declare class Trie {
54
75
  * @returns The converted string
55
76
  */
56
77
  convert(input: string): string;
78
+ /**
79
+ * Split input into segments on this trie's entries, longest match first.
80
+ *
81
+ * Every matched entry becomes its own segment, and the runs between them are
82
+ * emitted as segments too, so `segments.join("")` reconstructs the input
83
+ * exactly. Nothing is converted here — only cut.
84
+ *
85
+ * Exists for {@link ConverterFactoryWithSegmentation}; see there for why the
86
+ * cut changes results.
87
+ *
88
+ * @param input - The string to split
89
+ * @returns Segments whose concatenation equals `input`
90
+ */
91
+ segment(input: string): string[];
57
92
  }
93
+ /**
94
+ * Fold CJK Compatibility Ideographs to their unified equivalents.
95
+ *
96
+ * OpenCC does this with a 1002-entry dictionary
97
+ * (`CJK_Compatibility_Ideographs`) loaded as a normalization step by every
98
+ * config. **We ship no such table.** Those mappings are canonical singleton
99
+ * decompositions in the Unicode standard, which is precisely what
100
+ * `String.prototype.normalize` performs — checked entry by entry against
101
+ * opencc-js's copy: all 1002 agree, and NFC folds nothing the table misses.
102
+ * So ~8.7 KB of data becomes a call into the engine's own ICU, which has the
103
+ * side benefit of tracking new Unicode versions without a resync.
104
+ *
105
+ * Two deliberate details:
106
+ *
107
+ * 1. **NFC, not NFKC.** NFKC would also fold full-width forms (`,`→`,`,
108
+ * `A`→`A`) and enclosed characters (`㈱`→`(株)`). In Chinese prose that is
109
+ * destructive: full-width punctuation is correct typography, not a
110
+ * compatibility artifact.
111
+ * 2. **Only the two compatibility blocks are touched**, not the whole string.
112
+ * Whole-string NFC would also compose combining sequences the caller never
113
+ * asked us to touch. The pre-test means ordinary text — which has no
114
+ * compatibility ideographs at all — is returned as-is with no allocation.
115
+ *
116
+ * @param input - The string to normalize
117
+ * @returns The string with compatibility ideographs folded
118
+ */
119
+ export declare function normalizeCompatibilityIdeographs(input: string): string;
58
120
  /**
59
121
  * Create a converter from multiple dictionary groups
60
122
  * Each dictionary group is applied in sequence
@@ -62,26 +124,55 @@ export declare class Trie {
62
124
  * @returns Converter function
63
125
  */
64
126
  export declare function ConverterFactory(...dictGroups: DictGroup[]): (input: string) => string;
127
+ /**
128
+ * Like {@link ConverterFactory}, but cuts the input into segments first and
129
+ * runs every conversion step **inside each segment** instead of across the
130
+ * whole string.
131
+ *
132
+ * ## What this is for
133
+ *
134
+ * With a two-step chain (`cn → t`, then `t → tw`), the second step sees text
135
+ * the first step produced. Without segmentation it can match across a word
136
+ * boundary the first step established, and the regional vocabulary tables
137
+ * (`TWPhrases`, `HKPhrases`) then fire in places OpenCC does not fire them.
138
+ * Measured against OpenCC's own output on 1707 phrases in context, dropping
139
+ * segmentation changes 21 of them — always by over-applying:
140
+ *
141
+ * ```text
142
+ * 他优化了 OpenCC 他優化了 no segmentation 他最佳化了
143
+ * 他函数了 OpenCC 他函數了 no segmentation 他函式了
144
+ * 他宽带了 OpenCC 他寬帶了 no segmentation 他寬頻了
145
+ * ```
146
+ *
147
+ * Note the bare phrase still converts (`优化` → `最佳化`) either way. It is
148
+ * only *in context* that the boundary matters, which is what makes the bug
149
+ * easy to miss with word-list tests.
150
+ *
151
+ * ## Which dictionary to cut on
152
+ *
153
+ * The segmentation dictionary must be keyed in the **input's** script, since
154
+ * it is the raw input being cut: OpenCC uses `STPhrases` for `s2*` and
155
+ * `TSPhrases` for `*2s`. {@link segmentationDictsFor} encodes that choice.
156
+ *
157
+ * ## Cost
158
+ *
159
+ * One extra trie walk plus per-segment string handling — roughly 2× the
160
+ * conversion time (0.73 ms → 1.45 ms on a 15 000-character chapter, which cut
161
+ * into ~5200 segments). Only chains with two or more steps need it, and
162
+ * {@link segmentationDictsFor} returns nothing for the rest, so single-step
163
+ * conversions keep the cheap path.
164
+ *
165
+ * @param segmentation - Dictionary group to cut on, or `null` for no cutting
166
+ * @param dictGroups - Conversion steps, applied in order within each segment
167
+ * @returns Converter function
168
+ */
169
+ export declare function ConverterFactoryWithSegmentation(segmentation: DictGroup | null, ...dictGroups: DictGroup[]): (input: string) => string;
65
170
  /**
66
171
  * Create a custom converter with user-defined dictionary
67
172
  * @param dict - Custom dictionary entries
68
173
  * @returns Converter function
69
174
  */
70
175
  export declare function CustomConverter(dict: DictLike): (input: string) => string;
71
- /**
72
- * Wrap an inner converter with a protected dictionary layer.
73
- * Strings matching `protectedDict` are masked with PUA placeholders before
74
- * inner conversion runs, then restored afterward — guaranteeing the inner
75
- * dictionaries never see or modify them (hard override).
76
- *
77
- * Identical target values reuse the same placeholder char to economize the
78
- * 6400-slot PUA range; if more than 6400 distinct target values appear, a
79
- * RangeError is thrown.
80
- *
81
- * Safe to nest: each layer scans its input for existing PUA codepoints (from
82
- * outer layers) and allocates around them. PUA chars from outer layers pass
83
- * through unchanged.
84
- */
85
176
  export declare function ProtectedConverter(protectedDict: DictLike, innerConvert: (input: string) => string): (input: string) => string;
86
177
  /**
87
178
  * Reverse a packed dict string ("k1 v1|k2 v2") into `[value, key][]` entries.
@@ -121,4 +212,3 @@ export declare function reverseDictString(data: string): string[][];
121
212
  * @returns Array of `[key, value]` pairs ready to pass to `protectedDict`
122
213
  */
123
214
  export declare function parseOpenCCDict(text: string): string[][];
124
- //# sourceMappingURL=core.d.ts.map