@virgo-nsh/highlighter 0.0.0-stage → 0.1.1

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 (82) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +21 -0
  3. package/README.md +88 -2
  4. package/dist/catalog/index.d.ts +1 -0
  5. package/dist/catalog/index.js +2 -0
  6. package/dist/highlighter.d.ts +39 -0
  7. package/dist/highlighter.js +192 -0
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.js +1 -0
  10. package/dist/internal/browser/ONNX-RUNTIME-LICENSE.txt +21 -0
  11. package/dist/internal/browser/assets.d.ts +52 -0
  12. package/dist/internal/browser/assets.js +181 -0
  13. package/dist/internal/browser/decode.d.ts +16 -0
  14. package/dist/internal/browser/decode.js +75 -0
  15. package/dist/internal/browser/engine.d.ts +4 -0
  16. package/dist/internal/browser/engine.js +107 -0
  17. package/dist/internal/browser/index.d.ts +13 -0
  18. package/dist/internal/browser/index.js +135 -0
  19. package/dist/internal/browser/ort-wasm-simd-threaded.mjs +60 -0
  20. package/dist/internal/browser/ort-wasm-simd-threaded.wasm +0 -0
  21. package/dist/internal/browser/sessions.d.ts +9 -0
  22. package/dist/internal/browser/sessions.js +57 -0
  23. package/dist/internal/browser/structured.d.ts +9 -0
  24. package/dist/internal/browser/structured.js +88 -0
  25. package/dist/internal/browser/types.d.ts +37 -0
  26. package/dist/internal/browser/types.js +1 -0
  27. package/dist/internal/browser/windowing.d.ts +7 -0
  28. package/dist/internal/browser/windowing.js +81 -0
  29. package/dist/internal/browser/worker.d.ts +1 -0
  30. package/dist/internal/browser/worker.js +22 -0
  31. package/dist/internal/core/catalog/code.d.ts +2 -0
  32. package/dist/internal/core/catalog/code.js +371 -0
  33. package/dist/internal/core/catalog/formats.d.ts +2 -0
  34. package/dist/internal/core/catalog/formats.js +144 -0
  35. package/dist/internal/core/catalog/index.d.ts +15 -0
  36. package/dist/internal/core/catalog/index.js +64 -0
  37. package/dist/internal/core/catalog/types.d.ts +20 -0
  38. package/dist/internal/core/catalog/types.js +1 -0
  39. package/dist/internal/core/composition/html.d.ts +11 -0
  40. package/dist/internal/core/composition/html.js +61 -0
  41. package/dist/internal/core/composition/markdown.d.ts +10 -0
  42. package/dist/internal/core/composition/markdown.js +66 -0
  43. package/dist/internal/core/composition/php.d.ts +9 -0
  44. package/dist/internal/core/composition/php.js +54 -0
  45. package/dist/internal/core/composition/svelte.d.ts +9 -0
  46. package/dist/internal/core/composition/svelte.js +67 -0
  47. package/dist/internal/core/composition/vue.d.ts +9 -0
  48. package/dist/internal/core/composition/vue.js +69 -0
  49. package/dist/internal/core/highlighter.d.ts +11 -0
  50. package/dist/internal/core/highlighter.js +26 -0
  51. package/dist/internal/core/index.d.ts +7 -0
  52. package/dist/internal/core/index.js +3 -0
  53. package/dist/internal/core/language.d.ts +2 -0
  54. package/dist/internal/core/language.js +2 -0
  55. package/dist/internal/core/manifest.d.ts +8 -0
  56. package/dist/internal/core/manifest.js +1 -0
  57. package/dist/internal/core/pack.d.ts +23 -0
  58. package/dist/internal/core/pack.js +1 -0
  59. package/dist/internal/core/registry.d.ts +6 -0
  60. package/dist/internal/core/registry.js +14 -0
  61. package/dist/internal/core/result.d.ts +30 -0
  62. package/dist/internal/core/result.js +1 -0
  63. package/dist/internal/core/schema.d.ts +10 -0
  64. package/dist/internal/core/schema.js +1 -0
  65. package/dist/internal/html/index.d.ts +1 -0
  66. package/dist/internal/html/index.js +1 -0
  67. package/dist/internal/html/render.d.ts +8 -0
  68. package/dist/internal/html/render.js +71 -0
  69. package/dist/model-assets.d.ts +14 -0
  70. package/dist/model-assets.js +895 -0
  71. package/dist/remote.d.ts +24 -0
  72. package/dist/remote.js +129 -0
  73. package/dist/theme.css +1344 -0
  74. package/dist/themes/all.css +2150 -0
  75. package/dist/themes/base.css +942 -0
  76. package/dist/themes/contrast.css +1344 -0
  77. package/dist/themes/default.css +1344 -0
  78. package/dist/themes/index.d.ts +2 -0
  79. package/dist/themes/index.js +17 -0
  80. package/dist/themes/languages/typescript.css +2 -0
  81. package/dist/themes/muted.css +1344 -0
  82. package/package.json +43 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1
4
+
5
+ - Add `highlighter.observeElement()` for opt-in, one-time highlighting of existing code blocks as they enter the viewport or a custom scroll container.
6
+ - Support `rootMargin` to start highlighting before the block becomes visible. The default margin is `0px`.
7
+ - Return a cleanup function that stops observation and skips late rendering when a block is removed or reused.
8
+
9
+ ## 0.1.0
10
+
11
+ - Publish the browser highlighter as `@virgo-nsh/highlighter`, with semantic spans, escaped HTML, themes, and on-demand loading of separately hosted models.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Neural Semantic Highlighting contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, 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,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,89 @@
1
- # Temporary Holding Version
1
+ # Virgo NSH
2
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.
3
+ Neural semantic highlighting for source code and file formats. NSH runs ONNX
4
+ inference in a browser Web Worker and returns escaped HTML and semantic spans.
5
+
6
+ [Try the live Playground](https://nsh.virgogalaxy.com/) ·
7
+ [React, Vue and vanilla JS](https://github.com/virgo-galaxy/virgo-nsh#react-vue-and-vanilla-javascript) ·
8
+ [简体中文](https://github.com/virgo-galaxy/virgo-nsh/blob/main/README.zh-CN.md)
9
+
10
+ ## Install
11
+
12
+ In a frontend project with an ESM bundler such as Vite:
13
+
14
+ ```bash
15
+ npm install @virgo-nsh/highlighter
16
+ ```
17
+
18
+ ## Serve model assets
19
+
20
+ The npm package includes the API, HTML renderer, CSS themes and browser runtime.
21
+ Serve the ONNX models and their JSON metadata from your app or a static host.
22
+ The browser downloads the files on first use and runs inference locally.
23
+
24
+ For versions 0.1.0 and 0.1.1, download and unpack the
25
+ [matching model source snapshot](https://github.com/virgo-galaxy/virgo-nsh/archive/7109bac49340b94ad5350778e32ee0d4196c5698.tar.gz).
26
+ From its root, export the model families you need with Node.js 24 and pnpm 11:
27
+
28
+ ```bash
29
+ pnpm install --frozen-lockfile
30
+ pnpm build:packages
31
+ node scripts/export-model-assets.mjs --models typescript,css
32
+ ```
33
+
34
+ For a Vite app, copy the contents of `artifacts/browser/models/` to
35
+ `public/models/` and keep the `v1/` directory intact. Set `modelBaseUrl` to
36
+ `/models/`. For a separate host, set it to the HTTPS directory that contains
37
+ `v1/` and allow cross-origin reads. Use `resolveAssetUrl` for signed URLs.
38
+ See the [model delivery guide](https://github.com/virgo-galaxy/virgo-nsh/blob/main/docs/model-delivery.md).
39
+
40
+ ## Highlight a code block
41
+
42
+ Add `<div id="example"></div>` to the page and use this in your client entry:
43
+
44
+ ```js
45
+ import { createHighlighter } from "@virgo-nsh/highlighter";
46
+ import "@virgo-nsh/highlighter/theme.css";
47
+
48
+ const highlighter = createHighlighter({
49
+ modelBaseUrl: "/models/",
50
+ languages: ["tsx", "scss"],
51
+ });
52
+
53
+ const { html } = await highlighter.highlight("const App = () => <button>Hello</button>;", {
54
+ language: "tsx",
55
+ });
56
+ document.querySelector("#example").innerHTML = html;
57
+ ```
58
+
59
+ Reuse the highlighter across code blocks and call `highlighter.close()` when the
60
+ app is done with it. Serve the app over HTTPS or localhost in a browser with
61
+ module Workers, WebAssembly SIMD and Web Crypto.
62
+
63
+ Use `@virgo-nsh/highlighter/catalog` to list content types. Load all presets with
64
+ `@virgo-nsh/highlighter/themes.css` and see the
65
+ [theme guide](https://github.com/virgo-galaxy/virgo-nsh/blob/main/docs/themes.md)
66
+ for light and dark modes and custom CSS.
67
+
68
+ ## Highlight on scroll
69
+
70
+ Use `observeElement()` to highlight an existing `<code>` or `<pre><code>` block
71
+ once, when it comes into view.
72
+
73
+ ```ts
74
+ const stop = highlighter.observeElement(codeElement, {
75
+ language: "tsx",
76
+ rootMargin: "128px",
77
+ });
78
+
79
+ // Call stop() when the block is removed or reused.
80
+ ```
81
+
82
+ The default root is the viewport and the default margin is `0px`. Set `root`
83
+ to use a scroll container. Without Intersection Observer, highlighting starts
84
+ immediately. The optional `onError` callback receives inference errors.
85
+
86
+ ## License
87
+
88
+ The project's code and documentation are licensed under MIT. The package
89
+ includes the `LICENSE` file and the original ONNX Runtime license notice.
@@ -0,0 +1 @@
1
+ export { contentCategories, type ContentCategory, type ContentType, contentTypes, documentKindForFilename, getContentType, normalizeLanguageId, } from "../internal/core/catalog/index.js";
@@ -0,0 +1,2 @@
1
+ // Metadata-only entry: importing this module does not import models, WASM or workers.
2
+ export { contentCategories, contentTypes, documentKindForFilename, getContentType, normalizeLanguageId, } from "../internal/core/catalog/index.js";
@@ -0,0 +1,39 @@
1
+ import { type BrowserModel, type BrowserRuntimeOptions } from "./internal/browser/index.js";
2
+ import { type HighlightRequest, type HighlightResult } from "./internal/core/index.js";
3
+ import { type RemoteModelOptions } from "./remote.js";
4
+ export type { ModelAssetRequest, RemoteModelOptions } from "./remote.js";
5
+ export type { BrowserRuntimeOptions, ModelCacheOptions } from "./internal/browser/index.js";
6
+ export { clearModelCache, ModelAssetError } from "./internal/browser/index.js";
7
+ export interface HighlighterOptions extends RemoteModelOptions, BrowserRuntimeOptions {
8
+ /** Local descriptors, or content IDs/aliases when a remote source is configured. */
9
+ languages?: readonly (BrowserModel | string)[];
10
+ }
11
+ export interface HighlightedCode {
12
+ language: string;
13
+ /** Escaped token markup for an existing <pre class="nsh"><code>. */
14
+ value: string;
15
+ /** Complete <pre class="nsh"><code> markup, ready for insertion. */
16
+ html: string;
17
+ result: HighlightResult;
18
+ }
19
+ export interface ObserveElementOptions extends Pick<IntersectionObserverInit, "root" | "rootMargin"> {
20
+ language?: string;
21
+ /** Called if highlighting fails. The original source stays in the code block. */
22
+ onError?: (error: unknown) => void;
23
+ }
24
+ export interface BrowserHighlighter {
25
+ highlight(code: string, options: {
26
+ language: string;
27
+ }): Promise<HighlightedCode>;
28
+ highlightTokens(request: HighlightRequest): Promise<HighlightResult>;
29
+ highlightElement(element: HTMLElement, options?: {
30
+ language?: string;
31
+ }): Promise<HighlightedCode>;
32
+ /** Highlight once on intersection and return a function that stops observation and rendering. */
33
+ observeElement(element: HTMLElement, options?: ObserveElementOptions): () => void;
34
+ supports(language: string): boolean;
35
+ languages(): readonly string[];
36
+ close(): void;
37
+ }
38
+ /** Configure selected models explicitly; no Node/Python imports or source uploads. */
39
+ export declare function createHighlighter(options?: HighlighterOptions): BrowserHighlighter;
@@ -0,0 +1,192 @@
1
+ import { BrowserRuntime } from "./internal/browser/index.js";
2
+ import { createHighlighter as createCoreHighlighter, normalizeLanguageId, } from "./internal/core/index.js";
3
+ import { createCompositeHtmlPack } from "./internal/core/composition/html.js";
4
+ import { createCompositeMarkdownPack } from "./internal/core/composition/markdown.js";
5
+ import { createCompositePhpPack } from "./internal/core/composition/php.js";
6
+ import { createCompositeSveltePack } from "./internal/core/composition/svelte.js";
7
+ import { createCompositeVuePack } from "./internal/core/composition/vue.js";
8
+ import { renderCodeToHtml, renderToHtml } from "./internal/html/index.js";
9
+ import { RemoteModelSource } from "./remote.js";
10
+ export { clearModelCache, ModelAssetError } from "./internal/browser/index.js";
11
+ function applyElementHighlight(element, result) {
12
+ element.innerHTML = result.value;
13
+ const wrapper = element.parentElement?.tagName === "PRE" ? element.parentElement : element;
14
+ wrapper.classList.add("nsh");
15
+ wrapper.dataset.language = result.language;
16
+ }
17
+ /** Configure selected models explicitly; no Node/Python imports or source uploads. */
18
+ export function createHighlighter(options = {}) {
19
+ const runtime = new BrowserRuntime(options);
20
+ const base = new Map();
21
+ const remote = options.modelBaseUrl !== undefined || options.resolveAssetUrl !== undefined
22
+ ? new RemoteModelSource(options)
23
+ : undefined;
24
+ const models = new Map();
25
+ function collect(model) {
26
+ const previous = models.get(model.id);
27
+ if (previous && previous.sha256 !== model.sha256)
28
+ throw new Error(`Conflicting model versions: ${model.id}`);
29
+ if (previous)
30
+ return;
31
+ models.set(model.id, model);
32
+ for (const dependency of model.dependencies ?? [])
33
+ collect(dependency);
34
+ }
35
+ if (remote) {
36
+ const languages = options.languages;
37
+ if (languages?.some((language) => typeof language !== "string"))
38
+ throw new Error("Remote model selection accepts content IDs; use local descriptors without a remote source");
39
+ for (const asset of remote.select(languages))
40
+ base.set(asset.id, remote.createPack(asset, runtime));
41
+ }
42
+ else {
43
+ for (const model of options.languages ?? []) {
44
+ if (typeof model === "string")
45
+ throw new Error("Set modelBaseUrl or resolveAssetUrl to select remote languages by name");
46
+ collect(model);
47
+ }
48
+ for (const model of models.values())
49
+ base.set(model.id, runtime.createPack(model));
50
+ }
51
+ if (!base.size)
52
+ throw new Error("Provide language model descriptors, a modelBaseUrl or a resolveAssetUrl");
53
+ const packs = [...base].map(([id, pack]) => id === "markdown"
54
+ ? createCompositeMarkdownPack({
55
+ base: pack,
56
+ resolveLanguage: (name) => {
57
+ const kind = normalizeLanguageId(name);
58
+ return kind !== "markdown" && core.supports(kind) ? kind : undefined;
59
+ },
60
+ highlightEmbedded: (request) => core.highlight(request),
61
+ })
62
+ : id === "php"
63
+ ? createCompositePhpPack({
64
+ base: pack,
65
+ highlightEmbedded: (request) => core.highlight(request),
66
+ })
67
+ : id === "html"
68
+ ? createCompositeHtmlPack({
69
+ base: pack,
70
+ highlightEmbedded: (request) => core.highlight(request),
71
+ })
72
+ : id === "vue"
73
+ ? createCompositeVuePack({
74
+ base: pack,
75
+ highlightEmbedded: (request) => core.highlight(request),
76
+ })
77
+ : id === "svelte"
78
+ ? createCompositeSveltePack({
79
+ base: pack,
80
+ highlightEmbedded: (request) => core.highlight(request),
81
+ })
82
+ : pack);
83
+ const core = createCoreHighlighter({ packs });
84
+ let closed = false;
85
+ const pending = new Set();
86
+ const observations = new Set();
87
+ const infer = (request) => {
88
+ if (closed)
89
+ return Promise.reject(new Error("Browser highlighter is closed"));
90
+ return new Promise((resolve, reject) => {
91
+ pending.add(reject);
92
+ core.highlight(request).then((result) => {
93
+ pending.delete(reject);
94
+ resolve(result);
95
+ }, (error) => {
96
+ pending.delete(reject);
97
+ reject(error);
98
+ });
99
+ });
100
+ };
101
+ const kindFor = normalizeLanguageId;
102
+ const highlight = async (code, { language }) => {
103
+ const documentKind = kindFor(language);
104
+ const result = await infer({ source: code, documentKind });
105
+ const request = { source: code, documentKind, result };
106
+ return {
107
+ language: documentKind,
108
+ result,
109
+ value: renderCodeToHtml(request),
110
+ html: renderToHtml(request),
111
+ };
112
+ };
113
+ const highlightElementSource = async (element, language, source = element.textContent ?? "") => {
114
+ const kind = language ??
115
+ element.dataset.language ??
116
+ [...element.classList].find((name) => name.startsWith("language-"))?.slice(9) ??
117
+ element.parentElement?.dataset.language;
118
+ if (!kind)
119
+ throw new Error("Set a language, for example language-tsx or data-language=tsx");
120
+ return highlight(source, { language: kind });
121
+ };
122
+ return {
123
+ highlight,
124
+ highlightTokens: ({ source, documentKind }) => infer({ source, documentKind: kindFor(documentKind) }),
125
+ async highlightElement(element, { language } = {}) {
126
+ const result = await highlightElementSource(element, language);
127
+ applyElementHighlight(element, result);
128
+ return result;
129
+ },
130
+ observeElement(element, { language, root, rootMargin, onError } = {}) {
131
+ if (closed)
132
+ throw new Error("Browser highlighter is closed");
133
+ let observer;
134
+ let started = false;
135
+ let stopped = false;
136
+ const stop = () => {
137
+ stopped = true;
138
+ observer?.disconnect();
139
+ observations.delete(stop);
140
+ };
141
+ const highlightOnce = async () => {
142
+ if (started || stopped)
143
+ return;
144
+ started = true;
145
+ observer?.disconnect();
146
+ const code = (element.tagName === "PRE" && element.querySelector(":scope > code")) ||
147
+ element;
148
+ const source = code.textContent ?? "";
149
+ try {
150
+ const result = await highlightElementSource(code, language, source);
151
+ // The consumer can replace the code node or update its text during inference.
152
+ if (!stopped &&
153
+ (code === element || code.parentElement === element) &&
154
+ (code.textContent ?? "") === source) {
155
+ applyElementHighlight(code, result);
156
+ }
157
+ }
158
+ catch (error) {
159
+ if (!stopped)
160
+ onError?.(error);
161
+ }
162
+ finally {
163
+ stop();
164
+ }
165
+ };
166
+ if (typeof IntersectionObserver !== "undefined") {
167
+ observer = new IntersectionObserver((entries) => {
168
+ if (entries.some((entry) => entry.isIntersecting))
169
+ void highlightOnce();
170
+ }, { root, rootMargin });
171
+ }
172
+ observations.add(stop);
173
+ if (observer)
174
+ observer.observe(element);
175
+ else
176
+ void highlightOnce();
177
+ return stop;
178
+ },
179
+ supports: (language) => core.supports(kindFor(language)),
180
+ languages: () => core.documentKinds(),
181
+ close: () => {
182
+ closed = true;
183
+ for (const stop of observations)
184
+ stop();
185
+ for (const reject of pending)
186
+ reject(new Error("Browser highlighter is closed"));
187
+ pending.clear();
188
+ remote?.close();
189
+ runtime.close();
190
+ },
191
+ };
192
+ }
@@ -0,0 +1 @@
1
+ export { type BrowserHighlighter, type BrowserRuntimeOptions, clearModelCache, createHighlighter, type HighlightedCode, type HighlighterOptions, ModelAssetError, type ModelAssetRequest, type ModelCacheOptions, type ObserveElementOptions, type RemoteModelOptions, } from "./highlighter.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { clearModelCache, createHighlighter, ModelAssetError, } from "./highlighter.js";
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Microsoft Corporation
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, 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,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,52 @@
1
+ export interface ModelCacheOptions {
2
+ persistent?: boolean;
3
+ /** Best-effort shared CacheStorage budget, in bytes. */
4
+ maxBytes?: number;
5
+ }
6
+ export interface BrowserRuntimeOptions {
7
+ cache?: ModelCacheOptions;
8
+ maxLoadedModels?: number;
9
+ downloadTimeoutMs?: number;
10
+ }
11
+ export interface RuntimePolicy {
12
+ cache: {
13
+ persistent: boolean;
14
+ maxBytes: number;
15
+ };
16
+ maxLoadedModels: number;
17
+ downloadTimeoutMs: number;
18
+ }
19
+ export declare function runtimePolicy(options?: BrowserRuntimeOptions): RuntimePolicy;
20
+ type ErrorCode = "http" | "network" | "timeout" | "integrity";
21
+ export interface ModelAssetFailure {
22
+ name: "ModelAssetError";
23
+ code: ErrorCode;
24
+ modelId: string;
25
+ kind: "model" | "metadata";
26
+ message: string;
27
+ status?: number;
28
+ }
29
+ export declare class ModelAssetError extends Error {
30
+ readonly code: ErrorCode;
31
+ readonly modelId: string;
32
+ readonly kind: "model" | "metadata";
33
+ readonly status?: number | undefined;
34
+ readonly name = "ModelAssetError";
35
+ constructor(code: ErrorCode, modelId: string, kind: "model" | "metadata", status?: number | undefined);
36
+ toJSON(): ModelAssetFailure;
37
+ }
38
+ export declare function clearModelCache(): Promise<boolean>;
39
+ interface AssetRequest {
40
+ modelId: string;
41
+ kind: "model" | "metadata";
42
+ sha256: string;
43
+ url(): string | Promise<string>;
44
+ signal?: AbortSignal;
45
+ }
46
+ /** Cache keys contain only digests; neither source text nor signed URLs are persisted. */
47
+ export declare class ModelAssetCache {
48
+ #private;
49
+ constructor(options?: BrowserRuntimeOptions);
50
+ load(request: AssetRequest): Promise<ArrayBuffer>;
51
+ }
52
+ export {};
@@ -0,0 +1,181 @@
1
+ export function runtimePolicy(options = {}) {
2
+ const result = {
3
+ cache: {
4
+ persistent: options.cache?.persistent ?? true,
5
+ maxBytes: options.cache?.maxBytes ?? 64_000_000,
6
+ },
7
+ maxLoadedModels: options.maxLoadedModels ?? 4,
8
+ downloadTimeoutMs: options.downloadTimeoutMs ?? 30_000,
9
+ };
10
+ if (typeof result.cache.persistent !== "boolean" ||
11
+ !Number.isSafeInteger(result.cache.maxBytes) ||
12
+ result.cache.maxBytes < 0 ||
13
+ !Number.isInteger(result.maxLoadedModels) ||
14
+ result.maxLoadedModels < 1 ||
15
+ !Number.isInteger(result.downloadTimeoutMs) ||
16
+ result.downloadTimeoutMs < 1 ||
17
+ result.downloadTimeoutMs > 2_147_483_647)
18
+ throw new Error("Invalid browser model cache or download policy");
19
+ return result;
20
+ }
21
+ export class ModelAssetError extends Error {
22
+ code;
23
+ modelId;
24
+ kind;
25
+ status;
26
+ name = "ModelAssetError";
27
+ constructor(code, modelId, kind, status) {
28
+ super(code === "http"
29
+ ? `Unable to load ${modelId} ${kind} (${status})`
30
+ : code === "timeout"
31
+ ? `Loading ${modelId} ${kind} timed out; retry or check the resource host`
32
+ : code === "integrity"
33
+ ? `Browser model${kind === "metadata" ? " metadata" : ""} integrity mismatch: ${modelId}`
34
+ : `Unable to load ${modelId} ${kind}; check network access and CORS`);
35
+ this.code = code;
36
+ this.modelId = modelId;
37
+ this.kind = kind;
38
+ this.status = status;
39
+ }
40
+ toJSON() {
41
+ return {
42
+ name: this.name,
43
+ code: this.code,
44
+ modelId: this.modelId,
45
+ kind: this.kind,
46
+ message: this.message,
47
+ status: this.status,
48
+ };
49
+ }
50
+ }
51
+ const CACHE_NAME = "nsh-model-assets-v1";
52
+ const keyFor = (sha256) => `https://nsh-model-cache.invalid/v1/${sha256}`;
53
+ const hash = async (bytes) => Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (byte) => byte.toString(16).padStart(2, "0")).join("");
54
+ export async function clearModelCache() {
55
+ try {
56
+ return typeof caches !== "undefined" && (await caches.delete(CACHE_NAME));
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ }
62
+ /** Cache keys contain only digests; neither source text nor signed URLs are persisted. */
63
+ export class ModelAssetCache {
64
+ #policy;
65
+ #disabled = false;
66
+ constructor(options = {}) {
67
+ this.#policy = runtimePolicy(options);
68
+ }
69
+ async #open() {
70
+ if (!this.#policy.cache.persistent || !this.#policy.cache.maxBytes || this.#disabled)
71
+ return;
72
+ try {
73
+ return typeof caches === "undefined" ? undefined : await caches.open(CACHE_NAME);
74
+ }
75
+ catch {
76
+ this.#disabled = true;
77
+ return;
78
+ }
79
+ }
80
+ async #write(cache, key, bytes) {
81
+ if (bytes.byteLength > this.#policy.cache.maxBytes)
82
+ return;
83
+ try {
84
+ await cache.put(key, new Response(bytes.slice(0), {
85
+ headers: {
86
+ "X-NSH-Bytes": String(bytes.byteLength),
87
+ "X-NSH-Accessed": String(Date.now()),
88
+ },
89
+ }));
90
+ const entries = await Promise.all((await cache.keys()).map(async (request) => {
91
+ const response = await cache.match(request);
92
+ return {
93
+ request,
94
+ bytes: Number(response?.headers.get("X-NSH-Bytes") ?? 0),
95
+ accessed: Number(response?.headers.get("X-NSH-Accessed") ?? 0),
96
+ };
97
+ }));
98
+ let total = entries.reduce((sum, entry) => sum + entry.bytes, 0);
99
+ for (const entry of entries.sort((a, b) => a.accessed - b.accessed)) {
100
+ if (total <= this.#policy.cache.maxBytes)
101
+ break;
102
+ await cache.delete(entry.request);
103
+ total -= entry.bytes;
104
+ }
105
+ }
106
+ catch {
107
+ this.#disabled = true;
108
+ }
109
+ }
110
+ async load(request) {
111
+ const controller = new AbortController();
112
+ const cancel = () => controller.abort(request.signal?.reason);
113
+ if (request.signal?.aborted)
114
+ cancel();
115
+ else
116
+ request.signal?.addEventListener("abort", cancel, { once: true });
117
+ const timer = setTimeout(() => controller.abort(new ModelAssetError("timeout", request.modelId, request.kind)), this.#policy.downloadTimeoutMs);
118
+ let onAbort;
119
+ const interrupted = new Promise((_, reject) => {
120
+ onAbort = () => reject(controller.signal.reason);
121
+ if (controller.signal.aborted)
122
+ onAbort();
123
+ else
124
+ controller.signal.addEventListener("abort", onAbort, { once: true });
125
+ });
126
+ const operation = (async () => {
127
+ const cache = await this.#open();
128
+ const key = keyFor(request.sha256);
129
+ if (cache) {
130
+ try {
131
+ const cached = await cache.match(key);
132
+ if (cached) {
133
+ const bytes = await cached.arrayBuffer();
134
+ if ((await hash(bytes)) === request.sha256) {
135
+ controller.signal.throwIfAborted();
136
+ await this.#write(cache, key, bytes);
137
+ return bytes;
138
+ }
139
+ await cache.delete(key);
140
+ }
141
+ }
142
+ catch (error) {
143
+ controller.signal.throwIfAborted();
144
+ void error;
145
+ this.#disabled = true;
146
+ }
147
+ }
148
+ controller.signal.throwIfAborted();
149
+ const url = await request.url();
150
+ controller.signal.throwIfAborted();
151
+ let response;
152
+ let bytes;
153
+ try {
154
+ response = await fetch(url, { signal: controller.signal });
155
+ if (!response.ok)
156
+ throw new ModelAssetError("http", request.modelId, request.kind, response.status);
157
+ bytes = await response.arrayBuffer();
158
+ }
159
+ catch (error) {
160
+ controller.signal.throwIfAborted();
161
+ if (error instanceof ModelAssetError)
162
+ throw error;
163
+ throw new ModelAssetError("network", request.modelId, request.kind);
164
+ }
165
+ if ((await hash(bytes)) !== request.sha256)
166
+ throw new ModelAssetError("integrity", request.modelId, request.kind);
167
+ controller.signal.throwIfAborted();
168
+ if (cache && !this.#disabled)
169
+ await this.#write(cache, key, bytes);
170
+ return bytes;
171
+ })();
172
+ try {
173
+ return await Promise.race([operation, interrupted]);
174
+ }
175
+ finally {
176
+ clearTimeout(timer);
177
+ request.signal?.removeEventListener("abort", cancel);
178
+ controller.signal.removeEventListener("abort", onAbort);
179
+ }
180
+ }
181
+ }
@@ -0,0 +1,16 @@
1
+ import type { HighlightResult, SemanticSpan } from "../core/index.js";
2
+ import type { BrowserModel } from "./types.js";
3
+ /** Original UTF-8 starts and UTF-16 offsets; no source-language parsing. */
4
+ export declare function characterMap(source: string): {
5
+ bytes: number[];
6
+ units: number[];
7
+ };
8
+ export declare function argmax(data: ArrayLike<number>, offset: number, width: number): number;
9
+ /** Stream committed model windows; retain only one pending span's logits. */
10
+ export declare class SpanDecoder {
11
+ #private;
12
+ readonly spans: SemanticSpan[];
13
+ constructor(model: BrowserModel);
14
+ append(start: number, end: number, boundary: number, types: ArrayLike<number>, typeOffset: number, modifiers: ArrayLike<number>, modifierOffset: number): void;
15
+ finish(): HighlightResult;
16
+ }