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
@@ -12,6 +12,19 @@ const SKIP_TAGS = new Set(["SCRIPT", "STYLE", "TEXTAREA", "CODE", "PRE"]);
12
12
  * inputs (text/password/search/…) hold user data and are left untouched.
13
13
  */
14
14
  const CONVERTIBLE_INPUT_TYPES = new Set(["button", "submit", "reset"]);
15
+ /**
16
+ * Attributes whose value is **text the user reads**, so it must follow the
17
+ * page's conversion. Not to be confused with attributes that hold data.
18
+ *
19
+ * The distinction that matters here is display-vs-data, not element-vs-element:
20
+ * an editable input's `value` is the user's own text and is left alone, but its
21
+ * `placeholder` is UI chrome exactly like an `<img alt>` — leaving it behind
22
+ * means a page converted to Traditional still shows Simplified hint text in
23
+ * every empty field. `aria-label` and `title` are the same thing for screen
24
+ * readers and tooltips; skipping them silently degrades the accessible copy
25
+ * while the visible copy converts.
26
+ */
27
+ const TEXT_ATTRIBUTES = ["placeholder", "title", "aria-label"];
15
28
  /**
16
29
  * Class name to ignore conversion
17
30
  */
@@ -23,22 +36,36 @@ const IGNORE_CLASS = "ignore-opencc";
23
36
  */
24
37
  export function HTMLConverter(options) {
25
38
  const { converter, rootNode, fromLangTag, toLangTag } = options;
26
- // Store original values for restoration
39
+ /**
40
+ * Original values, keyed by node and then by SLOT.
41
+ *
42
+ * One string per node is not enough: a single `<input>` can carry both a
43
+ * converted `value` and a converted `placeholder`, an `<img>` both `alt` and
44
+ * `title`. With a flat `WeakMap<Node, string>` the second conversion reuses
45
+ * the first one's stored original and `restore()` writes it into the wrong
46
+ * slot. Slot is `"#text"`, `"#value"`, or the attribute name.
47
+ */
27
48
  const originalValues = new WeakMap();
28
49
  const changedLangNodes = new WeakSet();
50
+ const TEXT_SLOT = "#text";
51
+ const VALUE_SLOT = "#value";
29
52
  /**
30
53
  * Convert all text nodes in the DOM
31
54
  */
32
55
  function convert() {
33
56
  const fromLangLower = fromLangTag.toLowerCase();
34
- // Record the pre-conversion value exactly once per node. Repeated convert()
35
- // calls then re-convert from the stored original instead of from
57
+ // Record the pre-conversion value exactly once per (node, slot). Repeated
58
+ // convert() calls then re-convert from the stored original instead of from
36
59
  // already-converted text, and restore() always returns the true original.
37
- function originalOf(node, current) {
38
- if (!originalValues.has(node)) {
39
- originalValues.set(node, current);
60
+ function originalOf(node, slot, current) {
61
+ let slots = originalValues.get(node);
62
+ if (!slots) {
63
+ slots = new Map();
64
+ originalValues.set(node, slots);
40
65
  }
41
- return originalValues.get(node);
66
+ if (!slots.has(slot))
67
+ slots.set(slot, current);
68
+ return slots.get(slot);
42
69
  }
43
70
  function processNode(node, langMatched) {
44
71
  // Skip elements with ignore-opencc class
@@ -63,12 +90,23 @@ export function HTMLConverter(options) {
63
90
  if (SKIP_TAGS.has(node.tagName)) {
64
91
  return;
65
92
  }
93
+ // Attributes that render as text, on any element. Runs before the
94
+ // INPUT early-return below so an editable field's `placeholder` still
95
+ // converts even though its `value` (user data) must not.
96
+ if (langMatched) {
97
+ for (const attr of TEXT_ATTRIBUTES) {
98
+ const current = node.getAttribute(attr);
99
+ if (current) {
100
+ node.setAttribute(attr, converter(originalOf(node, attr, current)));
101
+ }
102
+ }
103
+ }
66
104
  // INPUT is a void element: convert button-like labels, then stop —
67
105
  // it has no child text nodes to recurse into.
68
106
  if (node.tagName === "INPUT") {
69
107
  const input = node;
70
108
  if (langMatched && CONVERTIBLE_INPUT_TYPES.has(input.type)) {
71
- input.value = converter(originalOf(input, input.value));
109
+ input.value = converter(originalOf(input, VALUE_SLOT, input.value));
72
110
  }
73
111
  return;
74
112
  }
@@ -79,14 +117,14 @@ export function HTMLConverter(options) {
79
117
  if (name === "description" || name === "keywords") {
80
118
  const content = node.getAttribute("content");
81
119
  if (content) {
82
- node.setAttribute("content", converter(originalOf(node, content)));
120
+ node.setAttribute("content", converter(originalOf(node, "content", content)));
83
121
  }
84
122
  }
85
123
  }
86
124
  else if (node.tagName === "IMG") {
87
125
  const alt = node.getAttribute("alt");
88
126
  if (alt) {
89
- node.setAttribute("alt", converter(originalOf(node, alt)));
127
+ node.setAttribute("alt", converter(originalOf(node, "alt", alt)));
90
128
  }
91
129
  }
92
130
  }
@@ -96,7 +134,7 @@ export function HTMLConverter(options) {
96
134
  if (child.nodeType === Node.TEXT_NODE && langMatched) {
97
135
  const text = child.nodeValue;
98
136
  if (text) {
99
- child.nodeValue = converter(originalOf(child, text));
137
+ child.nodeValue = converter(originalOf(child, TEXT_SLOT, text));
100
138
  }
101
139
  }
102
140
  else if (child.nodeType === Node.ELEMENT_NODE) {
@@ -118,21 +156,23 @@ export function HTMLConverter(options) {
118
156
  if (node instanceof Element && changedLangNodes.has(node)) {
119
157
  node.setAttribute("lang", fromLangTag);
120
158
  }
121
- // Restore text content
122
- const originalValue = originalValues.get(node);
123
- if (originalValue !== undefined) {
124
- if (node.nodeType === Node.TEXT_NODE) {
125
- node.nodeValue = originalValue;
126
- }
127
- else if (node instanceof Element) {
128
- if (node.tagName === "META") {
129
- node.setAttribute("content", originalValue);
159
+ // Restore every slot we recorded. Keyed by slot rather than dispatched on
160
+ // tagName: one element can have several converted slots (an <input> with
161
+ // both `value` and `placeholder`), and a tagName switch can only put back
162
+ // one of them.
163
+ const slots = originalValues.get(node);
164
+ if (slots) {
165
+ for (const [slot, original] of slots) {
166
+ if (slot === TEXT_SLOT) {
167
+ node.nodeValue = original;
130
168
  }
131
- else if (node.tagName === "IMG") {
132
- node.setAttribute("alt", originalValue);
133
- }
134
- else if (node.tagName === "INPUT") {
135
- node.value = originalValue;
169
+ else if (node instanceof Element) {
170
+ if (slot === VALUE_SLOT) {
171
+ node.value = original;
172
+ }
173
+ else {
174
+ node.setAttribute(slot, original);
175
+ }
136
176
  }
137
177
  }
138
178
  }
@@ -145,4 +185,3 @@ export function HTMLConverter(options) {
145
185
  }
146
186
  return { convert, restore };
147
187
  }
148
- //# sourceMappingURL=html-converter.js.map
package/dist/index.d.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  /**
2
2
  * OpenCC JS - Main Entry Point
3
3
  */
4
- export { Trie, ConverterFactory, CustomConverter, ProtectedConverter, parseOpenCCDict } from "./core.js";
4
+ export { Trie, ConverterFactory, ConverterFactoryWithSegmentation, CustomConverter, ProtectedConverter, normalizeCompatibilityIdeographs, parseOpenCCDict, reverseDictString, } from "./core.js";
5
5
  export type { DictLike, DictGroup } from "./core.js";
6
6
  export { ConverterBuilder, createConverter, getDictFiles } from "./converter.js";
7
7
  export type { ConverterOptions, LocalePreset } from "./converter.js";
8
8
  export { HTMLConverter } from "./html-converter.js";
9
9
  export type { HTMLConverterOptions } from "./html-converter.js";
10
- export { variants2standard, standard2variants, allDictFiles } from "./presets.js";
10
+ export { variants2standard, standard2variants, allDictFiles, segmentationDictsFor } from "./presets.js";
11
11
  export type { LocaleCode } from "./presets.js";
12
- //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,12 +1,21 @@
1
1
  /**
2
2
  * OpenCC JS - Main Entry Point
3
3
  */
4
- // Core exports
5
- export { Trie, ConverterFactory, CustomConverter, ProtectedConverter, parseOpenCCDict } from "./core.js";
4
+ // Core exports.
5
+ //
6
+ // `ConverterFactoryWithSegmentation` and `normalizeCompatibilityIdeographs`
7
+ // belong here next to `ConverterFactory`, not only on the `./core` subpath:
8
+ // anyone assembling a custom chain from this entry would otherwise find the
9
+ // unsegmented factory as the only option and silently lose regional-phrase
10
+ // boundary handling (他优化了 → 他最佳化了). Exporting the plain factory but
11
+ // not the segmented one reads as "segmentation is internal", when it is in
12
+ // fact what every preset uses.
13
+ export { Trie, ConverterFactory, ConverterFactoryWithSegmentation, CustomConverter, ProtectedConverter, normalizeCompatibilityIdeographs, parseOpenCCDict, reverseDictString, } from "./core.js";
6
14
  // Converter exports
7
15
  export { ConverterBuilder, createConverter, getDictFiles } from "./converter.js";
8
16
  // HTML Converter exports
9
17
  export { HTMLConverter } from "./html-converter.js";
10
- // Preset exports
11
- export { variants2standard, standard2variants, allDictFiles } from "./presets.js";
12
- //# sourceMappingURL=index.js.map
18
+ // Preset exports. `segmentationDictsFor` ships too — a custom chain needs it
19
+ // to know WHICH dict to cut on, and getting that wrong (cutting an `s2*`
20
+ // chain on a traditional-keyed dict) fails silently.
21
+ export { variants2standard, standard2variants, allDictFiles, segmentationDictsFor } from "./presets.js";
package/dist/presets.d.ts CHANGED
@@ -8,20 +8,108 @@
8
8
  * - tw: Traditional Chinese (Taiwan)
9
9
  * - twp: Traditional Chinese (Taiwan) with phrase conversion
10
10
  * - hk: Traditional Chinese (Hong Kong)
11
+ * - hkp: Traditional Chinese (Hong Kong) with phrase conversion
11
12
  * - jp: Japanese Shinjitai
12
13
  * - t: OpenCC standard Traditional Chinese
13
14
  */
14
- export type LocaleCode = "cn" | "tw" | "twp" | "hk" | "jp" | "t";
15
+ export type LocaleCode = "cn" | "tw" | "twp" | "hk" | "hkp" | "jp" | "t";
15
16
  /**
16
- * Dictionary file names for converting from variants to OpenCC standard
17
+ * Dictionary file names for converting from variants to OpenCC standard.
18
+ *
19
+ * Each array is ONE conversion step, merged into a single trie. Order is the
20
+ * REVERSE of OpenCC's `conversion_chain` order: OpenCC consults its dicts
21
+ * first-match-wins, our trie is last-write-wins, so the highest-priority dict
22
+ * (the phrase dicts) must be listed LAST. Chains mirror `tw2t` / `hk2t` /
23
+ * `tw2sp` / `hk2sp` in OpenCC's data/config.
17
24
  */
18
25
  export declare const variants2standard: Record<string, string[]>;
19
26
  /**
20
- * Dictionary file names for converting from OpenCC standard to variants
27
+ * Dictionary file names for converting from OpenCC standard to variants.
28
+ * Same ordering rule as above; chains mirror `t2tw` / `t2hk` / `s2twp` / `s2hkp`.
29
+ *
30
+ * The `*VariantsPhrases` dicts are what keep proper nouns from being
31
+ * over-converted (張棟樑 must not become 張棟梁, 純喫茶 not 純吃茶) — dropping
32
+ * them silently diverges from OpenCC on hundreds of entries.
21
33
  */
22
34
  export declare const standard2variants: Record<string, string[]>;
23
35
  /**
24
36
  * All dictionary file names
25
37
  */
26
38
  export declare const allDictFiles: string[];
27
- //# sourceMappingURL=presets.d.ts.map
39
+ /**
40
+ * Which dictionary to cut the input on before running the conversion chain,
41
+ * or `[]` for "don't segment".
42
+ *
43
+ * Segmentation only earns its cost when the chain has a **second** step that
44
+ * could match across boundaries the first step set — see
45
+ * `ConverterFactoryWithSegmentation`. OpenCC therefore declares a
46
+ * `segmentation` on exactly eight configs (`s2tw`, `s2twp`, `s2hk`, `s2hkp`,
47
+ * `tw2s`, `tw2sp`, `hk2s`, `hk2sp`) and on none of the single-step ones
48
+ * (`s2t`, `t2tw`, `tw2t`, `t2s`, `t2hk`, `hk2t`, `jp2t`, `t2jp`). This
49
+ * function reproduces that set rather than inventing a broader rule:
50
+ *
51
+ * - **cn → tw/twp/hk/hkp** cuts on `STPhrases`.
52
+ * - **tw/twp/hk/hkp → cn** cuts on `TSPhrases`.
53
+ * - everything else, including anything touching `t` or `jp`, does not cut.
54
+ *
55
+ * The direction of the dictionary is the part worth remembering: it is the
56
+ * **raw input** being cut, so the keys must be in the input's script.
57
+ * `s2*` cuts on the simplified-keyed `STPhrases`; `*2s` cuts on the
58
+ * traditional-keyed `TSPhrases` — which lives in the chain's *second* step,
59
+ * not its first. Picking "the first step's phrase dict" looks tidier and is
60
+ * wrong for `tw2s`.
61
+ *
62
+ * `jp` is excluded deliberately: Shinjitai conversion has no phrase table
63
+ * keyed in the source script, and OpenCC declares no segmentation for it.
64
+ *
65
+ * ## The second segmentation dict: `STPhrases_GeneratedFromRegionalPhrases`
66
+ *
67
+ * OpenCC's `s2*` configs segment on **two** dictionaries — `STPhrases` plus a
68
+ * generated one that maps each regional term's simplified projection to its
69
+ * plain traditional form (`出租车 出租車`), keeping the term whole through
70
+ * segmentation so the regional table can replace it as a unit. Without it
71
+ * `出租车司机` under-applies to `出租車司機` where OpenCC gives `計程車司機`.
72
+ *
73
+ * We once thought its filter was unrecoverable (a naive derivation yielded 276
74
+ * extra entries) and documented it as a known gap. The actual rule was found
75
+ * by reading OpenCC's `generate_st_phrases_from_regional_phrases.py`: project
76
+ * the keys of HKPhrases + TWPhrases through t2s and **drop projections shorter
77
+ * than 3 code points** — short keys would split longer Simplified words before
78
+ * STPhrases could match them. That one filter reproduces all 508 upstream
79
+ * entries exactly. The sync script now generates the dict; see
80
+ * `generateRegionalStPhrases` comments there for the full recipe.
81
+ */
82
+ export declare function segmentationDictsFor(from: LocaleCode, to: LocaleCode): string[];
83
+ /**
84
+ * How the custom CNTWPhrases dict should be applied to a conversion:
85
+ * `"forward"` as shipped (cn keys → tw values), `"reverse"` swapped, or `null`
86
+ * to leave it out entirely.
87
+ */
88
+ export type PhraseDictDirection = "forward" | "reverse" | null;
89
+ /**
90
+ * Decide whether — and in which direction — CNTWPhrases applies. This is the
91
+ * single home for the rule: the main entry, both one-way bundles and the full
92
+ * bundle all call it. Do not inline a copy at a call site — four copies is how
93
+ * the four entry points came to disagree with each other.
94
+ *
95
+ * - Crossing INTO Taiwan vocabulary from outside it → `"forward"`.
96
+ * - Leaving Taiwan vocabulary for `cn` → `"reverse"`.
97
+ * - Everything else → `null`.
98
+ *
99
+ * Two asymmetries worth keeping straight, both deliberate:
100
+ *
101
+ * 1. A `tw`/`twp` SOURCE never gets the forward dict, even aimed at `twp`. Its
102
+ * keys are simplified, so against traditional input the only ones that can
103
+ * match are the script-invariant terms (土豆, 芝士, 高考, 雪糕, 薯片) — exactly
104
+ * the entries whose meaning differs in Taiwan (土豆 is peanut there, not
105
+ * 馬鈴薯). A `t`/`hk`/`jp` source aimed at `twp` DOES get it, and should:
106
+ * 芝士→起司 and 雪糕→冰淇淋 are the intended HK→TW conversions.
107
+ * 2. `"reverse"` is confined to `to === "cn"`, not to any non-Taiwan target,
108
+ * because the reversed values are simplified (計程車 → 出租车) and would put
109
+ * simplified characters into a traditional target.
110
+ *
111
+ * @param loadCustomPhrases - Defaults to on when either end is `twp`. An
112
+ * explicit `true` enables the rule but does not override it: directions that
113
+ * score `null` (e.g. `cn → hk`) still get no dict.
114
+ */
115
+ export declare function phraseDictDirection(from: LocaleCode, to: LocaleCode, loadCustomPhrases?: boolean): PhraseDictDirection;
package/dist/presets.js CHANGED
@@ -3,27 +3,133 @@
3
3
  * Defines dictionary mappings for different Chinese variants
4
4
  */
5
5
  /**
6
- * Dictionary file names for converting from variants to OpenCC standard
6
+ * Dictionary file names for converting from variants to OpenCC standard.
7
+ *
8
+ * Each array is ONE conversion step, merged into a single trie. Order is the
9
+ * REVERSE of OpenCC's `conversion_chain` order: OpenCC consults its dicts
10
+ * first-match-wins, our trie is last-write-wins, so the highest-priority dict
11
+ * (the phrase dicts) must be listed LAST. Chains mirror `tw2t` / `hk2t` /
12
+ * `tw2sp` / `hk2sp` in OpenCC's data/config.
7
13
  */
8
14
  export const variants2standard = {
9
- cn: ["STCharacters", "STPhrases"],
15
+ // The generated dict sits between: upstream's group is
16
+ // [STPhrases ∪ Generated] short-circuit STCharacters, so in last-write-wins
17
+ // order STPhrases stays highest. Its value is the point — 出租车 must become
18
+ // 出租車 as a pinned unit (char-wise conversion could pick wrong variants for
19
+ // ambiguous characters), and segmentation needs it as a boundary entry.
20
+ cn: ["STCharacters", "STPhrases_GeneratedFromRegionalPhrases", "STPhrases"],
10
21
  hk: ["HKVariantsRev", "HKVariantsRevPhrases"],
22
+ hkp: ["HKVariantsRev", "HKVariantsRevPhrases", "HKPhrasesRev"],
11
23
  tw: ["TWVariantsRev", "TWVariantsRevPhrases"],
12
24
  twp: ["TWVariantsRev", "TWVariantsRevPhrases", "TWPhrasesRev"],
13
25
  jp: ["JPShinjitaiCharacters", "JPShinjitaiPhrases"],
14
26
  };
15
27
  /**
16
- * Dictionary file names for converting from OpenCC standard to variants
28
+ * Dictionary file names for converting from OpenCC standard to variants.
29
+ * Same ordering rule as above; chains mirror `t2tw` / `t2hk` / `s2twp` / `s2hkp`.
30
+ *
31
+ * The `*VariantsPhrases` dicts are what keep proper nouns from being
32
+ * over-converted (張棟樑 must not become 張棟梁, 純喫茶 not 純吃茶) — dropping
33
+ * them silently diverges from OpenCC on hundreds of entries.
17
34
  */
18
35
  export const standard2variants = {
19
36
  cn: ["TSCharacters", "TSPhrases"],
20
- hk: ["HKVariants"],
21
- tw: ["TWVariants"],
22
- twp: ["TWVariants", "TWPhrases"],
37
+ hk: ["HKVariants", "HKVariantsPhrases"],
38
+ hkp: ["HKVariants", "HKVariantsPhrases", "HKPhrases"],
39
+ tw: ["TWVariants", "TWVariantsPhrases"],
40
+ twp: ["TWVariants", "TWVariantsPhrases", "TWPhrases"],
23
41
  jp: ["JPShinjitaiCharactersRev"],
24
42
  };
25
43
  /**
26
44
  * All dictionary file names
27
45
  */
28
46
  export const allDictFiles = [...new Set([...Object.values(variants2standard).flat(), ...Object.values(standard2variants).flat()])];
29
- //# sourceMappingURL=presets.js.map
47
+ /** Traditional variants that carry their own regional vocabulary tables. */
48
+ const REGIONAL_VARIANTS = new Set(["tw", "twp", "hk", "hkp"]);
49
+ /**
50
+ * Which dictionary to cut the input on before running the conversion chain,
51
+ * or `[]` for "don't segment".
52
+ *
53
+ * Segmentation only earns its cost when the chain has a **second** step that
54
+ * could match across boundaries the first step set — see
55
+ * `ConverterFactoryWithSegmentation`. OpenCC therefore declares a
56
+ * `segmentation` on exactly eight configs (`s2tw`, `s2twp`, `s2hk`, `s2hkp`,
57
+ * `tw2s`, `tw2sp`, `hk2s`, `hk2sp`) and on none of the single-step ones
58
+ * (`s2t`, `t2tw`, `tw2t`, `t2s`, `t2hk`, `hk2t`, `jp2t`, `t2jp`). This
59
+ * function reproduces that set rather than inventing a broader rule:
60
+ *
61
+ * - **cn → tw/twp/hk/hkp** cuts on `STPhrases`.
62
+ * - **tw/twp/hk/hkp → cn** cuts on `TSPhrases`.
63
+ * - everything else, including anything touching `t` or `jp`, does not cut.
64
+ *
65
+ * The direction of the dictionary is the part worth remembering: it is the
66
+ * **raw input** being cut, so the keys must be in the input's script.
67
+ * `s2*` cuts on the simplified-keyed `STPhrases`; `*2s` cuts on the
68
+ * traditional-keyed `TSPhrases` — which lives in the chain's *second* step,
69
+ * not its first. Picking "the first step's phrase dict" looks tidier and is
70
+ * wrong for `tw2s`.
71
+ *
72
+ * `jp` is excluded deliberately: Shinjitai conversion has no phrase table
73
+ * keyed in the source script, and OpenCC declares no segmentation for it.
74
+ *
75
+ * ## The second segmentation dict: `STPhrases_GeneratedFromRegionalPhrases`
76
+ *
77
+ * OpenCC's `s2*` configs segment on **two** dictionaries — `STPhrases` plus a
78
+ * generated one that maps each regional term's simplified projection to its
79
+ * plain traditional form (`出租车 出租車`), keeping the term whole through
80
+ * segmentation so the regional table can replace it as a unit. Without it
81
+ * `出租车司机` under-applies to `出租車司機` where OpenCC gives `計程車司機`.
82
+ *
83
+ * We once thought its filter was unrecoverable (a naive derivation yielded 276
84
+ * extra entries) and documented it as a known gap. The actual rule was found
85
+ * by reading OpenCC's `generate_st_phrases_from_regional_phrases.py`: project
86
+ * the keys of HKPhrases + TWPhrases through t2s and **drop projections shorter
87
+ * than 3 code points** — short keys would split longer Simplified words before
88
+ * STPhrases could match them. That one filter reproduces all 508 upstream
89
+ * entries exactly. The sync script now generates the dict; see
90
+ * `generateRegionalStPhrases` comments there for the full recipe.
91
+ */
92
+ export function segmentationDictsFor(from, to) {
93
+ if (from === "cn" && REGIONAL_VARIANTS.has(to))
94
+ return ["STPhrases", "STPhrases_GeneratedFromRegionalPhrases"];
95
+ if (to === "cn" && REGIONAL_VARIANTS.has(from))
96
+ return ["TSPhrases"];
97
+ return [];
98
+ }
99
+ /** Locales that carry Taiwan vocabulary. `t`/`hk`/`jp` are traditional but not Taiwanese. */
100
+ const isTwVocab = (locale) => locale === "tw" || locale === "twp";
101
+ /**
102
+ * Decide whether — and in which direction — CNTWPhrases applies. This is the
103
+ * single home for the rule: the main entry, both one-way bundles and the full
104
+ * bundle all call it. Do not inline a copy at a call site — four copies is how
105
+ * the four entry points came to disagree with each other.
106
+ *
107
+ * - Crossing INTO Taiwan vocabulary from outside it → `"forward"`.
108
+ * - Leaving Taiwan vocabulary for `cn` → `"reverse"`.
109
+ * - Everything else → `null`.
110
+ *
111
+ * Two asymmetries worth keeping straight, both deliberate:
112
+ *
113
+ * 1. A `tw`/`twp` SOURCE never gets the forward dict, even aimed at `twp`. Its
114
+ * keys are simplified, so against traditional input the only ones that can
115
+ * match are the script-invariant terms (土豆, 芝士, 高考, 雪糕, 薯片) — exactly
116
+ * the entries whose meaning differs in Taiwan (土豆 is peanut there, not
117
+ * 馬鈴薯). A `t`/`hk`/`jp` source aimed at `twp` DOES get it, and should:
118
+ * 芝士→起司 and 雪糕→冰淇淋 are the intended HK→TW conversions.
119
+ * 2. `"reverse"` is confined to `to === "cn"`, not to any non-Taiwan target,
120
+ * because the reversed values are simplified (計程車 → 出租车) and would put
121
+ * simplified characters into a traditional target.
122
+ *
123
+ * @param loadCustomPhrases - Defaults to on when either end is `twp`. An
124
+ * explicit `true` enables the rule but does not override it: directions that
125
+ * score `null` (e.g. `cn → hk`) still get no dict.
126
+ */
127
+ export function phraseDictDirection(from, to, loadCustomPhrases) {
128
+ if (!(loadCustomPhrases ?? (from === "twp" || to === "twp")))
129
+ return null;
130
+ if (!isTwVocab(from) && isTwVocab(to))
131
+ return "forward";
132
+ if (isTwVocab(from) && to === "cn")
133
+ return "reverse";
134
+ return null;
135
+ }