conare 0.30.0 → 0.34.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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // conare: TypeScript client for the Conare API. Zero dependencies; uses global fetch.
2
- export const VERSION = "0.30.0";
2
+ export const VERSION = "0.34.0";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
5
  /** Above the API's 110 s deadline for a write: a call given up sooner is retried while the first still runs. */
@@ -9,23 +9,33 @@ const WRITE_TIMEOUT_MS = 120_000;
9
9
  const GZIP_MIN_BYTES = 8 * 1024;
10
10
  const CHECK_BATCH = 1000;
11
11
  function toParse(body) {
12
+ const usage = body.usage
13
+ ? { usage: { pages: body.usage.pages, ...(body.usage.index_tokens !== undefined ? { indexTokens: body.usage.index_tokens } : {}) } }
14
+ : {};
12
15
  if (body.state === "parsing")
13
- return { id: body.id, state: "parsing" };
14
- if (body.state === "failed")
15
- return { id: body.id, state: "failed", error: body.error ?? { code: "unavailable", message: "the parse failed" } };
16
+ return { id: body.id, state: "parsing", ...usage };
17
+ if (body.state === "failed") {
18
+ const error = body.error ?? { code: "unavailable", message: "the parse failed" };
19
+ const details = toErrorDetails(error.details);
20
+ return { id: body.id, state: "failed", error: { code: error.code, message: error.message, ...(details ? { details } : {}) } };
21
+ }
16
22
  return {
17
23
  id: body.id,
18
24
  state: "done",
19
25
  type: body.type,
20
26
  name: body.name,
27
+ ...(body.title ? { title: body.title } : {}),
28
+ ...(body.source_url ? { sourceUrl: body.source_url } : {}),
21
29
  pages: body.pages ?? null,
30
+ ...(body.sheets ? { sheets: body.sheets } : {}),
22
31
  markdown: body.markdown,
23
32
  parts: body.parts,
24
33
  withoutText: body.without_text,
25
34
  ocrFailed: body.ocr_failed ?? [],
35
+ ...usage,
26
36
  };
27
37
  }
28
- /** The query parameters of `ParseOptions`. */
38
+ /** The query parameters of `ParseOptions` but `sheets` (withSheets). */
29
39
  function parseQuery(options) {
30
40
  return {
31
41
  ...(options.type ? { type: options.type } : {}),
@@ -33,8 +43,17 @@ function parseQuery(options) {
33
43
  ...(options.password ? { password: options.password } : {}),
34
44
  ...(options.layout ? { layout: "true" } : {}),
35
45
  ...(options.wait === undefined ? {} : { wait: String(options.wait) }),
46
+ ...(options.range ? { range: options.range } : {}),
47
+ ...(options.formulas ? { formulas: "true" } : {}),
48
+ ...(options.vision ? { vision: "true" } : {}),
36
49
  };
37
50
  }
51
+ /** query with a `sheet` parameter per name of `options.sheets` (the API repeats it). */
52
+ function withSheets(query, options) {
53
+ for (const sheet of options.sheets ?? [])
54
+ query.append("sheet", sheet);
55
+ return query;
56
+ }
38
57
  function toFileUpload(body) {
39
58
  const pending = body.ocr_pending ?? [];
40
59
  return {
@@ -93,6 +112,8 @@ function toOrganization(o) {
93
112
  out.default = true;
94
113
  if (o.created_at)
95
114
  out.createdAt = o.created_at;
115
+ if (typeof o.spend_cap_usd === "number")
116
+ out.spendCapUsd = o.spend_cap_usd;
96
117
  return out;
97
118
  }
98
119
  function toKey(k) {
@@ -102,6 +123,8 @@ function toKey(k) {
102
123
  hint: k.hint,
103
124
  namespaces: k.namespaces,
104
125
  modelsOnly: k.models_only,
126
+ readOnly: k.read_only ?? false,
127
+ rateLimitPercent: k.rate_limit_percent ?? null,
105
128
  organizations: k.organizations,
106
129
  createdAt: k.created_at,
107
130
  lastUsedAt: k.last_used_at,
@@ -109,18 +132,34 @@ function toKey(k) {
109
132
  customer: k.customer ?? false,
110
133
  };
111
134
  }
112
- // ---- Errors ----------------------------------------------------------------
113
- /** Every failure the SDK throws. `status` is 0 when no response arrived. */
135
+ function toErrorDetails(wire) {
136
+ if (!wire || typeof wire !== "object")
137
+ return null;
138
+ const details = {
139
+ ...(typeof wire.status === "number" ? { status: wire.status } : {}),
140
+ ...(typeof wire.retry_after_s === "number" ? { retryAfterSeconds: wire.retry_after_s } : {}),
141
+ ...(typeof wire.source_id === "string" ? { sourceId: wire.source_id } : {}),
142
+ ...(typeof wire.deletes_at === "string" ? { deletesAt: new Date(wire.deletes_at) } : {}),
143
+ };
144
+ return Object.keys(details).length > 0 ? details : null;
145
+ }
146
+ /**
147
+ * Every failure the SDK throws. `status` is 0 when no response arrived. `details` is what the error
148
+ * carries beside its message, when it does: for a URL the API fetched, the status its site answered; for
149
+ * `source_deleting`, the source and when it is deleted.
150
+ */
114
151
  export class ConareError extends Error {
115
152
  status;
116
153
  code;
117
154
  requestId;
118
- constructor(status, code, message, requestId = null) {
155
+ details;
156
+ constructor(status, code, message, requestId = null, details = null) {
119
157
  super(message);
120
158
  this.name = "ConareError";
121
159
  this.status = status;
122
160
  this.code = code;
123
161
  this.requestId = requestId;
162
+ this.details = details;
124
163
  }
125
164
  }
126
165
  /**
@@ -247,13 +286,16 @@ export class Conare {
247
286
  /**
248
287
  * A new organization of your customer, with a customer key: one per company you serve, with its own
249
288
  * namespaces, keys, sources, usage and limits. `externalId` is your own id for it, unique within your
250
- * customer: a create with one already used answers that organization and makes none. Mint the key its
251
- * traffic runs on with `createKey()` on a client whose `organization` is its `id`.
289
+ * customer: a create with one already used answers that organization and makes none (its spend cap as it
290
+ * is). `spendCapUsd` is its own monthly spend cap (`setOrganizationSpendCap()`). Mint the key its traffic
291
+ * runs on with `createKey()` on a client whose `organization` is its `id`.
252
292
  */
253
293
  async createOrganization(input, options = {}) {
254
294
  const request = { name: input.name };
255
295
  if (input.externalId !== undefined)
256
296
  request.external_id = input.externalId;
297
+ if (input.spendCapUsd !== undefined)
298
+ request.spend_cap_usd = input.spendCapUsd;
257
299
  const body = await this.request("POST", "/organizations", request, options);
258
300
  return toOrganization(body.organization);
259
301
  }
@@ -267,6 +309,16 @@ export class Conare {
267
309
  const body = await this.request("PATCH", `/organizations/${encodeURIComponent(id)}`, { name }, options);
268
310
  return toOrganization(body.organization);
269
311
  }
312
+ /**
313
+ * Sets one organization's own monthly spend cap in whole dollars (1-10,000,000), or removes it with null,
314
+ * with a customer key; your customer's default organization takes one too. Once the organization's
315
+ * charges this month reach it, its billed calls fail with a ConareError 402 `spend_cap_reached` and your
316
+ * other organizations are still served.
317
+ */
318
+ async setOrganizationSpendCap(id, usd, options = {}) {
319
+ const body = await this.request("PATCH", `/organizations/${encodeURIComponent(id)}`, { spend_cap_usd: usd }, options);
320
+ return toOrganization(body.organization);
321
+ }
270
322
  /**
271
323
  * Deletes one organization of your customer for good, with a customer key. Delete its namespaces and
272
324
  * sources first (a client whose `organization` is its `id`): until then it answers 409 `conflict`.
@@ -295,17 +347,21 @@ export class Conare {
295
347
  month: body.month,
296
348
  count: body.count,
297
349
  active: body.active,
350
+ capped: body.capped,
298
351
  total: body.total,
299
352
  top10Share: body.top10_share,
300
353
  matched: body.matched,
301
- rows: body.rows.map((r) => ({ id: r.id, name: r.name, ...(r.external_id ? { externalId: r.external_id } : {}), charges: r.charges })),
354
+ rows: body.rows.map((r) => ({ id: r.id, name: r.name, ...(r.external_id ? { externalId: r.external_id } : {}), charges: r.charges, spendCapMicros: r.spend_cap_micros ?? null })),
302
355
  rest: body.rest,
303
356
  };
304
357
  }
305
358
  /**
306
359
  * A key of this client's `organization`, with a customer key: the key a company's traffic runs on,
307
360
  * reaching that organization alone. `namespaces` scopes it (exact names, or prefixes ending in `*`),
308
- * `modelsOnly` keeps it to the model routes, `expiresAt` ends it. The secret is in this answer only.
361
+ * `modelsOnly` keeps it to the model routes, `readOnly` to the calls that change nothing stored
362
+ * (every write answers 403 `read_only_key`), `rateLimitPercent` (1-100) caps it at that percent of each of the
363
+ * organization's rate limits (past it, 429 `rate_limited` for this key alone), `expiresAt` ends it. The secret is in
364
+ * this answer only.
309
365
  */
310
366
  async createKey(input, options = {}) {
311
367
  const request = { name: input.name };
@@ -313,6 +369,10 @@ export class Conare {
313
369
  request.namespaces = input.namespaces;
314
370
  if (input.modelsOnly)
315
371
  request.models_only = true;
372
+ if (input.readOnly)
373
+ request.read_only = true;
374
+ if (input.rateLimitPercent !== undefined)
375
+ request.rate_limit_percent = input.rateLimitPercent;
316
376
  if (input.expiresAt !== undefined)
317
377
  request.expires_at = input.expiresAt instanceof Date ? input.expiresAt.toISOString() : input.expiresAt;
318
378
  const body = await this.request("POST", "/keys", request, options);
@@ -334,18 +394,20 @@ export class Conare {
334
394
  if (options.tokenEmbeddings)
335
395
  request.token_embeddings = true;
336
396
  const body = await this.request("POST", "/embed", request, options);
397
+ const usage = body.usage ? { usage: { embedTokens: body.usage.embed_tokens } } : {};
337
398
  if (options.tokenEmbeddings) {
338
399
  return {
339
400
  embeddings: body.embeddings,
340
401
  tokenEmbeddings: body.token_embeddings ?? [],
341
402
  tokenDimensions: body.token_dimensions ?? 0,
342
403
  denseWeight: body.dense_weight ?? 0,
404
+ ...usage,
343
405
  };
344
406
  }
345
407
  if (options.outputDtype === "int8") {
346
- return { values: body.embeddings.map((v) => Int8Array.from(v)), scales: body.scales ?? [] };
408
+ return { values: body.embeddings.map((v) => Int8Array.from(v)), scales: body.scales ?? [], ...usage };
347
409
  }
348
- return body.embeddings;
410
+ return Object.assign(body.embeddings, usage);
349
411
  }
350
412
  /**
351
413
  * Rerank 1-100 documents against a query, best first. Each document is 1-24,000 characters, the query at
@@ -355,16 +417,29 @@ export class Conare {
355
417
  async rerank(query, documents, options = {}) {
356
418
  const body = await this.request("POST", "/rerank", { query, documents, top_k: options.topK }, options);
357
419
  const results = body.results.map((r) => ({ index: r.index, score: r.score, document: documents[r.index] ?? "" }));
358
- return Object.assign(results, { unscored: body.unscored ?? [] });
420
+ const usage = body.usage ? { usage: { rerankTokens: body.usage.rerank_tokens, rerankCalls: body.usage.rerank_calls } } : {};
421
+ return Object.assign(results, { unscored: body.unscored ?? [], ...usage });
359
422
  }
360
423
  /**
361
424
  * Parses a file to Markdown and stores nothing: the same parser, options and result as `uploadFile`.
362
- * `file` is its bytes, or `{ url }` (an https URL on a public address, fetched by the API). A file OCR
425
+ * `file` is its bytes, or `{ url }` (an http or https URL on a public address, fetched by the API, which
426
+ * reads the one page named and does not consult robots.txt; the result then carries `sourceUrl` and a page's
427
+ * `title`). A URL that does not answer its file throws what its site did (`gone`, `refused`, `slow_down`,
428
+ * `unreachable`, ...) with `details.status`; a page that holds no text until a browser runs its scripts
429
+ * throws 422 `needs_javascript`, which `render: true` asks to have read through a browser. `links: true`
430
+ * writes a web page's links as Markdown links (its menus' and footer's too); `mainContent: true` reads its
431
+ * main content alone. A file OCR
363
432
  * reads answers once OCR is done within `wait` seconds (default 60), else `{ id, state: "parsing" }`:
364
433
  * `getParse(id)` answers the result (kept 24 hours). Any API key can parse, a models-only key too.
365
434
  */
366
435
  async parse(file, options = {}) {
367
- const query = new URLSearchParams({ ...(options.name ? { name: options.name } : {}), ...parseQuery(options) });
436
+ const query = withSheets(new URLSearchParams({
437
+ ...(options.name ? { name: options.name } : {}),
438
+ ...parseQuery(options),
439
+ ...(options.render ? { render: "true" } : {}),
440
+ ...(options.links ? { links: "true" } : {}),
441
+ ...(options.mainContent ? { main_content: "true" } : {}),
442
+ }), options);
368
443
  const body = await this.request("POST", `/parse?${query}`, file, { timeout: 120_000, ...options });
369
444
  return toParse(body);
370
445
  }
@@ -518,6 +593,8 @@ export class Namespace {
518
593
  async write(documents, options) {
519
594
  const all = Array.isArray(documents) ? documents : [documents];
520
595
  const out = [];
596
+ // Summed over the batches; undefined if any batch answered none (an older server).
597
+ let usage = { documentsWritten: 0, indexTokens: 0 };
521
598
  for (let i = 0; i < all.length; i += BATCH_SIZE) {
522
599
  const batch = all.slice(i, i + BATCH_SIZE);
523
600
  const key = options?.idempotencyKey;
@@ -547,7 +624,12 @@ export class Namespace {
547
624
  }
548
625
  out.push(result);
549
626
  });
627
+ usage = usage && body.usage
628
+ ? { documentsWritten: usage.documentsWritten + body.usage.documents_written, indexTokens: usage.indexTokens + body.usage.index_tokens }
629
+ : undefined;
550
630
  }
631
+ if (usage)
632
+ out.usage = usage;
551
633
  return out;
552
634
  }
553
635
  /**
@@ -566,13 +648,13 @@ export class Namespace {
566
648
  * `withoutText`); before that it is `queued` or `parsing`, and `getFile` follows it.
567
649
  */
568
650
  async uploadFile(file, name, options = {}) {
569
- const query = new URLSearchParams({
651
+ const query = withSheets(new URLSearchParams({
570
652
  name,
571
653
  ...(options.id ? { id: options.id } : {}),
572
654
  ...(options.user ? { user: options.user } : {}),
573
655
  ...(options.metadata ? { metadata: JSON.stringify(options.metadata) } : {}),
574
656
  ...parseQuery(options),
575
- });
657
+ }), options);
576
658
  const waitS = typeof options.wait === "number" ? options.wait : options.wait === false ? 0 : 60;
577
659
  const timeout = Math.max(300_000, waitS * 1000 + 60_000);
578
660
  const body = await this.client.request("POST", this.path(`/files?${query}`), file, { timeout, ...options });
@@ -597,7 +679,54 @@ export class Namespace {
597
679
  */
598
680
  async query(query, options = {}) {
599
681
  const body = await this.client.request("POST", this.path("/query"), queryBody(query, options), options);
600
- return Object.assign(body.results, { degraded: body.degraded ?? [] });
682
+ return Object.assign(body.results, { degraded: body.degraded ?? [] }, body.usage ? { usage: { queries: body.usage.queries } } : {});
683
+ }
684
+ /**
685
+ * A search answered as a record: the fields `schema` names, each filled from the passages the search read (`topK`
686
+ * of them, at least 20 and at most 50) with the document, address and words that state it, or null when no passage states
687
+ * it (every field null when nothing matched). `record` is null when the answer model was unavailable; `results`
688
+ * are the search's. Pass the schema inline, or declared `as const`, to type each value: an `enum` field is one of
689
+ * its values.
690
+ */
691
+ async queryRecord(query, schema, options = {}) {
692
+ const body = await this.client.request("POST", this.path("/query"), { ...queryBody(query, options), answer: { schema } }, options);
693
+ return {
694
+ record: body.answer ?? null,
695
+ sources: body.answer_sources ?? {},
696
+ results: Object.assign(body.results, { degraded: body.degraded ?? [] }, body.usage ? { usage: { queries: body.usage.queries } } : {}),
697
+ sourcePassages: body.answer_passages ?? [],
698
+ };
699
+ }
700
+ /**
701
+ * A page of the namespace's changes after `cursor`, oldest first: the documents created, changed and deleted as
702
+ * its website, Cloud Storage and file sources read them (and deleted their documents). Without `cursor`, from the
703
+ * start: every document it holds. Keep `nextCursor` and pass it as `cursor` next time; while `hasMore`, call
704
+ * again at once. `limit` is 1-1000 rows, default 100. Rows are kept 90 days, a live document's latest whatever
705
+ * its age; a cursor whose unread rows were dropped throws 410 `cursor_expired`: list again without it. Documents
706
+ * written with `add` or `write` are not listed. `source` keeps the rows to one source's documents, `since` and
707
+ * `until` to a time window: one re-read of a website is `{ source, since: <its sync's start> }`. A web page's
708
+ * `changed` row says how it changed (`diff`).
709
+ */
710
+ async changes(options = {}) {
711
+ const { cursor, limit, source, since, until, ...rest } = options;
712
+ const q = new URLSearchParams();
713
+ if (cursor)
714
+ q.set("cursor", cursor);
715
+ if (limit)
716
+ q.set("limit", String(limit));
717
+ if (source)
718
+ q.set("source", source);
719
+ if (since)
720
+ q.set("since", since instanceof Date ? since.toISOString() : since);
721
+ if (until)
722
+ q.set("until", until instanceof Date ? until.toISOString() : until);
723
+ const qs = q.toString();
724
+ const body = await this.client.request("GET", this.path(`/changes${qs ? `?${qs}` : ""}`), undefined, rest);
725
+ return {
726
+ changes: body.changes.map((c) => ({ ...c, at: new Date(c.at) })),
727
+ nextCursor: body.next_cursor,
728
+ hasMore: body.has_more,
729
+ };
601
730
  }
602
731
  /**
603
732
  * The documents whose text matches a regular expression, or a near spelling (`{ query, max_distance }`),
@@ -613,7 +742,7 @@ export class Namespace {
613
742
  limit: options.limit,
614
743
  cursor: options.cursor,
615
744
  }, options);
616
- return { matches: body.matches, nextCursor: body.next_cursor ?? null };
745
+ return { matches: body.matches, nextCursor: body.next_cursor ?? null, ...(body.usage ? { usage: { queries: body.usage.queries } } : {}) };
617
746
  }
618
747
  /**
619
748
  * A deep search, page by page: ranks `maxResults` documents once (at least `topK`; at most 1,000,
@@ -629,12 +758,12 @@ export class Namespace {
629
758
  : await this.client.request("POST", this.path("/query"), { ...queryBody(query, options), max_results: options.maxResults }, options);
630
759
  if (!cursor) {
631
760
  cursor = page.next_cursor ?? null;
632
- yield { results: page.results, nextCursor: cursor, degraded: page.degraded ?? [] };
761
+ yield { results: page.results, nextCursor: cursor, degraded: page.degraded ?? [], ...pageUsage(page) };
633
762
  }
634
763
  while (cursor) {
635
764
  page = await this.client.request("POST", this.path("/query"), { cursor, top_k: options.topK }, options);
636
765
  cursor = page.next_cursor ?? null;
637
- yield { results: page.results, nextCursor: cursor, degraded: page.degraded ?? [] };
766
+ yield { results: page.results, nextCursor: cursor, degraded: page.degraded ?? [], ...pageUsage(page) };
638
767
  }
639
768
  }
640
769
  /** One document by id, or null if it does not exist. */
@@ -673,6 +802,16 @@ export class Namespace {
673
802
  cursor = page.next_cursor;
674
803
  } while (cursor);
675
804
  }
805
+ /**
806
+ * How many documents match `filter`, `user` and `userPrefix` (a query's), exactly; with none, the namespace's.
807
+ * A document counts once, however long. `$ne`, `$nin` and `$text` throw 400 `invalid_filter`; a filter too many
808
+ * documents match to count exactly throws 400 `invalid_request`: narrow it.
809
+ */
810
+ async count(options = {}) {
811
+ const { filter, user, userPrefix, ...rest } = options;
812
+ const out = await this.client.request("POST", this.path("/documents/count"), { filter, user, user_prefix: userPrefix }, rest);
813
+ return out.count;
814
+ }
676
815
  /** Delete one document. Throws a ConareError with status 404 (`document_not_found`) if it does not exist. */
677
816
  async delete(id, options) {
678
817
  await this.client.request("DELETE", this.path(`/documents/${segment(id)}`), undefined, options);
@@ -751,17 +890,78 @@ export class Sources {
751
890
  * automatic. A web source (`update<WebSource>`): 3600 to 604800, or null for a day; each website is its own
752
891
  * source with its own interval. A Google Cloud Storage source (`update<GCSSource>`): 900 to 604800, or null for
753
892
  * an hour.
893
+ *
894
+ * A web source of `urls` takes new pages: `urls` is the whole list afterwards (as `connect` takes it), or
895
+ * `addUrls` and `removeUrls` change the list it has. Its next sync starts now: a new page is read, a page it keeps
896
+ * keeps its documents and is read again only when it changed, and a page taken off loses its documents.
897
+ *
898
+ * A web source of a `site` takes a new `maxPages` (1 to 5,000): its next sync starts now and keeps at most that
899
+ * many pages; with a smaller number, the documents of the pages it no longer keeps are removed.
754
900
  */
755
901
  async update(id, params, options) {
756
- return toAnySource(await this.client.request("PATCH", `/sources/${segment(id)}`, { sync_interval_s: params.syncIntervalSeconds }, options));
902
+ const body = {
903
+ sync_interval_s: params.syncIntervalSeconds,
904
+ urls: params.urls,
905
+ add_urls: params.addUrls,
906
+ remove_urls: params.removeUrls,
907
+ max_pages: params.maxPages,
908
+ };
909
+ return toAnySource(await this.client.request("PATCH", `/sources/${segment(id)}`, body, options));
910
+ }
911
+ /**
912
+ * One page of sources, not every source: on the first page the connected apps, then the custom, files, Google
913
+ * Cloud Storage and web sources, newest first, which carry their `kind` (`custom`, `files`, `gcs`, `web`); a
914
+ * connected app has none. `limit` (1-200, default 100) counts the sources with a `kind`; the connected apps all
915
+ * come on the first page. `namespace`, `user` and `type` keep the sources whose field equals the value;
916
+ * `health: "failing"` keeps the sources that need you (a failing source, an app whose status is `error`).
917
+ * `nextCursor` is the next page's `cursor` (pass the same filters with it), null on the last. `total`, on the
918
+ * first page, is how many sources every page holds: `list({ limit: 1 })` reads how many there are. A web source
919
+ * comes with how many pages it has (`config.pages`), not its `urls`: `get()` answers them. For every source,
920
+ * iterate `all()`, which follows `nextCursor` page by page.
921
+ */
922
+ async list(params = {}, options) {
923
+ const query = new URLSearchParams();
924
+ for (const key of ["namespace", "user", "type", "health", "cursor"]) {
925
+ const value = params[key];
926
+ if (value)
927
+ query.set(key, value);
928
+ }
929
+ // Named even when it is the default: a request without a limit gets the API's largest page.
930
+ query.set("limit", String(params.limit ?? 100));
931
+ const body = await this.client.request("GET", `/sources?${query}`, undefined, options);
932
+ return {
933
+ data: body.sources.map(toAnySource),
934
+ nextCursor: body.next_cursor ?? null,
935
+ ...(typeof body.total === "number" ? { total: body.total } : {}),
936
+ };
937
+ }
938
+ /** Every source `list()` pages through, fetched page by page as you iterate, with its filters and page size. */
939
+ async *all(params = {}, options) {
940
+ let cursor = null;
941
+ do {
942
+ const page = await this.list(cursor ? { ...params, cursor } : params, options);
943
+ yield* page.data;
944
+ cursor = page.nextCursor;
945
+ } while (cursor);
757
946
  }
758
947
  /**
759
- * Every source: the connected apps, then the custom, files and Google Cloud Storage sources, which carry
760
- * their `kind` (`custom`, `files`, `gcs`); a connected app has none.
948
+ * How many sources write into each namespace, by type, and how many of them fail or sync now: the sources
949
+ * `list()` pages through, counted, without the sources themselves (one read, however many there are). A source
950
+ * fails as `list({ health: "failing" })` lists it; one syncs while a sync of it runs, or while a connected app is
951
+ * `syncing` or `connecting`. `namespace` counts that namespace's alone. Namespaces come by name, each one's types
952
+ * the most sources first.
761
953
  */
762
- async list(options) {
763
- const body = await this.client.request("GET", "/sources", undefined, options);
764
- return body.sources.map(toAnySource);
954
+ async summary(params = {}, options) {
955
+ const query = params.namespace ? `?${new URLSearchParams({ namespace: params.namespace })}` : "";
956
+ const body = await this.client.request("GET", `/sources/summary${query}`, undefined, options);
957
+ return {
958
+ ...toSourceCounts(body),
959
+ namespaces: body.namespaces.map((n) => ({
960
+ namespace: n.namespace,
961
+ ...toSourceCounts(n),
962
+ types: n.types.map((t) => ({ type: t.type, ...toSourceCounts(t) })),
963
+ })),
964
+ };
765
965
  }
766
966
  /** One source by id. */
767
967
  async get(id, options) {
@@ -770,7 +970,7 @@ export class Sources {
770
970
  /**
771
971
  * Start a sync now. `full: true` re-reads everything the app holds instead of what changed: documents
772
972
  * that changed are rewritten and ones Conare no longer keeps are deleted. It is for Gmail and the apps
773
- * Conare reads itself (other apps answer 400), and Gmail's rows are billed again (`cost.usdPerMillionRows`).
973
+ * Conare reads itself (other apps answer 400), and only documents that changed are indexed again (rows cost what `cost.usdPerMillionRows` says: nothing where connectors are free).
774
974
  *
775
975
  * A connected app answers the `Source`, due to sync now. A Google Cloud Storage or web source answers the sync
776
976
  * `Run` it queued (409 `run_active` while one is queued or running). A custom or files source has nothing
@@ -810,12 +1010,29 @@ export class Sources {
810
1010
  /**
811
1011
  * Disconnect a source. Pass `deleteDocuments: true` to also delete what it synced; without it a
812
1012
  * connected app's and a custom source's documents stay. A Google Cloud Storage, web or files
813
- * source's documents always go with it. A custom source's delete is a run, which `runs.get` follows
814
- * until the source is `deleted`.
1013
+ * source's documents always go with it, at the end of its grace: an hour, or `graceSeconds` (0 to
1014
+ * 86,400; 0 deletes them now). Until its `deletesAt` they stay searchable and `restore` brings it
1015
+ * back. Deleted again in its grace, `graceSeconds: 0` deletes it now (it can no longer be restored); another
1016
+ * value brings `deletesAt` nearer, never later. A custom source's delete is a run, which `runs.get` follows
1017
+ * until the source is `deleted`. It needs a key that writes (in the console, an organization admin).
815
1018
  */
816
1019
  async delete(id, options = {}) {
817
- const qs = options.deleteDocuments ? "?delete_documents=true" : "";
818
- await this.client.request("DELETE", `/sources/${segment(id)}${qs}`, undefined, options);
1020
+ const query = [];
1021
+ if (options.deleteDocuments)
1022
+ query.push("delete_documents=true");
1023
+ if (options.graceSeconds !== undefined)
1024
+ query.push(`grace_s=${options.graceSeconds}`);
1025
+ await this.client.request("DELETE", `/sources/${segment(id)}${query.length ? `?${query.join("&")}` : ""}`, undefined, options);
1026
+ }
1027
+ /**
1028
+ * Bring back a Google Cloud Storage, web or files source deleted with a grace, before its
1029
+ * `deletesAt`: active again with every document it held, its next sync due now. An active source
1030
+ * is answered as it is; once its delete has started it answers 409 `delete_started`. It takes what
1031
+ * `delete` takes: a key that writes (in the console, an organization admin).
1032
+ */
1033
+ async restore(id, options) {
1034
+ const body = await this.client.request("POST", `/sources/${segment(id)}/restore`, undefined, options);
1035
+ return toAnySource(body);
819
1036
  }
820
1037
  /** The apps you can connect. */
821
1038
  async types(options) {
@@ -1054,7 +1271,9 @@ export class Events {
1054
1271
  };
1055
1272
  }
1056
1273
  }
1057
- /** A source by its `kind`: a connected app has none; a custom, files, Google Cloud Storage or web source names it. */
1274
+ function toSourceCounts(c) {
1275
+ return { sources: c.sources, failing: c.failing, syncing: c.syncing, lastSuccessAt: c.last_success_at ?? null };
1276
+ }
1058
1277
  function toAnySource(s) {
1059
1278
  if (!("kind" in s))
1060
1279
  return toSource(s);
@@ -1066,7 +1285,8 @@ function toAnySource(s) {
1066
1285
  app: null,
1067
1286
  user: null,
1068
1287
  config: {
1069
- urls: s.config?.urls ?? [],
1288
+ ...(s.config?.urls ? { urls: s.config.urls } : {}),
1289
+ pages: s.config?.pages ?? s.config?.urls?.length ?? 0,
1070
1290
  syncIntervalSeconds: s.config?.sync_interval_s ?? 0,
1071
1291
  ...(s.config?.site ? { site: s.config.site, maxPages: s.config.max_pages } : {}),
1072
1292
  },
@@ -1118,6 +1338,7 @@ function toCustomSource(s) {
1118
1338
  },
1119
1339
  documents: s.documents,
1120
1340
  documentsVerifiedAt: date(s.documents_verified_at),
1341
+ ...(s.deletes_at ? { deletesAt: new Date(s.deletes_at) } : {}),
1121
1342
  createdAt: new Date(s.created_at),
1122
1343
  updatedAt: new Date(s.updated_at),
1123
1344
  };
@@ -1294,6 +1515,10 @@ function toSource(s) {
1294
1515
  : null,
1295
1516
  };
1296
1517
  }
1518
+ /** A search page's `usage`, when the server answered one. */
1519
+ function pageUsage(page) {
1520
+ return page.usage ? { usage: { queries: page.usage.queries } } : {};
1521
+ }
1297
1522
  function toError(res, text) {
1298
1523
  const requestId = res.headers.get("x-request-id");
1299
1524
  let error;
@@ -1303,7 +1528,7 @@ function toError(res, text) {
1303
1528
  catch {
1304
1529
  // Not JSON: fall back to the status.
1305
1530
  }
1306
- return new ConareError(res.status, error?.code ?? `http_${res.status}`, error?.message ?? (res.statusText || `HTTP ${res.status}`), error?.request_id ?? requestId);
1531
+ return new ConareError(res.status, error?.code ?? `http_${res.status}`, error?.message ?? (res.statusText || `HTTP ${res.status}`), error?.request_id ?? requestId, toErrorDetails(error?.details));
1307
1532
  }
1308
1533
  const ID_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1309
1534
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.30.0",
3
+ "version": "0.34.0",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",