webslm 0.3.1 → 0.4.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/dist/index.d.ts CHANGED
@@ -18,9 +18,9 @@ import type { SafetensorsHeader } from "./safetensors.js";
18
18
  export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, splitReasoning, stream, unloadAll, type Answer, type AskOptions, type Chat, type ChatOptions, type ChatTurnOptions, type LLM, type PromptOptions, type SharedAskOptions, type SharedStreamOptions, type TextStream, } from "./simple.js";
19
19
  export { detectCapabilities, getWebGpuAdapterSummary, type Capabilities, type CapabilityEnvironment, type GpuAdapterLike, type GpuLike, type WebGpuAdapterSummary, } from "./capabilities.js";
20
20
  export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, type ModelFamily, } from "./models.js";
21
- export type { Activations, AdapterMode, AdapterSource, ApplyAdapterOptions, ChatMessage, ChatStream, GeneratedToken, CpuInfo, CompletionOptions, Device, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
21
+ export type { Activations, AdapterMode, AdapterSource, ApplyAdapterOptions, Backend, ChatMessage, ChatStream, GeneratedToken, CpuInfo, CompletionOptions, Device, FetchFile, FileData, FinishReason, GenerateOptions, GenerationConfig, GenerationResult, WeightCacheInfo, LoadedFile, LoadModelOptions, LoadProgress, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions, } from "./types.js";
22
22
  export { WebslmError, type WebslmErrorCode } from "./errors.js";
23
- export { CURATED_MODELS, type CuratedModel } from "./curated.js";
23
+ export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, type CheckpointTraits, type CuratedModel, type SamplingDefaults, type SamplingSet, } from "./curated.js";
24
24
  export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, type CheckModelOptions, type HubModel, type HubOptions, type ModelCheck, type SearchModelsOptions, } from "./hub.js";
25
25
  export { cacheUsage, deleteCachedModel, listCachedModels, type CacheOptions, type CachedModel, type CachedRevision, type CacheUsage, } from "./cache-management.js";
26
26
  export type { Dtype, SafetensorsHeader, TensorInfo } from "./safetensors.js";
package/dist/index.js CHANGED
@@ -19,7 +19,7 @@ export { ask, DEFAULT_MAX_TOKENS, DEFAULT_MODEL, DEFAULT_TEMPERATURE, load, spli
19
19
  export { detectCapabilities, getWebGpuAdapterSummary, } from "./capabilities.js";
20
20
  export { createEngine, EngineHandle, loadModel, Model, MODEL_FAMILIES, Session, } from "./models.js";
21
21
  export { WebslmError } from "./errors.js";
22
- export { CURATED_MODELS } from "./curated.js";
22
+ export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, } from "./curated.js";
23
23
  export { checkModel, DEFAULT_HUB_URL, EMBEDDING_REASON, isEmbeddingModel, formatParams, searchModels, SUPPORTED_MODEL_TYPES, } from "./hub.js";
24
24
  export { cacheUsage, deleteCachedModel, listCachedModels, } from "./cache-management.js";
25
25
  export { selectWasmFlavour, supportsRelaxedSimd, supportsWasmThreads, } from "./wasm-flavour.js";
package/dist/models.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /** Public model API: {@link loadModel}, {@link Model} and {@link Session}. */
2
2
  import { EngineClient } from "./client.js";
3
- import type { AdapterSource, ApplyAdapterOptions, ChatMessage, ChatStream, CompletionOptions, Device, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions } from "./types.js";
3
+ import { type CheckpointTraits } from "./curated.js";
4
+ import type { AdapterSource, Backend, ApplyAdapterOptions, ChatMessage, ChatStream, CompletionOptions, Device, FetchFile, GenerateOptions, LoadModelOptions, LoraInfo, ModelInfo, ModelSource, Quant, ScoreOptions, ScoreOutput, StepOptions } from "./types.js";
4
5
  /**
5
6
  * An engine (a worker, or the calling thread) that several models can share
6
7
  * (see {@link LoadModelOptions.engine}): one WebAssembly instance, its memory
@@ -31,11 +32,16 @@ export declare function createEngine(options?: {
31
32
  }): Promise<EngineHandle>;
32
33
  /**
33
34
  * Validates `device` (default `"auto"`). The engine decides what actually
34
- * runs: `"auto"` is WebGPU for models above ~100M parameters when an adapter
35
- * is available, the CPU otherwise; `"webgpu"` falls back to the CPU (with
36
- * {@link ModelInfo.deviceNote} saying why) when no GPU device can be created.
35
+ * runs: `"auto"` is the GPU for models above ~100M parameters when an adapter
36
+ * is available, the CPU otherwise; `"gpu"` (or `"webgpu"`) asks for the GPU
37
+ * (see {@link LoadModelOptions.device}).
37
38
  */
38
39
  export declare function resolveDevice(device: Device | undefined): Device;
40
+ /**
41
+ * Validates `backend`. Its default is `WEBSLM_BACKEND` in Node (to pin a
42
+ * deployment to one engine without changing code), else `"auto"`.
43
+ */
44
+ export declare function resolveBackend(backend: Backend | undefined, env?: Readonly<Record<string, string | undefined>> | undefined): Backend;
39
45
  /** Normalized form of a {@link ModelSource}. */
40
46
  export type NormalizedSource = {
41
47
  readonly kind: "hub";
@@ -82,6 +88,15 @@ export declare function resolveAutoQuant(source: NormalizedSource, options: Load
82
88
  quant: Quant;
83
89
  note?: string;
84
90
  }>;
91
+ /**
92
+ * `options` with the sampling fields it leaves unset taken from the model
93
+ * card of a curated repository ({@link recommendedSampling}), for the
94
+ * thinking mode its `templateKwargs.enable_thinking` asks for. Unchanged for
95
+ * other repositories, and with `temperature: 0` (greedy decoding).
96
+ *
97
+ * @internal
98
+ */
99
+ export declare function withRecommendedSampling<T extends GenerateOptions>(options: T, checkpoint: string | CheckpointTraits | undefined): T;
85
100
  /** Operations shared by {@link Model} (its default session) and {@link Session}. */
86
101
  declare abstract class Conversation {
87
102
  #private;
@@ -89,6 +104,8 @@ declare abstract class Conversation {
89
104
  protected readonly modelId: number;
90
105
  protected abstract readonly sessionId: number | undefined;
91
106
  protected abstract readonly hasChatTemplate: boolean;
107
+ /** What picks the model's recommended sampling. */
108
+ protected abstract readonly checkpoint: CheckpointTraits;
92
109
  protected abstract onLength(length: number): void;
93
110
  constructor(client: EngineClient, modelId: number);
94
111
  /**
@@ -133,6 +150,7 @@ export declare class Model extends Conversation {
133
150
  readonly cacheDir?: string;
134
151
  }, ownsEngine?: boolean);
135
152
  protected get hasChatTemplate(): boolean;
153
+ protected get checkpoint(): CheckpointTraits;
136
154
  protected onLength(): void;
137
155
  /** Architecture, sizes, quant, backend and the files loaded (with SHA-256). */
138
156
  info(): ModelInfo;
@@ -185,6 +203,7 @@ export declare class Session extends Conversation {
185
203
  /** @internal */
186
204
  constructor(client: EngineClient, modelId: number, sessionId: number, info: ModelInfo, onDispose: () => void);
187
205
  protected get hasChatTemplate(): boolean;
206
+ protected get checkpoint(): CheckpointTraits;
188
207
  protected onLength(length: number): void;
189
208
  /** Positions in the cache (as of the last completed call). */
190
209
  get length(): number;
package/dist/models.js CHANGED
@@ -1,6 +1,7 @@
1
1
  /** Public model API: {@link loadModel}, {@link Model} and {@link Session}. */
2
2
  import { AsyncQueue } from "./async-queue.js";
3
3
  import { EngineClient } from "./client.js";
4
+ import { recommendedSampling } from "./curated.js";
4
5
  import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
5
6
  import { autoQuant, getBrowserResources, readCheckpointShapes } from "./fit.js";
6
7
  import { checkModel } from "./hub.js";
@@ -44,9 +45,9 @@ export async function createEngine(options = {}) {
44
45
  }
45
46
  /**
46
47
  * Validates `device` (default `"auto"`). The engine decides what actually
47
- * runs: `"auto"` is WebGPU for models above ~100M parameters when an adapter
48
- * is available, the CPU otherwise; `"webgpu"` falls back to the CPU (with
49
- * {@link ModelInfo.deviceNote} saying why) when no GPU device can be created.
48
+ * runs: `"auto"` is the GPU for models above ~100M parameters when an adapter
49
+ * is available, the CPU otherwise; `"gpu"` (or `"webgpu"`) asks for the GPU
50
+ * (see {@link LoadModelOptions.device}).
50
51
  */
51
52
  export function resolveDevice(device) {
52
53
  switch (device ?? "auto") {
@@ -54,12 +55,28 @@ export function resolveDevice(device) {
54
55
  return "auto";
55
56
  case "cpu":
56
57
  return "cpu";
58
+ case "gpu":
59
+ return "gpu";
57
60
  case "webgpu":
58
61
  return "webgpu";
59
62
  default:
60
63
  throw new WebslmError("INVALID_ARGUMENT", `unknown device "${String(device)}"`);
61
64
  }
62
65
  }
66
+ const BACKENDS = ["auto", "native", "wasm"];
67
+ /**
68
+ * Validates `backend`. Its default is `WEBSLM_BACKEND` in Node (to pin a
69
+ * deployment to one engine without changing code), else `"auto"`.
70
+ */
71
+ export function resolveBackend(backend, env = globalThis.process?.env) {
72
+ const fromEnv = env?.["WEBSLM_BACKEND"]?.trim();
73
+ const value = backend ?? (fromEnv === undefined || fromEnv === "" ? "auto" : fromEnv);
74
+ if (!BACKENDS.includes(value)) {
75
+ const where = backend === undefined ? `WEBSLM_BACKEND (${String(fromEnv)})` : "backend";
76
+ throw new WebslmError("INVALID_ARGUMENT", `${where} must be one of ${BACKENDS.join(", ")}`);
77
+ }
78
+ return value;
79
+ }
63
80
  /** Checks a source and turns a repository id string into a hub source. */
64
81
  export function normalizeSource(source, revision) {
65
82
  if (typeof source === "string") {
@@ -174,6 +191,7 @@ function requestPersistentStorage() {
174
191
  */
175
192
  export async function loadModel(source, options = {}) {
176
193
  const device = resolveDevice(options.device);
194
+ const backend = resolveBackend(options.backend);
177
195
  const requested = options.quant ?? "q8";
178
196
  if (requested !== "auto" && !QUANTS.includes(requested)) {
179
197
  throw new WebslmError("INVALID_ARGUMENT", `quant must be one of ${QUANTS.join(", ")} or auto`);
@@ -202,11 +220,14 @@ export async function loadModel(source, options = {}) {
202
220
  ...(adapter === undefined ? {} : { adapter: toWire(adapter, options.token) }),
203
221
  options: {
204
222
  quant,
223
+ ...(requested === "auto" ? { autoQuant: true } : {}),
205
224
  device,
225
+ ...(backend === "auto" ? {} : { backend }),
206
226
  ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
207
227
  ...(options.adapterMode === undefined ? {} : { adapterMode: options.adapterMode }),
208
228
  ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
209
229
  ...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
230
+ ...(options.weightCache === false ? { weightCache: false } : {}),
210
231
  ...(options.deterministic === true ? { deterministic: true } : {}),
211
232
  ...(options.activations === undefined ? {} : { activations: options.activations }),
212
233
  ...(options.wasmFlavour === undefined ? {} : { wasmFlavour: options.wasmFlavour }),
@@ -218,7 +239,9 @@ export async function loadModel(source, options = {}) {
218
239
  ...(normalized.kind === "fetch" ? { onRead: normalized.fetch } : {}),
219
240
  ...(adapter?.kind === "fetch" ? { onAdapterRead: adapter.fetch } : {}),
220
241
  });
221
- const info = quantNote === undefined ? result.info : { ...result.info, quantNote };
242
+ // The native engine chose the format again, from the machine's memory
243
+ // (its own note says why when it did not load q8).
244
+ const info = quantNote === undefined || result.info.runtime === "native" ? result.info : { ...result.info, quantNote };
222
245
  return new Model(client, result.model, info, {
223
246
  ...(normalized.kind === "fetch" ? { fetch: normalized.fetch } : {}),
224
247
  ...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
@@ -332,6 +355,32 @@ function wireOptions(options) {
332
355
  out.contextShift = options.contextShift;
333
356
  return out;
334
357
  }
358
+ /**
359
+ * `options` with the sampling fields it leaves unset taken from the model
360
+ * card of a curated repository ({@link recommendedSampling}), for the
361
+ * thinking mode its `templateKwargs.enable_thinking` asks for. Unchanged for
362
+ * other repositories, and with `temperature: 0` (greedy decoding).
363
+ *
364
+ * @internal
365
+ */
366
+ export function withRecommendedSampling(options, checkpoint) {
367
+ if (options.temperature === 0)
368
+ return options;
369
+ const think = options.templateKwargs?.["enable_thinking"];
370
+ const recommended = recommendedSampling(checkpoint, typeof think === "boolean" ? think : undefined);
371
+ if (recommended === undefined)
372
+ return options;
373
+ const out = { ...options };
374
+ for (const key of Object.keys(recommended)) {
375
+ if (out[key] === undefined)
376
+ out[key] = recommended[key];
377
+ }
378
+ return out;
379
+ }
380
+ /** What picks a loaded model's recommended sampling. */
381
+ function checkpointTraits(info) {
382
+ return { repo: info.repo, modelType: info.modelType, doSample: info.generationConfig.doSample };
383
+ }
335
384
  /** A `delta` message as a {@link GeneratedToken}. */
336
385
  function generatedToken(delta) {
337
386
  return {
@@ -464,7 +513,7 @@ class Conversation {
464
513
  return text;
465
514
  }
466
515
  #stream(body, generateOptions) {
467
- const options = wireOptions(generateOptions);
516
+ const options = wireOptions(withRecommendedSampling(generateOptions, this.checkpoint));
468
517
  const { onPrefill } = generateOptions;
469
518
  const session = this.sessionId === undefined ? {} : { session: this.sessionId };
470
519
  // Stopping aborts the request; the engine then ends the generation
@@ -534,6 +583,9 @@ export class Model extends Conversation {
534
583
  get hasChatTemplate() {
535
584
  return this.#info.hasChatTemplate;
536
585
  }
586
+ get checkpoint() {
587
+ return checkpointTraits(this.#info);
588
+ }
537
589
  onLength() { }
538
590
  /** Architecture, sizes, quant, backend and the files loaded (with SHA-256). */
539
591
  info() {
@@ -642,6 +694,9 @@ export class Session extends Conversation {
642
694
  get hasChatTemplate() {
643
695
  return this.#info.hasChatTemplate;
644
696
  }
697
+ get checkpoint() {
698
+ return checkpointTraits(this.#info);
699
+ }
645
700
  onLength(length) {
646
701
  this.#length = length;
647
702
  }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * The native engine in Node: a Node-API addon built from the same Rust
3
+ * engine (`crates/webslm-node`). Each release attaches it to its GitHub
4
+ * Release for every platform (`webslm-node-<version>-<platform>.node.gz`),
5
+ * and the published package carries their SHA-256 (`native-manifest.json`).
6
+ * On first use the addon of this platform is downloaded into the cache
7
+ * directory, checked against the manifest and loaded; later runs load it
8
+ * from the cache, without network. When it cannot be (no build for this
9
+ * platform, offline, a failed download, a checksum that does not match) the
10
+ * WebAssembly engine runs instead. No install script runs.
11
+ *
12
+ * The addon runs the native CPU kernels (NEON, AVX2, AVX-512 VNNI) on every
13
+ * core and the GPU through `wgpu` (Metal on macOS, Vulkan or DX12 on Linux
14
+ * and Windows), with the device rules of the command-line tool.
15
+ *
16
+ * Node-only: the engine imports this module only in Node; browser bundles
17
+ * never download or load the addon.
18
+ */
19
+ /** What `info()` of a native model reports (the WebAssembly fields, `device` added). */
20
+ export interface NativeModelInfo {
21
+ readonly device: "gpu" | "cpu";
22
+ readonly [key: string]: unknown;
23
+ }
24
+ /** Stops a native call (see `CancelToken` in `crates/webslm-node`). */
25
+ export interface NativeCancelToken {
26
+ cancel(): void;
27
+ readonly cancelled: boolean;
28
+ }
29
+ export type NativeDeltaCallback = (text: string, token: number, info: {
30
+ logprob?: number;
31
+ topLogprobs?: [number, number][];
32
+ forced?: boolean;
33
+ } | null) => void;
34
+ export type NativePrefillCallback = (done: number, total: number) => void;
35
+ /** A session of a native model; every call resolves on the model's thread. */
36
+ export interface NativeSession {
37
+ chat(messagesJson: string, optionsJson: string, onDelta: NativeDeltaCallback | null, onPrefill: NativePrefillCallback | null, cancel: NativeCancelToken | null): Promise<unknown>;
38
+ generate(prompt: string, optionsJson: string, onDelta: NativeDeltaCallback | null, onPrefill: NativePrefillCallback | null, cancel: NativeCancelToken | null): Promise<unknown>;
39
+ fork(): Promise<NativeSession>;
40
+ scoreContinuations(prefix: Uint32Array, continuationsJson: string): Promise<Float32Array[]>;
41
+ shiftContext(keep: number, drop: number): Promise<number>;
42
+ score(ids: Uint32Array, optionsJson: string): Promise<unknown>;
43
+ step(id: number, optionsJson: string): Promise<unknown>;
44
+ truncate(length: number): Promise<number>;
45
+ reset(): Promise<void>;
46
+ readonly length: number;
47
+ free(): void;
48
+ }
49
+ /** Settings of a load that only the native engine takes. */
50
+ export interface NativeLoadArgs {
51
+ readonly adapterDir?: string;
52
+ readonly weightCacheDir?: string;
53
+ readonly weightCacheKey?: string;
54
+ readonly threads?: number;
55
+ }
56
+ /** A model loaded by the native engine. */
57
+ export interface NativeModel {
58
+ info(): NativeModelInfo;
59
+ applyAdapter(dir: string, optionsJson: string): Promise<unknown>;
60
+ removeAdapter(): Promise<unknown>;
61
+ createSession(): Promise<NativeSession>;
62
+ chat: NativeSession["chat"];
63
+ generate: NativeSession["generate"];
64
+ reset(): Promise<void>;
65
+ tokenize(text: string, addSpecialTokens: boolean): Promise<Uint32Array>;
66
+ detokenize(ids: Uint32Array, skipSpecialTokens: boolean): Promise<string>;
67
+ renderChat(messagesJson: string, kwargsJson: string): Promise<string>;
68
+ free(): void;
69
+ }
70
+ /** The exports of the addon. */
71
+ export interface NativeAddon {
72
+ version(): string;
73
+ supportedModelTypes(): string[];
74
+ buildInfo(): {
75
+ version: string;
76
+ target: string;
77
+ kernels: string;
78
+ threads: number;
79
+ };
80
+ readonly NativeModel: {
81
+ load(dir: string, optionsJson: string, args?: NativeLoadArgs | null): Promise<NativeModel>;
82
+ };
83
+ readonly CancelToken: new () => NativeCancelToken;
84
+ }
85
+ /** Where the addon came from, or why it could not load. */
86
+ export type NativeAvailability = {
87
+ readonly addon: NativeAddon;
88
+ readonly source: string;
89
+ } | {
90
+ readonly addon?: undefined;
91
+ readonly reason: string;
92
+ };
93
+ /** What {@link nativePlatform} reads; `process` by default. */
94
+ export interface PlatformInfo {
95
+ readonly platform: string;
96
+ readonly arch: string;
97
+ /** Linux only: whether the C library is musl (Alpine) rather than glibc. */
98
+ readonly musl?: boolean;
99
+ }
100
+ /** The platforms the native engine is released for. */
101
+ export declare const NATIVE_PLATFORMS: readonly ["darwin-arm64", "darwin-x64", "linux-x64-gnu", "linux-arm64-gnu", "linux-x64-musl", "linux-arm64-musl", "win32-x64-msvc"];
102
+ export type NativePlatform = (typeof NATIVE_PLATFORMS)[number];
103
+ /** Where the release assets are downloaded from (`WEBSLM_NATIVE_URL` replaces it: a mirror, or tests). */
104
+ export declare const NATIVE_RELEASES = "https://github.com/maxgfr/webslm/releases/download";
105
+ /** Most milliseconds the download of the addon may take before WebAssembly runs instead. */
106
+ export declare const NATIVE_DOWNLOAD_TIMEOUT_MS = 30000;
107
+ /** The native platform of `info`, when the engine is released for it. */
108
+ export declare function nativePlatform(info: PlatformInfo): NativePlatform | undefined;
109
+ /**
110
+ * `native-manifest.json`, written into the package when it is published
111
+ * (`scripts/release/native-manifest.mjs`): for each platform, the asset on
112
+ * the GitHub Release of the version and the SHA-256 of its bytes and of the
113
+ * addon inside.
114
+ */
115
+ export interface NativeManifest {
116
+ readonly version: string;
117
+ readonly assets: Readonly<Record<string, {
118
+ readonly file: string;
119
+ readonly size: number;
120
+ readonly sha256: string;
121
+ readonly nodeSha256: string;
122
+ }>>;
123
+ }
124
+ /** Why the native engine cannot run; `auto` falls back to WebAssembly with this reason. */
125
+ export declare class NativeUnavailable extends Error {
126
+ readonly name = "NativeUnavailable";
127
+ }
128
+ /** What {@link fetchNativeAddon} needs; tests pass a fake manifest and server. */
129
+ export interface NativeFetchOptions {
130
+ readonly platform: NativePlatform;
131
+ /** The version of this package: the release the asset comes from. */
132
+ readonly version: string;
133
+ /** `undefined` when the package has none (built from source). */
134
+ readonly manifest: NativeManifest | undefined;
135
+ /** The webslm cache directory; the addon goes to `<cacheDir>/native/<version>/`. */
136
+ readonly cacheDir: string;
137
+ /** Default {@link NATIVE_RELEASES}. */
138
+ readonly baseUrl?: string;
139
+ /** Network access forbidden (`WEBSLM_OFFLINE`): only a cached addon is used. */
140
+ readonly offline?: boolean;
141
+ /** Default {@link NATIVE_DOWNLOAD_TIMEOUT_MS}. */
142
+ readonly timeoutMs?: number;
143
+ readonly fetch?: typeof fetch;
144
+ }
145
+ /**
146
+ * The path of a verified copy of the addon for `options.platform`: the one
147
+ * in the cache when its SHA-256 matches the manifest, else the release asset,
148
+ * downloaded, checked (compressed and uncompressed), and stored in the cache.
149
+ * Throws {@link NativeUnavailable} with the reason otherwise.
150
+ */
151
+ export declare function fetchNativeAddon(options: NativeFetchOptions): Promise<string>;
152
+ /** Whether `auto` may pick the native engine in this runtime. */
153
+ export declare function nativeAutoAllowed(process: {
154
+ versions: Record<string, string | undefined>;
155
+ }): boolean;
156
+ /**
157
+ * Loads the addon once per thread: `WEBSLM_NATIVE_PATH` (a `.node` file, for
158
+ * local builds) when set, else the release asset of this platform and
159
+ * version, from `<cacheDir>/native/<version>/` or downloaded there first and
160
+ * checked against `native-manifest.json` (see {@link fetchNativeAddon}).
161
+ * Resolves with the reason when it cannot be used.
162
+ */
163
+ export declare function loadNativeAddon(cacheDir?: string): Promise<NativeAvailability>;
164
+ /** @internal Forgets the loaded addon (tests). */
165
+ export declare function resetNativeAddon(): void;
package/dist/native.js ADDED
@@ -0,0 +1,243 @@
1
+ /**
2
+ * The native engine in Node: a Node-API addon built from the same Rust
3
+ * engine (`crates/webslm-node`). Each release attaches it to its GitHub
4
+ * Release for every platform (`webslm-node-<version>-<platform>.node.gz`),
5
+ * and the published package carries their SHA-256 (`native-manifest.json`).
6
+ * On first use the addon of this platform is downloaded into the cache
7
+ * directory, checked against the manifest and loaded; later runs load it
8
+ * from the cache, without network. When it cannot be (no build for this
9
+ * platform, offline, a failed download, a checksum that does not match) the
10
+ * WebAssembly engine runs instead. No install script runs.
11
+ *
12
+ * The addon runs the native CPU kernels (NEON, AVX2, AVX-512 VNNI) on every
13
+ * core and the GPU through `wgpu` (Metal on macOS, Vulkan or DX12 on Linux
14
+ * and Windows), with the device rules of the command-line tool.
15
+ *
16
+ * Node-only: the engine imports this module only in Node; browser bundles
17
+ * never download or load the addon.
18
+ */
19
+ import { importNode } from "./runtime.js";
20
+ /** The platforms the native engine is released for. */
21
+ export const NATIVE_PLATFORMS = [
22
+ "darwin-arm64",
23
+ "darwin-x64",
24
+ "linux-x64-gnu",
25
+ "linux-arm64-gnu",
26
+ "linux-x64-musl",
27
+ "linux-arm64-musl",
28
+ "win32-x64-msvc",
29
+ ];
30
+ /** Where the release assets are downloaded from (`WEBSLM_NATIVE_URL` replaces it: a mirror, or tests). */
31
+ export const NATIVE_RELEASES = "https://github.com/maxgfr/webslm/releases/download";
32
+ /** Most milliseconds the download of the addon may take before WebAssembly runs instead. */
33
+ export const NATIVE_DOWNLOAD_TIMEOUT_MS = 30_000;
34
+ /** The native platform of `info`, when the engine is released for it. */
35
+ export function nativePlatform(info) {
36
+ let platform;
37
+ switch (info.platform) {
38
+ case "darwin":
39
+ platform = `darwin-${info.arch}`;
40
+ break;
41
+ case "linux":
42
+ platform = `linux-${info.arch}-${info.musl === true ? "musl" : "gnu"}`;
43
+ break;
44
+ case "win32":
45
+ platform = `win32-${info.arch}-msvc`;
46
+ break;
47
+ default:
48
+ return undefined;
49
+ }
50
+ return NATIVE_PLATFORMS.includes(platform) ? platform : undefined;
51
+ }
52
+ /** Why the native engine cannot run; `auto` falls back to WebAssembly with this reason. */
53
+ export class NativeUnavailable extends Error {
54
+ name = "NativeUnavailable";
55
+ }
56
+ async function sha256Hex(bytes) {
57
+ const crypto = await importNode("crypto");
58
+ return crypto.createHash("sha256").update(bytes).digest("hex");
59
+ }
60
+ /**
61
+ * The path of a verified copy of the addon for `options.platform`: the one
62
+ * in the cache when its SHA-256 matches the manifest, else the release asset,
63
+ * downloaded, checked (compressed and uncompressed), and stored in the cache.
64
+ * Throws {@link NativeUnavailable} with the reason otherwise.
65
+ */
66
+ export async function fetchNativeAddon(options) {
67
+ const { manifest, version, platform } = options;
68
+ if (manifest === undefined) {
69
+ throw new NativeUnavailable("this build of webslm has no native-manifest.json (built from source: set WEBSLM_NATIVE_PATH)");
70
+ }
71
+ if (manifest.version !== version) {
72
+ throw new NativeUnavailable(`native-manifest.json describes ${manifest.version}, webslm is ${version}`);
73
+ }
74
+ const entry = manifest.assets[platform];
75
+ if (entry === undefined)
76
+ throw new NativeUnavailable(`no native build of ${version} for ${platform}`);
77
+ const fs = await importNode("fs/promises");
78
+ const path = await importNode("path");
79
+ const dir = path.join(options.cacheDir, "native", version);
80
+ const file = path.join(dir, entry.file.replace(/\.gz$/, ""));
81
+ const cached = await fs.readFile(file).catch(() => undefined);
82
+ if (cached !== undefined && (await sha256Hex(cached)) === entry.nodeSha256)
83
+ return file;
84
+ if (options.offline === true) {
85
+ throw new NativeUnavailable(`offline mode is on and the native engine ${version} is not in the cache`);
86
+ }
87
+ const url = `${options.baseUrl ?? NATIVE_RELEASES}/v${version}/${entry.file}`;
88
+ let gzipped;
89
+ try {
90
+ const response = await (options.fetch ?? fetch)(url, {
91
+ signal: AbortSignal.timeout(options.timeoutMs ?? NATIVE_DOWNLOAD_TIMEOUT_MS),
92
+ });
93
+ if (!response.ok)
94
+ throw new Error(`HTTP ${response.status}`);
95
+ gzipped = new Uint8Array(await response.arrayBuffer());
96
+ }
97
+ catch (error) {
98
+ const message = error instanceof Error ? error.message : String(error);
99
+ throw new NativeUnavailable(`cannot download the native engine from ${url} (${message})`);
100
+ }
101
+ if ((await sha256Hex(gzipped)) !== entry.sha256) {
102
+ throw new NativeUnavailable(`the native engine downloaded from ${url} does not match its SHA-256`);
103
+ }
104
+ const zlib = await importNode("zlib");
105
+ let addon;
106
+ try {
107
+ addon = zlib.gunzipSync(gzipped);
108
+ }
109
+ catch {
110
+ throw new NativeUnavailable(`the native engine downloaded from ${url} is not a gzip file`);
111
+ }
112
+ if ((await sha256Hex(addon)) !== entry.nodeSha256) {
113
+ throw new NativeUnavailable(`the native engine downloaded from ${url} does not match its SHA-256`);
114
+ }
115
+ // Written under a temporary name and renamed: concurrent processes never
116
+ // load a partial file.
117
+ await fs.mkdir(dir, { recursive: true });
118
+ const partial = `${file}.${Date.now()}-${Math.random().toString(36).slice(2)}.partial`;
119
+ try {
120
+ await fs.writeFile(partial, addon);
121
+ await fs.rename(partial, file);
122
+ }
123
+ catch (error) {
124
+ await fs.rm(partial, { force: true }).catch(() => { });
125
+ const message = error instanceof Error ? error.message : String(error);
126
+ throw new NativeUnavailable(`cannot store the native engine in ${dir} (${message})`);
127
+ }
128
+ return file;
129
+ }
130
+ function nodeProcess() {
131
+ return globalThis.process;
132
+ }
133
+ /** Whether Linux runs on musl: glibc reports its version in the process report. */
134
+ async function isMusl(process) {
135
+ try {
136
+ const report = process.report?.getReport();
137
+ if (report?.header !== undefined)
138
+ return report.header.glibcVersionRuntime === undefined;
139
+ }
140
+ catch {
141
+ // Reports can be turned off.
142
+ }
143
+ try {
144
+ const fs = await importNode("fs/promises");
145
+ return (await fs.readFile("/usr/bin/ldd", "utf8")).includes("musl");
146
+ }
147
+ catch {
148
+ return false;
149
+ }
150
+ }
151
+ /** Whether `auto` may pick the native engine in this runtime. */
152
+ export function nativeAutoAllowed(process) {
153
+ // Deno runs Node-API addons only with `--allow-ffi`, and would prompt for
154
+ // it: there `backend: "native"` asks for it explicitly.
155
+ return process.versions["deno"] === undefined;
156
+ }
157
+ let availability;
158
+ /**
159
+ * Loads the addon once per thread: `WEBSLM_NATIVE_PATH` (a `.node` file, for
160
+ * local builds) when set, else the release asset of this platform and
161
+ * version, from `<cacheDir>/native/<version>/` or downloaded there first and
162
+ * checked against `native-manifest.json` (see {@link fetchNativeAddon}).
163
+ * Resolves with the reason when it cannot be used.
164
+ */
165
+ export function loadNativeAddon(cacheDir) {
166
+ availability ??= (async () => {
167
+ const process = nodeProcess();
168
+ if (process === undefined)
169
+ return { reason: "the native engine runs in Node only" };
170
+ const { createRequire } = await importNode("module");
171
+ const base = import.meta.url;
172
+ const loadModule = createRequire(base);
173
+ const version = packageVersion(loadModule);
174
+ const explicit = process.env["WEBSLM_NATIVE_PATH"]?.trim();
175
+ let source;
176
+ if (explicit !== undefined && explicit !== "") {
177
+ source = explicit;
178
+ }
179
+ else {
180
+ const platform = nativePlatform({
181
+ platform: process.platform,
182
+ arch: process.arch,
183
+ ...(process.platform === "linux" ? { musl: await isMusl(process) } : {}),
184
+ });
185
+ if (platform === undefined)
186
+ return { reason: `no native build for ${process.platform}-${process.arch}` };
187
+ if (version === undefined)
188
+ return { reason: "the version of webslm is unknown" };
189
+ const { defaultCacheDir } = await import("./cache/node-fs.js");
190
+ const { offlineMode } = await import("./hub.js");
191
+ const baseUrl = process.env["WEBSLM_NATIVE_URL"]?.trim();
192
+ try {
193
+ source = await fetchNativeAddon({
194
+ platform,
195
+ version,
196
+ manifest: readManifest(loadModule),
197
+ cacheDir: cacheDir ?? (await defaultCacheDir()),
198
+ offline: offlineMode(),
199
+ ...(baseUrl === undefined || baseUrl === "" ? {} : { baseUrl }),
200
+ });
201
+ }
202
+ catch (error) {
203
+ return { reason: error instanceof Error ? error.message : String(error) };
204
+ }
205
+ }
206
+ let addon;
207
+ try {
208
+ addon = loadModule(source);
209
+ }
210
+ catch (error) {
211
+ const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
212
+ return { reason: `${source} does not load (${message})` };
213
+ }
214
+ const actual = addon.version();
215
+ if (version !== undefined && actual !== version) {
216
+ return { reason: `${source} is version ${actual}, webslm is ${version}` };
217
+ }
218
+ return { addon, source };
219
+ })();
220
+ return availability;
221
+ }
222
+ /** The version of this package, from its `package.json`. */
223
+ function packageVersion(loadModule) {
224
+ try {
225
+ return loadModule("../package.json").version;
226
+ }
227
+ catch {
228
+ return undefined;
229
+ }
230
+ }
231
+ /** The package's `native-manifest.json`, when it has one (the published package does). */
232
+ function readManifest(loadModule) {
233
+ try {
234
+ return loadModule("../native-manifest.json");
235
+ }
236
+ catch {
237
+ return undefined;
238
+ }
239
+ }
240
+ /** @internal Forgets the loaded addon (tests). */
241
+ export function resetNativeAddon() {
242
+ availability = undefined;
243
+ }