webslm 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.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +373 -2
  3. package/dist/ai-sdk/index.d.ts +81 -0
  4. package/dist/ai-sdk/index.js +90 -0
  5. package/dist/ai-sdk/language-model.d.ts +77 -0
  6. package/dist/ai-sdk/language-model.js +422 -0
  7. package/dist/ai-sdk/loader.d.ts +54 -0
  8. package/dist/ai-sdk/loader.js +170 -0
  9. package/dist/ai-sdk/output.d.ts +43 -0
  10. package/dist/ai-sdk/output.js +152 -0
  11. package/dist/ai-sdk/prompt.d.ts +21 -0
  12. package/dist/ai-sdk/prompt.js +111 -0
  13. package/dist/async-queue.d.ts +22 -0
  14. package/dist/async-queue.js +70 -0
  15. package/dist/cache/cache-api.d.ts +29 -0
  16. package/dist/cache/cache-api.js +115 -0
  17. package/dist/cache/index.d.ts +21 -0
  18. package/dist/cache/index.js +42 -0
  19. package/dist/cache/memory.d.ts +12 -0
  20. package/dist/cache/memory.js +61 -0
  21. package/dist/cache/models.d.ts +67 -0
  22. package/dist/cache/models.js +107 -0
  23. package/dist/cache/node-fs.d.ts +21 -0
  24. package/dist/cache/node-fs.js +147 -0
  25. package/dist/cache/opfs.d.ts +69 -0
  26. package/dist/cache/opfs.js +181 -0
  27. package/dist/cache/store.d.ts +53 -0
  28. package/dist/cache/store.js +64 -0
  29. package/dist/cache-management.d.ts +23 -0
  30. package/dist/cache-management.js +58 -0
  31. package/dist/capabilities.d.ts +67 -0
  32. package/dist/capabilities.js +55 -0
  33. package/dist/client.d.ts +61 -0
  34. package/dist/client.js +256 -0
  35. package/dist/curated.d.ts +22 -0
  36. package/dist/curated.js +53 -0
  37. package/dist/download.d.ts +51 -0
  38. package/dist/download.js +289 -0
  39. package/dist/engine.d.ts +54 -0
  40. package/dist/engine.js +510 -0
  41. package/dist/errors.d.ts +81 -0
  42. package/dist/errors.js +89 -0
  43. package/dist/hub.d.ts +185 -0
  44. package/dist/hub.js +409 -0
  45. package/dist/index.d.ts +37 -0
  46. package/dist/index.js +41 -0
  47. package/dist/models.d.ts +225 -0
  48. package/dist/models.js +730 -0
  49. package/dist/node-pool-worker.d.ts +6 -0
  50. package/dist/node-pool-worker.js +32 -0
  51. package/dist/node-web-worker.d.ts +23 -0
  52. package/dist/node-web-worker.js +84 -0
  53. package/dist/node-worker.d.ts +2 -0
  54. package/dist/node-worker.js +9 -0
  55. package/dist/pool-worker.d.ts +36 -0
  56. package/dist/pool-worker.js +30 -0
  57. package/dist/pool.d.ts +17 -0
  58. package/dist/pool.js +41 -0
  59. package/dist/protocol.d.ts +246 -0
  60. package/dist/protocol.js +19 -0
  61. package/dist/runtime.d.ts +21 -0
  62. package/dist/runtime.js +53 -0
  63. package/dist/safetensors.d.ts +20 -0
  64. package/dist/safetensors.js +2 -0
  65. package/dist/simple.d.ts +310 -0
  66. package/dist/simple.js +553 -0
  67. package/dist/types.d.ts +412 -0
  68. package/dist/types.js +2 -0
  69. package/dist/wasm-flavour.d.ts +85 -0
  70. package/dist/wasm-flavour.js +169 -0
  71. package/dist/wasm.d.ts +34 -0
  72. package/dist/wasm.js +38 -0
  73. package/dist/worker.d.ts +6 -0
  74. package/dist/worker.js +11 -0
  75. package/package.json +92 -3
  76. package/wasm/relaxed/webslm_wasm.d.ts +325 -0
  77. package/wasm/relaxed/webslm_wasm.js +1899 -0
  78. package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
  79. package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +56 -0
  80. package/wasm/simd/webslm_wasm.d.ts +325 -0
  81. package/wasm/simd/webslm_wasm.js +1899 -0
  82. package/wasm/simd/webslm_wasm_bg.wasm +0 -0
  83. package/wasm/simd/webslm_wasm_bg.wasm.d.ts +56 -0
  84. package/wasm/threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +108 -0
  85. package/wasm/threads/webslm_wasm.d.ts +357 -0
  86. package/wasm/threads/webslm_wasm.js +2100 -0
  87. package/wasm/threads/webslm_wasm_bg.wasm +0 -0
  88. package/wasm/threads/webslm_wasm_bg.wasm.d.ts +66 -0
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Layout of cached checkpoints inside a {@link CacheStore}:
3
+ *
4
+ * ```text
5
+ * {repo}/refs/{revision} commit sha a revision resolved to
6
+ * {repo}/{sha}/.webslm.json manifest: files, sizes, hashes, completeness
7
+ * {repo}/{sha}/{file} checkpoint files
8
+ * ```
9
+ */
10
+ import { type CacheStore } from "./store.js";
11
+ /** Manifest of one cached revision. */
12
+ export interface CacheManifest {
13
+ readonly version: 1;
14
+ readonly repo: string;
15
+ /** Commit sha the files belong to. */
16
+ readonly sha: string;
17
+ /** Files the model needs, with their expected size and known hashes. */
18
+ readonly files: Readonly<Record<string, CachedFileInfo>>;
19
+ /** Whether every file is fully downloaded. */
20
+ readonly complete: boolean;
21
+ /** ISO date of the last change. */
22
+ readonly updatedAt: string;
23
+ }
24
+ export interface CachedFileInfo {
25
+ readonly size: number;
26
+ /** SHA-256 of the stored bytes, computed while downloading. */
27
+ readonly sha256?: string;
28
+ /** Whether the file is fully downloaded (and verified when the hub gave a hash). */
29
+ readonly complete: boolean;
30
+ }
31
+ /** A cached revision of a repository. */
32
+ export interface CachedRevision {
33
+ readonly sha: string;
34
+ /** Branches or tags that resolved to this sha. */
35
+ readonly refs: readonly string[];
36
+ readonly files: readonly {
37
+ readonly name: string;
38
+ readonly sizeBytes: number;
39
+ }[];
40
+ readonly sizeBytes: number;
41
+ readonly complete: boolean;
42
+ }
43
+ /** A cached repository. */
44
+ export interface CachedModel {
45
+ readonly repo: string;
46
+ readonly revisions: readonly CachedRevision[];
47
+ readonly sizeBytes: number;
48
+ /** Where it is stored: `"opfs"`, `"cache-api"`, `"fs"` or `"memory"`. */
49
+ readonly storage: string;
50
+ }
51
+ export declare const MANIFEST_FILE = ".webslm.json";
52
+ /** Checks a repository id and returns it normalized. */
53
+ export declare function checkRepoId(repo: string): string;
54
+ export declare function refPath(repo: string, revision: string): string;
55
+ export declare function revisionDir(repo: string, sha: string): string;
56
+ export declare function filePath(repo: string, sha: string, file: string): string;
57
+ export declare function manifestPath(repo: string, sha: string): string;
58
+ export declare function readRef(store: CacheStore, repo: string, revision: string): Promise<string | undefined>;
59
+ export declare function writeRef(store: CacheStore, repo: string, revision: string, sha: string): Promise<void>;
60
+ export declare function readManifest(store: CacheStore, repo: string, sha: string): Promise<CacheManifest | undefined>;
61
+ export declare function writeManifest(store: CacheStore, manifest: CacheManifest): Promise<void>;
62
+ /** Every cached repository of `store`. */
63
+ export declare function listCachedModelsIn(store: CacheStore): Promise<CachedModel[]>;
64
+ /** Removes a cached repository (every revision) from `store`. */
65
+ export declare function deleteCachedModelIn(store: CacheStore, repo: string): Promise<void>;
66
+ /** Bytes used by `store`. */
67
+ export declare function cacheBytesIn(store: CacheStore): Promise<number>;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Layout of cached checkpoints inside a {@link CacheStore}:
3
+ *
4
+ * ```text
5
+ * {repo}/refs/{revision} commit sha a revision resolved to
6
+ * {repo}/{sha}/.webslm.json manifest: files, sizes, hashes, completeness
7
+ * {repo}/{sha}/{file} checkpoint files
8
+ * ```
9
+ */
10
+ import { joinPath, readText, writeText } from "./store.js";
11
+ export const MANIFEST_FILE = ".webslm.json";
12
+ /** Checks a repository id and returns it normalized. */
13
+ export function checkRepoId(repo) {
14
+ const trimmed = repo.trim().replace(/^\/+|\/+$/g, "");
15
+ if (!/^[\w.-]+(\/[\w.-]+)?$/.test(trimmed) || trimmed.split("/").some((s) => /^\.+$/.test(s))) {
16
+ throw new Error(`invalid repository id "${repo}" (expected "owner/name")`);
17
+ }
18
+ return trimmed;
19
+ }
20
+ export function refPath(repo, revision) {
21
+ return joinPath(repo, "refs", encodeURIComponent(revision));
22
+ }
23
+ export function revisionDir(repo, sha) {
24
+ return joinPath(repo, sha);
25
+ }
26
+ export function filePath(repo, sha, file) {
27
+ return joinPath(repo, sha, file);
28
+ }
29
+ export function manifestPath(repo, sha) {
30
+ return joinPath(repo, sha, MANIFEST_FILE);
31
+ }
32
+ export async function readRef(store, repo, revision) {
33
+ const sha = (await readText(store, refPath(repo, revision)))?.trim();
34
+ return sha === undefined || sha === "" ? undefined : sha;
35
+ }
36
+ export async function writeRef(store, repo, revision, sha) {
37
+ await writeText(store, refPath(repo, revision), sha);
38
+ }
39
+ export async function readManifest(store, repo, sha) {
40
+ const text = await readText(store, manifestPath(repo, sha));
41
+ if (text === undefined)
42
+ return undefined;
43
+ try {
44
+ const manifest = JSON.parse(text);
45
+ return manifest.version === 1 && manifest.sha === sha ? manifest : undefined;
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ }
51
+ export async function writeManifest(store, manifest) {
52
+ await writeText(store, manifestPath(manifest.repo, manifest.sha), JSON.stringify(manifest, null, 2));
53
+ }
54
+ /** Every cached repository of `store`. */
55
+ export async function listCachedModelsIn(store) {
56
+ const entries = await store.list("");
57
+ const manifests = entries.filter((e) => e.path.endsWith(`/${MANIFEST_FILE}`));
58
+ const byRepo = new Map();
59
+ for (const entry of manifests) {
60
+ const parts = entry.path.split("/");
61
+ const sha = parts[parts.length - 2];
62
+ const repo = parts.slice(0, -2).join("/");
63
+ if (sha === undefined || repo === "")
64
+ continue;
65
+ const manifest = await readManifest(store, repo, sha);
66
+ const dir = `${revisionDir(repo, sha)}/`;
67
+ const files = entries
68
+ .filter((e) => e.path.startsWith(dir) && !e.path.endsWith(`/${MANIFEST_FILE}`))
69
+ .map((e) => ({ name: e.path.slice(dir.length), sizeBytes: e.size }));
70
+ const refs = [];
71
+ const refDir = `${repo}/refs/`;
72
+ for (const ref of entries.filter((e) => e.path.startsWith(refDir))) {
73
+ const name = decodeURIComponent(ref.path.slice(refDir.length));
74
+ if ((await readRef(store, repo, name)) === sha)
75
+ refs.push(name);
76
+ }
77
+ const revisions = byRepo.get(repo) ?? [];
78
+ revisions.push({
79
+ sha,
80
+ refs,
81
+ files,
82
+ sizeBytes: files.reduce((n, f) => n + f.sizeBytes, 0),
83
+ complete: manifest?.complete === true,
84
+ });
85
+ byRepo.set(repo, revisions);
86
+ }
87
+ return [...byRepo]
88
+ .map(([repo, revisions]) => ({
89
+ repo,
90
+ revisions,
91
+ sizeBytes: revisions.reduce((n, r) => n + r.sizeBytes, 0),
92
+ storage: store.kind,
93
+ }))
94
+ .sort((a, b) => a.repo.localeCompare(b.repo));
95
+ }
96
+ /** Removes a cached repository (every revision) from `store`. */
97
+ export async function deleteCachedModelIn(store, repo) {
98
+ await store.remove(checkRepoId(repo));
99
+ // Drop the owner directory when it became empty.
100
+ const owner = repo.includes("/") ? repo.split("/")[0] : undefined;
101
+ if (owner !== undefined && (await store.list(owner)).length === 0)
102
+ await store.remove(owner);
103
+ }
104
+ /** Bytes used by `store`. */
105
+ export async function cacheBytesIn(store) {
106
+ return (await store.list("")).reduce((n, e) => n + e.size, 0);
107
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Directory store for Node.js: `WEBSLM_CACHE_DIR`, or `~/.cache/webslm`
3
+ * (`$XDG_CACHE_HOME/webslm` when set).
4
+ */
5
+ import { type CacheEntry, type CacheStore, type CacheWriter } from "./store.js";
6
+ /** The default cache directory in Node. */
7
+ export declare function defaultCacheDir(): Promise<string>;
8
+ export declare class NodeFsStore implements CacheStore {
9
+ #private;
10
+ readonly kind = "fs";
11
+ readonly resumable = true;
12
+ readonly root: string;
13
+ private constructor();
14
+ /** Opens (and creates) the cache directory `root` (default {@link defaultCacheDir}). */
15
+ static open(root?: string): Promise<NodeFsStore>;
16
+ size(path: string): Promise<number | undefined>;
17
+ openWriter(path: string, offset: number): Promise<CacheWriter>;
18
+ read(path: string, start?: number, end?: number): Promise<Uint8Array>;
19
+ list(prefix: string): Promise<CacheEntry[]>;
20
+ remove(path: string): Promise<void>;
21
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Directory store for Node.js: `WEBSLM_CACHE_DIR`, or `~/.cache/webslm`
3
+ * (`$XDG_CACHE_HOME/webslm` when set).
4
+ */
5
+ import { importNode } from "../runtime.js";
6
+ import { pathSegments, resolveRange, } from "./store.js";
7
+ /** The default cache directory in Node. */
8
+ export async function defaultCacheDir() {
9
+ const env = globalThis.process
10
+ ?.env;
11
+ const path = await importNode("path");
12
+ if (env?.WEBSLM_CACHE_DIR)
13
+ return env.WEBSLM_CACHE_DIR;
14
+ if (env?.XDG_CACHE_HOME)
15
+ return path.join(env.XDG_CACHE_HOME, "webslm");
16
+ const os = await importNode("os");
17
+ return path.join(os.homedir(), ".cache", "webslm");
18
+ }
19
+ export class NodeFsStore {
20
+ kind = "fs";
21
+ resumable = true;
22
+ root;
23
+ #fs;
24
+ #path;
25
+ constructor(root, fs, path) {
26
+ this.root = root;
27
+ this.#fs = fs;
28
+ this.#path = path;
29
+ }
30
+ /** Opens (and creates) the cache directory `root` (default {@link defaultCacheDir}). */
31
+ static async open(root) {
32
+ const fs = await importNode("fs/promises");
33
+ const path = await importNode("path");
34
+ const dir = root ?? (await defaultCacheDir());
35
+ await fs.mkdir(dir, { recursive: true });
36
+ return new NodeFsStore(dir, fs, path);
37
+ }
38
+ #resolve(path) {
39
+ return this.#path.join(this.root, ...pathSegments(path));
40
+ }
41
+ async size(path) {
42
+ try {
43
+ const stats = await this.#fs.stat(this.#resolve(path));
44
+ return stats.isDirectory() ? undefined : stats.size;
45
+ }
46
+ catch (error) {
47
+ if (isMissing(error))
48
+ return undefined;
49
+ throw error;
50
+ }
51
+ }
52
+ async openWriter(path, offset) {
53
+ const file = this.#resolve(path);
54
+ await this.#fs.mkdir(this.#path.dirname(file), { recursive: true });
55
+ const size = (await this.size(path)) ?? 0;
56
+ if (offset > size)
57
+ throw new RangeError(`cannot write "${path}" from ${offset}: it is shorter`);
58
+ const handle = await this.#fs.open(file, size === 0 ? "w" : "r+");
59
+ await handle.truncate(offset);
60
+ let position = offset;
61
+ let closed = false;
62
+ const finish = async () => {
63
+ if (closed)
64
+ return;
65
+ closed = true;
66
+ await handle.sync();
67
+ await handle.close();
68
+ };
69
+ return {
70
+ write: async (chunk) => {
71
+ await handle.write(chunk, 0, chunk.length, position);
72
+ position += chunk.length;
73
+ },
74
+ close: finish,
75
+ abort: finish,
76
+ };
77
+ }
78
+ async read(path, start, end) {
79
+ let handle;
80
+ try {
81
+ handle = await this.#fs.open(this.#resolve(path), "r");
82
+ }
83
+ catch (error) {
84
+ if (isMissing(error)) {
85
+ const missing = new Error(`"${path}" is not in the cache`);
86
+ missing.name = "NotFoundError";
87
+ throw missing;
88
+ }
89
+ throw error;
90
+ }
91
+ try {
92
+ const { size } = await handle.stat();
93
+ const [s, e] = resolveRange(path, size, start, end);
94
+ const out = new Uint8Array(e - s);
95
+ let done = 0;
96
+ while (done < out.length) {
97
+ const { bytesRead } = await handle.read(out, done, out.length - done, s + done);
98
+ if (bytesRead === 0)
99
+ throw new Error(`unexpected end of "${path}"`);
100
+ done += bytesRead;
101
+ }
102
+ return out;
103
+ }
104
+ finally {
105
+ await handle.close();
106
+ }
107
+ }
108
+ async list(prefix) {
109
+ const segments = pathSegments(prefix);
110
+ const entries = [];
111
+ const walk = async (dir, base) => {
112
+ let children;
113
+ try {
114
+ children = await this.#fs.readdir(dir, { withFileTypes: true });
115
+ }
116
+ catch (error) {
117
+ if (isMissing(error))
118
+ return;
119
+ throw error;
120
+ }
121
+ for (const child of children) {
122
+ const path = base === "" ? child.name : `${base}/${child.name}`;
123
+ const full = this.#path.join(dir, child.name);
124
+ if (child.isDirectory())
125
+ await walk(full, path);
126
+ else if (child.isFile())
127
+ entries.push({ path, size: (await this.#fs.stat(full)).size });
128
+ }
129
+ };
130
+ await walk(this.#path.join(this.root, ...segments), segments.join("/"));
131
+ return entries.sort((a, b) => a.path.localeCompare(b.path));
132
+ }
133
+ async remove(path) {
134
+ const segments = pathSegments(path);
135
+ if (segments.length === 0) {
136
+ for (const child of await this.#fs.readdir(this.root, { withFileTypes: true })) {
137
+ await this.#fs.rm(this.#path.join(this.root, child.name), { recursive: true, force: true });
138
+ }
139
+ return;
140
+ }
141
+ await this.#fs.rm(this.#resolve(path), { recursive: true, force: true });
142
+ }
143
+ }
144
+ function isMissing(error) {
145
+ const code = error?.code;
146
+ return code === "ENOENT" || code === "ENOTDIR";
147
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Origin Private File System store.
3
+ *
4
+ * Files live under the `webslm/` directory of OPFS. In a dedicated worker,
5
+ * writes go through synchronous access handles (fast, and the only writable
6
+ * API in Safari); on the main thread through writable streams. Reads take a
7
+ * `File` snapshot and slice it, which never locks the file.
8
+ */
9
+ import { type CacheEntry, type CacheStore, type CacheWriter } from "./store.js";
10
+ /** The subset of `FileSystemSyncAccessHandle` used here. */
11
+ export interface SyncAccessHandle {
12
+ write(buffer: Uint8Array, options?: {
13
+ at?: number;
14
+ }): number;
15
+ truncate(size: number): void;
16
+ getSize(): number;
17
+ flush(): void;
18
+ close(): void;
19
+ }
20
+ /** The subset of `FileSystemWritableFileStream` used here. */
21
+ export interface WritableFileStream {
22
+ write(data: Uint8Array): Promise<void>;
23
+ seek(position: number): Promise<void>;
24
+ truncate(size: number): Promise<void>;
25
+ close(): Promise<void>;
26
+ }
27
+ /** The subset of `FileSystemFileHandle` used here. */
28
+ export interface FileHandle {
29
+ readonly kind: "file";
30
+ readonly name: string;
31
+ getFile(): Promise<Blob>;
32
+ createSyncAccessHandle?: () => Promise<SyncAccessHandle>;
33
+ createWritable?: (options?: {
34
+ keepExistingData?: boolean;
35
+ }) => Promise<WritableFileStream>;
36
+ }
37
+ /** The subset of `FileSystemDirectoryHandle` used here. */
38
+ export interface DirectoryHandle {
39
+ readonly kind: "directory";
40
+ readonly name: string;
41
+ getDirectoryHandle(name: string, options?: {
42
+ create?: boolean;
43
+ }): Promise<DirectoryHandle>;
44
+ getFileHandle(name: string, options?: {
45
+ create?: boolean;
46
+ }): Promise<FileHandle>;
47
+ removeEntry(name: string, options?: {
48
+ recursive?: boolean;
49
+ }): Promise<void>;
50
+ entries(): AsyncIterable<[string, DirectoryHandle | FileHandle]>;
51
+ }
52
+ /** Name of the directory holding the cache at the root of OPFS. */
53
+ export declare const OPFS_DIRECTORY = "webslm";
54
+ /** Returns the OPFS root, or `undefined` when OPFS is not available. */
55
+ export declare function opfsRoot(): Promise<DirectoryHandle | undefined>;
56
+ export declare class OpfsStore implements CacheStore {
57
+ #private;
58
+ readonly kind = "opfs";
59
+ readonly resumable = true;
60
+ /** `root` is the directory holding the cache (`webslm/` in OPFS). */
61
+ constructor(root: DirectoryHandle);
62
+ /** Opens the cache in OPFS, or returns `undefined` when OPFS is unavailable. */
63
+ static open(): Promise<OpfsStore | undefined>;
64
+ size(path: string): Promise<number | undefined>;
65
+ openWriter(path: string, offset: number): Promise<CacheWriter>;
66
+ read(path: string, start?: number, end?: number): Promise<Uint8Array>;
67
+ list(prefix: string): Promise<CacheEntry[]>;
68
+ remove(path: string): Promise<void>;
69
+ }
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Origin Private File System store.
3
+ *
4
+ * Files live under the `webslm/` directory of OPFS. In a dedicated worker,
5
+ * writes go through synchronous access handles (fast, and the only writable
6
+ * API in Safari); on the main thread through writable streams. Reads take a
7
+ * `File` snapshot and slice it, which never locks the file.
8
+ */
9
+ import { pathSegments, resolveRange, } from "./store.js";
10
+ /** Name of the directory holding the cache at the root of OPFS. */
11
+ export const OPFS_DIRECTORY = "webslm";
12
+ /** Returns the OPFS root, or `undefined` when OPFS is not available. */
13
+ export async function opfsRoot() {
14
+ const storage = globalThis.navigator?.storage;
15
+ if (typeof storage?.getDirectory !== "function")
16
+ return undefined;
17
+ try {
18
+ return (await storage.getDirectory());
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ export class OpfsStore {
25
+ kind = "opfs";
26
+ resumable = true;
27
+ #root;
28
+ /** `root` is the directory holding the cache (`webslm/` in OPFS). */
29
+ constructor(root) {
30
+ this.#root = root;
31
+ }
32
+ /** Opens the cache in OPFS, or returns `undefined` when OPFS is unavailable. */
33
+ static async open() {
34
+ const root = await opfsRoot();
35
+ if (root === undefined)
36
+ return undefined;
37
+ try {
38
+ return new OpfsStore(await root.getDirectoryHandle(OPFS_DIRECTORY, { create: true }));
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ async #directory(segments, create) {
45
+ let dir = this.#root;
46
+ for (const segment of segments)
47
+ dir = await dir.getDirectoryHandle(segment, { create });
48
+ return dir;
49
+ }
50
+ async #file(path, create) {
51
+ const segments = pathSegments(path);
52
+ const name = segments.pop();
53
+ if (name === undefined)
54
+ throw new Error("empty cache path");
55
+ const dir = await this.#directory(segments, create);
56
+ return dir.getFileHandle(name, { create });
57
+ }
58
+ async size(path) {
59
+ try {
60
+ return (await (await this.#file(path, false)).getFile()).size;
61
+ }
62
+ catch (error) {
63
+ if (isMissing(error))
64
+ return undefined;
65
+ throw error;
66
+ }
67
+ }
68
+ async openWriter(path, offset) {
69
+ const handle = await this.#file(path, true);
70
+ if (typeof handle.createSyncAccessHandle === "function") {
71
+ const access = await handle.createSyncAccessHandle();
72
+ try {
73
+ if (offset > access.getSize()) {
74
+ throw new RangeError(`cannot write "${path}" from ${offset}: it is shorter`);
75
+ }
76
+ access.truncate(offset);
77
+ }
78
+ catch (error) {
79
+ access.close();
80
+ throw error;
81
+ }
82
+ let position = offset;
83
+ let closed = false;
84
+ const finish = async () => {
85
+ if (closed)
86
+ return;
87
+ closed = true;
88
+ access.flush();
89
+ access.close();
90
+ };
91
+ return {
92
+ write: async (chunk) => {
93
+ let done = 0;
94
+ while (done < chunk.length) {
95
+ const written = access.write(chunk.subarray(done), { at: position });
96
+ if (written <= 0)
97
+ throw new Error(`short write to "${path}"`);
98
+ done += written;
99
+ position += written;
100
+ }
101
+ },
102
+ close: finish,
103
+ abort: finish,
104
+ };
105
+ }
106
+ if (typeof handle.createWritable === "function") {
107
+ if (offset > (await handle.getFile()).size) {
108
+ throw new RangeError(`cannot write "${path}" from ${offset}: it is shorter`);
109
+ }
110
+ const stream = await handle.createWritable({ keepExistingData: true });
111
+ await stream.truncate(offset);
112
+ await stream.seek(offset);
113
+ let closed = false;
114
+ const finish = async () => {
115
+ if (closed)
116
+ return;
117
+ closed = true;
118
+ await stream.close();
119
+ };
120
+ return {
121
+ write: (chunk) => stream.write(chunk),
122
+ close: finish,
123
+ // Closing commits what was written, so a later download can resume.
124
+ abort: finish,
125
+ };
126
+ }
127
+ throw new Error("this browser cannot write to the Origin Private File System");
128
+ }
129
+ async read(path, start, end) {
130
+ const file = await (await this.#file(path, false)).getFile();
131
+ const [s, e] = resolveRange(path, file.size, start, end);
132
+ return new Uint8Array(await file.slice(s, e).arrayBuffer());
133
+ }
134
+ async list(prefix) {
135
+ const segments = pathSegments(prefix);
136
+ let dir;
137
+ try {
138
+ dir = await this.#directory(segments, false);
139
+ }
140
+ catch (error) {
141
+ if (isMissing(error))
142
+ return [];
143
+ throw error;
144
+ }
145
+ const entries = [];
146
+ const walk = async (handle, base) => {
147
+ for await (const [name, child] of handle.entries()) {
148
+ const path = base === "" ? name : `${base}/${name}`;
149
+ if (child.kind === "directory")
150
+ await walk(child, path);
151
+ else
152
+ entries.push({ path, size: (await child.getFile()).size });
153
+ }
154
+ };
155
+ await walk(dir, segments.join("/"));
156
+ return entries.sort((a, b) => a.path.localeCompare(b.path));
157
+ }
158
+ async remove(path) {
159
+ const segments = pathSegments(path);
160
+ const name = segments.pop();
161
+ try {
162
+ if (name === undefined) {
163
+ for await (const [child] of this.#root.entries()) {
164
+ await this.#root.removeEntry(child, { recursive: true });
165
+ }
166
+ return;
167
+ }
168
+ const dir = await this.#directory(segments, false);
169
+ await dir.removeEntry(name, { recursive: true });
170
+ }
171
+ catch (error) {
172
+ if (!isMissing(error))
173
+ throw error;
174
+ }
175
+ }
176
+ }
177
+ /** OPFS reports missing entries as `NotFoundError` (and wrong kinds as `TypeMismatchError`). */
178
+ function isMissing(error) {
179
+ const name = error?.name;
180
+ return name === "NotFoundError" || name === "TypeMismatchError";
181
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Storage for downloaded checkpoints.
3
+ *
4
+ * Paths are relative to the cache root and use `/`:
5
+ * `{repo}/{sha}/{file}` for files, `{repo}/{sha}/.webslm.json` for the
6
+ * manifest and `{repo}/refs/{revision}` for resolved revisions. Each backend
7
+ * places that tree somewhere of its own: the `webslm/` directory of OPFS, a
8
+ * Cache API cache, a directory in Node, or memory.
9
+ */
10
+ /** A file being written, appended to from the offset it was opened at. */
11
+ export interface CacheWriter {
12
+ write(chunk: Uint8Array): Promise<void>;
13
+ /** Flushes and commits the file. */
14
+ close(): Promise<void>;
15
+ /** Discards a writer that will not be closed (the bytes written so far may stay). */
16
+ abort(): Promise<void>;
17
+ }
18
+ /** A stored file and its size. */
19
+ export interface CacheEntry {
20
+ readonly path: string;
21
+ readonly size: number;
22
+ }
23
+ export interface CacheStore {
24
+ /** `"opfs"`, `"cache-api"`, `"memory"` or `"fs"`. */
25
+ readonly kind: string;
26
+ /** Whether a partial file can be extended (resumable downloads). */
27
+ readonly resumable: boolean;
28
+ /** Size of a stored file, `undefined` when absent. */
29
+ size(path: string): Promise<number | undefined>;
30
+ /**
31
+ * Opens `path` for writing from byte `offset`: bytes after it are dropped,
32
+ * bytes before it are kept (`offset` must not exceed the current size).
33
+ */
34
+ openWriter(path: string, offset: number): Promise<CacheWriter>;
35
+ /** Reads bytes `[start, end)` of a stored file, or the whole file. */
36
+ read(path: string, start?: number, end?: number): Promise<Uint8Array>;
37
+ /** Every stored file under `prefix` (a directory path, `""` for all). */
38
+ list(prefix: string): Promise<CacheEntry[]>;
39
+ /** Removes a file or a directory tree. Missing paths are ignored. */
40
+ remove(path: string): Promise<void>;
41
+ }
42
+ /** Splits a cache path into its segments, refusing anything that could escape the root. */
43
+ export declare function pathSegments(path: string): string[];
44
+ /** Joins path segments with `/`. */
45
+ export declare function joinPath(...parts: string[]): string;
46
+ /** Reads a stored UTF-8 text file, `undefined` when absent. */
47
+ export declare function readText(store: CacheStore, path: string): Promise<string | undefined>;
48
+ /** Writes a whole UTF-8 text file. */
49
+ export declare function writeText(store: CacheStore, path: string, text: string): Promise<void>;
50
+ /** Concatenates chunks into one array. */
51
+ export declare function concatChunks(chunks: readonly Uint8Array[], total?: number): Uint8Array;
52
+ /** Validates a `[start, end)` range against a file size and returns it resolved. */
53
+ export declare function resolveRange(path: string, size: number, start?: number, end?: number): [number, number];