js-opencc 1.4.0 → 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 (126) hide show
  1. package/README.md +118 -120
  2. package/README.zh-Hant.md +222 -0
  3. package/data/custom/CNTWPhrases.txt +6 -0
  4. package/dist/bundles/cn2t.d.ts +5 -4
  5. package/dist/bundles/cn2t.js +70 -13
  6. package/dist/bundles/full.d.ts +8 -3
  7. package/dist/bundles/full.js +42 -19
  8. package/dist/bundles/t2cn.d.ts +5 -4
  9. package/dist/bundles/t2cn.js +58 -11
  10. package/dist/converter.d.ts +11 -2
  11. package/dist/converter.js +60 -28
  12. package/dist/core.d.ts +120 -16
  13. package/dist/core.js +403 -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 -0
  17. package/dist/dict/HKPhrases.js +2 -0
  18. package/dist/dict/HKPhrasesRev.d.ts +2 -0
  19. package/dist/dict/HKPhrasesRev.js +2 -0
  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 -0
  23. package/dist/dict/HKVariantsPhrases.js +2 -0
  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 -0
  51. package/dist/dict/TWVariantsPhrases.js +2 -0
  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 +5 -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 +92 -4
  63. package/dist/presets.js +113 -7
  64. package/dist/umd/cn2t.js +640 -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 +657 -126
  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 +658 -107
  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/HKVariants.d.ts.map +0 -1
  90. package/dist/dict/HKVariants.js.map +0 -1
  91. package/dist/dict/HKVariantsRev.d.ts.map +0 -1
  92. package/dist/dict/HKVariantsRev.js.map +0 -1
  93. package/dist/dict/HKVariantsRevPhrases.d.ts.map +0 -1
  94. package/dist/dict/HKVariantsRevPhrases.js.map +0 -1
  95. package/dist/dict/JPShinjitaiCharacters.d.ts.map +0 -1
  96. package/dist/dict/JPShinjitaiCharacters.js.map +0 -1
  97. package/dist/dict/JPShinjitaiCharactersRev.d.ts.map +0 -1
  98. package/dist/dict/JPShinjitaiCharactersRev.js.map +0 -1
  99. package/dist/dict/JPShinjitaiPhrases.d.ts.map +0 -1
  100. package/dist/dict/JPShinjitaiPhrases.js.map +0 -1
  101. package/dist/dict/STCharacters.d.ts.map +0 -1
  102. package/dist/dict/STCharacters.js.map +0 -1
  103. package/dist/dict/STPhrases.d.ts.map +0 -1
  104. package/dist/dict/STPhrases.js.map +0 -1
  105. package/dist/dict/TSCharacters.d.ts.map +0 -1
  106. package/dist/dict/TSCharacters.js.map +0 -1
  107. package/dist/dict/TSPhrases.d.ts.map +0 -1
  108. package/dist/dict/TSPhrases.js.map +0 -1
  109. package/dist/dict/TWPhrases.d.ts.map +0 -1
  110. package/dist/dict/TWPhrases.js.map +0 -1
  111. package/dist/dict/TWPhrasesRev.d.ts.map +0 -1
  112. package/dist/dict/TWPhrasesRev.js.map +0 -1
  113. package/dist/dict/TWVariants.d.ts.map +0 -1
  114. package/dist/dict/TWVariants.js.map +0 -1
  115. package/dist/dict/TWVariantsRev.d.ts.map +0 -1
  116. package/dist/dict/TWVariantsRev.js.map +0 -1
  117. package/dist/dict/TWVariantsRevPhrases.d.ts.map +0 -1
  118. package/dist/dict/TWVariantsRevPhrases.js.map +0 -1
  119. package/dist/dict/index.d.ts.map +0 -1
  120. package/dist/dict/index.js.map +0 -1
  121. package/dist/html-converter.d.ts.map +0 -1
  122. package/dist/html-converter.js.map +0 -1
  123. package/dist/index.d.ts.map +0 -1
  124. package/dist/index.js.map +0 -1
  125. package/dist/presets.d.ts.map +0 -1
  126. package/dist/presets.js.map +0 -1
@@ -2,22 +2,31 @@
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 } 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";
13
+ import TWVariantsPhrases from "../dict/TWVariantsPhrases.js";
12
14
  import TWPhrases from "../dict/TWPhrases.js";
13
15
  import HKVariants from "../dict/HKVariants.js";
16
+ import HKVariantsPhrases from "../dict/HKVariantsPhrases.js";
17
+ import HKPhrases from "../dict/HKPhrases.js";
14
18
  import JPShinjitaiCharactersRev from "../dict/JPShinjitaiCharactersRev.js";
19
+ import CNTWPhrases from "../dict/CNTWPhrases.js";
15
20
  const dictMap = {
16
21
  STCharacters,
17
22
  STPhrases,
23
+ STPhrases_GeneratedFromRegionalPhrases,
18
24
  TWVariants,
25
+ TWVariantsPhrases,
19
26
  TWPhrases,
20
27
  HKVariants,
28
+ HKVariantsPhrases,
29
+ HKPhrases,
21
30
  JPShinjitaiCharactersRev,
22
31
  };
23
32
  /**
@@ -33,22 +42,70 @@ const dictMap = {
33
42
  * `fetch` the text and use `parseOpenCCDict()`.
34
43
  */
35
44
  function Converter(options, protectedDict) {
45
+ // Only cn→variant dicts ship here; reject another source rather than ignore
46
+ // it and run the cn→tw chain over input the caller declared as traditional.
47
+ if (options.from !== undefined && options.from !== "cn") {
48
+ throw new Error(`cn2t bundle only converts from 'cn', got '${options.from}' — use the full bundle for other directions`);
49
+ }
50
+ if (options.to === "cn") {
51
+ throw new Error(`cn2t bundle cannot convert to 'cn' — use the t2cn bundle`);
52
+ }
36
53
  const dictGroups = [];
37
- // From cn to standard (always needed)
38
- dictGroups.push([STCharacters, STPhrases]);
39
- // From standard to target variant
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]);
58
+ // From standard to target variant. Unknown locales and preset files missing
59
+ // from dictMap throw loudly — silently skipping a step would return
60
+ // partially-converted text (JS callers bypass the TS type check).
40
61
  if (options.to !== "t") {
41
- const dictFiles = standard2variants[options.to] || [];
42
- const dicts = dictFiles.map((name) => dictMap[name]).filter(Boolean);
43
- if (dicts.length) {
44
- dictGroups.push(dicts);
45
- }
62
+ const dictFiles = standard2variants[options.to];
63
+ // Array.isArray, not truthiness: `standard2variants["constructor"]` is a
64
+ // truthy prototype member that would fall through to an opaque TypeError.
65
+ if (!Array.isArray(dictFiles))
66
+ throw new Error(`Unknown 'to' locale: ${options.to}`);
67
+ dictGroups.push(dictFiles.map((name) => {
68
+ const d = dictMap[name];
69
+ // typeof, not truthiness: a dict CAN legitimately optimize to "" (all
70
+ // entries single-char identity pairs), and this also rejects prototype
71
+ // members like "toString" that `in` would accept.
72
+ if (typeof d !== "string")
73
+ throw new Error(`Dictionary ${name} missing from cn2t bundle`);
74
+ return d;
75
+ }));
76
+ }
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.
102
+ if (phraseDictDirection("cn", options.to, options.loadCustomPhrases)) {
103
+ convert = ProtectedConverter(CNTWPhrases, convert);
46
104
  }
47
- let convert = ConverterFactory(...dictGroups);
48
105
  if (protectedDict) {
49
106
  convert = ProtectedConverter(protectedDict, convert);
50
107
  }
51
108
  return convert;
52
109
  }
53
- export { Converter, CustomConverter, ConverterFactory, ProtectedConverter, parseOpenCCDict, HTMLConverter, Trie };
54
- //# sourceMappingURL=cn2t.js.map
110
+ // // 带切段的工厂也导出:只给不带切段的那个,自己拼链的人会静默丢掉地区词边界处理
111
+ export { Converter, CustomConverter, ConverterFactory, ConverterFactoryWithSegmentation, ProtectedConverter, normalizeCompatibilityIdeographs, parseOpenCCDict, HTMLConverter, Trie, };
@@ -1,13 +1,19 @@
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[];
8
8
  interface ConverterOptions {
9
9
  from: LocaleCode;
10
10
  to: LocaleCode;
11
+ /**
12
+ * Whether to consider the custom CNTWPhrases dict (default: on when either
13
+ * end is `twp`). `true` enables it only in the directions
14
+ * `phraseDictDirection` supports; `false` disables it everywhere.
15
+ */
16
+ loadCustomPhrases?: boolean;
11
17
  }
12
18
  /**
13
19
  * Create a converter with the specified locales.
@@ -30,6 +36,5 @@ declare const Locale: {
30
36
  [k: string]: string[];
31
37
  };
32
38
  };
33
- export { Converter, CustomConverter, ConverterFactory, ProtectedConverter, parseOpenCCDict, HTMLConverter, Locale, Trie };
39
+ export { Converter, CustomConverter, ConverterFactory, ConverterFactoryWithSegmentation, ProtectedConverter, normalizeCompatibilityIdeographs, parseOpenCCDict, HTMLConverter, Locale, Trie, };
34
40
  export type { ConverterOptions, HTMLConverterOptions, LocaleCode, DictLike, DictGroup };
35
- //# sourceMappingURL=full.d.ts.map
@@ -1,19 +1,24 @@
1
1
  /**
2
2
  * Full bundle - includes all locales and converters
3
3
  */
4
- import { Trie, ConverterFactory, CustomConverter, ProtectedConverter, parseOpenCCDict } 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 } 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";
15
+ import HKVariantsPhrases from "../dict/HKVariantsPhrases.js";
14
16
  import HKVariantsRev from "../dict/HKVariantsRev.js";
15
17
  import HKVariantsRevPhrases from "../dict/HKVariantsRevPhrases.js";
18
+ import HKPhrases from "../dict/HKPhrases.js";
19
+ import HKPhrasesRev from "../dict/HKPhrasesRev.js";
16
20
  import TWVariants from "../dict/TWVariants.js";
21
+ import TWVariantsPhrases from "../dict/TWVariantsPhrases.js";
17
22
  import TWVariantsRev from "../dict/TWVariantsRev.js";
18
23
  import TWVariantsRevPhrases from "../dict/TWVariantsRevPhrases.js";
19
24
  import TWPhrases from "../dict/TWPhrases.js";
@@ -21,15 +26,21 @@ import TWPhrasesRev from "../dict/TWPhrasesRev.js";
21
26
  import JPShinjitaiCharacters from "../dict/JPShinjitaiCharacters.js";
22
27
  import JPShinjitaiCharactersRev from "../dict/JPShinjitaiCharactersRev.js";
23
28
  import JPShinjitaiPhrases from "../dict/JPShinjitaiPhrases.js";
29
+ import CNTWPhrases from "../dict/CNTWPhrases.js";
24
30
  const dict = {
25
31
  STCharacters,
26
32
  STPhrases,
33
+ STPhrases_GeneratedFromRegionalPhrases,
27
34
  TSCharacters,
28
35
  TSPhrases,
29
36
  HKVariants,
37
+ HKVariantsPhrases,
30
38
  HKVariantsRev,
31
39
  HKVariantsRevPhrases,
40
+ HKPhrases,
41
+ HKPhrasesRev,
32
42
  TWVariants,
43
+ TWVariantsPhrases,
33
44
  TWVariantsRev,
34
45
  TWVariantsRevPhrases,
35
46
  TWPhrases,
@@ -53,30 +64,42 @@ const dict = {
53
64
  function Converter(options, protectedDict) {
54
65
  // Reject unknown locales loudly rather than silently skipping a step and
55
66
  // returning partially-converted text (JS callers bypass the TS type check).
56
- if (options.from !== "t" && !variants2standard[options.from]) {
67
+ // Array.isArray, not truthiness: `variants2standard["constructor"]` is a
68
+ // truthy prototype member that would fall through to an opaque TypeError.
69
+ if (options.from !== "t" && !Array.isArray(variants2standard[options.from])) {
57
70
  throw new Error(`Unknown 'from' locale: ${options.from}`);
58
71
  }
59
- if (options.to !== "t" && !standard2variants[options.to]) {
72
+ if (options.to !== "t" && !Array.isArray(standard2variants[options.to])) {
60
73
  throw new Error(`Unknown 'to' locale: ${options.to}`);
61
74
  }
62
75
  const dictGroups = [];
63
76
  // From variant to standard
64
77
  if (options.from !== "t") {
65
- const dictFiles = variants2standard[options.from] || [];
66
- const dicts = dictFiles.map((name) => dict[name]).filter(Boolean);
67
- if (dicts.length) {
68
- dictGroups.push(dicts);
69
- }
78
+ dictGroups.push(variants2standard[options.from].map((name) => dict[name]));
70
79
  }
71
80
  // From standard to variant
72
81
  if (options.to !== "t") {
73
- const dictFiles = standard2variants[options.to] || [];
74
- const dicts = dictFiles.map((name) => dict[name]).filter(Boolean);
75
- if (dicts.length) {
76
- dictGroups.push(dicts);
77
- }
82
+ dictGroups.push(standard2variants[options.to].map((name) => dict[name]));
83
+ }
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.
99
+ const phraseDir = phraseDictDirection(options.from, options.to, options.loadCustomPhrases);
100
+ if (phraseDir) {
101
+ convert = ProtectedConverter(phraseDir === "reverse" ? reverseDictString(CNTWPhrases) : CNTWPhrases, convert);
78
102
  }
79
- let convert = ConverterFactory(...dictGroups);
80
103
  if (protectedDict) {
81
104
  convert = ProtectedConverter(protectedDict, convert);
82
105
  }
@@ -84,8 +107,8 @@ function Converter(options, protectedDict) {
84
107
  }
85
108
  // Locale data for ConverterBuilder compatibility
86
109
  const Locale = {
87
- from: Object.fromEntries(Object.entries(variants2standard).map(([locale, files]) => [locale, files.map((name) => dict[name]).filter(Boolean)])),
88
- to: Object.fromEntries(Object.entries(standard2variants).map(([locale, files]) => [locale, files.map((name) => dict[name]).filter(Boolean)])),
110
+ from: Object.fromEntries(Object.entries(variants2standard).map(([locale, files]) => [locale, files.map((name) => dict[name])])),
111
+ to: Object.fromEntries(Object.entries(standard2variants).map(([locale, files]) => [locale, files.map((name) => dict[name])])),
89
112
  };
90
- export { Converter, CustomConverter, ConverterFactory, ProtectedConverter, parseOpenCCDict, HTMLConverter, Locale, Trie };
91
- //# sourceMappingURL=full.js.map
113
+ // // 带切段的工厂也导出:只给不带切段的那个,自己拼链的人会静默丢掉地区词边界处理
114
+ export { Converter, CustomConverter, ConverterFactory, ConverterFactoryWithSegmentation, ProtectedConverter, normalizeCompatibilityIdeographs, parseOpenCCDict, HTMLConverter, Locale, Trie, };
@@ -2,13 +2,15 @@
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
- type SourceLocale = "t" | "tw" | "twp" | "hk" | "jp";
8
+ type SourceLocale = "t" | "tw" | "twp" | "hk" | "hkp" | "jp";
9
9
  interface ConverterOptions {
10
10
  from: SourceLocale;
11
11
  to?: "cn";
12
+ /** Whether to load the custom CNTWPhrases dict (default: on for `from: "twp"`) */
13
+ loadCustomPhrases?: boolean;
12
14
  }
13
15
  /**
14
16
  * Create a converter from Traditional variants to Simplified Chinese.
@@ -19,6 +21,5 @@ interface ConverterOptions {
19
21
  * pass the dict explicitly (use `parseOpenCCDict` for OpenCC-format text).
20
22
  */
21
23
  declare function Converter(options: ConverterOptions, protectedDict?: DictLike): (input: string) => string;
22
- export { Converter, CustomConverter, ConverterFactory, ProtectedConverter, parseOpenCCDict, HTMLConverter, Trie };
24
+ export { Converter, CustomConverter, ConverterFactory, ConverterFactoryWithSegmentation, ProtectedConverter, normalizeCompatibilityIdeographs, parseOpenCCDict, HTMLConverter, Trie, };
23
25
  export type { ConverterOptions, HTMLConverterOptions, DictLike, DictGroup };
24
- //# 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 } 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 } 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";
@@ -13,8 +13,10 @@ import TWVariantsRevPhrases from "../dict/TWVariantsRevPhrases.js";
13
13
  import TWPhrasesRev from "../dict/TWPhrasesRev.js";
14
14
  import HKVariantsRev from "../dict/HKVariantsRev.js";
15
15
  import HKVariantsRevPhrases from "../dict/HKVariantsRevPhrases.js";
16
+ import HKPhrasesRev from "../dict/HKPhrasesRev.js";
16
17
  import JPShinjitaiCharacters from "../dict/JPShinjitaiCharacters.js";
17
18
  import JPShinjitaiPhrases from "../dict/JPShinjitaiPhrases.js";
19
+ import CNTWPhrases from "../dict/CNTWPhrases.js";
18
20
  const dictMap = {
19
21
  TSCharacters,
20
22
  TSPhrases,
@@ -23,6 +25,7 @@ const dictMap = {
23
25
  TWPhrasesRev,
24
26
  HKVariantsRev,
25
27
  HKVariantsRevPhrases,
28
+ HKPhrasesRev,
26
29
  JPShinjitaiCharacters,
27
30
  JPShinjitaiPhrases,
28
31
  };
@@ -35,22 +38,66 @@ const dictMap = {
35
38
  * pass the dict explicitly (use `parseOpenCCDict` for OpenCC-format text).
36
39
  */
37
40
  function Converter(options, protectedDict) {
41
+ // Only variant→cn dicts ship here; reject another target rather than ignore
42
+ // it and hand back simplified text to a caller who asked for traditional.
43
+ if (options.to !== undefined && options.to !== "cn") {
44
+ throw new Error(`t2cn bundle only converts to 'cn', got '${options.to}' — use the full bundle for other directions`);
45
+ }
46
+ if (options.from === "cn") {
47
+ throw new Error(`t2cn bundle cannot convert from 'cn' — use the cn2t bundle`);
48
+ }
38
49
  const dictGroups = [];
39
- // From source variant to standard
50
+ // From source variant to standard. Unknown locales and preset files missing
51
+ // from dictMap throw loudly — silently skipping a step would return
52
+ // partially-converted text (JS callers bypass the TS type check).
40
53
  if (options.from !== "t") {
41
- const dictFiles = variants2standard[options.from] || [];
42
- const dicts = dictFiles.map((name) => dictMap[name]).filter(Boolean);
43
- if (dicts.length) {
44
- dictGroups.push(dicts);
45
- }
54
+ const dictFiles = variants2standard[options.from];
55
+ // Array.isArray, not truthiness: `variants2standard["constructor"]` is a
56
+ // truthy prototype member that would fall through to an opaque TypeError.
57
+ if (!Array.isArray(dictFiles))
58
+ throw new Error(`Unknown 'from' locale: ${options.from}`);
59
+ dictGroups.push(dictFiles.map((name) => {
60
+ const d = dictMap[name];
61
+ // typeof, not truthiness: a dict CAN legitimately optimize to "" (all
62
+ // entries single-char identity pairs), and this also rejects prototype
63
+ // members like "toString" that `in` would accept.
64
+ if (typeof d !== "string")
65
+ throw new Error(`Dictionary ${name} missing from t2cn bundle`);
66
+ return d;
67
+ }));
46
68
  }
47
69
  // From standard to cn (always needed)
48
70
  dictGroups.push([TSCharacters, TSPhrases]);
49
- let convert = ConverterFactory(...dictGroups);
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.
94
+ if (phraseDictDirection(options.from, "cn", options.loadCustomPhrases)) {
95
+ convert = ProtectedConverter(reverseDictString(CNTWPhrases), convert);
96
+ }
50
97
  if (protectedDict) {
51
98
  convert = ProtectedConverter(protectedDict, convert);
52
99
  }
53
100
  return convert;
54
101
  }
55
- export { Converter, CustomConverter, ConverterFactory, ProtectedConverter, parseOpenCCDict, HTMLConverter, Trie };
56
- //# sourceMappingURL=t2cn.js.map
102
+ // // 带切段的工厂也导出:只给不带切段的那个,自己拼链的人会静默丢掉地区词边界处理
103
+ export { Converter, CustomConverter, ConverterFactory, ConverterFactoryWithSegmentation, ProtectedConverter, normalizeCompatibilityIdeographs, parseOpenCCDict, HTMLConverter, Trie, };
@@ -12,7 +12,11 @@ export interface ConverterOptions {
12
12
  from: LocaleCode;
13
13
  /** Target locale code */
14
14
  to: LocaleCode;
15
- /** Whether to load custom phrase dictionary (default: true for twp) */
15
+ /**
16
+ * Whether to consider the custom CNTWPhrases dict (default: on when either
17
+ * end is `twp`). `true` enables it only in the directions
18
+ * `phraseDictDirection` supports; `false` disables it everywhere.
19
+ */
16
20
  loadCustomPhrases?: boolean;
17
21
  }
18
22
  /**
@@ -21,6 +25,12 @@ export interface ConverterOptions {
21
25
  export interface LocalePreset {
22
26
  from: Record<string, DictGroup>;
23
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>;
24
34
  }
25
35
  /**
26
36
  * Create a Converter factory with locale preset
@@ -68,4 +78,3 @@ export declare function getDictFiles(from: LocaleCode, to: LocaleCode): string[]
68
78
  export declare function createConverter(options: ConverterOptions, protectedDict?: DictLike): Promise<(input: string) => string>;
69
79
  export type { LocaleCode } from "./presets.js";
70
80
  export type { DictLike, DictGroup } from "./core.js";
71
- //# 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 } from "./core.js";
7
- import { variants2standard, standard2variants } 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
  /**
@@ -68,6 +74,8 @@ export function getDictFiles(from, to) {
68
74
  }
69
75
  return groups;
70
76
  }
77
+ /** Memo for the auto-loaded package dict — see `createConverter` for why. */
78
+ let packageProtectedDict;
71
79
  /**
72
80
  * Try to auto-load the bundled `data/custom/ProtectedDict.txt`. Returns undefined in
73
81
  * browsers/Deno, on any I/O error, or when the file parses to zero entries.
@@ -110,15 +118,28 @@ export async function createConverter(options, protectedDict) {
110
118
  console.warn("[js-opencc] The `applyCharFixes` option was removed in v1.3.x. " +
111
119
  "CharFixes.txt is replaced by `protectedDict` (hard override) — see README migration section.");
112
120
  }
113
- // Auto-load bundled data/custom/ProtectedDict.txt if no explicit dict provided
114
- if (!protectedDict) {
115
- protectedDict = await tryLoadPackageProtectedDict();
121
+ // Auto-load bundled data/custom/ProtectedDict.txt if no explicit dict provided.
122
+ // Memoized like innerConverterCache: the file ships with the package and never
123
+ // changes at runtime, and re-reading it dominates everything else in a batch
124
+ // (200 cached calls: 82ms re-reading vs 0.1ms with the read hoisted out).
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) {
132
+ if (!packageProtectedDict)
133
+ packageProtectedDict = tryLoadPackageProtectedDict();
134
+ protectedDict = await packageProtectedDict;
116
135
  }
117
- const loadPhrases = options.loadCustomPhrases ?? (options.to === "twp" || options.from === "twp");
118
- const key = `${options.from}|${options.to}|${loadPhrases}`;
136
+ // Key on the resolved phrase direction, not the raw option: two calls that
137
+ // differ only in an explicit flag matching the default share one converter.
138
+ const phraseDir = phraseDictDirection(options.from, options.to, options.loadCustomPhrases);
139
+ const key = `${options.from}|${options.to}|${phraseDir}`;
119
140
  let innerPromise = innerConverterCache.get(key);
120
141
  if (!innerPromise) {
121
- innerPromise = buildInnerConverter(options.from, options.to, loadPhrases).catch((e) => {
142
+ innerPromise = buildInnerConverter(options.from, options.to, phraseDir).catch((e) => {
122
143
  // Evict failed builds (e.g. a dict chunk 404 after a redeploy) so a later
123
144
  // call can retry instead of replaying the cached rejection forever.
124
145
  innerConverterCache.delete(key);
@@ -131,12 +152,12 @@ export async function createConverter(options, protectedDict) {
131
152
  // Empty protection ([] / "") returns the cached inner converter directly.
132
153
  return protectedDict && protectedDict.length ? ProtectedConverter(protectedDict, convert) : convert;
133
154
  }
134
- // Inner converters are pure functions of (from, to, loadPhrases) over static
155
+ // Inner converters are pure functions of (from, to, phraseDir) over static
135
156
  // dict data — cache the BUILD PROMISE so concurrent calls (e.g. a batch
136
157
  // converting N files) share one trie build instead of racing N of them.
137
158
  // protectedDict varies per call and wraps outside the cache.
138
159
  const innerConverterCache = new Map();
139
- async function buildInnerConverter(from, to, loadPhrases) {
160
+ async function buildInnerConverter(from, to, phraseDir) {
140
161
  // Dict module strings ("k1 v1|k2 v2") go straight into the trie —
141
162
  // Trie.loadDict parses that format natively.
142
163
  const loadDict = async (name) => {
@@ -159,25 +180,36 @@ async function buildInnerConverter(from, to, loadPhrases) {
159
180
  if (group.length)
160
181
  dictGroups.push(group);
161
182
  }
162
- // (b) CNTWPhrases (ordinary vocabulary dict, stays in main chain)
163
- if (loadPhrases) {
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).
208
+ if (phraseDir) {
164
209
  const phrases = await loadDict("CNTWPhrases");
165
210
  if (phrases) {
166
- if (from === "twp" && to === "cn") {
167
- // Key/value swap needs parsed entries; value = everything after the
168
- // first space (values may contain spaces, same rule as Trie.loadDict).
169
- const reversed = phrases.split("|").map((entry) => {
170
- const sep = entry.indexOf(" ");
171
- return [entry.slice(sep + 1), entry.slice(0, sep)];
172
- });
173
- dictGroups.unshift([reversed]);
174
- }
175
- else {
176
- dictGroups.unshift([phrases]);
177
- }
211
+ convert = ProtectedConverter(phraseDir === "reverse" ? reverseDictString(phrases) : phrases, convert);
178
212
  }
179
213
  }
180
- // (c) Build the inner converter chain
181
- return ConverterFactory(...dictGroups);
214
+ return convert;
182
215
  }
183
- //# sourceMappingURL=converter.js.map