@wazootech/worlds-sdk 0.0.0-stage → 0.11.3-rc.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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +288 -2
  3. package/THIRD_PARTY_NOTICES.md +279 -0
  4. package/dist/ai-sdk.d.ts +27 -0
  5. package/dist/ai-sdk.js +28 -0
  6. package/dist/build-search-result-id-qxdmXp0V.js +12 -0
  7. package/dist/chunk-and-embed-0crm0xLl.js +75 -0
  8. package/dist/client-BJ45zmXU.d.ts +74 -0
  9. package/dist/client-BWh0UAM0.js +45 -0
  10. package/dist/embedding-service-DebRMVmn.d.ts +15 -0
  11. package/dist/embedding-service.d.ts +3 -0
  12. package/dist/embedding-service.js +19 -0
  13. package/dist/index.d.ts +8 -0
  14. package/dist/index.js +9 -0
  15. package/dist/memory.d.ts +26 -0
  16. package/dist/memory.js +29 -0
  17. package/dist/mod-8Zh1f9vW.d.ts +24 -0
  18. package/dist/mod-BuF_B_xU.d.ts +362 -0
  19. package/dist/mod-CHiiyEER.d.ts +79 -0
  20. package/dist/mod-ClDFMN-C.d.ts +625 -0
  21. package/dist/mod-Dmrdrb03.d.ts +13 -0
  22. package/dist/quad-chunker.d.ts +2 -0
  23. package/dist/quad-chunker.js +1 -0
  24. package/dist/quad-store-BGCOUBxK.js +851 -0
  25. package/dist/quad-store.d.ts +2 -0
  26. package/dist/quad-store.js +3 -0
  27. package/dist/rdf-formats-BkGt5RDB.js +93 -0
  28. package/dist/rdfjs-BNVjLSNL.js +190 -0
  29. package/dist/rdfjs.d.ts +79 -0
  30. package/dist/rdfjs.js +1 -0
  31. package/dist/search-index.d.ts +2 -0
  32. package/dist/search-index.js +219 -0
  33. package/dist/sparql-engine.d.ts +2 -0
  34. package/dist/sparql-engine.js +0 -0
  35. package/dist/testing.d.ts +301 -0
  36. package/dist/testing.js +786 -0
  37. package/dist/tfjs-use.d.ts +42 -0
  38. package/dist/tfjs-use.js +315 -0
  39. package/dist/wazoo.d.ts +86 -0
  40. package/dist/wazoo.js +347 -0
  41. package/package.json +119 -4
@@ -0,0 +1,42 @@
1
+ import "@tensorflow/tfjs-backend-wasm";
2
+ import { t as EmbeddingService } from "./embedding-service-DebRMVmn.js";
3
+ /**
4
+ * UniversalSentenceEncoderEmbeddingServiceOptions provides configuration for
5
+ * the TF.js Universal Sentence Encoder embedding service.
6
+ */
7
+ interface UniversalSentenceEncoderEmbeddingServiceOptions {
8
+ /**
9
+ * modelUrl is the custom URL or local file path to the model.json file.
10
+ * Defaults to the TF Hub USE lite model when omitted.
11
+ */
12
+ modelUrl?: string;
13
+ /**
14
+ * vocabUrl is the custom URL or local file path to the vocab.json file.
15
+ * Defaults to the Google Cloud Storage USE vocabulary when omitted.
16
+ */
17
+ vocabUrl?: string;
18
+ }
19
+ /**
20
+ * UniversalSentenceEncoderEmbeddingService provides 512-dimensional text
21
+ * embeddings using TensorFlow.js Universal Sentence Encoder lite.
22
+ */
23
+ export declare class UniversalSentenceEncoderEmbeddingService implements EmbeddingService {
24
+ private readonly options;
25
+ private modelPromise;
26
+ /**
27
+ * options is the configuration for local or remote model resources.
28
+ */
29
+ constructor(options?: UniversalSentenceEncoderEmbeddingServiceOptions);
30
+ /**
31
+ * getModel lazily loads and caches the underlying USE lite model.
32
+ */
33
+ private getModel;
34
+ /**
35
+ * embed converts text segments into 512-dimensional vector arrays.
36
+ *
37
+ * @param texts Array of clean input sequences targeted for vectorizing.
38
+ * @returns Vector space projection arrays matching the input array index positioning.
39
+ */
40
+ embed(texts: string[]): Promise<number[][]>;
41
+ }
42
+ export type { UniversalSentenceEncoderEmbeddingServiceOptions };
@@ -0,0 +1,315 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { isAbsolute } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import "@tensorflow/tfjs-backend-wasm";
5
+ import * as tf from "@tensorflow/tfjs";
6
+ // src/tfjs-use/tokenizer/string-to-chars.ts
7
+ /**
8
+ * @license
9
+ * Copyright 2019 Google LLC. All Rights Reserved.
10
+ * Licensed under the Apache License, Version 2.0 (the "License");
11
+ * you may not use this file except in compliance with the License.
12
+ * You may obtain a copy of the License at
13
+ *
14
+ * http://www.apache.org/licenses/LICENSE-2.0
15
+ *
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ * =============================================================================
22
+ */
23
+ /** stringToChars splits a string into unicode-aware character symbols. */
24
+ const stringToChars = (input) => {
25
+ const symbols = [];
26
+ for (const symbol of input) symbols.push(symbol);
27
+ return symbols;
28
+ };
29
+ // src/tfjs-use/tokenizer/trie.ts
30
+ /**
31
+ * @license
32
+ * Copyright 2019 Google LLC. All Rights Reserved.
33
+ * Licensed under the Apache License, Version 2.0 (the "License");
34
+ * you may not use this file except in compliance with the License.
35
+ * You may obtain a copy of the License at
36
+ *
37
+ * http://www.apache.org/licenses/LICENSE-2.0
38
+ *
39
+ * Unless required by applicable law or agreed to in writing, software
40
+ * distributed under the License is distributed on an "AS IS" BASIS,
41
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
42
+ * See the License for the specific language governing permissions and
43
+ * limitations under the License.
44
+ * =============================================================================
45
+ */
46
+ var TrieNode = class {
47
+ parent;
48
+ end;
49
+ children;
50
+ word;
51
+ constructor() {
52
+ this.parent = null;
53
+ this.children = {};
54
+ this.end = false;
55
+ this.word = [
56
+ [],
57
+ 0,
58
+ 0
59
+ ];
60
+ }
61
+ };
62
+ /** Trie stores vocabulary tokens for SentencePiece-style prefix search. */
63
+ var Trie = class {
64
+ root;
65
+ constructor() {
66
+ this.root = new TrieNode();
67
+ }
68
+ /** insert adds a token into the trie. */
69
+ insert(word, score, index) {
70
+ let node = this.root;
71
+ const symbols = stringToChars(word);
72
+ for (let i = 0; i < symbols.length; i++) {
73
+ if (!node.children[symbols[i]]) {
74
+ node.children[symbols[i]] = new TrieNode();
75
+ node.children[symbols[i]].parent = node;
76
+ node.children[symbols[i]].word[0] = node.word[0].concat(symbols[i]);
77
+ }
78
+ node = node.children[symbols[i]];
79
+ if (i === symbols.length - 1) {
80
+ node.end = true;
81
+ node.word[1] = score;
82
+ node.word[2] = index;
83
+ }
84
+ }
85
+ }
86
+ /**
87
+ * commonPrefixSearch returns all tokens starting with the given symbol prefix.
88
+ *
89
+ * @param symbolPrefix The prefix symbols to match on.
90
+ */
91
+ commonPrefixSearch(symbolPrefix) {
92
+ const output = [];
93
+ let node = this.root.children[symbolPrefix[0]];
94
+ for (let i = 0; i < symbolPrefix.length && node; i++) {
95
+ if (node.end) output.push(node.word);
96
+ node = node.children[symbolPrefix[i + 1]];
97
+ }
98
+ if (!output.length) output.push([
99
+ [symbolPrefix[0]],
100
+ 0,
101
+ 0
102
+ ]);
103
+ return output;
104
+ }
105
+ };
106
+ // src/tfjs-use/tokenizer/tokenizer.ts
107
+ /**
108
+ * @license
109
+ * Copyright 2019 Google LLC. All Rights Reserved.
110
+ * Licensed under the Apache License, Version 2.0 (the "License");
111
+ * you may not use this file except in compliance with the License.
112
+ * You may obtain a copy of the License at
113
+ *
114
+ * http://www.apache.org/licenses/LICENSE-2.0
115
+ *
116
+ * Unless required by applicable law or agreed to in writing, software
117
+ * distributed under the License is distributed on an "AS IS" BASIS,
118
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
119
+ * See the License for the specific language governing permissions and
120
+ * limitations under the License.
121
+ * =============================================================================
122
+ */
123
+ /**
124
+ * Tokenizer.encode() is a port of `EncodeAsIds` from the SentencePiece library
125
+ * (https://github.com/google/sentencepiece). Encode uses the Viterbi algorithm
126
+ * to find the most likely sequence of tokens that comprise the input. For more
127
+ * details, refer to https://arxiv.org/pdf/1804.10959.pdf.
128
+ */
129
+ const separator = "▁";
130
+ function processInput(str) {
131
+ const normalized = str.normalize("NFKC");
132
+ return normalized.length > 0 ? separator + normalized.replace(/ /g, separator) : normalized;
133
+ }
134
+ const RESERVED_SYMBOLS_COUNT = 6;
135
+ /** Tokenizer encodes text into token ids using a SentencePiece-style vocabulary. */
136
+ var Tokenizer = class {
137
+ vocabulary;
138
+ reservedSymbolsCount;
139
+ trie;
140
+ constructor(vocabulary, reservedSymbolsCount = RESERVED_SYMBOLS_COUNT) {
141
+ this.vocabulary = vocabulary;
142
+ this.reservedSymbolsCount = reservedSymbolsCount;
143
+ this.trie = new Trie();
144
+ for (let i = this.reservedSymbolsCount; i < this.vocabulary.length; i++) this.trie.insert(this.vocabulary[i][0], this.vocabulary[i][1], i);
145
+ }
146
+ /** encode converts input text into token ids. */
147
+ encode(input) {
148
+ const nodes = [];
149
+ const words = [];
150
+ const best = [];
151
+ input = processInput(input);
152
+ const symbols = stringToChars(input);
153
+ for (let i = 0; i <= symbols.length; i++) {
154
+ nodes.push({});
155
+ words.push(0);
156
+ best.push(0);
157
+ }
158
+ for (let i = 0; i < symbols.length; i++) {
159
+ const matches = this.trie.commonPrefixSearch(symbols.slice(i));
160
+ for (let j = 0; j < matches.length; j++) {
161
+ const piece = matches[j];
162
+ const obj = {
163
+ key: piece[0],
164
+ score: piece[1],
165
+ index: piece[2]
166
+ };
167
+ const endPos = piece[0].length;
168
+ if (nodes[i + endPos][i] == null) nodes[i + endPos][i] = [];
169
+ nodes[i + endPos][i].push(obj);
170
+ }
171
+ }
172
+ for (let endPos = 0; endPos <= symbols.length; endPos++) for (const startPos in nodes[endPos]) {
173
+ const arr = nodes[endPos][startPos];
174
+ for (let j = 0; j < arr.length; j++) {
175
+ const word = arr[j];
176
+ const score = word.score + best[endPos - word.key.length];
177
+ if (best[endPos] === 0 || score >= best[endPos]) {
178
+ best[endPos] = score;
179
+ words[endPos] = arr[j].index;
180
+ }
181
+ }
182
+ }
183
+ const results = [];
184
+ let iter = words.length - 1;
185
+ while (iter > 0) {
186
+ results.push(words[iter]);
187
+ iter -= this.vocabulary[words[iter]][0].length;
188
+ }
189
+ const merged = [];
190
+ let isPreviousUnk = false;
191
+ for (let i = 0; i < results.length; i++) {
192
+ const id = results[i];
193
+ if (!(isPreviousUnk && id === 0)) merged.push(id);
194
+ isPreviousUnk = id === 0;
195
+ }
196
+ return merged.reverse();
197
+ }
198
+ };
199
+ /** loadVocabulary fetches and parses the USE vocabulary JSON file. */
200
+ async function loadVocabulary(pathToVocabulary) {
201
+ return (await tf.util.fetch(pathToVocabulary)).json();
202
+ }
203
+ // src/tfjs-use/universal-sentence-encoder-embedding-service.ts
204
+ /**
205
+ * BASE_PATH is the default remote path for USE lite vocabulary.
206
+ */
207
+ const BASE_PATH = "https://storage.googleapis.com/tfjs-models/savedmodel/universal_sentence_encoder";
208
+ /**
209
+ * DEFAULT_MODEL_URL is the default remote URL for the USE lite graph model.
210
+ */
211
+ const DEFAULT_MODEL_URL = "https://tfhub.dev/tensorflow/tfjs-model/universal-sentence-encoder-lite/1/default/1";
212
+ /**
213
+ * UniversalSentenceEncoderLite loads and runs the USE lite graph model via TF.js.
214
+ */
215
+ var UniversalSentenceEncoderLite = class {
216
+ model;
217
+ tokenizer;
218
+ /**
219
+ * loadModel loads the graph model from a URL or TF Hub.
220
+ */
221
+ loadModel(modelUrl) {
222
+ return modelUrl ? tf.loadGraphModel(modelUrl) : tf.loadGraphModel(DEFAULT_MODEL_URL, { fromTFHub: true });
223
+ }
224
+ /**
225
+ * load initializes the graph model and vocabulary tokenizer.
226
+ */
227
+ async load(modelUrl, vocabUrl) {
228
+ const [model, vocabulary] = await Promise.all([this.loadModel(modelUrl), loadVocabulary(vocabUrl ?? `${BASE_PATH}/vocab.json`)]);
229
+ this.model = model;
230
+ this.tokenizer = new Tokenizer(vocabulary);
231
+ }
232
+ /**
233
+ * embed returns a 2D tensor of shape [input.length, 512] containing USE
234
+ * embeddings.
235
+ *
236
+ * @param inputs Strings to embed.
237
+ */
238
+ async embed(inputs) {
239
+ const encodings = inputs.map((text) => this.tokenizer.encode(text));
240
+ const indicesArr = encodings.map((arr, i) => arr.map((_token, index) => [i, index]));
241
+ let flattenedIndicesArr = [];
242
+ for (let i = 0; i < indicesArr.length; i++) flattenedIndicesArr = flattenedIndicesArr.concat(indicesArr[i]);
243
+ const indices = tf.tensor2d(flattenedIndicesArr, [flattenedIndicesArr.length, 2], "int32");
244
+ const values = tf.tensor1d(tf.util.flatten(encodings), "int32");
245
+ const modelInputs = {
246
+ indices,
247
+ values
248
+ };
249
+ const embeddings = await this.model.executeAsync(modelInputs);
250
+ indices.dispose();
251
+ values.dispose();
252
+ return embeddings;
253
+ }
254
+ };
255
+ /**
256
+ * resolveModelResourcePath converts a local path or URL string into a file://
257
+ * URL that TF.js can load.
258
+ */
259
+ function resolveModelResourcePath(pathOrUrl) {
260
+ if (pathOrUrl.startsWith("http://") || pathOrUrl.startsWith("https://") || pathOrUrl.startsWith("file://")) return pathOrUrl;
261
+ if (isAbsolute(pathOrUrl)) return pathToFileURL(pathOrUrl).toString();
262
+ try {
263
+ return pathToFileURL(realpathSync(pathOrUrl)).toString();
264
+ } catch {
265
+ return pathOrUrl;
266
+ }
267
+ }
268
+ /**
269
+ * UniversalSentenceEncoderEmbeddingService provides 512-dimensional text
270
+ * embeddings using TensorFlow.js Universal Sentence Encoder lite.
271
+ */
272
+ var UniversalSentenceEncoderEmbeddingService = class {
273
+ options;
274
+ modelPromise = null;
275
+ /**
276
+ * options is the configuration for local or remote model resources.
277
+ */
278
+ constructor(options = {}) {
279
+ this.options = options;
280
+ tf.setBackend("wasm").catch(console.error);
281
+ }
282
+ /**
283
+ * getModel lazily loads and caches the underlying USE lite model.
284
+ */
285
+ async getModel() {
286
+ if (!this.modelPromise) {
287
+ const model = new UniversalSentenceEncoderLite();
288
+ const modelUrl = this.options.modelUrl ? resolveModelResourcePath(this.options.modelUrl) : void 0;
289
+ const vocabUrl = this.options.vocabUrl ? resolveModelResourcePath(this.options.vocabUrl) : void 0;
290
+ this.modelPromise = model.load(modelUrl, vocabUrl).then(() => model);
291
+ await this.modelPromise;
292
+ }
293
+ return this.modelPromise;
294
+ }
295
+ /**
296
+ * embed converts text segments into 512-dimensional vector arrays.
297
+ *
298
+ * @param texts Array of clean input sequences targeted for vectorizing.
299
+ * @returns Vector space projection arrays matching the input array index positioning.
300
+ */
301
+ async embed(texts) {
302
+ if (texts.length === 0) return [];
303
+ const tensor = await (await this.getModel()).embed(texts);
304
+ const data = await tensor.data();
305
+ tensor.dispose();
306
+ const dimensions = 512;
307
+ const result = [];
308
+ for (let i = 0; i < texts.length; i++) {
309
+ const slice = data.slice(i * dimensions, (i + 1) * dimensions);
310
+ result.push(Array.from(slice));
311
+ }
312
+ return result;
313
+ }
314
+ };
315
+ export { UniversalSentenceEncoderEmbeddingService };
@@ -0,0 +1,86 @@
1
+ import { n as WorldsSdkInterface } from "./client-BJ45zmXU.js";
2
+ import { Client } from "@wazootech/worlds-client";
3
+ import { $ as ImportRequest, X as ExportRequest, Z as ExportResponse, tt as QuadStoreInterface } from "./mod-ClDFMN-C.js";
4
+ import { C as ReindexResponse, D as SearchRequest, O as SearchResponse, S as ReindexRequest, w as SearchIndexInterface } from "./mod-BuF_B_xU.js";
5
+ import { c as SparqlRequest, i as SparqlResponse, s as SparqlEngineInterface } from "./mod-8Zh1f9vW.js";
6
+ /**
7
+ * CreateWazooSdkOptions configures the remote Worlds SDK client.
8
+ */
9
+ interface CreateWazooSdkOptions {
10
+ /** baseUrl is the root URL of the Worlds data-plane API. */
11
+ baseUrl: string;
12
+ /** token is the Bearer token used to authenticate requests. */
13
+ token: string;
14
+ /** worldId is the canonical world identifier (e.g. w_<ULID>). */
15
+ worldId: string;
16
+ }
17
+ /**
18
+ * createWazooSdk assembles a WorldsSdk backed by the remote Worlds API.
19
+ *
20
+ * It wires RemoteQuadStore, RemoteSearchIndex, and RemoteSparqlEngine adapters
21
+ * behind the standard SdkInterface, giving consumers a one-call remote
22
+ * connection to any hosted Worlds API instance.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * import { createWazooSdk } from "@wazootech/worlds-sdk/wazoo";
27
+ *
28
+ * const sdk = createWazooSdk({
29
+ * baseUrl: "https://data.wazoo.dev",
30
+ * token: process.env.WORLDS_TOKEN!,
31
+ * worldId: "w_my-world",
32
+ * });
33
+ *
34
+ * const results = await sdk.search({ query: "explores" });
35
+ * ```
36
+ */
37
+ export declare function createWazooSdk(options: CreateWazooSdkOptions): WorldsSdkInterface;
38
+ /**
39
+ * RemoteQuadStore implements QuadStoreInterface by delegating to the Worlds
40
+ * data-plane API via @wazootech/worlds-client.
41
+ *
42
+ * Limitations vs local backends:
43
+ * - `import.mode` is ignored (the API always merges). Replace semantics are
44
+ * not supported by the data-plane API.
45
+ * - `export` does not support QuadFilter (include/exclude) scoping.
46
+ */
47
+ export declare class RemoteQuadStore implements QuadStoreInterface {
48
+ private readonly client;
49
+ private readonly worldId;
50
+ constructor(client: Client, worldId: string);
51
+ import(request: ImportRequest): Promise<void>;
52
+ export(request: ExportRequest): Promise<ExportResponse>;
53
+ }
54
+ /**
55
+ * RemoteSearchIndex implements SearchIndexInterface by delegating to the Worlds
56
+ * data-plane API via @wazootech/worlds-client.
57
+ *
58
+ * Limitations vs local backends:
59
+ * - `search` returns at most 100 results. `topK` is sent as the API's `limit`,
60
+ * which caps the results after ranking.
61
+ * - `reindex` QuadFilter and readPageSize are ignored. A large world is
62
+ * reindexed in windows, and each call runs one window.
63
+ */
64
+ export declare class RemoteSearchIndex implements SearchIndexInterface {
65
+ private readonly client;
66
+ private readonly worldId;
67
+ constructor(client: Client, worldId: string);
68
+ search(request: SearchRequest): Promise<SearchResponse>;
69
+ reindex(_request?: ReindexRequest): Promise<ReindexResponse>;
70
+ }
71
+ /**
72
+ * RemoteSparqlEngine implements SparqlEngineInterface by delegating to the
73
+ * Worlds data-plane API via @wazootech/worlds-client.
74
+ *
75
+ * Limitations vs local engines:
76
+ * - `baseIri`, `timeoutMs`, and `signal` are ignored. The API determines
77
+ * timeout and does not support abort signals.
78
+ * - `provenance` is ignored. A caller cannot name the writer of a hosted world.
79
+ */
80
+ export declare class RemoteSparqlEngine implements SparqlEngineInterface {
81
+ private readonly client;
82
+ private readonly worldId;
83
+ constructor(client: Client, worldId: string);
84
+ execute(request: SparqlRequest): Promise<SparqlResponse>;
85
+ }
86
+ export type { CreateWazooSdkOptions };