@moss-dev/moss-web 1.0.0 → 1.2.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.2.0 resolves `@moss-dev/moss-wasm@0.15.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,13 +53,40 @@ 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
+ async getAuthHeader(): Promise<string> {
79
+ const { token } = await this.getAuthToken();
80
+ return `Bearer ${token}`;
81
+ }
82
+ }
83
+
84
+ const client = new MossClient(projectId, new MyBackendAuthenticator());
85
+ await client.getAuthToken(); // cached AuthToken
55
86
  ```
56
87
 
88
+ Tokens are cached until 60 seconds before expiry and refetched after a 401.
89
+
57
90
  **Options:**
58
91
 
59
92
  - `model` — `"moss-minilm"` (default, fast, for most use-cases) or `"moss-mediumlm"`
@@ -96,22 +129,70 @@ await client.getJobStatus(jobId);
96
129
  // Load index into browser memory for querying
97
130
  await client.loadIndex(name, options?);
98
131
 
132
+ // Load several indexes; failures are reported per name, successes are kept
133
+ await client.loadIndexes(names, options?);
134
+
99
135
  // Check if index is loaded locally
100
136
  await client.hasIndex(name);
101
137
 
102
138
  // Get local index info
103
139
  await client.getIndexInfo(name);
104
140
 
105
- // Query loaded index (runs in-browser)
141
+ // Query a foundation-model index using its server-bound immutable artifact
106
142
  await client.query(name, queryText, options?);
107
143
 
144
+ // Query a custom index with a caller-supplied embedding
145
+ await client.queryWithEmbedding(name, queryText, embedding, options?);
146
+
147
+ // Search several loaded indexes at once; results carry their source indexName
148
+ await client.queryMultiIndex(names, queryText, options?);
149
+
150
+ // Multi-index search with a caller-supplied embedding
151
+ await client.queryMultiIndexWithEmbedding(names, queryText, embedding, options?);
152
+
108
153
  // Refresh index from server
109
154
  await client.refreshIndex(name);
110
155
 
111
156
  // Unload index from browser memory
112
157
  await client.unloadIndex(name);
158
+
159
+ // Unload several indexes; names that are not loaded are ignored
160
+ await client.unloadIndexes(names);
113
161
  ```
114
162
 
163
+ `loadIndex` and `loadIndexes` accept `LoadIndexOptions` (`autoRefresh`,
164
+ `pollingIntervalInSeconds`) for parity with the Node SDK, but the browser SDK
165
+ does not honor them yet; use `refreshIndex` to pull server updates.
166
+
167
+ #### Multi-index search
168
+
169
+ All named indexes must already be loaded and share one embedding model
170
+ artifact. `topK` is the global cap across the union, not a per-index cap
171
+ (default `10`, matching the Node SDK; single-index `query` defaults to `5`), and
172
+ `alpha` behaves as it does for a single index: `1.0` embedding-only, `0.0`
173
+ keyword-only, values in between fuse both rankings (default `0.8`). Every
174
+ returned document carries the `indexName` it came from; single-index results
175
+ leave `indexName` unset.
176
+
177
+ ```typescript
178
+ const { loaded, failed } = await client.loadIndexes(["handbook", "changelog"]);
179
+ console.log(loaded, failed); // ["handbook", "changelog"] {}
180
+
181
+ const results = await client.queryMultiIndex(loaded, "refund policy", {
182
+ topK: 5,
183
+ alpha: 0.8,
184
+ });
185
+ results.docs.forEach((doc) => {
186
+ console.log(`${doc.indexName}/${doc.id}: ${doc.score}`);
187
+ });
188
+
189
+ await client.unloadIndexes(loaded);
190
+ ```
191
+
192
+ Multi-index search needs a `@moss-dev/moss-wasm` that exposes
193
+ `queryMultiIndexWithModelIdentity`; older packages fail fast with an upgrade
194
+ error.
195
+
115
196
  ### Cleanup
116
197
 
117
198
  ```typescript
@@ -0,0 +1,8 @@
1
+ export interface AuthToken {
2
+ token: string;
3
+ expiresIn: number;
4
+ }
5
+ export interface IAuthenticator {
6
+ getAuthToken(): Promise<AuthToken>;
7
+ getAuthHeader(): Promise<string>;
8
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
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
+ getAuthHeader(): Promise<string>;
9
+ invalidate(): void;
10
+ private fetchAndCache;
11
+ }
@@ -0,0 +1,35 @@
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
+ async getAuthHeader() {
23
+ const { token } = await this.getAuthToken();
24
+ return `Bearer ${token}`;
25
+ }
26
+ invalidate() {
27
+ this.cache = null;
28
+ }
29
+ async fetchAndCache() {
30
+ const { token, expiresIn } = await this.inner.getAuthToken();
31
+ const expiresAt = Date.now() + (expiresIn - 60) * 1000;
32
+ this.cache = { token, expiresIn, expiresAt };
33
+ return { token, expiresIn };
34
+ }
35
+ }
package/dist/client.d.ts CHANGED
@@ -1,20 +1,27 @@
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
11
  private embedder;
12
+ private projectKeyAuthenticator;
10
13
  private initPromise;
14
+ private readonly modelArtifacts;
11
15
  constructor(projectId: string, projectKey: string, options?: MossClientOptions);
16
+ constructor(projectId: string, authenticator: IAuthenticator, options?: MossClientOptions);
17
+ getAuthToken(): Promise<AuthToken>;
12
18
  /**
13
19
  * Create and initialize a new MossClient instance.
14
20
  * This is the recommended way to create a client as it ensures
15
21
  * the WASM modules are loaded before returning.
16
22
  */
17
23
  static create(projectId: string, projectKey: string, options?: MossClientOptions): Promise<MossClient>;
24
+ static create(projectId: string, authenticator: IAuthenticator, options?: MossClientOptions): Promise<MossClient>;
18
25
  private ensureInitialized;
19
26
  private doInit;
20
27
  private getIndexManager;
@@ -30,9 +37,43 @@ export declare class MossClient {
30
37
  getJobStatus(jobId: string): Promise<JobStatusResponse>;
31
38
  loadIndex(indexName: string, _options?: LoadIndexOptions): Promise<string>;
32
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>;
33
48
  hasIndex(indexName: string): Promise<boolean>;
34
49
  getIndexInfo(indexName: string): Promise<IndexInfo>;
35
50
  refreshIndex(indexName: string): Promise<RefreshResult>;
36
51
  query(indexName: string, query: string, options?: QueryOptions): Promise<SearchResult>;
52
+ queryWithEmbedding(indexName: string, query: string, embedding: Float32Array | number[], options?: QueryOptions): Promise<SearchResult>;
53
+ /**
54
+ * Search several loaded indexes in one call and return the global top-k,
55
+ * each result tagged with its source `indexName`. Local-only: every name
56
+ * must already be loaded, and all must share one embedding model artifact.
57
+ *
58
+ * `alpha` matches the single-index `query`: `1.0` is embedding-only, `0.0`
59
+ * is keyword-only, and values between fuse both rankings. `topK` is the
60
+ * global cap across the union, not a per-index cap.
61
+ */
62
+ queryMultiIndex(indexNames: string[], query: string, options?: QueryOptions): Promise<SearchResult>;
63
+ /** As `queryMultiIndex`, with a caller-supplied query vector. */
64
+ queryMultiIndexWithEmbedding(indexNames: string[], query: string, embedding: Float32Array | number[], options?: QueryOptions): Promise<SearchResult>;
65
+ /**
66
+ * The one model artifact identity every named index shares, or `null` when
67
+ * none of them has one (custom or legacy embeddings). Throws when they
68
+ * disagree, because a single query vector cannot serve two models.
69
+ */
70
+ private resolveSharedModelIdentity;
71
+ /** As `resolveSharedModelIdentity`, for the text path, which cannot embed
72
+ * without an exact identity to bind the vector to. */
73
+ private sharedModelIdentity;
74
+ private modelIdentityForIndex;
75
+ private modelIdentityFromInfo;
76
+ private modelIdentityFromRefresh;
77
+ private exactModelIdentity;
37
78
  dispose(): void;
38
79
  }
package/dist/client.js CHANGED
@@ -1,24 +1,48 @@
1
- import wasmInit, { IndexManager, ManageClient, Tokenizer as WasmTokenizer, poolAndNormalize, } from "@moss-dev/moss-wasm";
2
- import { Embedder } from "./embedder";
1
+ import wasmInit, { IndexManager, ManageClient, ModelKeyExchange, ProjectKeyAuthenticator, openSealedModel, poolAndNormalize, } from "@moss-dev/moss-wasm";
2
+ import { CachingAuthenticator } from "./auth/caching.authenticator.js";
3
+ import { Embedder } from "./embedder.js";
4
+ import { ModelArtifactOwnership } from "./model-artifact-ownership.js";
5
+ import { exactModelArtifactIdentity, provenanceAwareIndexManager, queryWithResolvedModelIdentity, requireMultiIndexIndexManager, requireProvenanceAwareIndexManager, } from "./wasm-runtime-capability.js";
3
6
  const DEFAULT_MODEL = "moss-minilm";
7
+ function sameModelArtifactIdentity(left, right) {
8
+ if (left === null || right === null)
9
+ return left === right;
10
+ return left.modelId === right.modelId
11
+ && left.version === right.version
12
+ && left.manifestSha256 === right.manifestSha256;
13
+ }
4
14
  export class MossClient {
5
- constructor(projectId, projectKey, options) {
15
+ constructor(projectId, auth, options) {
6
16
  this.initialized = false;
7
17
  this.indexManager = null;
8
18
  this.manageClient = null;
9
19
  this.embedder = null;
20
+ this.projectKeyAuthenticator = null;
10
21
  this.initPromise = null;
22
+ this.modelArtifacts = new ModelArtifactOwnership((identities) => {
23
+ this.embedder?.retainModelArtifacts(identities);
24
+ });
11
25
  this.projectId = projectId;
12
- this.projectKey = projectKey;
26
+ if (typeof auth === "string") {
27
+ this.projectKey = auth;
28
+ this.authenticator = null;
29
+ }
30
+ else {
31
+ this.projectKey = null;
32
+ this.authenticator = new CachingAuthenticator(auth);
33
+ }
13
34
  this.options = options ?? {};
14
35
  }
15
- /**
16
- * Create and initialize a new MossClient instance.
17
- * This is the recommended way to create a client as it ensures
18
- * the WASM modules are loaded before returning.
19
- */
20
- static async create(projectId, projectKey, options) {
21
- const client = new MossClient(projectId, projectKey, options);
36
+ async getAuthToken() {
37
+ if (!this.authenticator) {
38
+ throw new Error("getAuthToken() requires a custom IAuthenticator; the projectKey path exchanges tokens inside the WASM runtime");
39
+ }
40
+ return this.authenticator.getAuthToken();
41
+ }
42
+ static async create(projectId, auth, options) {
43
+ const client = typeof auth === "string"
44
+ ? new MossClient(projectId, auth, options)
45
+ : new MossClient(projectId, auth, options);
22
46
  await client.ensureInitialized();
23
47
  return client;
24
48
  }
@@ -32,16 +56,39 @@ export class MossClient {
32
56
  }
33
57
  async doInit() {
34
58
  await wasmInit(this.options.wasmUrl);
35
- if (this.options.baseUrl) {
36
- this.indexManager = IndexManager.withBaseUrl(this.projectId, this.projectKey, this.options.baseUrl);
37
- this.manageClient = ManageClient.withBaseUrl(this.projectId, this.projectKey, this.options.baseUrl);
59
+ let deliveryAuth;
60
+ if (this.authenticator) {
61
+ const auth = this.authenticator;
62
+ const getAuthHeader = () => auth.getAuthHeader();
63
+ const invalidate = () => auth.invalidate();
64
+ deliveryAuth = { getAuthHeader, invalidate };
65
+ this.indexManager = IndexManager.withAuthenticator(this.projectId, getAuthHeader, invalidate, this.options.baseUrl);
66
+ this.manageClient = ManageClient.withAuthenticator(this.projectId, getAuthHeader, invalidate, this.options.baseUrl);
38
67
  }
39
68
  else {
40
- this.indexManager = new IndexManager(this.projectId, this.projectKey);
41
- this.manageClient = new ManageClient(this.projectId, this.projectKey);
69
+ const projectKeyAuth = new ProjectKeyAuthenticator(this.projectId, this.projectKey);
70
+ this.projectKeyAuthenticator = projectKeyAuth;
71
+ deliveryAuth = {
72
+ getAuthHeader: () => projectKeyAuth.getAuthHeader(),
73
+ invalidate: () => projectKeyAuth.invalidate(),
74
+ };
75
+ if (this.options.baseUrl) {
76
+ this.indexManager = IndexManager.withBaseUrl(this.projectId, this.projectKey, this.options.baseUrl);
77
+ this.manageClient = ManageClient.withBaseUrl(this.projectId, this.projectKey, this.options.baseUrl);
78
+ }
79
+ else {
80
+ this.indexManager = new IndexManager(this.projectId, this.projectKey);
81
+ this.manageClient = new ManageClient(this.projectId, this.projectKey);
82
+ }
42
83
  }
43
84
  const model = this.options.model ?? DEFAULT_MODEL;
44
- this.embedder = new Embedder(model, WasmTokenizer, poolAndNormalize);
85
+ this.embedder = new Embedder(model, poolAndNormalize, {
86
+ projectId: this.projectId,
87
+ auth: deliveryAuth,
88
+ runtime: { newKeyExchange: () => new ModelKeyExchange(), openSealedModel },
89
+ baseUrl: this.options.baseUrl,
90
+ artifactOrigin: this.options.modelArtifactOrigin,
91
+ });
45
92
  await this.embedder.init(this.options.onnxWasmPath);
46
93
  this.initialized = true;
47
94
  }
@@ -57,12 +104,13 @@ export class MossClient {
57
104
  async createIndex(indexName, docs, options) {
58
105
  const manage = await this.getManageClient();
59
106
  const hasEmbeddings = docs.some((d) => Array.isArray(d.embedding) && d.embedding.length > 0);
60
- const modelId = options?.modelId ?? (hasEmbeddings ? "custom" : DEFAULT_MODEL);
107
+ const modelId = options?.modelId
108
+ ?? (hasEmbeddings ? "custom" : (this.options.model ?? DEFAULT_MODEL));
61
109
  return manage.createIndex(indexName, docs, modelId);
62
110
  }
63
111
  async createIndexFromFiles(indexName, files, options) {
64
112
  const manage = await this.getManageClient();
65
- const modelId = options?.modelId ?? DEFAULT_MODEL;
113
+ const modelId = options?.modelId ?? (this.options.model ?? DEFAULT_MODEL);
66
114
  return manage.createIndexFromFiles(indexName, files, modelId);
67
115
  }
68
116
  async addDocs(indexName, docs, options) {
@@ -96,12 +144,43 @@ export class MossClient {
96
144
  // ── Local index operations ─────────────────────────────────
97
145
  async loadIndex(indexName, _options) {
98
146
  const im = await this.getIndexManager();
99
- await im.loadIndex(indexName);
147
+ await this.modelArtifacts.replaceAfter(indexName, () => im.loadIndex(indexName), (info) => provenanceAwareIndexManager(im)
148
+ ? this.modelIdentityFromInfo(info)
149
+ : null, async () => {
150
+ await im.unloadIndex(indexName);
151
+ });
100
152
  return indexName;
101
153
  }
102
154
  async unloadIndex(indexName) {
103
155
  const im = await this.getIndexManager();
104
- return im.unloadIndex(indexName);
156
+ await this.modelArtifacts.removeAfter(indexName, () => im.unloadIndex(indexName));
157
+ }
158
+ /**
159
+ * Best-effort bulk load. Loads one index at a time so each keeps its own
160
+ * model artifact identity; failures are reported in `failed` and never roll
161
+ * back the indexes that did load.
162
+ */
163
+ async loadIndexes(indexNames, options) {
164
+ const result = { loaded: [], failed: {} };
165
+ for (const name of indexNames) {
166
+ try {
167
+ await this.loadIndex(name, options);
168
+ result.loaded.push(name);
169
+ }
170
+ catch (error) {
171
+ result.failed[name] = error instanceof Error ? error.message : String(error);
172
+ }
173
+ }
174
+ return result;
175
+ }
176
+ /** Best-effort bulk unload; names that are not loaded are ignored. */
177
+ async unloadIndexes(indexNames) {
178
+ for (const name of indexNames) {
179
+ try {
180
+ await this.unloadIndex(name);
181
+ }
182
+ catch { }
183
+ }
105
184
  }
106
185
  async hasIndex(indexName) {
107
186
  const im = await this.getIndexManager();
@@ -109,25 +188,129 @@ export class MossClient {
109
188
  }
110
189
  async getIndexInfo(indexName) {
111
190
  const im = await this.getIndexManager();
112
- return im.getIndexInfo(indexName);
191
+ return this.modelArtifacts.replaceAfter(indexName, () => im.getIndexInfo(indexName), (info) => provenanceAwareIndexManager(im)
192
+ ? this.modelIdentityFromInfo(info)
193
+ : null);
113
194
  }
114
195
  async refreshIndex(indexName) {
115
196
  const im = await this.getIndexManager();
116
- return im.refreshIndex(indexName);
197
+ return this.modelArtifacts.replaceAfter(indexName, () => im.refreshIndex(indexName), (result) => provenanceAwareIndexManager(im)
198
+ ? this.modelIdentityFromRefresh(result)
199
+ : null);
117
200
  }
118
201
  async query(indexName, query, options) {
119
202
  await this.ensureInitialized();
120
- const embedding = await this.embedder.embed(query);
121
- return this.indexManager.query(indexName, query, embedding, options?.topK, options?.alpha, options?.filter);
203
+ const manager = requireProvenanceAwareIndexManager(this.indexManager);
204
+ const identity = await this.modelIdentityForIndex(indexName);
205
+ if (!identity) {
206
+ throw new Error(`Index '${indexName}' has no foundation model artifact identity; use queryWithEmbedding`);
207
+ }
208
+ const embedding = await this.embedder.embed(query, identity);
209
+ return manager.queryWithModelIdentity(indexName, query, embedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter);
210
+ }
211
+ async queryWithEmbedding(indexName, query, embedding, options) {
212
+ const im = await this.getIndexManager();
213
+ const identity = await this.modelIdentityForIndex(indexName);
214
+ const queryEmbedding = embedding instanceof Float32Array
215
+ ? embedding
216
+ : new Float32Array(embedding);
217
+ return queryWithResolvedModelIdentity(im, identity, indexName, query, queryEmbedding, options?.topK, options?.alpha, options?.filter);
218
+ }
219
+ /**
220
+ * Search several loaded indexes in one call and return the global top-k,
221
+ * each result tagged with its source `indexName`. Local-only: every name
222
+ * must already be loaded, and all must share one embedding model artifact.
223
+ *
224
+ * `alpha` matches the single-index `query`: `1.0` is embedding-only, `0.0`
225
+ * is keyword-only, and values between fuse both rankings. `topK` is the
226
+ * global cap across the union, not a per-index cap.
227
+ */
228
+ async queryMultiIndex(indexNames, query, options) {
229
+ if (indexNames.length === 0) {
230
+ throw new Error("queryMultiIndex requires at least one index name");
231
+ }
232
+ await this.ensureInitialized();
233
+ const manager = requireMultiIndexIndexManager(this.indexManager);
234
+ const identity = await this.sharedModelIdentity(indexNames);
235
+ const embedding = await this.embedder.embed(query, identity);
236
+ return manager.queryMultiIndexWithModelIdentity(indexNames, query, embedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter);
237
+ }
238
+ /** As `queryMultiIndex`, with a caller-supplied query vector. */
239
+ async queryMultiIndexWithEmbedding(indexNames, query, embedding, options) {
240
+ if (indexNames.length === 0) {
241
+ throw new Error("queryMultiIndexWithEmbedding requires at least one index name");
242
+ }
243
+ await this.ensureInitialized();
244
+ const manager = requireMultiIndexIndexManager(this.indexManager);
245
+ const identity = await this.resolveSharedModelIdentity(indexNames);
246
+ const queryEmbedding = embedding instanceof Float32Array
247
+ ? embedding
248
+ : new Float32Array(embedding);
249
+ if (identity) {
250
+ return manager.queryMultiIndexWithModelIdentity(indexNames, query, queryEmbedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter);
251
+ }
252
+ return manager.queryMultiIndex(indexNames, query, queryEmbedding, options?.topK, options?.alpha, options?.filter);
253
+ }
254
+ /**
255
+ * The one model artifact identity every named index shares, or `null` when
256
+ * none of them has one (custom or legacy embeddings). Throws when they
257
+ * disagree, because a single query vector cannot serve two models.
258
+ */
259
+ async resolveSharedModelIdentity(indexNames) {
260
+ let shared = null;
261
+ let resolved = false;
262
+ for (const name of indexNames) {
263
+ const identity = await this.modelIdentityForIndex(name);
264
+ if (!resolved) {
265
+ shared = identity;
266
+ resolved = true;
267
+ continue;
268
+ }
269
+ if (!sameModelArtifactIdentity(shared, identity)) {
270
+ throw new Error(`all indexes must share one embedding model artifact identity; '${name}' differs from '${indexNames[0]}'`);
271
+ }
272
+ }
273
+ return shared;
274
+ }
275
+ /** As `resolveSharedModelIdentity`, for the text path, which cannot embed
276
+ * without an exact identity to bind the vector to. */
277
+ async sharedModelIdentity(indexNames) {
278
+ const identity = await this.resolveSharedModelIdentity(indexNames);
279
+ if (!identity) {
280
+ throw new Error(`Indexes ${JSON.stringify(indexNames)} have no shared foundation model artifact identity; use queryMultiIndexWithEmbedding`);
281
+ }
282
+ return identity;
283
+ }
284
+ async modelIdentityForIndex(indexName) {
285
+ if (this.modelArtifacts.has(indexName)) {
286
+ return this.modelArtifacts.get(indexName) ?? null;
287
+ }
288
+ await this.getIndexInfo(indexName);
289
+ return this.modelArtifacts.get(indexName) ?? null;
290
+ }
291
+ modelIdentityFromInfo(info) {
292
+ return this.exactModelIdentity(info.model.id, info.modelArtifactVersion, info.manifestSha256);
293
+ }
294
+ modelIdentityFromRefresh(result) {
295
+ if (!result.modelId) {
296
+ throw new Error(`Refresh for '${result.indexName}' omitted its model identity`);
297
+ }
298
+ return this.exactModelIdentity(result.modelId, result.modelArtifactVersion, result.manifestSha256);
299
+ }
300
+ exactModelIdentity(modelId, version, manifestSha256) {
301
+ return exactModelArtifactIdentity(modelId, version, manifestSha256);
122
302
  }
123
303
  dispose() {
304
+ this.modelArtifacts.clearAll();
124
305
  this.embedder?.dispose();
125
306
  this.indexManager?.free();
126
307
  this.manageClient?.free();
308
+ this.projectKeyAuthenticator?.free();
127
309
  this.initialized = false;
128
310
  this.indexManager = null;
129
311
  this.manageClient = null;
130
312
  this.embedder = null;
313
+ this.projectKeyAuthenticator = null;
131
314
  this.initPromise = null;
132
315
  }
133
316
  }
@@ -1,17 +1,19 @@
1
- import type { Tokenizer, poolAndNormalize as PoolAndNormalizeFn } from "@moss-dev/moss-wasm";
2
- import type { MossModel } from "./types";
1
+ import type { poolAndNormalize as PoolAndNormalizeFn } from "@moss-dev/moss-wasm";
2
+ import { type ModelDeliveryOptions } from "./model-delivery.js";
3
+ import type { ModelArtifactIdentity, MossModel } from "./types.js";
3
4
  export declare class Embedder {
4
- private session;
5
- private tokenizer;
6
5
  private readonly modelId;
7
- private readonly hiddenDim;
8
- private initPromise;
9
- private readonly wasmTokenizerCtor;
6
+ private readonly runtimes;
7
+ private retainedKeys;
10
8
  private readonly poolAndNormalize;
11
- constructor(modelId: MossModel, wasmTokenizerCtor: typeof Tokenizer, poolAndNormalize: typeof PoolAndNormalizeFn);
9
+ private readonly delivery;
10
+ constructor(modelId: MossModel, poolAndNormalize: typeof PoolAndNormalizeFn, delivery: ModelDeliveryOptions);
12
11
  init(onnxWasmPath?: string): Promise<void>;
13
- private _init;
14
- embed(text: string): Promise<Float32Array>;
15
- private poolResult;
12
+ embed(text: string, identity: ModelArtifactIdentity): Promise<Float32Array>;
13
+ retainModelArtifacts(identities: ModelArtifactIdentity[]): void;
14
+ private runtimeFor;
15
+ private identityKey;
16
+ private retireRuntime;
17
+ private loadRuntime;
16
18
  dispose(): void;
17
19
  }