@meritt/tokenmeter-wasm 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Alexey Simonenko, alexey@simonenko.dev, https://simonenko.xyz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@meritt/tokenmeter-wasm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Counts the tokens of text in o200k_base with tiktoken's algorithm and splits it into token groups on grapheme boundaries, in WebAssembly",
5
+ "keywords": [
6
+ "gpt",
7
+ "o200k_base",
8
+ "openai",
9
+ "tiktoken",
10
+ "tokenizer",
11
+ "tokens",
12
+ "wasm",
13
+ "webassembly"
14
+ ],
15
+ "license": "MIT",
16
+ "author": {
17
+ "name": "Alexey Simonenko",
18
+ "email": "alexey@simonenko.dev",
19
+ "url": "https://simonenko.xyz"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/meritt/tokenmeter.rs.git",
24
+ "directory": "packages/npm"
25
+ },
26
+ "type": "module",
27
+ "engines": {
28
+ "node": ">=26.13.0"
29
+ },
30
+ "sideEffects": false,
31
+ "exports": {
32
+ ".": "./tokenmeter.js",
33
+ "./tokenmeter.wasm": "./tokenmeter.wasm"
34
+ },
35
+ "files": [
36
+ "tokenmeter.js",
37
+ "tokenmeter.wasm"
38
+ ],
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "devEngines": {
43
+ "packageManager": {
44
+ "name": "pnpm",
45
+ "version": "^12.15.0",
46
+ "onFail": "download"
47
+ },
48
+ "runtime": {
49
+ "name": "node",
50
+ "version": "^26.13.0",
51
+ "onFail": "error"
52
+ }
53
+ }
6
54
  }
package/tokenmeter.js ADDED
@@ -0,0 +1,113 @@
1
+ const VERSION = '0.1.0';
2
+ const STATUS = ['ok', 'invalid_utf8', 'invalid_argument', 'internal'];
3
+ const OK = 0;
4
+ // tokenmeter_groups on wasm32: status, tokens, truncated, then groups as (pointer, length).
5
+ const SPLIT_SIZE = 20;
6
+
7
+ export class TokenMeterError extends Error {
8
+ constructor(code) {
9
+ super(code);
10
+ this.name = 'TokenMeterError';
11
+ this.code = code;
12
+ }
13
+ }
14
+
15
+ export async function load(source = new URL('./tokenmeter.wasm', import.meta.url)) {
16
+ const module = await compile(source);
17
+ const { exports } = await WebAssembly.instantiate(module, {});
18
+ return new TokenMeter(exports);
19
+ }
20
+
21
+ async function compile(source) {
22
+ if (source instanceof WebAssembly.Module) return source;
23
+ if (typeof source === 'string') source = new URL(source, import.meta.url);
24
+ if (source instanceof URL) {
25
+ if (source.protocol === 'file:') {
26
+ const { readFile } = await import('node:fs/promises');
27
+ return WebAssembly.compile(await readFile(source));
28
+ }
29
+ source = fetch(source);
30
+ }
31
+ if (source instanceof Promise || source instanceof Response) {
32
+ return WebAssembly.compileStreaming(source);
33
+ }
34
+ return WebAssembly.compile(source);
35
+ }
36
+
37
+ const encoder = new TextEncoder();
38
+ const decoder = new TextDecoder('utf-8', { fatal: true });
39
+
40
+ function encode(text) {
41
+ if (typeof text !== 'string') throw new TokenMeterError('invalid_argument');
42
+ // A lone surrogate has no UTF-8 form; TextEncoder would count U+FFFD instead.
43
+ if (!text.isWellFormed()) throw new TokenMeterError('invalid_utf8');
44
+ return encoder.encode(text);
45
+ }
46
+
47
+ class TokenMeter {
48
+ #x;
49
+
50
+ constructor(exports) {
51
+ this.#x = exports;
52
+ const version = typeof exports.tokenmeter_version === 'function' ? this.#cString(exports.tokenmeter_version()) : '';
53
+ if (version !== VERSION) throw new TokenMeterError('version');
54
+ this.version = VERSION;
55
+ this.encoding = this.#cString(exports.tokenmeter_encoding());
56
+ exports.tokenmeter_prepare();
57
+ }
58
+
59
+ count(text) {
60
+ const tokens = this.#with(encode(text), (p, n) => this.#x.tokenmeter_count(p, n) >>> 0);
61
+ if (tokens === 0xffffffff) throw new TokenMeterError('invalid_utf8');
62
+ return tokens;
63
+ }
64
+
65
+ split(text, limit = 200) {
66
+ if (!Number.isSafeInteger(limit) || limit < 0) throw new TokenMeterError('invalid_argument');
67
+ const bytes = encode(text);
68
+ const x = this.#x;
69
+ const out = x.tokenmeter_alloc(SPLIT_SIZE);
70
+ if (out === 0) throw new TokenMeterError('internal');
71
+ try {
72
+ this.#with(bytes, (p, n) => x.tokenmeter_split(p, n, limit, out));
73
+ // Read only after the call: memory may have grown and detached old views.
74
+ const view = new DataView(x.memory.buffer, out, SPLIT_SIZE);
75
+ const status = view.getUint32(0, true);
76
+ if (status !== OK) {
77
+ throw new TokenMeterError(STATUS[status] ?? 'internal');
78
+ }
79
+ const pairs = new Uint32Array(x.memory.buffer, view.getUint32(12, true), view.getUint32(16, true) * 2);
80
+ const groups = [];
81
+ let start = 0;
82
+ for (let i = 0; i < pairs.length; i += 2) {
83
+ groups.push({ text: decoder.decode(bytes.subarray(start, pairs[i])), tokens: pairs[i + 1] });
84
+ start = pairs[i];
85
+ }
86
+ const result = { tokens: view.getUint32(4, true), groups, truncated: view.getUint32(8, true) !== 0 };
87
+ x.tokenmeter_split_free(out);
88
+ return result;
89
+ } finally {
90
+ x.tokenmeter_dealloc(out, SPLIT_SIZE);
91
+ }
92
+ }
93
+
94
+ #with(bytes, use) {
95
+ const x = this.#x;
96
+ const n = bytes.length;
97
+ const p = x.tokenmeter_alloc(n);
98
+ if (n > 0 && p === 0) throw new TokenMeterError('invalid_argument');
99
+ try {
100
+ new Uint8Array(x.memory.buffer, p, n).set(bytes);
101
+ return use(p, n);
102
+ } finally {
103
+ x.tokenmeter_dealloc(p, n);
104
+ }
105
+ }
106
+
107
+ #cString(p) {
108
+ const memory = new Uint8Array(this.#x.memory.buffer);
109
+ let end = p;
110
+ while (memory[end] !== 0) end++;
111
+ return decoder.decode(memory.subarray(p, end));
112
+ }
113
+ }
Binary file
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.