@virgo-nsh/highlighter 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 +21 -0
- package/README.md +70 -2
- package/dist/catalog/index.d.ts +1 -0
- package/dist/catalog/index.js +2 -0
- package/dist/highlighter.d.ts +32 -0
- package/dist/highlighter.js +134 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/internal/browser/ONNX-RUNTIME-LICENSE.txt +21 -0
- package/dist/internal/browser/assets.d.ts +52 -0
- package/dist/internal/browser/assets.js +181 -0
- package/dist/internal/browser/decode.d.ts +16 -0
- package/dist/internal/browser/decode.js +75 -0
- package/dist/internal/browser/engine.d.ts +4 -0
- package/dist/internal/browser/engine.js +107 -0
- package/dist/internal/browser/index.d.ts +13 -0
- package/dist/internal/browser/index.js +135 -0
- package/dist/internal/browser/ort-wasm-simd-threaded.mjs +60 -0
- package/dist/internal/browser/ort-wasm-simd-threaded.wasm +0 -0
- package/dist/internal/browser/sessions.d.ts +9 -0
- package/dist/internal/browser/sessions.js +57 -0
- package/dist/internal/browser/structured.d.ts +9 -0
- package/dist/internal/browser/structured.js +88 -0
- package/dist/internal/browser/types.d.ts +37 -0
- package/dist/internal/browser/types.js +1 -0
- package/dist/internal/browser/windowing.d.ts +7 -0
- package/dist/internal/browser/windowing.js +81 -0
- package/dist/internal/browser/worker.d.ts +1 -0
- package/dist/internal/browser/worker.js +22 -0
- package/dist/internal/core/catalog/code.d.ts +2 -0
- package/dist/internal/core/catalog/code.js +371 -0
- package/dist/internal/core/catalog/formats.d.ts +2 -0
- package/dist/internal/core/catalog/formats.js +144 -0
- package/dist/internal/core/catalog/index.d.ts +15 -0
- package/dist/internal/core/catalog/index.js +64 -0
- package/dist/internal/core/catalog/types.d.ts +20 -0
- package/dist/internal/core/catalog/types.js +1 -0
- package/dist/internal/core/composition/html.d.ts +11 -0
- package/dist/internal/core/composition/html.js +61 -0
- package/dist/internal/core/composition/markdown.d.ts +10 -0
- package/dist/internal/core/composition/markdown.js +66 -0
- package/dist/internal/core/composition/php.d.ts +9 -0
- package/dist/internal/core/composition/php.js +54 -0
- package/dist/internal/core/composition/svelte.d.ts +9 -0
- package/dist/internal/core/composition/svelte.js +67 -0
- package/dist/internal/core/composition/vue.d.ts +9 -0
- package/dist/internal/core/composition/vue.js +69 -0
- package/dist/internal/core/highlighter.d.ts +11 -0
- package/dist/internal/core/highlighter.js +26 -0
- package/dist/internal/core/index.d.ts +7 -0
- package/dist/internal/core/index.js +3 -0
- package/dist/internal/core/language.d.ts +2 -0
- package/dist/internal/core/language.js +2 -0
- package/dist/internal/core/manifest.d.ts +8 -0
- package/dist/internal/core/manifest.js +1 -0
- package/dist/internal/core/pack.d.ts +23 -0
- package/dist/internal/core/pack.js +1 -0
- package/dist/internal/core/registry.d.ts +6 -0
- package/dist/internal/core/registry.js +14 -0
- package/dist/internal/core/result.d.ts +30 -0
- package/dist/internal/core/result.js +1 -0
- package/dist/internal/core/schema.d.ts +10 -0
- package/dist/internal/core/schema.js +1 -0
- package/dist/internal/html/index.d.ts +1 -0
- package/dist/internal/html/index.js +1 -0
- package/dist/internal/html/render.d.ts +8 -0
- package/dist/internal/html/render.js +71 -0
- package/dist/model-assets.d.ts +14 -0
- package/dist/model-assets.js +895 -0
- package/dist/remote.d.ts +24 -0
- package/dist/remote.js +129 -0
- package/dist/theme.css +1344 -0
- package/dist/themes/all.css +2150 -0
- package/dist/themes/base.css +942 -0
- package/dist/themes/contrast.css +1344 -0
- package/dist/themes/default.css +1344 -0
- package/dist/themes/index.d.ts +2 -0
- package/dist/themes/index.js +17 -0
- package/dist/themes/languages/typescript.css +2 -0
- package/dist/themes/muted.css +1344 -0
- package/package.json +42 -4
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,71 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Virgo NSH
|
|
2
2
|
|
|
3
|
-
|
|
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 version 0.1.0, 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
|
+
## License
|
|
69
|
+
|
|
70
|
+
The project's code and documentation are licensed under MIT. The package
|
|
71
|
+
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,32 @@
|
|
|
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 BrowserHighlighter {
|
|
20
|
+
highlight(code: string, options: {
|
|
21
|
+
language: string;
|
|
22
|
+
}): Promise<HighlightedCode>;
|
|
23
|
+
highlightTokens(request: HighlightRequest): Promise<HighlightResult>;
|
|
24
|
+
highlightElement(element: HTMLElement, options?: {
|
|
25
|
+
language?: string;
|
|
26
|
+
}): Promise<HighlightedCode>;
|
|
27
|
+
supports(language: string): boolean;
|
|
28
|
+
languages(): readonly string[];
|
|
29
|
+
close(): void;
|
|
30
|
+
}
|
|
31
|
+
/** Configure selected models explicitly; no Node/Python imports or source uploads. */
|
|
32
|
+
export declare function createHighlighter(options?: HighlighterOptions): BrowserHighlighter;
|
|
@@ -0,0 +1,134 @@
|
|
|
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
|
+
/** Configure selected models explicitly; no Node/Python imports or source uploads. */
|
|
12
|
+
export function createHighlighter(options = {}) {
|
|
13
|
+
const runtime = new BrowserRuntime(options);
|
|
14
|
+
const base = new Map();
|
|
15
|
+
const remote = options.modelBaseUrl !== undefined || options.resolveAssetUrl !== undefined
|
|
16
|
+
? new RemoteModelSource(options)
|
|
17
|
+
: undefined;
|
|
18
|
+
const models = new Map();
|
|
19
|
+
function collect(model) {
|
|
20
|
+
const previous = models.get(model.id);
|
|
21
|
+
if (previous && previous.sha256 !== model.sha256)
|
|
22
|
+
throw new Error(`Conflicting model versions: ${model.id}`);
|
|
23
|
+
if (previous)
|
|
24
|
+
return;
|
|
25
|
+
models.set(model.id, model);
|
|
26
|
+
for (const dependency of model.dependencies ?? [])
|
|
27
|
+
collect(dependency);
|
|
28
|
+
}
|
|
29
|
+
if (remote) {
|
|
30
|
+
const languages = options.languages;
|
|
31
|
+
if (languages?.some((language) => typeof language !== "string"))
|
|
32
|
+
throw new Error("Remote model selection accepts content IDs; use local descriptors without a remote source");
|
|
33
|
+
for (const asset of remote.select(languages))
|
|
34
|
+
base.set(asset.id, remote.createPack(asset, runtime));
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
for (const model of options.languages ?? []) {
|
|
38
|
+
if (typeof model === "string")
|
|
39
|
+
throw new Error("Set modelBaseUrl or resolveAssetUrl to select remote languages by name");
|
|
40
|
+
collect(model);
|
|
41
|
+
}
|
|
42
|
+
for (const model of models.values())
|
|
43
|
+
base.set(model.id, runtime.createPack(model));
|
|
44
|
+
}
|
|
45
|
+
if (!base.size)
|
|
46
|
+
throw new Error("Provide language model descriptors, a modelBaseUrl or a resolveAssetUrl");
|
|
47
|
+
const packs = [...base].map(([id, pack]) => id === "markdown"
|
|
48
|
+
? createCompositeMarkdownPack({
|
|
49
|
+
base: pack,
|
|
50
|
+
resolveLanguage: (name) => {
|
|
51
|
+
const kind = normalizeLanguageId(name);
|
|
52
|
+
return kind !== "markdown" && core.supports(kind) ? kind : undefined;
|
|
53
|
+
},
|
|
54
|
+
highlightEmbedded: (request) => core.highlight(request),
|
|
55
|
+
})
|
|
56
|
+
: id === "php"
|
|
57
|
+
? createCompositePhpPack({
|
|
58
|
+
base: pack,
|
|
59
|
+
highlightEmbedded: (request) => core.highlight(request),
|
|
60
|
+
})
|
|
61
|
+
: id === "html"
|
|
62
|
+
? createCompositeHtmlPack({
|
|
63
|
+
base: pack,
|
|
64
|
+
highlightEmbedded: (request) => core.highlight(request),
|
|
65
|
+
})
|
|
66
|
+
: id === "vue"
|
|
67
|
+
? createCompositeVuePack({
|
|
68
|
+
base: pack,
|
|
69
|
+
highlightEmbedded: (request) => core.highlight(request),
|
|
70
|
+
})
|
|
71
|
+
: id === "svelte"
|
|
72
|
+
? createCompositeSveltePack({
|
|
73
|
+
base: pack,
|
|
74
|
+
highlightEmbedded: (request) => core.highlight(request),
|
|
75
|
+
})
|
|
76
|
+
: pack);
|
|
77
|
+
const core = createCoreHighlighter({ packs });
|
|
78
|
+
let closed = false;
|
|
79
|
+
const pending = new Set();
|
|
80
|
+
const infer = (request) => {
|
|
81
|
+
if (closed)
|
|
82
|
+
return Promise.reject(new Error("Browser highlighter is closed"));
|
|
83
|
+
return new Promise((resolve, reject) => {
|
|
84
|
+
pending.add(reject);
|
|
85
|
+
core.highlight(request).then((result) => {
|
|
86
|
+
pending.delete(reject);
|
|
87
|
+
resolve(result);
|
|
88
|
+
}, (error) => {
|
|
89
|
+
pending.delete(reject);
|
|
90
|
+
reject(error);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
};
|
|
94
|
+
const kindFor = normalizeLanguageId;
|
|
95
|
+
const highlight = async (code, { language }) => {
|
|
96
|
+
const documentKind = kindFor(language);
|
|
97
|
+
const result = await infer({ source: code, documentKind });
|
|
98
|
+
const request = { source: code, documentKind, result };
|
|
99
|
+
return {
|
|
100
|
+
language: documentKind,
|
|
101
|
+
result,
|
|
102
|
+
value: renderCodeToHtml(request),
|
|
103
|
+
html: renderToHtml(request),
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
return {
|
|
107
|
+
highlight,
|
|
108
|
+
highlightTokens: ({ source, documentKind }) => infer({ source, documentKind: kindFor(documentKind) }),
|
|
109
|
+
async highlightElement(element, options = {}) {
|
|
110
|
+
const language = options.language ??
|
|
111
|
+
element.dataset.language ??
|
|
112
|
+
[...element.classList].find((name) => name.startsWith("language-"))?.slice(9) ??
|
|
113
|
+
element.parentElement?.dataset.language;
|
|
114
|
+
if (!language)
|
|
115
|
+
throw new Error("Set a language, for example language-tsx or data-language=tsx");
|
|
116
|
+
const result = await highlight(element.textContent ?? "", { language });
|
|
117
|
+
element.innerHTML = result.value;
|
|
118
|
+
const wrapper = element.parentElement?.tagName === "PRE" ? element.parentElement : element;
|
|
119
|
+
wrapper.classList.add("nsh");
|
|
120
|
+
wrapper.dataset.language = result.language;
|
|
121
|
+
return result;
|
|
122
|
+
},
|
|
123
|
+
supports: (language) => core.supports(kindFor(language)),
|
|
124
|
+
languages: () => core.documentKinds(),
|
|
125
|
+
close: () => {
|
|
126
|
+
closed = true;
|
|
127
|
+
for (const reject of pending)
|
|
128
|
+
reject(new Error("Browser highlighter is closed"));
|
|
129
|
+
pending.clear();
|
|
130
|
+
remote?.close();
|
|
131
|
+
runtime.close();
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { type BrowserHighlighter, type BrowserRuntimeOptions, clearModelCache, createHighlighter, type HighlightedCode, type HighlighterOptions, ModelAssetError, type ModelAssetRequest, type ModelCacheOptions, 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
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/** Original UTF-8 starts and UTF-16 offsets; no source-language parsing. */
|
|
2
|
+
export function characterMap(source) {
|
|
3
|
+
const bytes = [0];
|
|
4
|
+
const units = [0];
|
|
5
|
+
let byte = 0;
|
|
6
|
+
let unit = 0;
|
|
7
|
+
for (const character of source) {
|
|
8
|
+
const point = character.codePointAt(0);
|
|
9
|
+
if (point >= 0xd800 && point <= 0xdfff)
|
|
10
|
+
throw new Error("Source contains an unpaired surrogate");
|
|
11
|
+
byte += point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;
|
|
12
|
+
unit += character.length;
|
|
13
|
+
bytes.push(byte);
|
|
14
|
+
units.push(unit);
|
|
15
|
+
}
|
|
16
|
+
return { bytes, units };
|
|
17
|
+
}
|
|
18
|
+
export function argmax(data, offset, width) {
|
|
19
|
+
let best = 0;
|
|
20
|
+
for (let i = 1; i < width; i++)
|
|
21
|
+
if (data[offset + i] > data[offset + best])
|
|
22
|
+
best = i;
|
|
23
|
+
return best;
|
|
24
|
+
}
|
|
25
|
+
/** Stream committed model windows; retain only one pending span's logits. */
|
|
26
|
+
export class SpanDecoder {
|
|
27
|
+
spans = [];
|
|
28
|
+
#model;
|
|
29
|
+
#start;
|
|
30
|
+
#end = 0;
|
|
31
|
+
#types;
|
|
32
|
+
#flags = [];
|
|
33
|
+
constructor(model) {
|
|
34
|
+
this.#model = model;
|
|
35
|
+
this.#types = new Float64Array(model.schema.tokenTypes.length);
|
|
36
|
+
}
|
|
37
|
+
append(start, end, boundary, types, typeOffset, modifiers, modifierOffset) {
|
|
38
|
+
if (boundary === 0 || boundary === 1)
|
|
39
|
+
this.#flush();
|
|
40
|
+
if (boundary === 0)
|
|
41
|
+
return;
|
|
42
|
+
if (this.#start === undefined) {
|
|
43
|
+
this.#start = start;
|
|
44
|
+
this.#flags = this.#model.schema.modifiers.map((_, i) => 1 / (1 + Math.exp(-modifiers[modifierOffset + i])) >= this.#model.modifierThreshold);
|
|
45
|
+
}
|
|
46
|
+
this.#end = end;
|
|
47
|
+
for (let i = 0; i < this.#types.length; i++)
|
|
48
|
+
this.#types[i] += types[typeOffset + i];
|
|
49
|
+
}
|
|
50
|
+
#flush() {
|
|
51
|
+
if (this.#start === undefined)
|
|
52
|
+
return;
|
|
53
|
+
const tokenType = this.#model.schema.tokenTypes[argmax(this.#types, 0, this.#types.length)];
|
|
54
|
+
const span = { start: this.#start, end: this.#end, tokenType };
|
|
55
|
+
const roles = this.#model.decoder?.modifierRoles;
|
|
56
|
+
const modifiers = this.#model.schema.modifiers.filter((name, i) => this.#flags[i] && (!roles?.[name] || roles[name].includes(tokenType)));
|
|
57
|
+
if (modifiers.length)
|
|
58
|
+
span.modifiers = modifiers;
|
|
59
|
+
const previous = this.spans.at(-1);
|
|
60
|
+
if (previous &&
|
|
61
|
+
this.#model.decoder?.coalesceAdjacentTokenTypes?.includes(tokenType) &&
|
|
62
|
+
previous.tokenType === tokenType &&
|
|
63
|
+
previous.end === span.start &&
|
|
64
|
+
(previous.modifiers ?? []).join(" ") === modifiers.join(" "))
|
|
65
|
+
previous.end = span.end;
|
|
66
|
+
else
|
|
67
|
+
this.spans.push(span);
|
|
68
|
+
this.#start = undefined;
|
|
69
|
+
this.#types.fill(0);
|
|
70
|
+
}
|
|
71
|
+
finish() {
|
|
72
|
+
this.#flush();
|
|
73
|
+
return { offsetEncoding: "utf-16", spans: this.spans };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { HighlightResult } from "../core/index.js";
|
|
2
|
+
import { type BrowserRuntimeOptions } from "./assets.js";
|
|
3
|
+
import type { ModelRequest } from "./types.js";
|
|
4
|
+
export declare function highlight(model: ModelRequest, source: string, options?: BrowserRuntimeOptions): Promise<HighlightResult>;
|