llm-large-files 0.4.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
@@ -0,0 +1,850 @@
1
+ // Text files whose bytes are not all valid UTF-8.
2
+ //
3
+ // Such a file is one of two things. It is UTF-8 with a few characters that are not valid: a log cut
4
+ // at a byte count, a stray byte, a binary body in a log line. Or it was saved in an older encoding:
5
+ // Excel saves a Hebrew CSV in windows-1255, and Notepad saved text in the code page of Windows.
6
+ // Each line is looked at. When at least as many lines are UTF-8 as are not, or when at most one
7
+ // line in 200 is not UTF-8, the file is UTF-8, and each character that is not valid becomes U+FFFD
8
+ // and is counted. Otherwise the lines that are not UTF-8 are read in the older encoding that their
9
+ // letters fit, and in no other: a byte that this encoding does not have becomes U+FFFD, and is
10
+ // counted too. A line that is valid UTF-8 is read as UTF-8 all the same. When the letters fit no
11
+ // older encoding for sure, the file is read as UTF-8, with the count: letters that mean nothing
12
+ // would be worse than U+FFFD that the model is told of. A text file is never refused for its
13
+ // encoding. A file in CESU-8, which writes an emoji as two halves of a surrogate pair, is read with
14
+ // its emoji when that makes it valid UTF-8.
15
+
16
+ import { isAscii, isUtf8 } from "node:buffer";
17
+
18
+ /** The text of a file whose bytes are not all valid UTF-8, and how it was read. */
19
+ export type DecodedText = {
20
+ text: string;
21
+ /** The older encoding the file was read in, as TextDecoder names it: "windows-1255". */
22
+ encoding?: string;
23
+ /** The characters that were not valid in the encoding the file was read in (UTF-8, or `encoding`): each is now U+FFFD. */
24
+ replacedCharacters?: number;
25
+ };
26
+
27
+ /** Bytes looked at or decoded between two chances for other requests to run. */
28
+ const STEP_BYTES = 1024 * 1024;
29
+ /** Rows of lines in one encoding decoded between two chances for other requests to run: a few milliseconds. */
30
+ const RUNS_PER_STEP = 2048;
31
+ /**
32
+ * Lines up to this many bytes are looked at byte by byte; a longer one by `isAscii` and `isUtf8` of
33
+ * node:buffer, which cost a call each.
34
+ */
35
+ const SHORT_LINE = 256;
36
+ /**
37
+ * Lines in a row in a single-byte encoding, up to this many bytes, are read from a table of its
38
+ * characters: TextDecoder takes most of a microsecond for each call.
39
+ */
40
+ const SHORT_RUN = 64;
41
+ /** The encoding is chosen on lines that are not UTF-8, up to this many bytes: about a thousand rows of a CSV. */
42
+ const SAMPLE_BYTES = 64 * 1024;
43
+ /** In the encoding a file is read in, at most one word or sign in this many may look wrong. */
44
+ const WRONG_ONE_IN = 50;
45
+ /**
46
+ * A file with at most one line in this many that is not UTF-8 is read as UTF-8, ASCII lines
47
+ * counted: the other lines are stray bytes in a log, or a binary body it logged.
48
+ */
49
+ const STRAY_ONE_IN = 200;
50
+ /** U+FFFD, which TextDecoder writes for a character that is not valid. */
51
+ const REPLACEMENT = String.fromCharCode(0xfffd);
52
+ /**
53
+ * U+0080 to U+009F. TextDecoder gives them for some bytes that an older encoding has no character
54
+ * for (windows-1252 0x81, 0x8D, 0x8F, 0x90 and 0x9D, windows-1255 0x8A): none of the encodings
55
+ * here has a character of its own there.
56
+ */
57
+ const C1_CONTROLS = /[\u0080-\u009f]/g;
58
+
59
+ type Script = "Latin" | "Cyrillic" | "Hebrew" | "Arabic" | "Japanese";
60
+
61
+ /**
62
+ * The older encodings a file is recognized in, with the script of their letters. When the text
63
+ * fits more than one, the first wins: a Hebrew text read as windows-1251 gives Cyrillic letters
64
+ * that look like words, but a Russian text read as windows-1255 does not give Hebrew words.
65
+ * ISO-8859-1 is read as windows-1252, as browsers do, and ISO-8859-8 as windows-1255.
66
+ */
67
+ const ENCODINGS: ReadonlyArray<{ encoding: string; script: Script }> = [
68
+ { encoding: "windows-1255", script: "Hebrew" },
69
+ { encoding: "windows-1256", script: "Arabic" },
70
+ { encoding: "windows-1251", script: "Cyrillic" },
71
+ { encoding: "shift_jis", script: "Japanese" },
72
+ { encoding: "windows-1252", script: "Latin" },
73
+ ];
74
+
75
+ /**
76
+ * Reads bytes that `TextDecoder("utf-8", { fatal: true })` refused. A generator: it yields between
77
+ * steps of about a megabyte, and between the encodings it tries, so that the caller can let other
78
+ * requests run.
79
+ */
80
+ export function* decodeNotUtf8(bytes: Uint8Array): Generator<void, DecodedText> {
81
+ const lines = yield* scanLines(bytes);
82
+ // Every character that is not valid is half of a surrogate pair: an export in CESU-8.
83
+ if (lines.halves > 0 && lines.errors === lines.halves * 3) {
84
+ const text = yield* joinSurrogates(bytes);
85
+ if (text !== undefined) return { text };
86
+ }
87
+ // A byte-order mark says the file is UTF-8, whatever its lines look like.
88
+ const marked = bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
89
+ if (marked || lines.other <= lines.utf8 || lines.other * STRAY_ONE_IN <= lines.total) return yield* readAsUtf8(bytes, lines.errors);
90
+ const encoding = yield* firstThatFits(lines);
91
+ yield;
92
+ if (!encoding) return yield* readAsUtf8(bytes, lines.errors);
93
+ // The first encoding that fits, and no other, even for a byte further on that it does not have:
94
+ // in the next one, Hebrew would come out as Cyrillic letters. When some lines are UTF-8, they
95
+ // are read as UTF-8 all the same.
96
+ const { text, replaced } = lines.utf8 === 0 ? yield* decodeInSteps(bytes, encoding) : yield* decodeLines(bytes, encoding);
97
+ return { text, encoding, ...(replaced > 0 ? { replacedCharacters: replaced } : {}) };
98
+ }
99
+
100
+ /** The file as UTF-8. `errors` comes from `scanLines`: the text may hold U+FFFD of its own. */
101
+ function* readAsUtf8(bytes: Uint8Array, errors: number): Generator<void, DecodedText> {
102
+ const { text } = yield* decodeInSteps(bytes, "utf-8");
103
+ return { text, ...(errors > 0 ? { replacedCharacters: errors } : {}) };
104
+ }
105
+
106
+ /**
107
+ * The first of `ENCODINGS` that the lines which are not UTF-8 fit, or none. Lines of signs alone
108
+ * (– ’ € °) are the same bytes in the single-byte encodings, and say nothing: the lines with
109
+ * letters choose, wherever they are in the file, and the first lines only when no line has
110
+ * letters. In Shift_JIS, kana and most kanji have no byte of 0xC0 or more, and every byte from
111
+ * 0x81 on is part of a character: Shift_JIS is tried on the first lines. Checking an encoding
112
+ * takes a few milliseconds, and more the first time, when its table of bytes is made: this pauses
113
+ * before each.
114
+ */
115
+ function* firstThatFits(lines: Lines): Generator<void, string | undefined> {
116
+ const letters = lines.letters.length > 0 ? lines.letters : lines.sample;
117
+ for (const { encoding, script } of ENCODINGS) {
118
+ yield;
119
+ if (!supported(encoding)) continue;
120
+ if (script !== "Japanese") {
121
+ kindsOf(encoding);
122
+ yield;
123
+ }
124
+ if (fits(script === "Japanese" ? lines.sample : letters, encoding, script)) return encoding;
125
+ }
126
+ return undefined;
127
+ }
128
+
129
+ /** How the lines of a file read as UTF-8. */
130
+ type Lines = {
131
+ /** Lines with characters of more than one byte, at least as many as those that are not valid. */
132
+ utf8: number;
133
+ /** Lines with more bytes that are not valid UTF-8 than characters that are. */
134
+ other: number;
135
+ /** Every line, ASCII lines too. */
136
+ total: number;
137
+ /** The characters that are not valid, counted as TextDecoder counts the U+FFFD it writes. */
138
+ errors: number;
139
+ /**
140
+ * The first of the `other` lines, whole, one per line, up to `SAMPLE_BYTES`. Only a first line
141
+ * longer than that is cut.
142
+ */
143
+ sample: Uint8Array;
144
+ /**
145
+ * The `other` lines with a byte of 0xC0 or more, from anywhere in the file, as `sample` holds
146
+ * them. Such a byte is a letter in each single-byte encoding here, or a Hebrew point.
147
+ */
148
+ letters: Uint8Array;
149
+ /** Halves of a surrogate pair (0xED, then 0xA0 to 0xBF), which UTF-8 does not allow. */
150
+ halves: number;
151
+ };
152
+
153
+ /** Whole lines, one after another, up to `SAMPLE_BYTES`. */
154
+ function sampler(bytes: Uint8Array) {
155
+ const lines: Uint8Array[] = [];
156
+ let size = 0;
157
+ let full = false;
158
+ return {
159
+ add(start: number, end: number) {
160
+ if (full) return;
161
+ const room = SAMPLE_BYTES - size;
162
+ if (end - start <= room) {
163
+ lines.push(bytes.subarray(start, end));
164
+ size += end - start + 1;
165
+ } else {
166
+ // A line cut short could end in the middle of a Shift_JIS character: the sample ends
167
+ // before it, unless it is the first.
168
+ if (lines.length === 0) lines.push(bytes.subarray(start, start + room));
169
+ full = true;
170
+ }
171
+ },
172
+ joined: () => joinLines(lines),
173
+ };
174
+ }
175
+
176
+ /**
177
+ * Reads the bytes as the UTF-8 decoder of the Encoding Standard does (TextDecoder follows it), and
178
+ * counts, line by line, the characters of more than one byte and the ones that are not valid.
179
+ */
180
+ function* scanLines(bytes: Uint8Array): Generator<void, Lines> {
181
+ let utf8 = 0;
182
+ let other = 0;
183
+ let total = 0;
184
+ let errors = 0;
185
+ let halves = 0;
186
+ const sample = sampler(bytes);
187
+ const letters = sampler(bytes);
188
+ let lineStart = 0;
189
+ let lineErrors = 0;
190
+ let lineCharacters = 0;
191
+ let lineLetters = false;
192
+ // The bytes of a character cut in two by the start or the end of the file, as in a log cut at a
193
+ // byte count or a part made by `split -b`. Such a character is UTF-8 as far as it goes: it
194
+ // counts against its line only when other bytes of the line are not valid either.
195
+ let lineCut = 0;
196
+ const endLine = (end: number) => {
197
+ total++;
198
+ errors += lineErrors + lineCut;
199
+ const invalid = lineErrors > 0 ? lineErrors + lineCut : 0;
200
+ if (invalid === 0) {
201
+ if (lineCharacters > 0) utf8++;
202
+ } else if (lineCharacters >= invalid) {
203
+ utf8++;
204
+ } else {
205
+ other++;
206
+ sample.add(lineStart, end);
207
+ if (lineLetters) letters.add(lineStart, end);
208
+ }
209
+ lineErrors = 0;
210
+ lineCharacters = 0;
211
+ lineCut = 0;
212
+ lineLetters = false;
213
+ };
214
+ // One to three bytes that continue a character, at the start: the end of a character cut in two.
215
+ let start = 0;
216
+ while (start < 4 && start < bytes.length && (bytes[start]! & 0xc0) === 0x80) start++;
217
+ if (start === 4) start = 0;
218
+ lineCut = start;
219
+ // The bytes the character being read still needs, and the range the next one must be in.
220
+ let needed = 0;
221
+ let seen = 0;
222
+ let lower = 0x80;
223
+ let upper = 0xbf;
224
+ for (let from = 0; from < bytes.length; from += STEP_BYTES) {
225
+ const to = Math.min(bytes.length, from + STEP_BYTES);
226
+ for (let at = Math.max(from, start); at < to; at++) {
227
+ const byte = bytes[at]!;
228
+ if (needed === 0) {
229
+ if (byte < 0x80) {
230
+ if (byte === 0x0a) {
231
+ endLine(at);
232
+ lineStart = at + 1;
233
+ }
234
+ continue;
235
+ }
236
+ if (byte >= 0xc0) lineLetters = true;
237
+ if (byte >= 0xc2 && byte <= 0xdf) {
238
+ needed = 1;
239
+ } else if (byte >= 0xe0 && byte <= 0xef) {
240
+ if (byte === 0xe0) lower = 0xa0;
241
+ else if (byte === 0xed) upper = 0x9f;
242
+ needed = 2;
243
+ } else if (byte >= 0xf0 && byte <= 0xf4) {
244
+ if (byte === 0xf0) lower = 0x90;
245
+ else if (byte === 0xf4) upper = 0x8f;
246
+ needed = 3;
247
+ } else {
248
+ lineErrors++;
249
+ }
250
+ continue;
251
+ }
252
+ if (byte < lower || byte > upper) {
253
+ // After 0xED, 0xA0 to 0xBF begin half of a surrogate pair.
254
+ if (upper === 0x9f && byte > upper && byte <= 0xbf) halves++;
255
+ // The character ends before it is whole: that is one error, and this byte is read again.
256
+ needed = 0;
257
+ seen = 0;
258
+ lower = 0x80;
259
+ upper = 0xbf;
260
+ lineErrors++;
261
+ at--;
262
+ continue;
263
+ }
264
+ lower = 0x80;
265
+ upper = 0xbf;
266
+ if (++seen === needed) {
267
+ needed = 0;
268
+ seen = 0;
269
+ lineCharacters++;
270
+ }
271
+ }
272
+ yield;
273
+ }
274
+ // A character cut off by the end of the file.
275
+ if (needed !== 0) lineCut++;
276
+ if (lineStart < bytes.length) endLine(bytes.length);
277
+ return { utf8, other, total, errors, sample: sample.joined(), letters: letters.joined(), halves };
278
+ }
279
+
280
+ /** The lines, with a line feed between two. */
281
+ function joinLines(pieces: Uint8Array[]): Uint8Array {
282
+ const joined = new Uint8Array(Math.max(0, pieces.reduce((sum, piece) => sum + piece.length + 1, 0) - 1));
283
+ let at = 0;
284
+ pieces.forEach((piece, index) => {
285
+ if (index > 0) joined[at++] = 0x0a;
286
+ joined.set(piece, at);
287
+ at += piece.length;
288
+ });
289
+ return joined;
290
+ }
291
+
292
+ /**
293
+ * Decodes the bytes a megabyte at a time. In an older encoding, a byte the encoding does not have
294
+ * becomes U+FFFD (see `C1_CONTROLS`), and `replaced` counts the U+FFFD written: no older encoding
295
+ * here has a character of its own for it. As UTF-8, `replaced` is 0: `scanLines` counts.
296
+ */
297
+ function* decodeInSteps(bytes: Uint8Array, encoding: string): Generator<void, { text: string; replaced: number }> {
298
+ const decoder = decoderFor(encoding);
299
+ const pieces: string[] = [];
300
+ let replaced = 0;
301
+ const add = (decoded: string) => {
302
+ if (encoding === "utf-8") {
303
+ pieces.push(decoded);
304
+ return;
305
+ }
306
+ const piece = decoded.replace(C1_CONTROLS, REPLACEMENT);
307
+ pieces.push(piece);
308
+ replaced += replacements(piece);
309
+ };
310
+ for (let from = 0; from < bytes.length; from += STEP_BYTES) {
311
+ add(decoder.decode(bytes.subarray(from, from + STEP_BYTES), { stream: true }));
312
+ yield;
313
+ }
314
+ add(decoder.decode());
315
+ return { text: pieces.join(""), replaced };
316
+ }
317
+
318
+ /**
319
+ * Decodes a file with lines in two encodings: a line that is valid UTF-8 as UTF-8, any other line
320
+ * in the older `encoding`, as `decodeInSteps` does. `replaced` counts the U+FFFD written. A line
321
+ * feed is never part of a character in UTF-8 or Shift_JIS, so each line can be decoded alone.
322
+ * Lines in a row in the same encoding are decoded together, and an ASCII line goes with the line
323
+ * before it: it is the same text in each encoding here (Shift_JIS swaps three control characters,
324
+ * which ingest removes). A step ends after a megabyte, or after `RUNS_PER_STEP` such rows when the
325
+ * two encodings take turns, and a longer line is decoded a megabyte at a time.
326
+ */
327
+ function* decodeLines(bytes: Uint8Array, encoding: string): Generator<void, { text: string; replaced: number }> {
328
+ // A byte-order mark further on is kept, as in a file decoded whole.
329
+ const utf8 = new TextDecoder("utf-8", { ignoreBOM: true });
330
+ const older = decoderFor(encoding);
331
+ const chars = encoding === "shift_jis" ? undefined : charsOf(encoding);
332
+ // The text of each step, and of the step being decoded.
333
+ const pieces: string[] = [];
334
+ let step: string[] = [];
335
+ let replaced = 0;
336
+ // The lines from `runStart` on are all valid UTF-8, or all not, apart from ASCII lines.
337
+ let runStart = 0;
338
+ let runUtf8 = true;
339
+ let runs = 0;
340
+ // Decodes the lines from `runStart` to `end`, a megabyte at most: false when more is left.
341
+ const endRun = (end: number): boolean => {
342
+ if (end === runStart) return true;
343
+ if (!runUtf8 && chars && end - runStart <= SHORT_RUN) {
344
+ let piece = "";
345
+ for (let at = runStart; at < end; at++) {
346
+ const char = chars[bytes[at]!]!;
347
+ if (char === REPLACEMENT) replaced++;
348
+ piece += char;
349
+ }
350
+ step.push(piece);
351
+ } else {
352
+ const to = Math.min(end, runStart + STEP_BYTES);
353
+ const options = { stream: to < end };
354
+ if (runUtf8) {
355
+ step.push(utf8.decode(bytes.subarray(runStart, to), options));
356
+ } else {
357
+ const piece = older.decode(bytes.subarray(runStart, to), options).replace(C1_CONTROLS, REPLACEMENT);
358
+ step.push(piece);
359
+ replaced += replacements(piece);
360
+ }
361
+ if (to < end) {
362
+ runStart = to;
363
+ return false;
364
+ }
365
+ }
366
+ runStart = end;
367
+ runs++;
368
+ return true;
369
+ };
370
+ let stepEnd = STEP_BYTES;
371
+ for (let start = 0; start < bytes.length;) {
372
+ const feed = bytes.indexOf(0x0a, start);
373
+ const end = feed === -1 ? bytes.length : feed + 1;
374
+ const kind = lineKind(bytes, start, end);
375
+ if (kind !== "ascii" && (kind === "utf8") !== runUtf8) {
376
+ while (!endRun(start)) yield;
377
+ runUtf8 = kind === "utf8";
378
+ }
379
+ start = end;
380
+ if (start >= stepEnd || runs >= RUNS_PER_STEP) {
381
+ while (!endRun(start)) yield;
382
+ pieces.push(step.join(""));
383
+ step = [];
384
+ runs = 0;
385
+ stepEnd = start + STEP_BYTES;
386
+ yield;
387
+ }
388
+ }
389
+ while (!endRun(bytes.length)) yield;
390
+ pieces.push(step.join(""));
391
+ return { text: pieces.join(""), replaced };
392
+ }
393
+
394
+ /** Whether the line from `start` to `end` is ASCII, valid UTF-8 with characters of more than one byte, or not valid UTF-8. */
395
+ function lineKind(bytes: Uint8Array, start: number, end: number): "ascii" | "utf8" | "other" {
396
+ if (end - start > SHORT_LINE) {
397
+ const line = bytes.subarray(start, end);
398
+ return isAscii(line) ? "ascii" : isUtf8(line) ? "utf8" : "other";
399
+ }
400
+ let kind: "ascii" | "utf8" = "ascii";
401
+ for (let at = start; at < end; at++) {
402
+ const byte = bytes[at]!;
403
+ if (byte < 0x80) continue;
404
+ kind = "utf8";
405
+ // The bytes the character still needs, and the range the next one must be in, as in `scanLines`.
406
+ let needed: number;
407
+ let lower = 0x80;
408
+ let upper = 0xbf;
409
+ if (byte >= 0xc2 && byte <= 0xdf) {
410
+ needed = 1;
411
+ } else if (byte >= 0xe0 && byte <= 0xef) {
412
+ if (byte === 0xe0) lower = 0xa0;
413
+ else if (byte === 0xed) upper = 0x9f;
414
+ needed = 2;
415
+ } else if (byte >= 0xf0 && byte <= 0xf4) {
416
+ if (byte === 0xf0) lower = 0x90;
417
+ else if (byte === 0xf4) upper = 0x8f;
418
+ needed = 3;
419
+ } else {
420
+ return "other";
421
+ }
422
+ if (at + needed >= end) return "other";
423
+ for (; needed > 0; needed--) {
424
+ const next = bytes[++at]!;
425
+ if (next < lower || next > upper) return "other";
426
+ lower = 0x80;
427
+ upper = 0xbf;
428
+ }
429
+ }
430
+ return kind;
431
+ }
432
+
433
+ const charTables = new Map<string, string[]>();
434
+
435
+ /** The character each byte is in a single-byte encoding, as `decodeInSteps` reads it: U+FFFD for a byte the encoding does not have. */
436
+ function charsOf(encoding: string): string[] {
437
+ let chars = charTables.get(encoding);
438
+ if (!chars) {
439
+ const decoder = decoderFor(encoding);
440
+ chars = Array.from({ length: 256 }, (_, byte) => decoder.decode(Uint8Array.of(byte)).replace(C1_CONTROLS, REPLACEMENT));
441
+ charTables.set(encoding, chars);
442
+ }
443
+ return chars;
444
+ }
445
+
446
+ /** The U+FFFD in a text. */
447
+ function replacements(text: string): number {
448
+ let count = 0;
449
+ for (let at = text.indexOf(REPLACEMENT); at !== -1; at = text.indexOf(REPLACEMENT, at + 1)) count++;
450
+ return count;
451
+ }
452
+
453
+ /**
454
+ * The text of a file in CESU-8, as an Oracle database in its character set UTF8, or Java, writes
455
+ * it: a character past U+FFFF, such as an emoji, is two halves of a surrogate pair of three bytes
456
+ * each. Each pair is written as the four bytes of UTF-8. Undefined when the bytes are still not
457
+ * valid UTF-8 then.
458
+ */
459
+ function* joinSurrogates(bytes: Uint8Array): Generator<void, string | undefined> {
460
+ const joined = new Uint8Array(bytes.length);
461
+ let length = 0;
462
+ let copied = 0;
463
+ for (let from = 0; from < bytes.length; from += STEP_BYTES) {
464
+ const to = Math.min(bytes.length, from + STEP_BYTES);
465
+ for (let at = bytes.indexOf(0xed, Math.max(from, copied)); at !== -1 && at < to; at = bytes.indexOf(0xed, at + 1)) {
466
+ const high = surrogateAt(bytes, at);
467
+ const low = surrogateAt(bytes, at + 3);
468
+ if (high < 0xd800 || high > 0xdbff || low < 0xdc00 || low > 0xdfff) continue;
469
+ const code = 0x10000 + ((high - 0xd800) << 10) + (low - 0xdc00);
470
+ joined.set(bytes.subarray(copied, at), length);
471
+ length += at - copied;
472
+ joined[length++] = 0xf0 | (code >> 18);
473
+ joined[length++] = 0x80 | ((code >> 12) & 0x3f);
474
+ joined[length++] = 0x80 | ((code >> 6) & 0x3f);
475
+ joined[length++] = 0x80 | (code & 0x3f);
476
+ copied = at + 6;
477
+ at = copied - 1;
478
+ }
479
+ yield;
480
+ }
481
+ joined.set(bytes.subarray(copied), length);
482
+ length += bytes.length - copied;
483
+ try {
484
+ return new TextDecoder("utf-8", { fatal: true }).decode(joined.subarray(0, length));
485
+ } catch {
486
+ return undefined;
487
+ }
488
+ }
489
+
490
+ /** The surrogate that the three bytes at `at` would be in UTF-8 (0xED, then two that continue a character), or -1. */
491
+ function surrogateAt(bytes: Uint8Array, at: number): number {
492
+ const second = bytes[at + 1];
493
+ const third = bytes[at + 2];
494
+ if (bytes[at] !== 0xed || second === undefined || third === undefined || (second & 0xc0) !== 0x80 || (third & 0xc0) !== 0x80) return -1;
495
+ return 0xd000 | ((second & 0x3f) << 6) | (third & 0x3f);
496
+ }
497
+
498
+ /** The encodings the sample fits, the one to read the file in first. */
499
+ export function encodingsThatFit(sample: Uint8Array): string[] {
500
+ return ENCODINGS.filter(({ encoding, script }) => supported(encoding) && fits(sample, encoding, script)).map(({ encoding }) => encoding);
501
+ }
502
+
503
+ /** Whether the sample looks like text of the script, read in the encoding. */
504
+ function fits(sample: Uint8Array, encoding: string, script: Script): boolean {
505
+ return script === "Japanese" ? fitsJapanese(sample) : fitsSingleByte(sample, kindsOf(encoding), script);
506
+ }
507
+
508
+ /**
509
+ * A decoder for an older encoding. Node 20 reads windows-1252 (and its other Latin-1 labels) as
510
+ * Latin-1 in a decode call that is not streamed, so 0x80-0x9F come out as control characters
511
+ * ("’" as U+0092), until the decoder has been called once streamed: that call is made here.
512
+ */
513
+ function decoderFor(encoding: string, options?: TextDecoderOptions): TextDecoder {
514
+ const decoder = new TextDecoder(encoding, options);
515
+ decoder.decode(new Uint8Array(0), { stream: true });
516
+ return decoder;
517
+ }
518
+
519
+ /** Whether this runtime's TextDecoder has the encoding: a Node.js built without full ICU has only UTF-8, UTF-16 and Latin-1. */
520
+ function supported(encoding: string): boolean {
521
+ try {
522
+ new TextDecoder(encoding);
523
+ return true;
524
+ } catch {
525
+ return false;
526
+ }
527
+ }
528
+
529
+ /** What a character is, for telling whether a text is read in the right encoding. */
530
+ type CharKind = {
531
+ kind: "missing" | "control" | "letter" | "mark" | "joiner" | "separator" | "symbol";
532
+ script?: string;
533
+ upper?: boolean;
534
+ lower?: boolean;
535
+ /** A Hebrew final form (ך ם ן ף ץ), or Arabic ة: it ends a word. */
536
+ final?: boolean;
537
+ /** A letter the languages written in windows-1252 seldom use (see `RARE_LATIN`). */
538
+ rare?: boolean;
539
+ /** Š or Ž, which begin names such as Škoda: before letters of ASCII only, they are not rare. */
540
+ initial?: boolean;
541
+ /** A Cyrillic vowel. */
542
+ vowel?: boolean;
543
+ /** Ь or Ы, which begin no word. */
544
+ neverFirst?: boolean;
545
+ /** Й, which follows a vowel when it does not begin its word. */
546
+ afterVowel?: boolean;
547
+ /** An Arabic letter that every Arabic text is full of (see `FREQUENT_ARABIC`). */
548
+ frequent?: boolean;
549
+ };
550
+
551
+ /**
552
+ * Letters that the languages written in windows-1252 seldom use, but that text in another encoding
553
+ * read as windows-1252 is full of: Turkish ı ş ğ come out as ý þ ð, and Czech, Slovak and Croatian
554
+ * text, written in windows-1250, has š and ž among letters that come out wrong (ř as ø, č as è).
555
+ */
556
+ const RARE_LATIN = "ÐðÞþÝýŠšŽžƒ";
557
+ const INITIAL_LATIN = "ŠŽ";
558
+ /** Signs that Unicode files as letters: ª º µ ˆ. Between letters they are as odd as other signs. */
559
+ const SIGNS = "ªºµˆ";
560
+ /** Signs that stand between letters in words: apostrophes, the Catalan middle dot, the Hebrew geresh, gershayim and maqaf. */
561
+ const IN_WORD = "’‘·׳״־";
562
+ /** Letters that end a word: the Hebrew final forms, and Arabic ة, which KOI8-R и and Greek Ι come out as. */
563
+ const FINAL_FORMS = "ךםןףץة";
564
+ /**
565
+ * Cyrillic vowels, Ukrainian ones too, and Ъ, which is a vowel in Bulgarian. A Russian, Ukrainian,
566
+ * Bulgarian or Serbian word of five letters or more has one. Lower-case KOI8-R, or Greek capitals,
567
+ * read as windows-1251 give words without: "оплата" comes out as "ПРМБФБ".
568
+ */
569
+ const CYRILLIC_VOWELS = "АЕЁИОУЫЭЮЯЄІЇЪаеёиоуыэюяєіїъ";
570
+ /** No word begins with these (Bulgarian "ъгъл" begins with Ъ). KOI8-R "это" comes out as "ЬФП". */
571
+ const NEVER_FIRST = "ЬЫьы";
572
+ /** Й follows a vowel. KOI8-R and Greek и and ι come out as Й, after any letter. */
573
+ const AFTER_VOWEL = "Йй";
574
+ /**
575
+ * ل م ن ه و ى ي: in Arabic text, about two letters in five. Text in Cyrillic or Greek capitals,
576
+ * lower-case KOI8-R, or half-width katakana, read as windows-1256, gives other Arabic letters only.
577
+ */
578
+ const FREQUENT_ARABIC = "لمنهوىي";
579
+
580
+ const SCRIPTS: ReadonlyArray<[string, RegExp]> = [
581
+ ["Latin", /\p{Script=Latin}/u],
582
+ ["Cyrillic", /\p{Script=Cyrillic}/u],
583
+ ["Hebrew", /\p{Script=Hebrew}/u],
584
+ ["Arabic", /\p{Script=Arabic}/u],
585
+ ];
586
+
587
+ function kindOf(char: string | undefined): CharKind {
588
+ if (char === undefined) return { kind: "missing" };
589
+ const code = char.charCodeAt(0);
590
+ if (code >= 0x80 && code <= 0x9f) return { kind: "control" };
591
+ if (SIGNS.includes(char)) return { kind: "symbol" };
592
+ if (/\p{L}/u.test(char)) {
593
+ return {
594
+ kind: "letter",
595
+ script: SCRIPTS.find(([, pattern]) => pattern.test(char))?.[0] ?? "other",
596
+ upper: /\p{Lu}/u.test(char),
597
+ // ß has no capital in these encodings: "STRAßE" is written in capitals.
598
+ lower: /\p{Ll}/u.test(char) && char !== "ß",
599
+ final: FINAL_FORMS.includes(char),
600
+ rare: RARE_LATIN.includes(char),
601
+ initial: INITIAL_LATIN.includes(char),
602
+ vowel: CYRILLIC_VOWELS.includes(char),
603
+ neverFirst: NEVER_FIRST.includes(char),
604
+ afterVowel: AFTER_VOWEL.includes(char),
605
+ frequent: FREQUENT_ARABIC.includes(char),
606
+ };
607
+ }
608
+ if (/\p{M}/u.test(char)) return { kind: "mark" };
609
+ if (/\p{Cf}/u.test(char)) return { kind: "joiner" };
610
+ if (IN_WORD.includes(char) || /\p{Zs}/u.test(char)) return { kind: "separator" };
611
+ return { kind: "symbol" };
612
+ }
613
+
614
+ /** ASCII: letters, and everything else between words. */
615
+ const ASCII_KINDS: CharKind[] = Array.from({ length: 0x80 }, (_, code) => {
616
+ if (code >= 0x41 && code <= 0x5a) return { kind: "letter", script: "Latin", upper: true };
617
+ if (code >= 0x61 && code <= 0x7a) return { kind: "letter", script: "Latin", lower: true };
618
+ return { kind: "separator" };
619
+ });
620
+
621
+ const byteKinds = new Map<string, CharKind[]>();
622
+
623
+ /** The kind of character each byte is in a single-byte encoding, ASCII included. */
624
+ function kindsOf(encoding: string): CharKind[] {
625
+ let kinds = byteKinds.get(encoding);
626
+ if (!kinds) {
627
+ const decoder = decoderFor(encoding, { fatal: true });
628
+ kinds = [...ASCII_KINDS];
629
+ for (let byte = 0x80; byte <= 0xff; byte++) {
630
+ let char: string | undefined;
631
+ try {
632
+ char = decoder.decode(Uint8Array.of(byte));
633
+ } catch {
634
+ char = undefined;
635
+ }
636
+ kinds.push(kindOf(char));
637
+ }
638
+ byteKinds.set(encoding, kinds);
639
+ }
640
+ return kinds;
641
+ }
642
+
643
+ /**
644
+ * Whether the sample, read in a single-byte encoding, looks like text of its script. A word with
645
+ * letters other than ASCII must hold letters of one script, in a case that words have ("word",
646
+ * "Word", "WORD"), and a sign must not stand between two letters. In the Latin script, most
647
+ * letters of a word are ASCII, and seldom-used letters (`RARE_LATIN`) are wrong. Hebrew points
648
+ * follow a letter, and a final form ends its word, as Arabic ة does. A Cyrillic word has a vowel
649
+ * when it is long, begins with neither Ь nor Ы, and has Й only after a vowel. Arabic text may hold
650
+ * French words, and is full of the letters in `FREQUENT_ARABIC`. At most one word or sign in
651
+ * `WRONG_ONE_IN` may look wrong, a byte the encoding does not have counts as a wrong sign, and a
652
+ * script other than Latin needs a word of two letters or more.
653
+ */
654
+ function fitsSingleByte(sample: Uint8Array, kinds: CharKind[], script: Script): boolean {
655
+ let counted = 0;
656
+ let wrong = 0;
657
+ let words = 0;
658
+ // Letters of the script, and how many of them are frequent ones.
659
+ let scriptLetters = 0;
660
+ let frequent = 0;
661
+ // The word being read.
662
+ let letters = 0;
663
+ let ascii = 0;
664
+ let others = 0;
665
+ let vowels = 0;
666
+ let scripts = new Set<string>();
667
+ let odd = false;
668
+ let firstUpper = false;
669
+ let upperAfterFirst = false;
670
+ let uppers = 0;
671
+ let lowers = 0;
672
+ let afterFinal = false;
673
+ let afterVowel = false;
674
+ let rareFirst = false;
675
+ // A sign right after a letter: it is odd when a letter follows it.
676
+ let previousLetter = false;
677
+ let signAfterLetter = false;
678
+
679
+ const caseOk = () => uppers === 0 || lowers === 0 || (firstUpper && !upperAfterFirst);
680
+ const latinOk = () => caseOk() && !(others >= 3 && others > ascii);
681
+ const endWord = () => {
682
+ if (others > 0) {
683
+ counted++;
684
+ if (rareFirst && others > 1) odd = true;
685
+ if (script === "Cyrillic" && letters >= 5 && vowels === 0) odd = true;
686
+ const only = (name: string) => scripts.size === 1 && scripts.has(name);
687
+ let right = false;
688
+ if (!odd) {
689
+ if (script === "Latin") right = only("Latin") && latinOk();
690
+ else if (only(script) && ascii === 0 && (script !== "Cyrillic" || caseOk())) right = true;
691
+ else if (script === "Arabic" && only("Latin")) right = latinOk();
692
+ }
693
+ if (!right) wrong++;
694
+ else if (script === "Latin" || (only(script) && letters >= 2)) words++;
695
+ }
696
+ letters = ascii = others = vowels = uppers = lowers = 0;
697
+ scripts = new Set();
698
+ odd = firstUpper = upperAfterFirst = afterFinal = afterVowel = rareFirst = false;
699
+ };
700
+
701
+ for (const byte of sample) {
702
+ const kind = kinds[byte]!;
703
+ switch (kind.kind) {
704
+ case "letter":
705
+ if (signAfterLetter) wrong++;
706
+ signAfterLetter = false;
707
+ previousLetter = true;
708
+ letters++;
709
+ if (byte < 0x80) ascii++;
710
+ else others++;
711
+ scripts.add(kind.script!);
712
+ if (kind.script === script) {
713
+ scriptLetters++;
714
+ if (kind.frequent) frequent++;
715
+ }
716
+ if (kind.rare) {
717
+ if (letters === 1 && kind.initial) rareFirst = true;
718
+ else odd = true;
719
+ }
720
+ if (afterFinal) odd = true;
721
+ afterFinal = !!kind.final;
722
+ if (letters === 1 ? kind.neverFirst : kind.afterVowel && !afterVowel) odd = true;
723
+ afterVowel = !!kind.vowel;
724
+ if (kind.vowel) vowels++;
725
+ if (kind.upper) {
726
+ uppers++;
727
+ if (letters === 1) firstUpper = true;
728
+ else upperAfterFirst = true;
729
+ }
730
+ if (kind.lower) lowers++;
731
+ break;
732
+ case "mark":
733
+ // A point or vowel sign belongs to the letter before it.
734
+ if (letters === 0) odd = true;
735
+ others++;
736
+ break;
737
+ case "joiner":
738
+ break;
739
+ case "missing":
740
+ case "control":
741
+ counted++;
742
+ wrong++;
743
+ endWord();
744
+ previousLetter = signAfterLetter = false;
745
+ break;
746
+ case "symbol":
747
+ counted++;
748
+ endWord();
749
+ signAfterLetter = previousLetter;
750
+ previousLetter = false;
751
+ break;
752
+ case "separator":
753
+ // An apostrophe or a no-break space that is not ASCII is right: it may be all a text holds
754
+ // that is not ASCII.
755
+ if (byte >= 0x80) counted++;
756
+ endWord();
757
+ previousLetter = signAfterLetter = false;
758
+ break;
759
+ }
760
+ }
761
+ endWord();
762
+ return counted > 0 && wrong * WRONG_ONE_IN <= counted && (script === "Latin" || words > 0)
763
+ && (script !== "Arabic" || frequent * 10 >= scriptLetters);
764
+ }
765
+
766
+ /**
767
+ * Whether the sample reads as Japanese in Shift_JIS: every character a byte pair gives is one that
768
+ * Japanese text uses, at least one in ten is hiragana or katakana, and at most one in four
769
+ * characters of two bytes is a seldom-used kanji (JIS level 2 and after, first byte 0xE0 to 0xEF).
770
+ * Chinese, Korean or Thai text read as Shift_JIS gives characters from the user-defined area,
771
+ * half-width katakana and seldom-used kanji, but almost no hiragana.
772
+ *
773
+ * Half-width katakana, as Japanese bank files hold them, count as kana when they are written as
774
+ * words are: two or more in a row, ゙ and ゚ after a kana they voice, small kana and ー after a kana,
775
+ * and from both ends of their table, ヲ to ソ and ミ to ゚. A sign such as µ or · in windows-1252 is
776
+ * one half-width katakana alone. Cyrillic or Greek letters fill a block of 32 bytes, which gives
777
+ * half-width katakana from one end only: タ to ゚ from windows-1251 capitals or lower-case KOI8-R,
778
+ * ー to マ from ISO-8859-5 capitals.
779
+ */
780
+ function fitsJapanese(sample: Uint8Array): boolean {
781
+ let text: string;
782
+ try {
783
+ // With `stream`, a character cut in two at the end of the sample is left out, not taken for a wrong one.
784
+ text = new TextDecoder("shift_jis", { fatal: true }).decode(sample, { stream: true });
785
+ } catch {
786
+ return false;
787
+ }
788
+ let pairs = 0;
789
+ let seldom = 0;
790
+ for (let at = 0; at < sample.length; at++) {
791
+ const byte = sample[at]!;
792
+ if ((byte >= 0x81 && byte <= 0x9f) || byte >= 0xe0) {
793
+ pairs++;
794
+ if (byte >= 0xe0 && byte <= 0xef) seldom++;
795
+ at++;
796
+ }
797
+ }
798
+ let counted = 0;
799
+ let kana = 0;
800
+ let halfWidth = 0;
801
+ let firstRows = 0;
802
+ let lastRows = 0;
803
+ let wrong = 0;
804
+ let previous = 0;
805
+ // The half-width katakana in a row, and how many of them are ヲ to ソ, and ミ to ゚.
806
+ let run = 0;
807
+ let runFirst = 0;
808
+ let runLast = 0;
809
+ const endRun = () => {
810
+ if (run >= 2) {
811
+ halfWidth += run;
812
+ firstRows += runFirst;
813
+ lastRows += runLast;
814
+ }
815
+ run = runFirst = runLast = 0;
816
+ };
817
+ for (let index = 0; index < text.length; index++) {
818
+ const code = text.charCodeAt(index);
819
+ if (code >= 0xff66 && code <= 0xff9f) {
820
+ counted++;
821
+ run++;
822
+ if (code <= 0xff7f) runFirst++;
823
+ else if (code >= 0xff90) runLast++;
824
+ if (!halfWidthFollows(code, previous)) wrong++;
825
+ } else {
826
+ endRun();
827
+ if (code >= 0x80) {
828
+ counted++;
829
+ if (code >= 0x3041 && code <= 0x30ff) kana++;
830
+ // Control characters, and the user-defined area that the bytes 0xF0 to 0xF9 lead to.
831
+ else if (code <= 0x9f || (code >= 0xe000 && code <= 0xf8ff)) wrong++;
832
+ }
833
+ }
834
+ previous = code;
835
+ }
836
+ endRun();
837
+ if (firstRows * 10 >= halfWidth && lastRows * 10 >= halfWidth) kana += halfWidth;
838
+ return counted > 0 && wrong * WRONG_ONE_IN <= counted && kana >= 2 && kana * 10 >= counted && seldom * 4 <= pairs;
839
+ }
840
+
841
+ /** Whether a half-width katakana may follow the character before it. */
842
+ function halfWidthFollows(code: number, previous: number): boolean {
843
+ const kana = previous >= 0xff66 && previous <= 0xff9f;
844
+ // ゙ voices ウ, カ to ト, and ハ to ホ; ゚, ハ to ホ.
845
+ if (code === 0xff9e) return previous === 0xff73 || (previous >= 0xff76 && previous <= 0xff84) || (previous >= 0xff8a && previous <= 0xff8e);
846
+ if (code === 0xff9f) return previous >= 0xff8a && previous <= 0xff8e;
847
+ // Small ァ to ッ, and ー.
848
+ if (code >= 0xff67 && code <= 0xff70) return kana;
849
+ return true;
850
+ }