conare 0.29.0 → 0.33.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.29.0";
2
+ export const VERSION = "0.33.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 {
@@ -66,6 +85,21 @@ function toFileUpload(body) {
66
85
  ocrLayerOnly: body.ocr_layer_only ?? [],
67
86
  };
68
87
  }
88
+ /**
89
+ * Text `d` of `documents` scored for text `q` of `query` (one embedded with type "query", the other with
90
+ * "document", both with `tokenEmbeddings: true`): denseWeight × dot(the two vectors) + (1 − denseWeight) ×
91
+ * the mean, over the query's token embeddings, of each one's best dot product among the document's.
92
+ */
93
+ export function hybridScore(query, documents, q = 0, d = 0) {
94
+ const dot = (a, b) => a.reduce((sum, x, i) => sum + x * (b[i] ?? 0), 0);
95
+ const queryRows = query.tokenEmbeddings[q] ?? [];
96
+ const documentRows = documents.tokenEmbeddings[d] ?? [];
97
+ const tokens = queryRows.reduce((sum, row) => sum + documentRows.reduce((best, other) => Math.max(best, dot(row, other)), -Infinity), 0);
98
+ const dense = dot(query.embeddings[q] ?? [], documents.embeddings[d] ?? []);
99
+ if (queryRows.length === 0 || documentRows.length === 0)
100
+ return query.denseWeight * dense;
101
+ return query.denseWeight * dense + (1 - query.denseWeight) * (tokens / queryRows.length);
102
+ }
69
103
  /** The float vectors int8 embeddings stand for: values × scale. */
70
104
  export function dequantize(embeddings) {
71
105
  return embeddings.values.map((v, i) => Array.from(v, (x) => x * (embeddings.scales[i] ?? 0)));
@@ -78,6 +112,8 @@ function toOrganization(o) {
78
112
  out.default = true;
79
113
  if (o.created_at)
80
114
  out.createdAt = o.created_at;
115
+ if (typeof o.spend_cap_usd === "number")
116
+ out.spendCapUsd = o.spend_cap_usd;
81
117
  return out;
82
118
  }
83
119
  function toKey(k) {
@@ -87,6 +123,8 @@ function toKey(k) {
87
123
  hint: k.hint,
88
124
  namespaces: k.namespaces,
89
125
  modelsOnly: k.models_only,
126
+ readOnly: k.read_only ?? false,
127
+ rateLimitPercent: k.rate_limit_percent ?? null,
90
128
  organizations: k.organizations,
91
129
  createdAt: k.created_at,
92
130
  lastUsedAt: k.last_used_at,
@@ -94,18 +132,34 @@ function toKey(k) {
94
132
  customer: k.customer ?? false,
95
133
  };
96
134
  }
97
- // ---- Errors ----------------------------------------------------------------
98
- /** 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
+ */
99
151
  export class ConareError extends Error {
100
152
  status;
101
153
  code;
102
154
  requestId;
103
- constructor(status, code, message, requestId = null) {
155
+ details;
156
+ constructor(status, code, message, requestId = null, details = null) {
104
157
  super(message);
105
158
  this.name = "ConareError";
106
159
  this.status = status;
107
160
  this.code = code;
108
161
  this.requestId = requestId;
162
+ this.details = details;
109
163
  }
110
164
  }
111
165
  /**
@@ -232,13 +286,16 @@ export class Conare {
232
286
  /**
233
287
  * A new organization of your customer, with a customer key: one per company you serve, with its own
234
288
  * namespaces, keys, sources, usage and limits. `externalId` is your own id for it, unique within your
235
- * customer: a create with one already used answers that organization and makes none. Mint the key its
236
- * 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`.
237
292
  */
238
293
  async createOrganization(input, options = {}) {
239
294
  const request = { name: input.name };
240
295
  if (input.externalId !== undefined)
241
296
  request.external_id = input.externalId;
297
+ if (input.spendCapUsd !== undefined)
298
+ request.spend_cap_usd = input.spendCapUsd;
242
299
  const body = await this.request("POST", "/organizations", request, options);
243
300
  return toOrganization(body.organization);
244
301
  }
@@ -252,6 +309,16 @@ export class Conare {
252
309
  const body = await this.request("PATCH", `/organizations/${encodeURIComponent(id)}`, { name }, options);
253
310
  return toOrganization(body.organization);
254
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
+ }
255
322
  /**
256
323
  * Deletes one organization of your customer for good, with a customer key. Delete its namespaces and
257
324
  * sources first (a client whose `organization` is its `id`): until then it answers 409 `conflict`.
@@ -280,17 +347,21 @@ export class Conare {
280
347
  month: body.month,
281
348
  count: body.count,
282
349
  active: body.active,
350
+ capped: body.capped,
283
351
  total: body.total,
284
352
  top10Share: body.top10_share,
285
353
  matched: body.matched,
286
- 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 })),
287
355
  rest: body.rest,
288
356
  };
289
357
  }
290
358
  /**
291
359
  * A key of this client's `organization`, with a customer key: the key a company's traffic runs on,
292
360
  * reaching that organization alone. `namespaces` scopes it (exact names, or prefixes ending in `*`),
293
- * `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.
294
365
  */
295
366
  async createKey(input, options = {}) {
296
367
  const request = { name: input.name };
@@ -298,6 +369,10 @@ export class Conare {
298
369
  request.namespaces = input.namespaces;
299
370
  if (input.modelsOnly)
300
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;
301
376
  if (input.expiresAt !== undefined)
302
377
  request.expires_at = input.expiresAt instanceof Date ? input.expiresAt.toISOString() : input.expiresAt;
303
378
  const body = await this.request("POST", "/keys", request, options);
@@ -316,11 +391,23 @@ export class Conare {
316
391
  const request = { input: Array.isArray(input) ? input : [input], type: options.type ?? "document" };
317
392
  if (options.outputDtype)
318
393
  request.output_dtype = options.outputDtype;
394
+ if (options.tokenEmbeddings)
395
+ request.token_embeddings = true;
319
396
  const body = await this.request("POST", "/embed", request, options);
397
+ const usage = body.usage ? { usage: { embedTokens: body.usage.embed_tokens } } : {};
398
+ if (options.tokenEmbeddings) {
399
+ return {
400
+ embeddings: body.embeddings,
401
+ tokenEmbeddings: body.token_embeddings ?? [],
402
+ tokenDimensions: body.token_dimensions ?? 0,
403
+ denseWeight: body.dense_weight ?? 0,
404
+ ...usage,
405
+ };
406
+ }
320
407
  if (options.outputDtype === "int8") {
321
- 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 };
322
409
  }
323
- return body.embeddings;
410
+ return Object.assign(body.embeddings, usage);
324
411
  }
325
412
  /**
326
413
  * Rerank 1-100 documents against a query, best first. Each document is 1-24,000 characters, the query at
@@ -330,16 +417,29 @@ export class Conare {
330
417
  async rerank(query, documents, options = {}) {
331
418
  const body = await this.request("POST", "/rerank", { query, documents, top_k: options.topK }, options);
332
419
  const results = body.results.map((r) => ({ index: r.index, score: r.score, document: documents[r.index] ?? "" }));
333
- 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 });
334
422
  }
335
423
  /**
336
424
  * Parses a file to Markdown and stores nothing: the same parser, options and result as `uploadFile`.
337
- * `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
338
432
  * reads answers once OCR is done within `wait` seconds (default 60), else `{ id, state: "parsing" }`:
339
433
  * `getParse(id)` answers the result (kept 24 hours). Any API key can parse, a models-only key too.
340
434
  */
341
435
  async parse(file, options = {}) {
342
- 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);
343
443
  const body = await this.request("POST", `/parse?${query}`, file, { timeout: 120_000, ...options });
344
444
  return toParse(body);
345
445
  }
@@ -493,6 +593,8 @@ export class Namespace {
493
593
  async write(documents, options) {
494
594
  const all = Array.isArray(documents) ? documents : [documents];
495
595
  const out = [];
596
+ // Summed over the batches; undefined if any batch answered none (an older server).
597
+ let usage = { documentsWritten: 0, indexTokens: 0 };
496
598
  for (let i = 0; i < all.length; i += BATCH_SIZE) {
497
599
  const batch = all.slice(i, i + BATCH_SIZE);
498
600
  const key = options?.idempotencyKey;
@@ -522,7 +624,12 @@ export class Namespace {
522
624
  }
523
625
  out.push(result);
524
626
  });
627
+ usage = usage && body.usage
628
+ ? { documentsWritten: usage.documentsWritten + body.usage.documents_written, indexTokens: usage.indexTokens + body.usage.index_tokens }
629
+ : undefined;
525
630
  }
631
+ if (usage)
632
+ out.usage = usage;
526
633
  return out;
527
634
  }
528
635
  /**
@@ -541,13 +648,13 @@ export class Namespace {
541
648
  * `withoutText`); before that it is `queued` or `parsing`, and `getFile` follows it.
542
649
  */
543
650
  async uploadFile(file, name, options = {}) {
544
- const query = new URLSearchParams({
651
+ const query = withSheets(new URLSearchParams({
545
652
  name,
546
653
  ...(options.id ? { id: options.id } : {}),
547
654
  ...(options.user ? { user: options.user } : {}),
548
655
  ...(options.metadata ? { metadata: JSON.stringify(options.metadata) } : {}),
549
656
  ...parseQuery(options),
550
- });
657
+ }), options);
551
658
  const waitS = typeof options.wait === "number" ? options.wait : options.wait === false ? 0 : 60;
552
659
  const timeout = Math.max(300_000, waitS * 1000 + 60_000);
553
660
  const body = await this.client.request("POST", this.path(`/files?${query}`), file, { timeout, ...options });
@@ -572,7 +679,54 @@ export class Namespace {
572
679
  */
573
680
  async query(query, options = {}) {
574
681
  const body = await this.client.request("POST", this.path("/query"), queryBody(query, options), options);
575
- 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
+ };
576
730
  }
577
731
  /**
578
732
  * The documents whose text matches a regular expression, or a near spelling (`{ query, max_distance }`),
@@ -588,7 +742,7 @@ export class Namespace {
588
742
  limit: options.limit,
589
743
  cursor: options.cursor,
590
744
  }, options);
591
- 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 } } : {}) };
592
746
  }
593
747
  /**
594
748
  * A deep search, page by page: ranks `maxResults` documents once (at least `topK`; at most 1,000,
@@ -604,12 +758,12 @@ export class Namespace {
604
758
  : await this.client.request("POST", this.path("/query"), { ...queryBody(query, options), max_results: options.maxResults }, options);
605
759
  if (!cursor) {
606
760
  cursor = page.next_cursor ?? null;
607
- yield { results: page.results, nextCursor: cursor, degraded: page.degraded ?? [] };
761
+ yield { results: page.results, nextCursor: cursor, degraded: page.degraded ?? [], ...pageUsage(page) };
608
762
  }
609
763
  while (cursor) {
610
764
  page = await this.client.request("POST", this.path("/query"), { cursor, top_k: options.topK }, options);
611
765
  cursor = page.next_cursor ?? null;
612
- yield { results: page.results, nextCursor: cursor, degraded: page.degraded ?? [] };
766
+ yield { results: page.results, nextCursor: cursor, degraded: page.degraded ?? [], ...pageUsage(page) };
613
767
  }
614
768
  }
615
769
  /** One document by id, or null if it does not exist. */
@@ -624,13 +778,20 @@ export class Namespace {
624
778
  throw err;
625
779
  }
626
780
  }
627
- /** Every document (id, metadata, updatedAt), fetched page by page as you iterate. `limit` is the page size: 1-100, default 50. */
781
+ /**
782
+ * Every document (id, metadata, updatedAt), fetched page by page as you iterate. `limit` is the page size: 1-100, default 50.
783
+ * `order` is `"id"` (the default) or `"newest"`: newest first by the document's date (its `date`, else its `created_at`),
784
+ * else when it was last written. A namespace of more than 10,000 documents that holds documents written before
785
+ * 2026-11-14 and not indexed by date since throws 400 `order_unavailable`: list it by `"id"`.
786
+ */
628
787
  async *list(options = {}) {
629
788
  let cursor = null;
630
789
  do {
631
790
  const params = new URLSearchParams();
632
791
  if (options.limit)
633
792
  params.set("limit", String(options.limit));
793
+ if (options.order)
794
+ params.set("order", options.order);
634
795
  if (cursor)
635
796
  params.set("cursor", cursor);
636
797
  const qs = params.toString();
@@ -641,6 +802,16 @@ export class Namespace {
641
802
  cursor = page.next_cursor;
642
803
  } while (cursor);
643
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
+ }
644
815
  /** Delete one document. Throws a ConareError with status 404 (`document_not_found`) if it does not exist. */
645
816
  async delete(id, options) {
646
817
  await this.client.request("DELETE", this.path(`/documents/${segment(id)}`), undefined, options);
@@ -687,11 +858,12 @@ export class Sources {
687
858
  this.client = client;
688
859
  this.documents = new SourceDocuments(client);
689
860
  }
690
- /**
691
- * Create a custom source: a set of documents you push into `namespace`, keyed by your own ids.
692
- * With `user`, `users.delete(user)` deletes it with the user's documents.
693
- */
694
861
  async create(params, options) {
862
+ if (params.type === "web") {
863
+ const pages = "site" in params ? { site: params.site, max_pages: params.maxPages } : { urls: params.urls };
864
+ const body = await this.client.request("POST", "/sources", { type: "web", namespace: params.namespace, ...pages, name: params.name, sync_interval_s: params.syncIntervalSeconds }, options);
865
+ return toAnySource(body);
866
+ }
695
867
  const body = await this.client.request("POST", "/sources", { type: params.type, namespace: params.namespace, name: params.name, user: params.user }, options);
696
868
  return toCustomSource(body);
697
869
  }
@@ -713,17 +885,83 @@ export class Sources {
713
885
  }, options);
714
886
  return { source: toSource(body.source), connectUrl: body.connect_url ?? null };
715
887
  }
716
- /** Set how often a connected app syncs: seconds from 300 (5 minutes) to 2592000 (30 days), or null for automatic. */
888
+ /**
889
+ * Set how often a source syncs. A connected app: seconds from 300 (5 minutes) to 2592000 (30 days), or null for
890
+ * automatic. A web source (`update<WebSource>`): 3600 to 604800, or null for a day; each website is its own
891
+ * source with its own interval. A Google Cloud Storage source (`update<GCSSource>`): 900 to 604800, or null for
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.
900
+ */
717
901
  async update(id, params, options) {
718
- return toSource(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);
719
946
  }
720
947
  /**
721
- * Every source: the connected apps, then the custom, files and Google Cloud Storage sources, which carry
722
- * 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.
723
953
  */
724
- async list(options) {
725
- const body = await this.client.request("GET", "/sources", undefined, options);
726
- 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
+ };
727
965
  }
728
966
  /** One source by id. */
729
967
  async get(id, options) {
@@ -732,9 +970,9 @@ export class Sources {
732
970
  /**
733
971
  * Start a sync now. `full: true` re-reads everything the app holds instead of what changed: documents
734
972
  * that changed are rewritten and ones Conare no longer keeps are deleted. It is for Gmail and the apps
735
- * 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).
736
974
  *
737
- * A connected app answers the `Source`, due to sync now. A Google Cloud Storage source answers the sync
975
+ * A connected app answers the `Source`, due to sync now. A Google Cloud Storage or web source answers the sync
738
976
  * `Run` it queued (409 `run_active` while one is queued or running). A custom or files source has nothing
739
977
  * to sync: 409 `push_source`. A `Run` has `state` and a `Source` has `status`: `"state" in result` tells
740
978
  * them apart.
@@ -744,15 +982,57 @@ export class Sources {
744
982
  const body = await this.client.request("POST", `/sources/${segment(id)}/sync`, full ? { full: true } : undefined, request);
745
983
  return "run" in body ? toRun(body.run) : toSource(body);
746
984
  }
985
+ /**
986
+ * What a Google Cloud Storage or web source could not keep, in key order: `nextCursor` is the next page's
987
+ * `cursor`, null at the end.
988
+ */
989
+ async failures(id, params = {}, options) {
990
+ const query = [];
991
+ if (params.cursor)
992
+ query.push(`cursor=${encodeURIComponent(params.cursor)}`);
993
+ if (params.limit !== undefined)
994
+ query.push(`limit=${params.limit}`);
995
+ const body = await this.client.request("GET", `/sources/${segment(id)}/failures${query.length ? `?${query.join("&")}` : ""}`, undefined, options);
996
+ return {
997
+ data: body.data.map((f) => ({
998
+ externalId: f.external_id,
999
+ key: f.key,
1000
+ version: f.version,
1001
+ code: f.code,
1002
+ message: f.message,
1003
+ runId: f.run_id,
1004
+ attempts: f.attempts,
1005
+ failedAt: new Date(f.failed_at),
1006
+ })),
1007
+ nextCursor: body.next_cursor,
1008
+ };
1009
+ }
747
1010
  /**
748
1011
  * Disconnect a source. Pass `deleteDocuments: true` to also delete what it synced; without it a
749
- * connected app's and a custom source's documents stay. A Google Cloud Storage source's and a files
750
- * source's documents always go with it. A custom source's delete is a run, which `runs.get` follows
751
- * until the source is `deleted`.
1012
+ * connected app's and a custom source's documents stay. A Google Cloud Storage, web or files
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).
752
1018
  */
753
1019
  async delete(id, options = {}) {
754
- const qs = options.deleteDocuments ? "?delete_documents=true" : "";
755
- 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);
756
1036
  }
757
1037
  /** The apps you can connect. */
758
1038
  async types(options) {
@@ -991,10 +1271,28 @@ export class Events {
991
1271
  };
992
1272
  }
993
1273
  }
994
- /** A source by its `kind`: a connected app has none; a custom, files or Google Cloud Storage 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
+ }
995
1277
  function toAnySource(s) {
996
1278
  if (!("kind" in s))
997
1279
  return toSource(s);
1280
+ if (s.kind === "web") {
1281
+ return {
1282
+ ...toCustomSource(s),
1283
+ kind: "web",
1284
+ type: "web",
1285
+ app: null,
1286
+ user: null,
1287
+ config: {
1288
+ ...(s.config?.urls ? { urls: s.config.urls } : {}),
1289
+ pages: s.config?.pages ?? s.config?.urls?.length ?? 0,
1290
+ syncIntervalSeconds: s.config?.sync_interval_s ?? 0,
1291
+ ...(s.config?.site ? { site: s.config.site, maxPages: s.config.max_pages } : {}),
1292
+ },
1293
+ failures: s.failures ?? 0,
1294
+ };
1295
+ }
998
1296
  if (s.kind === "gcs") {
999
1297
  const c = s.config;
1000
1298
  return {
@@ -1040,6 +1338,7 @@ function toCustomSource(s) {
1040
1338
  },
1041
1339
  documents: s.documents,
1042
1340
  documentsVerifiedAt: date(s.documents_verified_at),
1341
+ ...(s.deletes_at ? { deletesAt: new Date(s.deletes_at) } : {}),
1043
1342
  createdAt: new Date(s.created_at),
1044
1343
  updatedAt: new Date(s.updated_at),
1045
1344
  };
@@ -1216,6 +1515,10 @@ function toSource(s) {
1216
1515
  : null,
1217
1516
  };
1218
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
+ }
1219
1522
  function toError(res, text) {
1220
1523
  const requestId = res.headers.get("x-request-id");
1221
1524
  let error;
@@ -1225,7 +1528,7 @@ function toError(res, text) {
1225
1528
  catch {
1226
1529
  // Not JSON: fall back to the status.
1227
1530
  }
1228
- 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));
1229
1532
  }
1230
1533
  const ID_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1231
1534
  /**