@moss-dev/moss-web 1.0.1 → 1.3.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/README.md CHANGED
@@ -18,12 +18,18 @@ Built on WebAssembly for near-native performance in any modern browser.
18
18
  npm install @moss-dev/moss-web
19
19
  ```
20
20
 
21
+ Version 1.3.0 resolves `@moss-dev/moss-wasm@0.16.0`. Text `query()` loads its
22
+ model through the Moss service using the client's credentials, so the service
23
+ must be reachable the first time a model is loaded; there is no offline
24
+ fallback. The only published npm versions before this are 1.0.0 and 1.0.1,
25
+ where `queryWithEmbedding()` remains available for caller-supplied embeddings.
26
+
21
27
  ## Quick Start
22
28
 
23
29
  ```typescript
24
30
  import { MossClient } from "@moss-dev/moss-web";
25
31
 
26
- // Initialize client (WASM/model download happens automatically on first use)
32
+ // Initialize client (WASM loads on first use; the exact model artifact loads on first query)
27
33
  const client = new MossClient("your-project-id", "your-project-key");
28
34
 
29
35
  // Create an index with documents
@@ -47,17 +53,53 @@ results.docs.forEach((doc) => {
47
53
  ### Creating a Client
48
54
 
49
55
  ```typescript
50
- // Simple: lazy initialization (WASM/model loads on first API call)
56
+ // Simple: lazy WASM initialization
51
57
  const client = new MossClient(projectId, projectKey, options?);
52
58
 
53
- // Alternative: eager initialization (WASM/model loads immediately)
59
+ // Alternative: eager WASM initialization
54
60
  const client = await MossClient.create(projectId, projectKey, options?);
61
+
62
+ // Production frontends: keep the project key on your server and pass an
63
+ // IAuthenticator that fetches short-lived tokens from your backend
64
+ const client = new MossClient(projectId, authenticator, options?);
65
+ const client = await MossClient.create(projectId, authenticator, options?);
66
+ ```
67
+
68
+ **Custom authenticator:**
69
+
70
+ ```typescript
71
+ import type { IAuthenticator, AuthToken } from "@moss-dev/moss-web";
72
+
73
+ class MyBackendAuthenticator implements IAuthenticator {
74
+ async getAuthToken(): Promise<AuthToken> {
75
+ const res = await fetch("/api/moss-token", { method: "POST" });
76
+ return res.json(); // { token, expiresIn }
77
+ }
78
+ }
79
+
80
+ const client = new MossClient(projectId, new MyBackendAuthenticator());
81
+ await client.getAuthToken(); // cached AuthToken
55
82
  ```
56
83
 
84
+ The client calls `getAuthToken()` only and sends the token as `Authorization: Bearer <token>`. `getAuthHeader()` on an `IAuthenticator` is optional and deprecated, since the client never calls it.
85
+
86
+ A token is cached until 60 seconds before it expires, or for 90% of its life when that is later, and refetched after a 401. A token whose `expiresIn` is not a positive finite number of seconds is not cached, so each request fetches a new one.
87
+
57
88
  **Options:**
58
89
 
59
90
  - `model` — `"moss-minilm"` (default, fast, for most use-cases) or `"moss-mediumlm"`
60
91
  - `baseUrl` — Custom API base URL (for self-hosted Moss instances)
92
+ - `onProgress` — Called with `{ modelId, loadedBytes, totalBytes, fromCache }` while the embedding model downloads
93
+
94
+ The first text query waits for the embedding model. The model grant request fails after 30 seconds without an answer. Each model file request aborts after 30 seconds without data and is retried once. The verified model is kept in the browser Cache API and checked against its SHA-256 before each use, so later page loads skip the download. On pages without the Cache API, such as plain HTTP, it downloads on each page load.
95
+
96
+ ```typescript
97
+ const client = new MossClient(projectId, projectKey, {
98
+ onProgress: ({ loadedBytes, totalBytes }) => {
99
+ progressBar.value = loadedBytes / totalBytes;
100
+ },
101
+ });
102
+ ```
61
103
 
62
104
  ### Index Management
63
105
 
@@ -96,22 +138,70 @@ await client.getJobStatus(jobId);
96
138
  // Load index into browser memory for querying
97
139
  await client.loadIndex(name, options?);
98
140
 
141
+ // Load several indexes; failures are reported per name, successes are kept
142
+ await client.loadIndexes(names, options?);
143
+
99
144
  // Check if index is loaded locally
100
145
  await client.hasIndex(name);
101
146
 
102
147
  // Get local index info
103
148
  await client.getIndexInfo(name);
104
149
 
105
- // Query loaded index (runs in-browser)
150
+ // Query a foundation-model index using its server-bound immutable artifact
106
151
  await client.query(name, queryText, options?);
107
152
 
153
+ // Query a custom index with a caller-supplied embedding
154
+ await client.queryWithEmbedding(name, queryText, embedding, options?);
155
+
156
+ // Search several loaded indexes at once; results carry their source indexName
157
+ await client.queryMultiIndex(names, queryText, options?);
158
+
159
+ // Multi-index search with a caller-supplied embedding
160
+ await client.queryMultiIndexWithEmbedding(names, queryText, embedding, options?);
161
+
108
162
  // Refresh index from server
109
163
  await client.refreshIndex(name);
110
164
 
111
165
  // Unload index from browser memory
112
166
  await client.unloadIndex(name);
167
+
168
+ // Unload several indexes; names that are not loaded are ignored
169
+ await client.unloadIndexes(names);
170
+ ```
171
+
172
+ `loadIndex` and `loadIndexes` accept `LoadIndexOptions` (`autoRefresh`,
173
+ `pollingIntervalInSeconds`) for parity with the Node SDK, but the browser SDK
174
+ does not honor them yet; use `refreshIndex` to pull server updates.
175
+
176
+ #### Multi-index search
177
+
178
+ All named indexes must already be loaded and share one embedding model
179
+ artifact. `topK` is the global cap across the union, not a per-index cap
180
+ (default `10`, matching the Node SDK; single-index `query` defaults to `5`), and
181
+ `alpha` behaves as it does for a single index: `1.0` embedding-only, `0.0`
182
+ keyword-only, values in between fuse both rankings (default `0.8`). Every
183
+ returned document carries the `indexName` it came from; single-index results
184
+ leave `indexName` unset.
185
+
186
+ ```typescript
187
+ const { loaded, failed } = await client.loadIndexes(["handbook", "changelog"]);
188
+ console.log(loaded, failed); // ["handbook", "changelog"] {}
189
+
190
+ const results = await client.queryMultiIndex(loaded, "refund policy", {
191
+ topK: 5,
192
+ alpha: 0.8,
193
+ });
194
+ results.docs.forEach((doc) => {
195
+ console.log(`${doc.indexName}/${doc.id}: ${doc.score}`);
196
+ });
197
+
198
+ await client.unloadIndexes(loaded);
113
199
  ```
114
200
 
201
+ Multi-index search needs a `@moss-dev/moss-wasm` that exposes
202
+ `queryMultiIndexWithModelIdentity`; older packages fail fast with an upgrade
203
+ error.
204
+
115
205
  ### Cleanup
116
206
 
117
207
  ```typescript
@@ -0,0 +1,14 @@
1
+ export interface AuthToken {
2
+ token: string;
3
+ /** Seconds until the token expires. A token without a positive finite value is not cached. */
4
+ expiresIn: number;
5
+ }
6
+ /**
7
+ * Supplies short-lived tokens to `MossClient`.
8
+ * The client calls `getAuthToken` only and sends `Authorization: Bearer <token>`.
9
+ */
10
+ export interface IAuthenticator {
11
+ getAuthToken(): Promise<AuthToken>;
12
+ /** @deprecated The client never calls this. It builds the header from `getAuthToken`. */
13
+ getAuthHeader?(): Promise<string>;
14
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ import type { IAuthenticator, AuthToken } from "./authenticator.interface";
2
+ export declare class CachingAuthenticator implements IAuthenticator {
3
+ private readonly inner;
4
+ private cache;
5
+ private inflight;
6
+ constructor(inner: IAuthenticator);
7
+ getAuthToken(): Promise<AuthToken>;
8
+ /** The header the client sends, built from `getAuthToken`. */
9
+ getAuthHeader(): Promise<string>;
10
+ invalidate(): void;
11
+ private fetchAndCache;
12
+ }
@@ -0,0 +1,49 @@
1
+ export class CachingAuthenticator {
2
+ constructor(inner) {
3
+ this.inner = inner;
4
+ this.cache = null;
5
+ this.inflight = null;
6
+ }
7
+ async getAuthToken() {
8
+ if (this.cache && this.cache.expiresAt > Date.now()) {
9
+ return { token: this.cache.token, expiresIn: this.cache.expiresIn };
10
+ }
11
+ if (this.inflight) {
12
+ return this.inflight;
13
+ }
14
+ this.inflight = this.fetchAndCache();
15
+ try {
16
+ return await this.inflight;
17
+ }
18
+ finally {
19
+ this.inflight = null;
20
+ }
21
+ }
22
+ /** The header the client sends, built from `getAuthToken`. */
23
+ async getAuthHeader() {
24
+ const { token } = await this.getAuthToken();
25
+ return `Bearer ${token}`;
26
+ }
27
+ invalidate() {
28
+ this.cache = null;
29
+ }
30
+ async fetchAndCache() {
31
+ const { token, expiresIn } = await this.inner.getAuthToken();
32
+ const lifetime = cacheLifetimeSeconds(expiresIn);
33
+ this.cache = lifetime > 0
34
+ ? { token, expiresIn, expiresAt: Date.now() + lifetime * 1000 }
35
+ : null;
36
+ return { token, expiresIn };
37
+ }
38
+ }
39
+ /**
40
+ * Seconds to serve a token from the cache: until 60 seconds
41
+ * before it expires, or for 90% of its life when that is later.
42
+ * Returns 0, meaning uncached, unless `expiresIn` is a positive finite number.
43
+ */
44
+ function cacheLifetimeSeconds(expiresIn) {
45
+ if (!Number.isFinite(expiresIn) || expiresIn <= 0) {
46
+ return 0;
47
+ }
48
+ return Math.max(expiresIn * 0.9, expiresIn - 60);
49
+ }
package/dist/client.d.ts CHANGED
@@ -1,26 +1,29 @@
1
- import type { MossClientOptions, IndexInfo, SearchResult, QueryOptions, RefreshResult, DocumentInfo, MutationResult, CreateIndexOptions, MutationOptions, ParseFileInput, JobStatusResponse, GetDocumentsOptions, LoadIndexOptions } from "./types";
1
+ import type { AuthToken, IAuthenticator } from "./auth/authenticator.interface.js";
2
+ import type { MossClientOptions, IndexInfo, SearchResult, QueryOptions, RefreshResult, DocumentInfo, MutationResult, CreateIndexOptions, MutationOptions, ParseFileInput, JobStatusResponse, GetDocumentsOptions, LoadIndexOptions, LoadIndexesResult } from "./types.js";
2
3
  export declare class MossClient {
3
4
  private readonly projectId;
4
5
  private readonly projectKey;
6
+ private readonly authenticator;
5
7
  private readonly options;
6
8
  private initialized;
7
9
  private indexManager;
8
10
  private manageClient;
9
- private defaultModel;
10
- private readonly embedders;
11
- private readonly indexModels;
11
+ private embedder;
12
+ private projectKeyAuthenticator;
12
13
  private initPromise;
14
+ private readonly modelArtifacts;
13
15
  constructor(projectId: string, projectKey: string, options?: MossClientOptions);
16
+ constructor(projectId: string, authenticator: IAuthenticator, options?: MossClientOptions);
17
+ getAuthToken(): Promise<AuthToken>;
14
18
  /**
15
19
  * Create and initialize a new MossClient instance.
16
20
  * This is the recommended way to create a client as it ensures
17
21
  * the WASM modules are loaded before returning.
18
22
  */
19
23
  static create(projectId: string, projectKey: string, options?: MossClientOptions): Promise<MossClient>;
24
+ static create(projectId: string, authenticator: IAuthenticator, options?: MossClientOptions): Promise<MossClient>;
20
25
  private ensureInitialized;
21
26
  private doInit;
22
- private getEmbedder;
23
- private resolveIndexModel;
24
27
  private getIndexManager;
25
28
  private getManageClient;
26
29
  createIndex(indexName: string, docs: DocumentInfo[], options?: CreateIndexOptions): Promise<MutationResult>;
@@ -34,9 +37,50 @@ export declare class MossClient {
34
37
  getJobStatus(jobId: string): Promise<JobStatusResponse>;
35
38
  loadIndex(indexName: string, _options?: LoadIndexOptions): Promise<string>;
36
39
  unloadIndex(indexName: string): Promise<void>;
40
+ /**
41
+ * Best-effort bulk load. Loads one index at a time so each keeps its own
42
+ * model artifact identity; failures are reported in `failed` and never roll
43
+ * back the indexes that did load.
44
+ */
45
+ loadIndexes(indexNames: string[], options?: LoadIndexOptions): Promise<LoadIndexesResult>;
46
+ /** Best-effort bulk unload; names that are not loaded are ignored. */
47
+ unloadIndexes(indexNames: string[]): Promise<void>;
37
48
  hasIndex(indexName: string): Promise<boolean>;
38
49
  getIndexInfo(indexName: string): Promise<IndexInfo>;
39
50
  refreshIndex(indexName: string): Promise<RefreshResult>;
51
+ /**
52
+ * Embeds `query` locally and searches one loaded index.
53
+ *
54
+ * A blank `query` (empty or only whitespace) returns no results at every
55
+ * `alpha`, without running the embedding model. `topK` 0 returns no results.
56
+ */
40
57
  query(indexName: string, query: string, options?: QueryOptions): Promise<SearchResult>;
58
+ queryWithEmbedding(indexName: string, query: string, embedding: Float32Array | number[], options?: QueryOptions): Promise<SearchResult>;
59
+ /**
60
+ * Search several loaded indexes in one call and return the global top-k,
61
+ * each result tagged with its source `indexName`. Local-only: every name
62
+ * must already be loaded, and all must share one embedding model artifact.
63
+ *
64
+ * `alpha` matches the single-index `query`: `1.0` is embedding-only, `0.0`
65
+ * is keyword-only, and values between fuse both rankings. `topK` is the
66
+ * global cap across the union, not a per-index cap, and 0 returns no results.
67
+ * A blank `query` returns no results without running the embedding model.
68
+ */
69
+ queryMultiIndex(indexNames: string[], query: string, options?: QueryOptions): Promise<SearchResult>;
70
+ /** As `queryMultiIndex`, with a caller-supplied query vector. */
71
+ queryMultiIndexWithEmbedding(indexNames: string[], query: string, embedding: Float32Array | number[], options?: QueryOptions): Promise<SearchResult>;
72
+ /**
73
+ * The one model artifact identity every named index shares, or `null` when
74
+ * none of them has one (custom or legacy embeddings). Throws when they
75
+ * disagree, because a single query vector cannot serve two models.
76
+ */
77
+ private resolveSharedModelIdentity;
78
+ /** As `resolveSharedModelIdentity`, for the text path, which cannot embed
79
+ * without an exact identity to bind the vector to. */
80
+ private sharedModelIdentity;
81
+ private modelIdentityForIndex;
82
+ private modelIdentityFromInfo;
83
+ private modelIdentityFromRefresh;
84
+ private exactModelIdentity;
41
85
  dispose(): void;
42
86
  }