llm-large-files 0.1.0 → 0.3.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 (91) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +32 -6
  3. package/dist/analyze.d.ts.map +1 -1
  4. package/dist/analyze.js +5 -1
  5. package/dist/analyze.js.map +1 -1
  6. package/dist/extract.d.ts +30 -7
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +94 -23
  9. package/dist/extract.js.map +1 -1
  10. package/dist/gemini/chat.d.ts +38 -2
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +83 -32
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts +34 -4
  15. package/dist/gemini/generate.d.ts.map +1 -1
  16. package/dist/gemini/generate.js +51 -8
  17. package/dist/gemini/generate.js.map +1 -1
  18. package/dist/gemini/index.d.ts +3 -3
  19. package/dist/gemini/index.d.ts.map +1 -1
  20. package/dist/gemini/index.js +2 -2
  21. package/dist/gemini/index.js.map +1 -1
  22. package/dist/index.d.ts +4 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/library.d.ts +37 -1
  27. package/dist/library.d.ts.map +1 -1
  28. package/dist/library.js +59 -7
  29. package/dist/library.js.map +1 -1
  30. package/dist/map-reduce.d.ts +7 -0
  31. package/dist/map-reduce.d.ts.map +1 -1
  32. package/dist/map-reduce.js +58 -16
  33. package/dist/map-reduce.js.map +1 -1
  34. package/dist/pdf-layout.d.ts +39 -0
  35. package/dist/pdf-layout.d.ts.map +1 -0
  36. package/dist/pdf-layout.js +820 -0
  37. package/dist/pdf-layout.js.map +1 -0
  38. package/dist/pdf-pages.d.ts +45 -0
  39. package/dist/pdf-pages.d.ts.map +1 -0
  40. package/dist/pdf-pages.js +336 -0
  41. package/dist/pdf-pages.js.map +1 -0
  42. package/dist/pdf-pictures.d.ts +20 -0
  43. package/dist/pdf-pictures.d.ts.map +1 -0
  44. package/dist/pdf-pictures.js +336 -0
  45. package/dist/pdf-pictures.js.map +1 -0
  46. package/dist/plan.d.ts +13 -3
  47. package/dist/plan.d.ts.map +1 -1
  48. package/dist/plan.js +27 -18
  49. package/dist/plan.js.map +1 -1
  50. package/dist/search.d.ts +17 -4
  51. package/dist/search.d.ts.map +1 -1
  52. package/dist/search.js +90 -24
  53. package/dist/search.js.map +1 -1
  54. package/dist/stores.d.ts +7 -1
  55. package/dist/stores.d.ts.map +1 -1
  56. package/dist/stores.js +37 -5
  57. package/dist/stores.js.map +1 -1
  58. package/dist/text.d.ts +18 -4
  59. package/dist/text.d.ts.map +1 -1
  60. package/dist/text.js +155 -15
  61. package/dist/text.js.map +1 -1
  62. package/dist/tools.d.ts +11 -0
  63. package/dist/tools.d.ts.map +1 -1
  64. package/dist/tools.js +156 -16
  65. package/dist/tools.js.map +1 -1
  66. package/dist/types.d.ts +63 -3
  67. package/dist/types.d.ts.map +1 -1
  68. package/docs/api.md +56 -11
  69. package/docs/configuration.md +298 -6
  70. package/docs/getting-started.md +41 -7
  71. package/docs/how-it-works.md +77 -11
  72. package/docs/security.md +54 -6
  73. package/package.json +96 -91
  74. package/src/analyze.ts +3 -1
  75. package/src/extract.ts +105 -24
  76. package/src/gemini/chat.ts +116 -34
  77. package/src/gemini/generate.ts +66 -10
  78. package/src/gemini/index.ts +3 -3
  79. package/src/index.ts +4 -3
  80. package/src/library.ts +308 -226
  81. package/src/map-reduce.ts +69 -16
  82. package/src/node/handlers.ts +122 -122
  83. package/src/pdf-layout.ts +807 -0
  84. package/src/pdf-pages.ts +315 -0
  85. package/src/pdf-pictures.ts +324 -0
  86. package/src/plan.ts +120 -98
  87. package/src/search.ts +85 -25
  88. package/src/stores.ts +165 -132
  89. package/src/text.ts +131 -14
  90. package/src/tools.ts +408 -264
  91. package/src/types.ts +228 -168
package/src/stores.ts CHANGED
@@ -1,132 +1,165 @@
1
- import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
2
- import path from "node:path";
3
- import type { DocumentMeta, DocumentStore, StoredDocument } from "./types.js";
4
-
5
- export const DOCUMENT_ID_PATTERN = /^doc_[a-f0-9]{32}$/;
6
-
7
- function expired(meta: DocumentMeta, now = new Date()): boolean {
8
- return Date.parse(meta.expiresAt) <= now.getTime();
9
- }
10
-
11
- /** Keeps documents in process memory. Good for tests and single-process demos. */
12
- export class MemoryDocumentStore implements DocumentStore {
13
- private readonly documents = new Map<string, StoredDocument>();
14
- private readonly now: () => Date;
15
-
16
- constructor(options: { now?: () => Date } = {}) {
17
- this.now = options.now ?? (() => new Date());
18
- }
19
-
20
- async put(document: StoredDocument): Promise<void> {
21
- this.documents.set(document.meta.id, document);
22
- }
23
-
24
- async get(id: string): Promise<StoredDocument | undefined> {
25
- const document = this.documents.get(id);
26
- if (document && expired(document.meta, this.now())) {
27
- this.documents.delete(id);
28
- return undefined;
29
- }
30
- return document;
31
- }
32
-
33
- async getMeta(id: string): Promise<DocumentMeta | undefined> {
34
- return (await this.get(id))?.meta;
35
- }
36
-
37
- async delete(id: string): Promise<boolean> {
38
- return this.documents.delete(id);
39
- }
40
-
41
- async sweep(now = this.now()): Promise<number> {
42
- let removed = 0;
43
- for (const [id, document] of this.documents) {
44
- if (expired(document.meta, now)) {
45
- this.documents.delete(id);
46
- removed++;
47
- }
48
- }
49
- return removed;
50
- }
51
- }
52
-
53
- /**
54
- * Keeps each document as `<id>.txt` plus `<id>.json` in one directory, so files survive a
55
- * server restart. Only IDs matching DOCUMENT_ID_PATTERN ever reach the file system.
56
- */
57
- export class FileDocumentStore implements DocumentStore {
58
- private readonly now: () => Date;
59
-
60
- constructor(private readonly directory: string, options: { now?: () => Date } = {}) {
61
- this.now = options.now ?? (() => new Date());
62
- }
63
-
64
- private paths(id: string): { text: string; meta: string } | undefined {
65
- if (!DOCUMENT_ID_PATTERN.test(id)) return undefined;
66
- return { text: path.join(this.directory, `${id}.txt`), meta: path.join(this.directory, `${id}.json`) };
67
- }
68
-
69
- async put(document: StoredDocument): Promise<void> {
70
- const paths = this.paths(document.meta.id);
71
- if (!paths) throw new Error("Invalid document ID.");
72
- await mkdir(this.directory, { recursive: true });
73
- await writeFile(paths.text, document.text, "utf8");
74
- // Write metadata last: a document without metadata is treated as absent.
75
- await writeFile(paths.meta, JSON.stringify(document.meta), "utf8");
76
- }
77
-
78
- async getMeta(id: string): Promise<DocumentMeta | undefined> {
79
- const paths = this.paths(id);
80
- if (!paths) return undefined;
81
- let meta: DocumentMeta;
82
- try {
83
- meta = JSON.parse(await readFile(paths.meta, "utf8")) as DocumentMeta;
84
- } catch {
85
- return undefined;
86
- }
87
- if (expired(meta, this.now())) {
88
- await this.delete(id);
89
- return undefined;
90
- }
91
- return meta;
92
- }
93
-
94
- async get(id: string): Promise<StoredDocument | undefined> {
95
- const meta = await this.getMeta(id);
96
- const paths = this.paths(id);
97
- if (!meta || !paths) return undefined;
98
- try {
99
- return { meta, text: await readFile(paths.text, "utf8") };
100
- } catch {
101
- return undefined;
102
- }
103
- }
104
-
105
- async delete(id: string): Promise<boolean> {
106
- const paths = this.paths(id);
107
- if (!paths) return false;
108
- const existed = Boolean(await readFile(paths.meta, "utf8").catch(() => null));
109
- await Promise.all([rm(paths.meta, { force: true }), rm(paths.text, { force: true })]);
110
- return existed;
111
- }
112
-
113
- async sweep(now = this.now()): Promise<number> {
114
- let entries: string[];
115
- try {
116
- entries = await readdir(this.directory);
117
- } catch {
118
- return 0;
119
- }
120
- let removed = 0;
121
- for (const entry of entries) {
122
- const id = entry.replace(/\.(json|txt)$/, "");
123
- if (!entry.endsWith(".json") || !DOCUMENT_ID_PATTERN.test(id)) continue;
124
- const meta = await readFile(path.join(this.directory, entry), "utf8").then((value) => JSON.parse(value) as DocumentMeta).catch(() => null);
125
- if (!meta || expired(meta, now)) {
126
- await this.delete(id);
127
- removed++;
128
- }
129
- }
130
- return removed;
131
- }
132
- }
1
+ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import type { DocumentMeta, DocumentStore, StoredDocument } from "./types.js";
4
+
5
+ export const DOCUMENT_ID_PATTERN = /^doc_[a-f0-9]{32}$/;
6
+
7
+ function expired(meta: DocumentMeta, now = new Date()): boolean {
8
+ return Date.parse(meta.expiresAt) <= now.getTime();
9
+ }
10
+
11
+ /** Keeps documents in process memory. Good for tests and single-process demos. */
12
+ export class MemoryDocumentStore implements DocumentStore {
13
+ private readonly documents = new Map<string, StoredDocument>();
14
+ private readonly originals = new Map<string, Uint8Array>();
15
+ private readonly now: () => Date;
16
+
17
+ constructor(options: { now?: () => Date } = {}) {
18
+ this.now = options.now ?? (() => new Date());
19
+ }
20
+
21
+ async put(document: StoredDocument): Promise<void> {
22
+ this.documents.set(document.meta.id, document);
23
+ }
24
+
25
+ async get(id: string): Promise<StoredDocument | undefined> {
26
+ const document = this.documents.get(id);
27
+ if (document && expired(document.meta, this.now())) {
28
+ await this.delete(id);
29
+ return undefined;
30
+ }
31
+ return document;
32
+ }
33
+
34
+ async getMeta(id: string): Promise<DocumentMeta | undefined> {
35
+ return (await this.get(id))?.meta;
36
+ }
37
+
38
+ async delete(id: string): Promise<boolean> {
39
+ this.originals.delete(id);
40
+ return this.documents.delete(id);
41
+ }
42
+
43
+ async sweep(now = this.now()): Promise<number> {
44
+ let removed = 0;
45
+ for (const [id, document] of this.documents) {
46
+ if (expired(document.meta, now)) {
47
+ await this.delete(id);
48
+ removed++;
49
+ }
50
+ }
51
+ return removed;
52
+ }
53
+
54
+ async putOriginal(id: string, bytes: Uint8Array): Promise<void> {
55
+ // A copy: the caller may reuse its buffer after the upload.
56
+ this.originals.set(id, bytes.slice());
57
+ }
58
+
59
+ async getOriginal(id: string): Promise<Uint8Array | undefined> {
60
+ return await this.get(id) ? this.originals.get(id) : undefined;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Keeps each document as `<id>.txt` plus `<id>.json` in one directory, so files survive a
66
+ * server restart, and its original file as `<id>.bin` when one is kept. Only IDs matching
67
+ * DOCUMENT_ID_PATTERN ever reach the file system.
68
+ */
69
+ export class FileDocumentStore implements DocumentStore {
70
+ private readonly now: () => Date;
71
+
72
+ constructor(private readonly directory: string, options: { now?: () => Date } = {}) {
73
+ this.now = options.now ?? (() => new Date());
74
+ }
75
+
76
+ private paths(id: string): { text: string; meta: string; original: string } | undefined {
77
+ if (!DOCUMENT_ID_PATTERN.test(id)) return undefined;
78
+ const file = (extension: string) => path.join(this.directory, `${id}.${extension}`);
79
+ return { text: file("txt"), meta: file("json"), original: file("bin") };
80
+ }
81
+
82
+ async put(document: StoredDocument): Promise<void> {
83
+ const paths = this.paths(document.meta.id);
84
+ if (!paths) throw new Error("Invalid document ID.");
85
+ await mkdir(this.directory, { recursive: true });
86
+ await writeFile(paths.text, document.text, "utf8");
87
+ // Write metadata last: a document without metadata is treated as absent.
88
+ await writeFile(paths.meta, JSON.stringify(document.meta), "utf8");
89
+ }
90
+
91
+ async getMeta(id: string): Promise<DocumentMeta | undefined> {
92
+ const paths = this.paths(id);
93
+ if (!paths) return undefined;
94
+ let meta: DocumentMeta;
95
+ try {
96
+ meta = JSON.parse(await readFile(paths.meta, "utf8")) as DocumentMeta;
97
+ } catch {
98
+ return undefined;
99
+ }
100
+ if (expired(meta, this.now())) {
101
+ await this.delete(id);
102
+ return undefined;
103
+ }
104
+ return meta;
105
+ }
106
+
107
+ async get(id: string): Promise<StoredDocument | undefined> {
108
+ const meta = await this.getMeta(id);
109
+ const paths = this.paths(id);
110
+ if (!meta || !paths) return undefined;
111
+ try {
112
+ return { meta, text: await readFile(paths.text, "utf8") };
113
+ } catch {
114
+ return undefined;
115
+ }
116
+ }
117
+
118
+ async delete(id: string): Promise<boolean> {
119
+ const paths = this.paths(id);
120
+ if (!paths) return false;
121
+ const existed = Boolean(await readFile(paths.meta, "utf8").catch(() => null));
122
+ await Promise.all([rm(paths.meta, { force: true }), rm(paths.text, { force: true }), rm(paths.original, { force: true })]);
123
+ return existed;
124
+ }
125
+
126
+ async putOriginal(id: string, bytes: Uint8Array): Promise<void> {
127
+ const paths = this.paths(id);
128
+ if (!paths) throw new Error("Invalid document ID.");
129
+ await mkdir(this.directory, { recursive: true });
130
+ // Written before the metadata (see put): until that exists, the document is treated as absent.
131
+ await writeFile(paths.original, bytes);
132
+ }
133
+
134
+ async getOriginal(id: string): Promise<Uint8Array | undefined> {
135
+ const paths = this.paths(id);
136
+ // The metadata decides whether the document is still there. getMeta also removes an expired one.
137
+ if (!paths || !await this.getMeta(id)) return undefined;
138
+ try {
139
+ const file = await readFile(paths.original);
140
+ return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
141
+ } catch {
142
+ return undefined;
143
+ }
144
+ }
145
+
146
+ async sweep(now = this.now()): Promise<number> {
147
+ let entries: string[];
148
+ try {
149
+ entries = await readdir(this.directory);
150
+ } catch {
151
+ return 0;
152
+ }
153
+ let removed = 0;
154
+ for (const entry of entries) {
155
+ const id = entry.replace(/\.(json|txt)$/, "");
156
+ if (!entry.endsWith(".json") || !DOCUMENT_ID_PATTERN.test(id)) continue;
157
+ const meta = await readFile(path.join(this.directory, entry), "utf8").then((value) => JSON.parse(value) as DocumentMeta).catch(() => null);
158
+ if (!meta || expired(meta, now)) {
159
+ await this.delete(id);
160
+ removed++;
161
+ }
162
+ }
163
+ return removed;
164
+ }
165
+ }
package/src/text.ts CHANGED
@@ -1,13 +1,41 @@
1
1
  /** Lines longer than this are split so line-based tools always return bounded output. */
2
2
  export const MAX_LINE_CHARACTERS = 2_000;
3
3
 
4
- /** Strips a BOM, unifies line endings, and removes control characters other than tab and newline. */
4
+ /**
5
+ * Terminal escape sequences: CSI ("ESC [ 31 m"), OSC ("ESC ] ... BEL"), character-set selection
6
+ * ("ESC ( B"), and two-character escapes. Coloured logs are full of them.
7
+ */
8
+ // eslint-disable-next-line no-control-regex
9
+ const ANSI_ESCAPE = /\x1b(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)?|[ -\/]+[0-~]|[@-Z\\-_])/g;
10
+
11
+ /**
12
+ * Strips a BOM, unifies line endings, and removes terminal escape sequences and control characters
13
+ * other than tab and newline.
14
+ */
5
15
  export function normalizeText(raw: string): string {
6
- return raw
7
- .replace(/^/, "")
8
- .replace(/\r\n?/g, "\n")
9
- // eslint-disable-next-line no-control-regex
10
- .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
16
+ let text = raw.replace(/^/, "").replace(/\r\n?/g, "\n");
17
+ // Remove whole sequences first. Dropping only the ESC byte would leave "[31mERROR[0m" behind.
18
+ if (text.includes("\x1b")) text = text.replace(ANSI_ESCAPE, "");
19
+ // eslint-disable-next-line no-control-regex
20
+ return text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
21
+ }
22
+
23
+ /**
24
+ * Lowercases for case-insensitive search without changing the string's length, so an offset in the
25
+ * result points at the same character in the original. "İ" (U+0130) is the one character whose
26
+ * lowercase form is longer; it is folded to "i".
27
+ */
28
+ export function foldCase(text: string): string {
29
+ const lower = (text.includes("\u0130") ? text.replaceAll("\u0130", "i") : text).toLowerCase();
30
+ if (lower.length === text.length) return lower;
31
+ // Not expected with today's Unicode data. Fold unit by unit and keep any unit that would grow.
32
+ let out = "";
33
+ for (let index = 0; index < text.length; index++) {
34
+ const unit = text[index]!;
35
+ const folded = unit.toLowerCase();
36
+ out += folded.length === 1 ? folded : unit;
37
+ }
38
+ return out;
11
39
  }
12
40
 
13
41
  /**
@@ -37,19 +65,108 @@ export function wrapLongLines(text: string, limit = MAX_LINE_CHARACTERS): { text
37
65
  return { text: out.join("\n"), wrapped };
38
66
  }
39
67
 
68
+ // Token cost of each kind of character, fitted to Gemini's countTokens on 60 texts (prose in
69
+ // eleven languages, source code, JSON, CSV, and eight log formats; Gemini 2.5, 3.5, and 3.8 count
70
+ // identically). On those texts the estimate is between 0.98 and 1.7 times Gemini's count.
71
+ const WORD = 1.1; // A run of ASCII letters.
72
+ const CASE_CHANGE = 1.3; // "camelCase", "HTTPServer", base64: each change starts a new piece.
73
+ const LONG_LETTER = 0.18; // Each letter past the 6th of a piece (the 3rd for capitals).
74
+ const LONG_AFTER = 6;
75
+ const LONG_AFTER_CAPITALS = 3;
76
+ const VERY_LONG_LETTER = 0.5; // Each letter past the 20th: no longer a word, but a key or a sequence.
77
+ const VERY_LONG_AFTER = 20;
78
+ const DIGIT = 1.2; // Digits are about one token each, so IDs, timestamps, and numbers are dense.
79
+ const PUNCTUATION = 0.85; // The first of a run of ASCII punctuation; the rest of the run is free.
80
+ const NEWLINE = 2.2;
81
+ const TAB = 1;
82
+ const LOOSE_SPACE = 0.2; // A space before anything but a letter. A space before a word is free.
83
+ const LATIN_EXTENDED = 0.6; // é, ü, ß
84
+ const GREEK = 0.4;
85
+ const CYRILLIC = 0.3;
86
+ const HEBREW = 0.52;
87
+ const ARABIC = 0.41;
88
+ const OTHER_SCRIPT = 0.45; // Devanagari, Thai, Georgian, and other alphabets and syllabaries.
89
+ const HAN = 0.7;
90
+ const KANA = 0.56;
91
+ const HANGUL = 0.7;
92
+ const SURROGATE = 0.5; // Half of an emoji or another character outside the basic plane.
93
+ const SYMBOL = 1; // Dashes, quotes, arrows, box drawing, and anything unclassified.
94
+
40
95
  /**
41
- * A deliberately conservative token estimate: about 4 characters per token for ASCII and
42
- * 1.5 for other scripts (Hebrew, CJK, etc.). Overestimating only moves a document to the
43
- * searchable path sooner, which is safe.
96
+ * Estimates how many tokens a model will count for `text`, without calling the model.
97
+ *
98
+ * Characters per token varies a lot with the kind of text: about 4.5 for English prose, 2 for
99
+ * Hebrew, and between 1 and 2 for logs, CSV, and hex, because digits cost about a token each. A
100
+ * flat "4 characters per token" is therefore right for a novel and three times too low for a log.
101
+ * This walks the text once and prices each kind of character. It leans high, which only moves a
102
+ * document to the searchable path sooner. The one kind of text it still counts low is a long run
103
+ * of random letters in a single case with no digits (about 70% of the real count).
44
104
  */
45
105
  export function estimateTokens(text: string): number {
46
- let ascii = 0;
47
- let other = 0;
106
+ let tokens = 0;
107
+ // The current run of ASCII letters: its length since the last case change, and its casing.
108
+ let piece = 0;
109
+ let capitalsInARow = 0;
110
+ let previousWasLower = false;
111
+ let previous = 0; // 1 = space, 2 = ASCII punctuation, 0 = anything else
48
112
  for (let index = 0; index < text.length; index++) {
49
- if (text.charCodeAt(index) < 0x80) ascii++;
50
- else other++;
113
+ const code = text.charCodeAt(index);
114
+ if ((code >= 97 && code <= 122) || (code >= 65 && code <= 90)) {
115
+ const capital = code <= 90;
116
+ if (piece === 0) tokens += WORD;
117
+ else if ((capital && previousWasLower) || (!capital && capitalsInARow >= 2)) {
118
+ tokens += CASE_CHANGE;
119
+ piece = 0;
120
+ }
121
+ piece++;
122
+ if (piece > VERY_LONG_AFTER) tokens += VERY_LONG_LETTER;
123
+ else if (piece > (capital ? LONG_AFTER_CAPITALS : LONG_AFTER)) tokens += LONG_LETTER;
124
+ capitalsInARow = capital ? capitalsInARow + 1 : 0;
125
+ previousWasLower = !capital;
126
+ previous = 0;
127
+ continue;
128
+ }
129
+ piece = 0;
130
+ capitalsInARow = 0;
131
+ previousWasLower = false;
132
+ if (code === 32) {
133
+ previous = 1;
134
+ continue;
135
+ }
136
+ if (previous === 1) tokens += LOOSE_SPACE;
137
+ if (code < 0x80) {
138
+ if (code >= 48 && code <= 57) tokens += DIGIT;
139
+ else if (code === 10) tokens += NEWLINE;
140
+ else if (code === 9) tokens += TAB;
141
+ else {
142
+ if (previous !== 2) tokens += PUNCTUATION;
143
+ previous = 2;
144
+ continue;
145
+ }
146
+ previous = 0;
147
+ continue;
148
+ }
149
+ previous = 0;
150
+ if (code < 0xc0) tokens += SYMBOL;
151
+ else if (code < 0x250) tokens += LATIN_EXTENDED;
152
+ else if (code < 0x370) tokens += OTHER_SCRIPT;
153
+ else if (code < 0x400) tokens += GREEK;
154
+ else if (code < 0x530) tokens += CYRILLIC;
155
+ else if (code < 0x590) tokens += OTHER_SCRIPT;
156
+ else if (code < 0x600) tokens += HEBREW;
157
+ else if (code < 0x700) tokens += ARABIC;
158
+ else if (code < 0x2000) tokens += OTHER_SCRIPT;
159
+ else if (code < 0x2e80) tokens += SYMBOL;
160
+ else if (code < 0x3400) tokens += KANA;
161
+ else if (code < 0xac00) tokens += HAN;
162
+ else if (code < 0xd800) tokens += HANGUL;
163
+ else if (code < 0xe000) tokens += SURROGATE;
164
+ else if (code < 0xf900) tokens += SYMBOL;
165
+ else if (code < 0xfb00) tokens += HAN;
166
+ else if (code < 0xff00) tokens += OTHER_SCRIPT;
167
+ else tokens += KANA;
51
168
  }
52
- return Math.ceil(ascii / 4 + other / 1.5);
169
+ return Math.ceil(tokens);
53
170
  }
54
171
 
55
172
  /** UTF-8 byte length without allocating an encoded copy. */