@shoof/cli 0.0.0-stage → 1.0.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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -2
  3. package/dist/shoof.js +1133 -0
  4. package/package.json +37 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ZoalTech Limited
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # Shoof AI CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `shoof` is the command line for [Shoof AI](https://shoofai.com), hosted AI
4
+ search for stores, blogs and apps. Search, ask for answers, import records,
5
+ run a resync, change settings, synonyms and rules, and read analytics from a
6
+ terminal. Every command takes `--json`, for scripts, CI and AI agents.
7
+
8
+ Needs Node.js 18 or later.
9
+
10
+ ```sh
11
+ npm install -g @shoof/cli
12
+ shoof login --app <appId> --key <adminKey>
13
+
14
+ shoof search "trail shoes"
15
+ shoof ask "what is the return policy?"
16
+ shoof records import products.jsonl
17
+ shoof records import catalog.jsonl --replace # a full resync: removes records not in the file
18
+ shoof synonyms add sofa couch
19
+ shoof analytics --no-results
20
+ ```
21
+
22
+ In CI, set `SHOOF_APP` and `SHOOF_ADMIN_KEY` instead of logging in.
23
+
24
+ `shoof --help` lists every command. The docs are at
25
+ https://docs.shoofai.com/cli/.
package/dist/shoof.js ADDED
@@ -0,0 +1,1133 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/main.ts
4
+ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
5
+ import { homedir } from "node:os";
6
+ import { dirname, join } from "node:path";
7
+
8
+ // src/cli.ts
9
+ import { parseArgs } from "node:util";
10
+
11
+ // ../js-client/src/http.ts
12
+ var DEFAULT_HOST = "https://api.shoofai.com";
13
+ var ShoofApiError = class extends Error {
14
+ constructor(status, code2, message, details, retryAfter) {
15
+ super(message);
16
+ this.status = status;
17
+ this.code = code2;
18
+ this.details = details;
19
+ this.retryAfter = retryAfter;
20
+ this.name = "ShoofApiError";
21
+ }
22
+ status;
23
+ code;
24
+ details;
25
+ retryAfter;
26
+ };
27
+ var MAX_RETRY_AFTER = 60;
28
+ var Transport = class {
29
+ constructor(apiKey, basePath, opts = {}) {
30
+ this.apiKey = apiKey;
31
+ this.basePath = basePath;
32
+ this.opts = opts;
33
+ this.host = (opts.host ?? DEFAULT_HOST).replace(/\/+$/, "");
34
+ this.fetchFn = opts.fetch ?? ((...a) => globalThis.fetch(...a));
35
+ this.timeoutMs = opts.timeoutMs ?? 1e4;
36
+ this.maxRetries = Math.max(0, opts.maxRetries ?? 2);
37
+ }
38
+ apiKey;
39
+ basePath;
40
+ opts;
41
+ host;
42
+ fetchFn;
43
+ timeoutMs;
44
+ maxRetries;
45
+ url(path, query) {
46
+ const u = `${this.host}${this.basePath}${path}`;
47
+ const qs = query ? Object.entries(query).filter(([, v]) => v !== void 0 && v !== "").map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&") : "";
48
+ return qs ? `${u}?${qs}` : u;
49
+ }
50
+ setApiKey(key2) {
51
+ this.apiKey = key2;
52
+ }
53
+ get key() {
54
+ return this.apiKey;
55
+ }
56
+ /**
57
+ * Sends a request, retrying as maxRetries says. `safe` marks a POST that only reads
58
+ * (a search), so it is retried like a GET.
59
+ */
60
+ async raw(method, path, init = {}) {
61
+ const retryable = init.safe || method !== "POST" || !!init.idempotencyKey;
62
+ for (let attempt = 0; ; attempt++) {
63
+ try {
64
+ return await this.once(method, path, init);
65
+ } catch (e) {
66
+ if (attempt >= this.maxRetries || init.signal?.aborted) throw e;
67
+ const wait = retryWait(e, retryable, attempt);
68
+ if (wait === void 0) throw e;
69
+ await sleep(wait, init.signal);
70
+ }
71
+ }
72
+ }
73
+ async once(method, path, init) {
74
+ const ctrl = new AbortController();
75
+ const timer = init.stream ? void 0 : setTimeout(() => ctrl.abort(new Error("timeout")), this.timeoutMs);
76
+ const onAbort = () => ctrl.abort(init.signal?.reason);
77
+ init.signal?.addEventListener("abort", onAbort, { once: true });
78
+ try {
79
+ const res = await this.fetchFn(this.url(path, init.query), {
80
+ method,
81
+ headers: {
82
+ "x-shoof-api-key": this.apiKey,
83
+ ...init.body !== void 0 ? { "content-type": "application/json" } : {},
84
+ ...init.stream ? { accept: "text/event-stream" } : {},
85
+ ...init.idempotencyKey ? { "idempotency-key": init.idempotencyKey } : {},
86
+ ...this.opts.headers
87
+ },
88
+ body: init.body !== void 0 ? JSON.stringify(init.body) : void 0,
89
+ signal: ctrl.signal
90
+ });
91
+ if (!res.ok) throw await toError(res);
92
+ return res;
93
+ } finally {
94
+ if (timer) clearTimeout(timer);
95
+ if (!init.stream) init.signal?.removeEventListener("abort", onAbort);
96
+ }
97
+ }
98
+ async json(method, path, init = {}) {
99
+ const res = await this.raw(method, path, init);
100
+ return await res.json();
101
+ }
102
+ };
103
+ function retryWait(e, retryable, attempt) {
104
+ const backoff = Math.min(8e3, 500 * 2 ** attempt) * (0.5 + Math.random() / 2);
105
+ if (e instanceof ShoofApiError) {
106
+ if (e.status === 429) {
107
+ if (e.retryAfter === void 0) return backoff;
108
+ return e.retryAfter <= MAX_RETRY_AFTER ? e.retryAfter * 1e3 : void 0;
109
+ }
110
+ if (e.status === 409 && e.code === "idempotency_key_in_use") return backoff;
111
+ return retryable && (e.status === 502 || e.status === 503 || e.status === 504) ? backoff : void 0;
112
+ }
113
+ return retryable && e instanceof TypeError ? backoff : void 0;
114
+ }
115
+ function sleep(ms, signal) {
116
+ return new Promise((resolve, reject) => {
117
+ const onAbort = () => {
118
+ clearTimeout(timer);
119
+ reject(signal?.reason);
120
+ };
121
+ const timer = setTimeout(() => {
122
+ signal?.removeEventListener("abort", onAbort);
123
+ resolve();
124
+ }, ms);
125
+ signal?.addEventListener("abort", onAbort, { once: true });
126
+ });
127
+ }
128
+ function newIdempotencyKey() {
129
+ const c = globalThis.crypto;
130
+ if (c?.randomUUID) return c.randomUUID();
131
+ return Math.random().toString(36).slice(2) + Date.now().toString(36) + Math.random().toString(36).slice(2);
132
+ }
133
+ async function toError(res) {
134
+ let body;
135
+ try {
136
+ body = await res.json();
137
+ } catch {
138
+ }
139
+ const e = body?.error;
140
+ const wait = Number(res.headers.get("retry-after"));
141
+ return new ShoofApiError(res.status, e?.code ?? `http_${res.status}`, e?.message ?? res.statusText ?? "Request failed", e?.details, wait > 0 ? wait : void 0);
142
+ }
143
+
144
+ // ../js-client/src/sse.ts
145
+ async function* parseSse(body, signal) {
146
+ const reader = body.getReader();
147
+ const decoder = new TextDecoder();
148
+ let buf = "";
149
+ const onAbort = () => reader.cancel().catch(() => {
150
+ });
151
+ signal?.addEventListener("abort", onAbort, { once: true });
152
+ try {
153
+ for (; ; ) {
154
+ const { value, done } = await reader.read();
155
+ if (done) break;
156
+ buf += decoder.decode(value, { stream: true });
157
+ let idx;
158
+ while ((idx = buf.search(/\r?\n\r?\n/)) >= 0) {
159
+ const raw = buf.slice(0, idx);
160
+ buf = buf.slice(idx).replace(/^\r?\n\r?\n/, "");
161
+ let event = "message";
162
+ const data = [];
163
+ for (const line of raw.split(/\r?\n/)) {
164
+ if (!line || line.startsWith(":")) continue;
165
+ const colon = line.indexOf(":");
166
+ const field = colon < 0 ? line : line.slice(0, colon);
167
+ const val = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
168
+ if (field === "event") event = val;
169
+ else if (field === "data") data.push(val);
170
+ }
171
+ if (data.length) yield { event, data: data.join("\n") };
172
+ }
173
+ }
174
+ } finally {
175
+ signal?.removeEventListener("abort", onAbort);
176
+ reader.releaseLock();
177
+ }
178
+ }
179
+
180
+ // ../js-client/src/index.ts
181
+ var ShoofClient = class {
182
+ appId;
183
+ userToken;
184
+ t;
185
+ configPromise;
186
+ constructor(opts) {
187
+ if (!opts.appId) throw new Error("appId is required");
188
+ if (!opts.apiKey) throw new Error("apiKey is required");
189
+ if (opts.apiKey.startsWith("shf_adm_") && typeof window !== "undefined") {
190
+ console.warn("[Shoof AI] An admin key is being used in a browser. Use a search key instead.");
191
+ }
192
+ this.appId = opts.appId;
193
+ this.userToken = opts.userToken ?? randomToken();
194
+ this.t = new Transport(opts.apiKey, `/v1/apps/${encodeURIComponent(opts.appId)}`, opts);
195
+ }
196
+ get host() {
197
+ return this.t.host;
198
+ }
199
+ /** Swap the key (e.g. after a secured key refresh) without recreating the client. */
200
+ setApiKey(key2) {
201
+ this.t.setApiKey(key2);
202
+ }
203
+ search(req, opts = {}) {
204
+ return this.t.json("POST", "/search", { body: { userToken: this.userToken, ...req }, signal: opts.signal, safe: true });
205
+ }
206
+ async multiSearch(requests, opts = {}) {
207
+ const res = await this.t.json("POST", "/multi-search", {
208
+ body: { requests: requests.map((r) => ({ userToken: this.userToken, ...r })) },
209
+ signal: opts.signal,
210
+ safe: true
211
+ });
212
+ return res.results;
213
+ }
214
+ autocomplete(q, opts = {}) {
215
+ return this.t.json("GET", "/autocomplete", {
216
+ query: {
217
+ q,
218
+ lang: opts.lang,
219
+ hits: opts.hits,
220
+ filters: opts.filters ? JSON.stringify(opts.filters) : void 0,
221
+ analytics: opts.analytics === false ? "false" : void 0,
222
+ userToken: this.userToken
223
+ },
224
+ signal: opts.signal
225
+ });
226
+ }
227
+ /** Values of one keyword facet (brand, categories, attributes.color…) whose words start with facetQuery. */
228
+ searchFacetValues(field, req = {}, opts = {}) {
229
+ return this.t.json("POST", `/facets/${encodeURIComponent(field)}/query`, { body: req, signal: opts.signal, safe: true });
230
+ }
231
+ async related(id, opts = {}) {
232
+ const res = await this.t.json("GET", `/records/${encodeURIComponent(id)}/related`, {
233
+ query: { lang: opts.lang, limit: opts.limit },
234
+ signal: opts.signal
235
+ });
236
+ return res.hits;
237
+ }
238
+ /** Records whose activity in the last day is well above their earlier rate. */
239
+ async trending(opts = {}) {
240
+ const res = await this.t.json("GET", "/trending", {
241
+ query: { limit: opts.limit, lang: opts.lang, type: opts.type, filters: opts.filters },
242
+ signal: opts.signal
243
+ });
244
+ return res.hits;
245
+ }
246
+ /** Searches rising over the last day. */
247
+ async trendingQueries(opts = {}) {
248
+ const res = await this.t.json("GET", "/trending/queries", {
249
+ query: { limit: opts.limit, lang: opts.lang },
250
+ signal: opts.signal
251
+ });
252
+ return res.queries;
253
+ }
254
+ /** What this visitor (the client's userToken) viewed lately, newest first, without exclude. Starter and up. */
255
+ async recentlyViewed(opts = {}) {
256
+ const res = await this.t.json("GET", "/recommendations/recently-viewed", {
257
+ query: { userToken: this.userToken, exclude: opts.exclude?.join(","), limit: opts.limit, lang: opts.lang },
258
+ signal: opts.signal
259
+ });
260
+ return res.hits;
261
+ }
262
+ /** What goes with a cart of these record ids: bought with them, then like the first. Starter and up. */
263
+ async cartRecommendations(ids, opts = {}) {
264
+ const res = await this.t.json("GET", "/recommendations/cart", {
265
+ query: { ids: ids.join(","), limit: opts.limit, lang: opts.lang },
266
+ signal: opts.signal
267
+ });
268
+ return res.hits;
269
+ }
270
+ /** Records most often purchased together with id. */
271
+ async boughtTogether(id, opts = {}) {
272
+ const res = await this.t.json("GET", `/records/${encodeURIComponent(id)}/bought-together`, {
273
+ query: { lang: opts.lang, limit: opts.limit },
274
+ signal: opts.signal
275
+ });
276
+ return res.hits;
277
+ }
278
+ /** Streams answer events as they arrive. */
279
+ async *answerStream(req, opts = {}) {
280
+ const res = await this.t.raw("POST", "/answer", { body: { userToken: this.userToken, ...req }, signal: opts.signal, stream: true, safe: true });
281
+ if (!res.body) throw new Error("Streaming is not supported by this fetch implementation");
282
+ for await (const { event, data } of parseSse(res.body, opts.signal)) {
283
+ let parsed;
284
+ try {
285
+ parsed = JSON.parse(data);
286
+ } catch {
287
+ continue;
288
+ }
289
+ yield { event, data: parsed };
290
+ }
291
+ }
292
+ /** Convenience wrapper around answerStream that resolves with the final text. */
293
+ async answer(req, handlers = {}) {
294
+ const out = { text: "", sources: [], mode: "none" };
295
+ for await (const ev of this.answerStream(req, { signal: handlers.signal })) {
296
+ switch (ev.event) {
297
+ case "sources":
298
+ out.sources = ev.data.sources;
299
+ out.queryId = ev.data.queryId;
300
+ out.query = ev.data.query;
301
+ handlers.onSources?.(ev.data.sources, ev.data.queryId);
302
+ break;
303
+ case "delta":
304
+ out.text += ev.data.text;
305
+ handlers.onDelta?.(ev.data.text, out.text);
306
+ break;
307
+ case "done":
308
+ out.mode = ev.data.mode;
309
+ break;
310
+ case "error":
311
+ throw new Error(ev.data.message);
312
+ }
313
+ }
314
+ return out;
315
+ }
316
+ /** Public widget config (facets, enabled features). Cached per client. */
317
+ config() {
318
+ return this.configPromise ??= this.t.json("GET", "/config").catch((e) => {
319
+ this.configPromise = void 0;
320
+ throw e;
321
+ });
322
+ }
323
+ /** Sends events, once each however often the request is retried. */
324
+ async sendEvents(events, opts = {}) {
325
+ if (!events.length) return;
326
+ const withUser = events.map((e) => ({ userToken: this.userToken, timestamp: Date.now(), ...e }));
327
+ await this.t.json("POST", "/events", { body: { events: withUser }, idempotencyKey: opts.idempotencyKey ?? newIdempotencyKey() });
328
+ }
329
+ /**
330
+ * Fire-and-forget events that survive page navigation (uses sendBeacon when available).
331
+ * The beacon body is text/plain so no CORS preflight is needed; the key goes in the URL.
332
+ */
333
+ beacon(events) {
334
+ if (!events.length) return;
335
+ this.fire("/events", { events: events.map((e) => ({ userToken: this.userToken, timestamp: Date.now(), ...e })) });
336
+ }
337
+ /**
338
+ * Tell Shoof AI about an error the widget caught, so it can fix it. Fire-and-forget; the
339
+ * report has no visitor token, and the server logs it without storing it.
340
+ */
341
+ reportError(report) {
342
+ this.fire("/widget-errors", report);
343
+ }
344
+ fire(path, payload) {
345
+ const body = JSON.stringify(payload);
346
+ const nav = typeof navigator !== "undefined" ? navigator : void 0;
347
+ if (nav?.sendBeacon) {
348
+ const ok = nav.sendBeacon(this.t.url(path, { apiKey: this.t.key }), new Blob([body], { type: "text/plain" }));
349
+ if (ok) return;
350
+ }
351
+ this.t.json("POST", path, { body: payload }).catch(() => {
352
+ });
353
+ }
354
+ clicked(queryId, objectId, position) {
355
+ this.beacon([{ type: "click", queryId, objectId, position }]);
356
+ }
357
+ /** The visitor opened the page of objectId (a product or post page). */
358
+ viewed(objectId) {
359
+ this.beacon([{ type: "view", objectId }]);
360
+ }
361
+ converted(queryId, objectId, value, currency, orderId) {
362
+ this.beacon([{ type: "conversion", queryId, objectId, value, currency, orderId }]);
363
+ }
364
+ };
365
+ function randomToken() {
366
+ const c = globalThis.crypto;
367
+ if (c?.randomUUID) return "anon-" + c.randomUUID();
368
+ return "anon-" + Math.random().toString(36).slice(2) + Date.now().toString(36);
369
+ }
370
+
371
+ // ../js-client/src/admin.ts
372
+ var ShoofAdminClient = class {
373
+ t;
374
+ constructor(opts) {
375
+ if (!opts.appId || !opts.apiKey) throw new Error("appId and apiKey are required");
376
+ this.t = new Transport(opts.apiKey, `/v1/apps/${encodeURIComponent(opts.appId)}`, { timeoutMs: 12e4, ...opts });
377
+ }
378
+ batch(req, opts = {}) {
379
+ return this.t.json("POST", "/records/batch", { body: req, query: { refresh: opts.refresh || void 0 }, idempotencyKey: key(opts) });
380
+ }
381
+ /** Splits large arrays into API-sized batches (500 upserts / 1000 deletes). */
382
+ async upsertAll(records2, opts = {}) {
383
+ const size = Math.min(opts.batchSize ?? 200, 500);
384
+ const total = { indexed: 0, updated: 0, skipped: 0, deleted: 0, embedded: 0, errors: [] };
385
+ for (let i = 0; i < records2.length; i += size) {
386
+ const r = await this.batch({ upserts: records2.slice(i, i + size), reindexId: opts.reindexId });
387
+ total.indexed += r.indexed;
388
+ total.updated += r.updated;
389
+ total.skipped += r.skipped;
390
+ total.embedded += r.embedded;
391
+ total.errors.push(...r.errors);
392
+ for (const w of r.warnings ?? []) {
393
+ total.warnings ??= [];
394
+ if (total.warnings.length < 50 && !total.warnings.includes(w)) total.warnings.push(w);
395
+ }
396
+ opts.onProgress?.(Math.min(i + size, records2.length), records2.length);
397
+ }
398
+ return total;
399
+ }
400
+ getRecord(id) {
401
+ return this.t.json("GET", `/records/${encodeURIComponent(id)}`);
402
+ }
403
+ deleteRecord(id) {
404
+ return this.t.json("DELETE", `/records/${encodeURIComponent(id)}`);
405
+ }
406
+ clear(opts = {}) {
407
+ return this.t.json("POST", "/records/clear", { body: {}, idempotencyKey: key(opts) });
408
+ }
409
+ startReindex(opts = {}) {
410
+ const { idempotencyKey, ...body } = opts;
411
+ return this.t.json("POST", "/reindex", { body, idempotencyKey: idempotencyKey ?? newIdempotencyKey() });
412
+ }
413
+ reindexStatus() {
414
+ return this.t.json("GET", "/reindex");
415
+ }
416
+ /**
417
+ * Waits up to 20s for the copy of the live index; past that, throws a 409
418
+ * `reindex_copying` ShoofApiError. Retry later (reindexStatus() shows progress).
419
+ */
420
+ commitReindex(reindexId, opts = {}) {
421
+ return this.t.json("POST", "/reindex/commit", { body: { reindexId }, idempotencyKey: key(opts) });
422
+ }
423
+ cancelReindex() {
424
+ return this.t.json("DELETE", "/reindex");
425
+ }
426
+ status() {
427
+ return this.t.json("GET", "/status");
428
+ }
429
+ /** The settings with every default applied, and their version (bumped on each change). */
430
+ getSettings() {
431
+ return this.t.json("GET", "/settings");
432
+ }
433
+ /** Replaces all settings; anything left out goes back to its default. */
434
+ setSettings(settings2) {
435
+ return this.t.json("PUT", "/settings", { body: settings2 });
436
+ }
437
+ /** Replaces only the top-level settings given. */
438
+ patchSettings(settings2) {
439
+ return this.t.json("PATCH", "/settings", { body: settings2 });
440
+ }
441
+ /** The supported languages, for indexLanguages, queryLanguages and the dictionaries. */
442
+ async languages() {
443
+ return (await this.t.json("GET", "/languages")).languages;
444
+ }
445
+ /**
446
+ * Declares the languages your content is in: the ones the app doesn't index yet are added to its index languages
447
+ * (as many as fit, up to 6), which rebuilds its index. Languages are never removed this way. Codes can be as sites
448
+ * send them ("ar", "fr_FR", "pt-BR"). Call it before a full sync, so the new index analyzes them.
449
+ */
450
+ declareLanguages(languages) {
451
+ return this.t.json("POST", "/languages", { body: { languages } });
452
+ }
453
+ /** A language's built-in stop words, which the stop words dictionary adds to or takes words off. */
454
+ async builtinStopWords(lang) {
455
+ return (await this.t.json("GET", `/languages/${lang}/stop-words`)).stopWords;
456
+ }
457
+ /** The stop words, plurals and compounds dictionaries. */
458
+ async getDictionaries() {
459
+ return (await this.t.json("GET", "/dictionaries")).dictionaries;
460
+ }
461
+ /**
462
+ * Replaces one dictionary in every language. Stop words and plurals apply at once; compounds rebuild the index
463
+ * (index.rebuild says how far along it is).
464
+ */
465
+ putDictionary(name, value) {
466
+ return this.t.json("PUT", `/dictionaries/${name}`, { body: value });
467
+ }
468
+ /**
469
+ * Sets the facets for a kind of site: "store" (type, categories, brand, price and
470
+ * availability) or "blog" (type, categories, tags, author and date). With
471
+ * `ifUnchanged`, only while the facets are still a preset's, so facets chosen by
472
+ * hand stay; `applied` says whether they changed.
473
+ */
474
+ applyPreset(preset, opts = {}) {
475
+ const { idempotencyKey, ...rest } = opts;
476
+ return this.t.json("POST", "/settings/preset", { body: { preset, ...rest }, idempotencyKey: idempotencyKey ?? newIdempotencyKey() });
477
+ }
478
+ /**
479
+ * Search analytics as the dashboard shows them, for a range (ISO dates; the last
480
+ * 14 days by default) within the plan's retention.
481
+ */
482
+ analytics(opts = {}) {
483
+ return this.t.json("GET", "/analytics", { query: opts });
484
+ }
485
+ async fieldCoverage() {
486
+ return this.t.json("GET", "/fields/coverage");
487
+ }
488
+ async getSynonyms() {
489
+ return (await this.t.json("GET", "/synonyms")).synonyms;
490
+ }
491
+ async setSynonyms(synonyms2) {
492
+ return (await this.t.json("PUT", "/synonyms", { body: synonyms2 })).synonyms;
493
+ }
494
+ async getRules() {
495
+ return (await this.t.json("GET", "/rules")).rules;
496
+ }
497
+ async setRules(rules2) {
498
+ return (await this.t.json("PUT", "/rules", { body: rules2 })).rules;
499
+ }
500
+ };
501
+ function key(opts) {
502
+ return opts.idempotencyKey ?? newIdempotencyKey();
503
+ }
504
+
505
+ // src/cli.ts
506
+ var VERSION = true ? "1.0.0" : "0.0.0-dev";
507
+ var UsageError = class extends Error {
508
+ };
509
+ var MAX_BATCH = 500;
510
+ var MAX_BATCH_BYTES = 8 * 1024 * 1024;
511
+ var OPTIONS = {
512
+ json: { type: "boolean" },
513
+ help: { type: "boolean", short: "h" },
514
+ version: { type: "boolean", short: "v" },
515
+ app: { type: "string" },
516
+ key: { type: "string" },
517
+ host: { type: "string" },
518
+ page: { type: "string" },
519
+ "hits-per-page": { type: "string", short: "n" },
520
+ filters: { type: "string" },
521
+ lang: { type: "string" },
522
+ mode: { type: "string" },
523
+ "batch-size": { type: "string" },
524
+ replace: { type: "boolean" },
525
+ yes: { type: "boolean", short: "y" },
526
+ "no-copy": { type: "boolean" },
527
+ restart: { type: "boolean" },
528
+ input: { type: "string" },
529
+ from: { type: "string" },
530
+ to: { type: "string" },
531
+ interval: { type: "string" },
532
+ "no-results": { type: "boolean" }
533
+ };
534
+ var HELP = `shoof ${VERSION}: the Shoof AI command line
535
+
536
+ Usage: shoof <command> [arguments] [--json]
537
+
538
+ Account
539
+ login --app <appId> --key <adminKey> Check and save the app and key
540
+ logout Forget the saved app and key
541
+ status The app's records, plan and index
542
+
543
+ Search
544
+ search <query> [-n 10] [--page 0] [--filters JSON] [--lang en] [--mode hybrid]
545
+ ask <question> [--lang en] An AI answer, with its sources
546
+
547
+ Records
548
+ records import <file.jsonl|file.json|-> [--batch-size 500] [--replace]
549
+ records get <id>
550
+ records delete <id>...
551
+ records clear --yes Delete every record
552
+
553
+ Reindex
554
+ reindex start [--no-copy] [--restart] | status | commit [reindexId] | cancel
555
+
556
+ Configuration
557
+ settings get [name]
558
+ settings set <name> <value> The value is JSON, or else a string
559
+ settings preset <store|blog>
560
+ synonyms list | add <term> <term>... | add --input <word> <term>... | remove <id>
561
+ rules list | add <JSON|@file.json> | remove <id>
562
+
563
+ Analytics
564
+ analytics [--from 2026-10-01] [--to 2026-11-01] [--interval day] [--no-results]
565
+
566
+ Options
567
+ --json Print JSON, for scripts and agents
568
+ --app, --key, --host
569
+ Override the saved app, key and API host
570
+ -h, --help This help
571
+ -v, --version The version
572
+
573
+ The app and key come from the flags, then SHOOF_APP, SHOOF_ADMIN_KEY and
574
+ SHOOF_HOST, then what \`shoof login\` saved. Docs: https://docs.shoofai.com/cli/
575
+ `;
576
+ async function run(argv, io) {
577
+ let flags = {};
578
+ try {
579
+ const parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
580
+ flags = parsed.values;
581
+ const [cmd, ...rest] = parsed.positionals;
582
+ if (flags.version) {
583
+ io.out(VERSION + "\n");
584
+ return 0;
585
+ }
586
+ if (flags.help || !cmd || cmd === "help") {
587
+ io.out(HELP);
588
+ return 0;
589
+ }
590
+ await dispatch(cmd, rest, flags, io);
591
+ return 0;
592
+ } catch (e) {
593
+ return fail(e, flags, io);
594
+ }
595
+ }
596
+ function fail(e, flags, io) {
597
+ if (e instanceof UsageError || e instanceof TypeError && "code" in e && String(e.code).startsWith("ERR_PARSE_ARGS")) {
598
+ io.err(`${e.message}
599
+ Run \`shoof --help\` for usage.
600
+ `);
601
+ return 2;
602
+ }
603
+ if (e instanceof ShoofApiError) {
604
+ if (flags.json) {
605
+ io.err(JSON.stringify({ error: { status: e.status, code: e.code, message: e.message, details: e.details } }) + "\n");
606
+ } else {
607
+ io.err(`Error ${e.status} ${e.code}: ${e.message}
608
+ `);
609
+ if (Array.isArray(e.details)) {
610
+ for (const d of e.details) io.err(` ${d.path ? d.path + ": " : ""}${d.message ?? JSON.stringify(d)}
611
+ `);
612
+ }
613
+ }
614
+ return 1;
615
+ }
616
+ const message = e instanceof Error ? e.message : String(e);
617
+ io.err(flags.json ? JSON.stringify({ error: { code: "cli_error", message } }) + "\n" : `Error: ${message}
618
+ `);
619
+ return 1;
620
+ }
621
+ async function target(flags, io) {
622
+ const saved = await io.loadConfig();
623
+ const appId = flags.app ?? io.env.SHOOF_APP ?? saved.appId;
624
+ const key2 = flags.key ?? io.env.SHOOF_ADMIN_KEY ?? saved.key;
625
+ const host = flags.host ?? io.env.SHOOF_HOST ?? saved.host ?? DEFAULT_HOST;
626
+ if (!appId || !key2) {
627
+ throw new UsageError("No app or key. Run `shoof login --app <appId> --key <adminKey>`, or set SHOOF_APP and SHOOF_ADMIN_KEY.");
628
+ }
629
+ return { appId, key: key2, host };
630
+ }
631
+ function admin(t, io) {
632
+ return new ShoofAdminClient({ appId: t.appId, apiKey: t.key, host: t.host, fetch: io.fetch, headers: { "user-agent": `shoof-cli/${VERSION}` }, maxRetries: 0 });
633
+ }
634
+ function searcher(t, io) {
635
+ return new ShoofClient({ appId: t.appId, apiKey: t.key, host: t.host, fetch: io.fetch, userToken: "shoof-cli", headers: { "user-agent": `shoof-cli/${VERSION}` } });
636
+ }
637
+ async function retrying(io, call, tries = 5) {
638
+ for (let i = 1; ; i++) {
639
+ try {
640
+ return await call();
641
+ } catch (e) {
642
+ const retry = e instanceof ShoofApiError ? e.status === 429 || e.status === 502 || e.status === 503 : e instanceof TypeError;
643
+ if (!retry || i >= tries) throw e;
644
+ const wait = e instanceof ShoofApiError && e.retryAfter ? e.retryAfter * 1e3 : 1e3 * 2 ** (i - 1);
645
+ io.err(`${e instanceof Error ? e.message : e}; retrying in ${Math.ceil(wait / 1e3)}s
646
+ `);
647
+ await (io.sleep ?? sleep2)(wait);
648
+ }
649
+ }
650
+ }
651
+ var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
652
+ async function dispatch(cmd, args, flags, io) {
653
+ const print = (data, human) => io.out(flags.json ? JSON.stringify(data, null, 2) + "\n" : human());
654
+ switch (cmd) {
655
+ case "login":
656
+ return login(flags, io, print);
657
+ case "logout":
658
+ await io.saveConfig(null);
659
+ return print({ loggedOut: true }, () => `Forgot the saved app and key (${io.configPath}).
660
+ `);
661
+ case "status": {
662
+ const s = await admin(await target(flags, io), io).status();
663
+ return print(
664
+ s,
665
+ () => table([
666
+ ["App", `${s.name} (${s.appId})`],
667
+ ["Plan", s.plan],
668
+ ["Records", `${fmt(s.records)}${s.embeddings ? `, ${fmt(s.embedded)} with embeddings` : ""}`],
669
+ ["Types", s.types.map((t) => `${t.value} ${fmt(t.count)}`).join(", ") || "-"],
670
+ ["Languages", s.langs.map((t) => `${t.value} ${fmt(t.count)}`).join(", ") || "-"],
671
+ ["Index version", String(s.indexVersion)],
672
+ ["Reindex", s.reindex ? `${s.reindex.reindexId}, started ${s.reindex.startedAt}` : "none"],
673
+ ["Last sync", s.lastSyncedAt ?? "never"]
674
+ ])
675
+ );
676
+ }
677
+ case "search":
678
+ return search(args, flags, io, print);
679
+ case "ask":
680
+ return ask(args, flags, io);
681
+ case "records":
682
+ return records(args, flags, io, print);
683
+ case "reindex":
684
+ return reindex(args, flags, io, print);
685
+ case "settings":
686
+ return settings(args, flags, io, print);
687
+ case "synonyms":
688
+ return synonyms(args, flags, io, print);
689
+ case "rules":
690
+ return rules(args, flags, io, print);
691
+ case "analytics":
692
+ return analytics(flags, io, print);
693
+ default:
694
+ throw new UsageError(`Unknown command "${cmd}".`);
695
+ }
696
+ }
697
+ async function login(flags, io, print) {
698
+ const appId = flags.app ?? io.env.SHOOF_APP;
699
+ const key2 = flags.key ?? io.env.SHOOF_ADMIN_KEY;
700
+ const host = flags.host ?? io.env.SHOOF_HOST;
701
+ if (!appId || !key2) throw new UsageError("Give the app and its admin key: `shoof login --app <appId> --key <adminKey>`, or set SHOOF_APP and SHOOF_ADMIN_KEY.");
702
+ const t = { appId, key: key2, host: host ?? DEFAULT_HOST };
703
+ let name = appId;
704
+ let searchOnly = false;
705
+ try {
706
+ name = (await admin(t, io).status()).name;
707
+ } catch (e) {
708
+ if (!(e instanceof ShoofApiError && e.status === 403 && e.code === "forbidden")) throw e;
709
+ searchOnly = true;
710
+ }
711
+ await io.saveConfig({ appId, key: key2, ...host ? { host } : {} });
712
+ print(
713
+ { appId, name, host: t.host, searchOnly, config: io.configPath },
714
+ () => `Logged in to ${name} (${appId}) on ${t.host}.
715
+ ` + (searchOnly ? "That is a search key: search and ask work, and the other commands need an admin key.\n" : "") + `Saved to ${io.configPath}.
716
+ `
717
+ );
718
+ }
719
+ async function search(args, flags, io, print) {
720
+ const q = args.join(" ");
721
+ const req = {
722
+ q,
723
+ page: int(flags.page, "--page"),
724
+ hitsPerPage: int(flags["hits-per-page"], "--hits-per-page"),
725
+ lang: flags.lang,
726
+ mode: flags.mode,
727
+ filters: flags.filters ? parseJson(flags.filters, "--filters") : void 0,
728
+ // Searches from a terminal aren't visitors': keep them out of analytics.
729
+ analytics: false
730
+ };
731
+ const res = await searcher(await target(flags, io), io).search(req);
732
+ print(res, () => {
733
+ const head = `${fmt(res.nbHits)} result${res.nbHits === 1 ? "" : "s"}${q ? ` for "${q}"` : ""}` + (res.nbPages > 1 ? ` (page ${res.page + 1} of ${res.nbPages})` : "") + "\n";
734
+ return head + res.hits.map((h, i) => hitLine(h, res.page * res.hitsPerPage + i + 1)).join("");
735
+ });
736
+ }
737
+ function hitLine(h, n) {
738
+ return `${String(n).padStart(3)}. ${h.title || "(no title)"} [${h.id}]
739
+ ` + (h.url ? ` ${h.url}
740
+ ` : "");
741
+ }
742
+ async function ask(args, flags, io) {
743
+ const q = args.join(" ").trim();
744
+ if (!q) throw new UsageError('Ask a question: shoof ask "<question>"');
745
+ const client = searcher(await target(flags, io), io);
746
+ if (flags.json) {
747
+ const res2 = await client.answer({ q, lang: flags.lang });
748
+ io.out(JSON.stringify(res2, null, 2) + "\n");
749
+ return;
750
+ }
751
+ const res = await client.answer({ q, lang: flags.lang }, { onDelta: (d) => io.out(d) });
752
+ io.out(res.text ? "\n" : "No answer.\n");
753
+ if (res.sources.length) {
754
+ io.out("\nSources:\n" + res.sources.map((s) => ` [${s.n}] ${s.title}${s.url ? ` ${s.url}` : ""}
755
+ `).join(""));
756
+ }
757
+ }
758
+ async function records(args, flags, io, print) {
759
+ const [sub, ...rest] = args;
760
+ switch (sub) {
761
+ case "import":
762
+ return importRecords(rest, flags, io, print);
763
+ case "get": {
764
+ const id = one(rest, "records get <id>");
765
+ const rec = await admin(await target(flags, io), io).getRecord(id);
766
+ return print(rec, () => JSON.stringify(rec, null, 2) + "\n");
767
+ }
768
+ case "delete": {
769
+ if (!rest.length) throw new UsageError("Give the ids: shoof records delete <id>...");
770
+ const a = admin(await target(flags, io), io);
771
+ let deleted = 0;
772
+ for (let i = 0; i < rest.length; i += 1e3) {
773
+ deleted += (await retrying(io, () => a.batch({ deletes: rest.slice(i, i + 1e3) }))).deleted;
774
+ }
775
+ return print({ deleted }, () => `Deleted ${fmt(deleted)} record${deleted === 1 ? "" : "s"}.
776
+ `);
777
+ }
778
+ case "clear": {
779
+ const t = await target(flags, io);
780
+ if (!flags.yes) throw new UsageError(`This deletes every record in ${t.appId}. Run it again with --yes.`);
781
+ const res = await admin(t, io).clear();
782
+ return print(res, () => `Deleted ${fmt(res.deleted)} records from ${t.appId}.
783
+ `);
784
+ }
785
+ default:
786
+ throw new UsageError(sub ? `Unknown records command "${sub}".` : "Use records import, get, delete or clear.");
787
+ }
788
+ }
789
+ function parseRecords(text) {
790
+ const body = text.replace(/^/, "").trim();
791
+ if (!body) return [];
792
+ if (body.startsWith("[")) {
793
+ const arr = parseJson(body, "the file");
794
+ if (!Array.isArray(arr)) throw new UsageError("The file must hold a JSON array of records, or one record per line.");
795
+ return arr;
796
+ }
797
+ const out = [];
798
+ body.split(/\r?\n/).forEach((line, i) => {
799
+ if (!line.trim()) return;
800
+ try {
801
+ out.push(JSON.parse(line));
802
+ } catch (e) {
803
+ throw new UsageError(`Line ${i + 1} isn't JSON: ${e.message}`);
804
+ }
805
+ });
806
+ return out;
807
+ }
808
+ function batches(recs, size) {
809
+ const out = [];
810
+ let cur = [];
811
+ let bytes = 0;
812
+ for (const r of recs) {
813
+ const n = JSON.stringify(r).length + 1;
814
+ if (cur.length && (cur.length >= size || bytes + n > MAX_BATCH_BYTES)) {
815
+ out.push(cur);
816
+ cur = [];
817
+ bytes = 0;
818
+ }
819
+ cur.push(r);
820
+ bytes += n;
821
+ }
822
+ if (cur.length) out.push(cur);
823
+ return out;
824
+ }
825
+ async function importRecords(args, flags, io, print) {
826
+ const file = one(args, "records import <file.jsonl|file.json|->");
827
+ const size = int(flags["batch-size"], "--batch-size") ?? MAX_BATCH;
828
+ if (size < 1 || size > MAX_BATCH) throw new UsageError(`--batch-size must be 1 to ${MAX_BATCH}.`);
829
+ const recs = parseRecords(await io.read(file));
830
+ const t = await target(flags, io);
831
+ const a = admin(t, io);
832
+ let reindexId;
833
+ if (flags.replace) {
834
+ reindexId = (await a.startReindex()).reindexId;
835
+ io.err(`Started resync ${reindexId}; records not in the file are removed when it commits.
836
+ `);
837
+ }
838
+ const total = { indexed: 0, updated: 0, skipped: 0, deleted: 0, embedded: 0, errors: [] };
839
+ const ok = [];
840
+ recs.forEach((r, i) => {
841
+ const id = r?.id;
842
+ if (typeof id === "string" && id.trim()) ok.push(r);
843
+ else total.errors.push({ id: `record ${fmt(i + 1)}`, error: "it has no id" });
844
+ });
845
+ const warnings = /* @__PURE__ */ new Set();
846
+ let sent = total.errors.length;
847
+ for (const chunk of batches(ok, size)) {
848
+ const r = await retrying(io, () => a.batch({ upserts: chunk, reindexId }));
849
+ total.indexed += r.indexed;
850
+ total.updated += r.updated;
851
+ total.skipped += r.skipped;
852
+ total.embedded += r.embedded;
853
+ total.errors.push(...r.errors);
854
+ for (const w of r.warnings ?? []) warnings.add(w);
855
+ sent += chunk.length;
856
+ io.err(`Sent ${fmt(sent)} of ${fmt(recs.length)} records
857
+ `);
858
+ }
859
+ let commit;
860
+ let committed = false;
861
+ if (reindexId) {
862
+ if (total.errors.length) {
863
+ io.err(`Not committing resync ${reindexId}: ${total.errors.length} records failed, and committing would remove them. Fix them and run the import again, or run \`shoof reindex commit\` to keep what was sent.
864
+ `);
865
+ } else {
866
+ commit = await commitWhenCopied(a, reindexId, io);
867
+ committed = true;
868
+ }
869
+ }
870
+ const result = { records: recs.length, ...total, warnings: [...warnings], ...reindexId ? { reindexId, committed, commit } : {} };
871
+ print(result, () => {
872
+ let s = `${fmt(recs.length)} records: ${fmt(total.indexed)} added, ${fmt(total.updated)} updated, ${fmt(total.skipped)} unchanged, ${fmt(total.embedded)} embedded.
873
+ `;
874
+ if (commit) s += `Resync committed: ${fmt(commit.count)} records live, ${fmt(commit.swept)} removed.
875
+ `;
876
+ for (const w of warnings) s += `Warning: ${w}
877
+ `;
878
+ for (const e of total.errors.slice(0, 50)) s += `Failed ${e.id}: ${e.error}
879
+ `;
880
+ if (total.errors.length > 50) s += `...and ${total.errors.length - 50} more failed.
881
+ `;
882
+ return s;
883
+ });
884
+ if (total.errors.length) throw new Error(`${total.errors.length} of ${recs.length} records failed.`);
885
+ }
886
+ async function commitWhenCopied(a, reindexId, io) {
887
+ for (let i = 0; ; i++) {
888
+ try {
889
+ return await a.commitReindex(reindexId);
890
+ } catch (e) {
891
+ if (!(e instanceof ShoofApiError && e.code === "reindex_copying") || i >= 60) throw e;
892
+ io.err("The live index is still being copied; waiting to commit.\n");
893
+ await (io.sleep ?? sleep2)(5e3);
894
+ }
895
+ }
896
+ }
897
+ async function reindex(args, flags, io, print) {
898
+ const [sub, ...rest] = args;
899
+ const a = admin(await target(flags, io), io);
900
+ switch (sub) {
901
+ case "start": {
902
+ const r = await a.startReindex({ copy: !flags["no-copy"], restart: !!flags.restart });
903
+ return print(
904
+ r,
905
+ () => `${r.resumed ? "Resumed" : "Started"} resync ${r.reindexId}. Send records with this reindexId, then run \`shoof reindex commit\`.
906
+ `
907
+ );
908
+ }
909
+ case "status": {
910
+ const r = await a.reindexStatus();
911
+ return print(
912
+ r,
913
+ () => r.active ? table([
914
+ ["Resync", r.reindexId ?? ""],
915
+ ["Started", r.startedAt ?? ""],
916
+ ["Copying", r.copying ? `yes, ${fmt(r.copied ?? 0)} of ${fmt(r.total ?? 0)}` : "done"],
917
+ ["Pending", fmt(r.pendingDocs ?? 0)]
918
+ ]) : "No resync in progress.\n"
919
+ );
920
+ }
921
+ case "commit": {
922
+ let id = rest[0];
923
+ if (!id) {
924
+ const st = await a.reindexStatus();
925
+ if (!st.active || !st.reindexId) throw new UsageError("No resync in progress.");
926
+ id = st.reindexId;
927
+ }
928
+ const r = await commitWhenCopied(a, id, io);
929
+ return print(r, () => `Committed: index version ${r.version}, ${fmt(r.count)} records live, ${fmt(r.swept)} removed.
930
+ `);
931
+ }
932
+ case "cancel": {
933
+ const r = await a.cancelReindex();
934
+ return print(r, () => r.aborted ? "Cancelled the resync.\n" : "No resync in progress.\n");
935
+ }
936
+ default:
937
+ throw new UsageError(sub ? `Unknown reindex command "${sub}".` : "Use reindex start, status, commit or cancel.");
938
+ }
939
+ }
940
+ async function settings(args, flags, io, print) {
941
+ const [sub, ...rest] = args;
942
+ const a = admin(await target(flags, io), io);
943
+ switch (sub) {
944
+ case "get": {
945
+ const res = await a.getSettings();
946
+ if (!rest.length) return print(res.settings, () => JSON.stringify(res.settings, null, 2) + "\n");
947
+ const name = rest[0];
948
+ if (!(name in res.settings)) throw new UsageError(`There is no setting "${name}".`);
949
+ const value = res.settings[name];
950
+ return print(value, () => (typeof value === "string" ? value : JSON.stringify(value, null, 2)) + "\n");
951
+ }
952
+ case "set": {
953
+ const [name, ...value] = rest;
954
+ if (!name || !value.length) throw new UsageError("Use: shoof settings set <name> <value>");
955
+ const raw = value.join(" ");
956
+ let parsed = raw;
957
+ try {
958
+ parsed = JSON.parse(raw);
959
+ } catch {
960
+ }
961
+ const res = await a.patchSettings({ [name]: parsed });
962
+ const saved = res.settings[name];
963
+ return print(saved, () => `Set ${name} to ${JSON.stringify(saved)}.
964
+ `);
965
+ }
966
+ case "preset": {
967
+ const preset = one(rest, "settings preset <store|blog>");
968
+ if (preset !== "store" && preset !== "blog") throw new UsageError('The preset is "store" or "blog".');
969
+ const res = await a.applyPreset(preset);
970
+ return print(res.settings, () => `Applied the ${preset} preset.
971
+ `);
972
+ }
973
+ default:
974
+ throw new UsageError(sub ? `Unknown settings command "${sub}".` : "Use settings get, set or preset.");
975
+ }
976
+ }
977
+ function synonymText(s) {
978
+ return s.kind === "oneway" ? `${s.input} -> ${s.terms.join(", ")}` : s.terms.join(" = ");
979
+ }
980
+ async function synonyms(args, flags, io, print) {
981
+ const [sub, ...rest] = args;
982
+ const a = admin(await target(flags, io), io);
983
+ switch (sub) {
984
+ case "list":
985
+ case void 0: {
986
+ const list = await a.getSynonyms();
987
+ return print(list, () => list.length ? list.map((s) => `${s.id ?? "-"} ${synonymText(s)}
988
+ `).join("") : "No synonyms.\n");
989
+ }
990
+ case "add": {
991
+ const syn = flags.input ? { kind: "oneway", input: flags.input, terms: rest } : { kind: "synonym", terms: rest };
992
+ if (rest.length < (flags.input ? 1 : 2)) {
993
+ throw new UsageError("Give two or more terms that mean the same (shoof synonyms add sofa couch), or --input <word> and the terms it finds.");
994
+ }
995
+ const saved = await a.setSynonyms([...await a.getSynonyms(), syn]);
996
+ const added = saved[saved.length - 1];
997
+ return print(added, () => `Added ${added.id ?? ""} ${synonymText(added)}
998
+ `);
999
+ }
1000
+ case "remove": {
1001
+ const id = one(rest, "synonyms remove <id>");
1002
+ const list = await a.getSynonyms();
1003
+ const kept = list.filter((s) => s.id !== id);
1004
+ if (kept.length === list.length) throw new UsageError(`No synonym has the id "${id}"; \`shoof synonyms list\` shows them.`);
1005
+ await a.setSynonyms(kept);
1006
+ return print({ removed: id }, () => `Removed ${id}.
1007
+ `);
1008
+ }
1009
+ default:
1010
+ throw new UsageError(`Unknown synonyms command "${sub}". Use synonyms list, add or remove.`);
1011
+ }
1012
+ }
1013
+ async function rules(args, flags, io, print) {
1014
+ const [sub, ...rest] = args;
1015
+ const a = admin(await target(flags, io), io);
1016
+ switch (sub) {
1017
+ case "list":
1018
+ case void 0: {
1019
+ const list = await a.getRules();
1020
+ return print(
1021
+ list,
1022
+ () => list.length ? list.map((r) => `${r.id ?? "-"} ${r.enabled === false ? "off" : "on "} ${r.match ?? "is"} "${r.pattern}"${r.description ? ` ${r.description}` : ""}
1023
+ `).join("") : "No rules.\n"
1024
+ );
1025
+ }
1026
+ case "add": {
1027
+ const src = one(rest, "rules add <JSON|@file.json>");
1028
+ const rule = parseJson(src.startsWith("@") ? await io.read(src.slice(1)) : src, "the rule");
1029
+ if (!rule || typeof rule !== "object" || Array.isArray(rule)) throw new UsageError("The rule must be a JSON object.");
1030
+ delete rule.id;
1031
+ const saved = await a.setRules([...await a.getRules(), { enabled: true, ...rule }]);
1032
+ const added = saved[saved.length - 1];
1033
+ return print(added, () => `Added rule ${added.id ?? ""} for "${added.pattern}".
1034
+ `);
1035
+ }
1036
+ case "remove": {
1037
+ const id = one(rest, "rules remove <id>");
1038
+ const list = await a.getRules();
1039
+ const kept = list.filter((r) => r.id !== id);
1040
+ if (kept.length === list.length) throw new UsageError(`No rule has the id "${id}"; \`shoof rules list\` shows them.`);
1041
+ await a.setRules(kept);
1042
+ return print({ removed: id }, () => `Removed rule ${id}.
1043
+ `);
1044
+ }
1045
+ default:
1046
+ throw new UsageError(`Unknown rules command "${sub}". Use rules list, add or remove.`);
1047
+ }
1048
+ }
1049
+ async function analytics(flags, io, print) {
1050
+ const interval = flags.interval;
1051
+ if (interval !== void 0 && interval !== "hour" && interval !== "day" && interval !== "week") throw new UsageError("--interval is hour, day or week.");
1052
+ const r = await admin(await target(flags, io), io).analytics({ from: flags.from, to: flags.to, interval });
1053
+ if (flags["no-results"]) {
1054
+ return print(
1055
+ r.noResultQueries,
1056
+ () => r.noResultQueries.length ? `Searches with no results:
1057
+ ` + r.noResultQueries.map((q) => ` ${fmt(q.count).padStart(7)} ${q.query}
1058
+ `).join("") : "No searches without results.\n"
1059
+ );
1060
+ }
1061
+ const pct = (n) => `${(n * 100).toFixed(1)}%`;
1062
+ print(
1063
+ r,
1064
+ () => table([
1065
+ ["Searches", fmt(r.totals.searches)],
1066
+ ["Visitors", fmt(r.totals.users)],
1067
+ ["No results", pct(r.totals.noResultRate)],
1068
+ ["Click-through", pct(r.totals.clickThroughRate)],
1069
+ ["Conversion", pct(r.totals.conversionRate)]
1070
+ ]) + (r.topQueries.length ? `
1071
+ Top searches:
1072
+ ` + r.topQueries.map((q) => ` ${fmt(q.count).padStart(7)} ${q.query}
1073
+ `).join("") : "") + (r.noResultQueries.length ? `
1074
+ No results:
1075
+ ` + r.noResultQueries.map((q) => ` ${fmt(q.count).padStart(7)} ${q.query}
1076
+ `).join("") : "")
1077
+ );
1078
+ }
1079
+ function one(args, usage) {
1080
+ if (args.length !== 1 || !args[0]) throw new UsageError(`Use: shoof ${usage}`);
1081
+ return args[0];
1082
+ }
1083
+ function int(v, name) {
1084
+ if (v === void 0) return void 0;
1085
+ const n = Number(v);
1086
+ if (!Number.isInteger(n) || n < 0) throw new UsageError(`${name} must be a whole number.`);
1087
+ return n;
1088
+ }
1089
+ function parseJson(text, what) {
1090
+ try {
1091
+ return JSON.parse(text);
1092
+ } catch (e) {
1093
+ throw new UsageError(`${what} isn't valid JSON: ${e.message}`);
1094
+ }
1095
+ }
1096
+ function fmt(n) {
1097
+ return n.toLocaleString("en-US");
1098
+ }
1099
+ function table(rows) {
1100
+ const w = Math.max(...rows.map(([k]) => k.length));
1101
+ return rows.map(([k, v]) => `${k.padEnd(w)} ${v}
1102
+ `).join("");
1103
+ }
1104
+
1105
+ // src/main.ts
1106
+ var configPath = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "shoof", "config.json");
1107
+ async function readStdin() {
1108
+ const chunks = [];
1109
+ for await (const c of process.stdin) chunks.push(c);
1110
+ return Buffer.concat(chunks).toString("utf8");
1111
+ }
1112
+ var code = await run(process.argv.slice(2), {
1113
+ out: (s) => void process.stdout.write(s),
1114
+ err: (s) => void process.stderr.write(s),
1115
+ env: process.env,
1116
+ configPath,
1117
+ read: (path) => path === "-" ? readStdin() : readFile(path, "utf8"),
1118
+ async loadConfig() {
1119
+ try {
1120
+ return JSON.parse(await readFile(configPath, "utf8"));
1121
+ } catch (e) {
1122
+ if (e.code === "ENOENT") return {};
1123
+ throw new Error(`Can't read ${configPath}: ${e.message}`);
1124
+ }
1125
+ },
1126
+ async saveConfig(config) {
1127
+ if (!config) return rm(configPath, { force: true });
1128
+ await mkdir(dirname(configPath), { recursive: true, mode: 448 });
1129
+ await writeFile(configPath, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
1130
+ await chmod(configPath, 384);
1131
+ }
1132
+ });
1133
+ process.exitCode = code;
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@shoof/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "The Shoof AI command line: search, answers, records, reindexes, settings, synonyms, rules and analytics from the terminal.",
5
+ "keywords": [
6
+ "shoof",
7
+ "shoof ai",
8
+ "search",
9
+ "ai search",
10
+ "cli",
11
+ "semantic search"
12
+ ],
13
+ "homepage": "https://docs.shoofai.com/cli/",
14
+ "bugs": {
15
+ "url": "https://shoofai.com/support/",
16
+ "email": "support@shoofai.com"
17
+ },
18
+ "license": "MIT",
19
+ "author": "Shoof AI (https://shoofai.com)",
20
+ "type": "module",
21
+ "bin": {
22
+ "shoof": "dist/shoof.js"
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "engines": {
30
+ "node": ">=18"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "devDependencies": {
36
+ "esbuild": "^0.28.2",
37
+ "@shoof/js-client": "1.0.1",
38
+ "@shoof/schema": "1.0.0"
39
+ }
6
40
  }