conare 0.20.0 → 0.21.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,7 +1,24 @@
1
1
  // conare: TypeScript client for the Conare API. Zero dependencies; uses global fetch.
2
- export const VERSION = "0.20.0";
2
+ export const VERSION = "0.21.0";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
+ const CHECK_BATCH = 1000;
6
+ function toFileUpload(body) {
7
+ return {
8
+ fileId: body.file_id,
9
+ type: body.type,
10
+ ids: body.ids,
11
+ pages: body.pages ?? null,
12
+ sheets: body.sheets ?? null,
13
+ pagesOcr: body.pages_ocr ?? 0,
14
+ pagesWithoutText: body.pages_without_text ?? [],
15
+ ocrPending: body.ocr_pending ?? [],
16
+ };
17
+ }
18
+ /** The float vectors int8 embeddings stand for: values × scale. */
19
+ export function dequantize(embeddings) {
20
+ return embeddings.values.map((v, i) => Array.from(v, (x) => x * (embeddings.scales[i] ?? 0)));
21
+ }
5
22
  // ---- Errors ----------------------------------------------------------------
6
23
  /** Every failure the SDK throws. `status` is 0 when no response arrived. */
7
24
  export class ConareError extends Error {
@@ -28,6 +45,20 @@ function segment(value) {
28
45
  }
29
46
  return encodeURIComponent(value);
30
47
  }
48
+ /** A query's request body (snake_case). */
49
+ function queryBody(query, options) {
50
+ return {
51
+ query,
52
+ top_k: options.topK,
53
+ filter: options.filter,
54
+ rerank: options.rerank,
55
+ rerank_depth: options.rerankDepth,
56
+ retrievers: options.retrievers,
57
+ user: options.user,
58
+ user_prefix: options.userPrefix,
59
+ exclude_ids: options.excludeIds,
60
+ };
61
+ }
31
62
  // ---- Client ----------------------------------------------------------------
32
63
  /**
33
64
  * The Conare client.
@@ -38,6 +69,16 @@ function segment(value) {
38
69
  export class Conare {
39
70
  baseURL;
40
71
  sources;
72
+ /** Snapshot runs of custom sources, and any run by id. */
73
+ runs;
74
+ /** Files of documents written into a custom source. */
75
+ imports;
76
+ /** Delete everything Conare holds of one of your users. */
77
+ users;
78
+ /** What changed, in order. */
79
+ events;
80
+ /** The organization requests act for (`X-Conare-Org`); undefined: the key's own. */
81
+ organization;
41
82
  apiKey;
42
83
  timeout;
43
84
  maxRetries;
@@ -57,7 +98,12 @@ export class Conare {
57
98
  this.timeout = options.timeout ?? 60_000;
58
99
  this.maxRetries = options.maxRetries ?? 2;
59
100
  this.fetchFn = options.fetch ?? ((url, init) => fetch(url, init));
101
+ this.organization = options.organization || undefined;
60
102
  this.sources = new Sources(this);
103
+ this.runs = new Runs(this);
104
+ this.imports = new Imports(this);
105
+ this.users = new Users(this);
106
+ this.events = new Events(this);
61
107
  }
62
108
  /** A handle to one namespace. Nothing is sent until you call a method; the first write creates it. */
63
109
  namespace(name) {
@@ -65,16 +111,34 @@ export class Conare {
65
111
  }
66
112
  /**
67
113
  * Every namespace in the organization (a scoped key: every one it reaches) with its document
68
- * count; with `prefix`, only those whose name starts with it, e.g. one user's `"u7f3a9c-"`.
114
+ * count and models; with `prefix`, only those whose name starts with it, e.g. one user's `"u7f3a9c-"`.
69
115
  */
70
116
  async namespaces(options = {}) {
71
117
  const path = options.prefix ? `/namespaces?prefix=${encodeURIComponent(options.prefix)}` : "/namespaces";
72
118
  const body = await this.request("GET", path, undefined, options);
73
- return body.namespaces;
119
+ return body.namespaces.map((n) => ({
120
+ name: n.name,
121
+ documents: n.documents,
122
+ embeddingModel: n.embedding_model,
123
+ rerankModel: n.rerank_model,
124
+ }));
125
+ }
126
+ /**
127
+ * The organizations this key acts for, its own first. A multi-organization key lists each other one
128
+ * it still acts for; pass an `id` as the `organization` option of a client to act for it.
129
+ */
130
+ async organizations(options = {}) {
131
+ const body = await this.request("GET", "/organizations", undefined, options);
132
+ return body.organizations;
74
133
  }
75
- /** Embed texts. Use type "query" for search queries and "document" (default) for stored text. */
76
134
  async embed(input, options = {}) {
77
- const body = await this.request("POST", "/embed", { input: Array.isArray(input) ? input : [input], type: options.type ?? "document" }, options);
135
+ const request = { input: Array.isArray(input) ? input : [input], type: options.type ?? "document" };
136
+ if (options.outputDtype)
137
+ request.output_dtype = options.outputDtype;
138
+ const body = await this.request("POST", "/embed", request, options);
139
+ if (options.outputDtype === "int8") {
140
+ return { values: body.embeddings.map((v) => Int8Array.from(v)), scales: body.scales ?? [] };
141
+ }
78
142
  return body.embeddings;
79
143
  }
80
144
  /**
@@ -93,13 +157,13 @@ export class Conare {
93
157
  * the first answer and does nothing again. So every request is retried on 429, 5xx, 409
94
158
  * `idempotency_in_progress` (the first attempt is still running) and network errors.
95
159
  */
96
- async request(method, path, body, options = {}) {
160
+ async request(method, path, body, options = {}, headers = {}) {
97
161
  const key = method === "GET" ? undefined : (options.idempotencyKey ?? newIdempotencyKey());
98
162
  for (let attempt = 0;; attempt++) {
99
163
  let res;
100
164
  let text;
101
165
  try {
102
- [res, text] = await this.send(method, path, body, options, key);
166
+ [res, text] = await this.send(method, path, body, options, key, headers);
103
167
  }
104
168
  catch (err) {
105
169
  if (err instanceof ConareError && attempt < this.maxRetries) {
@@ -126,7 +190,7 @@ export class Conare {
126
190
  }
127
191
  }
128
192
  // One attempt, body included, under the timeout and the caller's signal.
129
- async send(method, path, body, options, idempotencyKey) {
193
+ async send(method, path, body, options, idempotencyKey, extra) {
130
194
  const controller = new AbortController();
131
195
  const timeout = options.timeout ?? this.timeout;
132
196
  const timer = setTimeout(() => controller.abort(), timeout);
@@ -144,6 +208,8 @@ export class Conare {
144
208
  Accept: "application/json",
145
209
  ...(body === undefined ? {} : { "Content-Type": raw ? "application/octet-stream" : "application/json" }),
146
210
  ...(idempotencyKey === undefined ? {} : { "Idempotency-Key": idempotencyKey }),
211
+ ...(this.organization === undefined ? {} : { "X-Conare-Org": this.organization }),
212
+ ...extra,
147
213
  },
148
214
  body: body === undefined ? undefined : raw ? body : JSON.stringify(body),
149
215
  signal: controller.signal,
@@ -177,13 +243,14 @@ export class Namespace {
177
243
  return `/namespaces/${segment(this.name)}${suffix}`;
178
244
  }
179
245
  /**
180
- * Create the namespace before its first write. Only a namespace with a sparse (SPLADE) index
181
- * needs this: a write creates one without. Its index never changes: creating it again with the
182
- * other setting is a 409. Returns whether it has a sparse index.
246
+ * Create the namespace before its first write. Only a namespace embedded by `embeddingModel`
247
+ * (one of your organization's models from `GET /models`) needs this: a write creates one with the
248
+ * default model. Its model never changes: creating it again with another one is a 409. Returns
249
+ * the model that embeds it.
183
250
  */
184
251
  async create(options = {}) {
185
- const body = await this.client.request("POST", "/namespaces", { name: this.name, sparse: options.sparse ?? false }, options);
186
- return { sparse: body.sparse };
252
+ const body = await this.client.request("POST", "/namespaces", { name: this.name, embedding_model: options.embeddingModel }, options);
253
+ return { embeddingModel: body.embedding_model };
187
254
  }
188
255
  /**
189
256
  * Add or replace documents. Accepts one or many; sends them in batches of 100. Returns the ids.
@@ -237,7 +304,9 @@ export class Namespace {
237
304
  * Store a PDF or an Excel workbook (.xlsx), at most 20 MiB: one document per PDF page with a
238
305
  * text layer (`<fileId>:page-3`) and Markdown tables per worksheet (`<fileId>:Sheet1-1`), each
239
306
  * with `file`, `file_id`, `file_type` and `page` or `sheet` metadata. `fileId` defaults to the
240
- * name in id characters; uploading the same one again replaces every document it made. Pages
307
+ * name in id characters (a name with characters outside ASCII also gets 8 hex digits of its hash, so
308
+ * such names do not collide); uploading the same one again replaces every document it made, and two
309
+ * uploads of one id run one at a time. Pages
241
310
  * without a text layer (scans, images) are read by OCR: by default after the answer
242
311
  * (`ocrPending`, stored within about a minute), with `wait: true` before it (`pagesOcr`). Pages
243
312
  * with no text even then are listed in `pagesWithoutText` and not stored.
@@ -249,38 +318,51 @@ export class Namespace {
249
318
  ...(options.wait ? { wait: "true" } : {}),
250
319
  });
251
320
  const body = await this.client.request("POST", this.path(`/files?${query}`), file, { timeout: 120_000, ...options });
252
- return {
253
- fileId: body.file_id,
254
- type: body.type,
255
- ids: body.ids,
256
- pages: body.pages ?? null,
257
- sheets: body.sheets ?? null,
258
- pagesOcr: body.pages_ocr ?? 0,
259
- pagesWithoutText: body.pages_without_text ?? [],
260
- ocrPending: body.ocr_pending ?? [],
261
- };
321
+ return toFileUpload(body);
322
+ }
323
+ /**
324
+ * An upload's outcome: the last upload of `fileId` here in the last 7 days. While OCR reads after the
325
+ * answer, `ocrPending` lists its pages; once it ended, the pages it read are in `ids` and `pagesOcr`, and
326
+ * those it could not read in `pagesWithoutText`. A file id with no upload throws 404 `file_not_found`.
327
+ */
328
+ async getFile(fileId, options) {
329
+ const body = await this.client.request("GET", this.path(`/files/${segment(fileId)}`), undefined, options);
330
+ return { ...toFileUpload(body), name: body.name, uploadedAt: new Date(body.uploaded_at) };
262
331
  }
263
332
  /**
264
- * Hybrid search, reranked. One result per document: its best passage. `retrievers` picks what
265
- * the search fuses (default `["vector", "keyword"]`); `"sparse"` needs a namespace created with
266
- * a sparse index. `rerankDepth` (1-100) has the reranker rank every passage among the first
267
- * that many in windows of 20 passages, then reads the best 20 of them together in one final
268
- * window that sets their order; unset, it reads one window of 20. `user` keeps the search to one user's documents and
269
- * `userPrefix` (ending in `:`) to a group's; both combine with `filter`.
333
+ * Hybrid search, reranked. One result per document: its best passage; `topK` documents when that
334
+ * many match. `retrievers` picks what the search fuses (default `["vector", "keyword"]`; listed
335
+ * retrievers run as listed, also on a vector-only custom model). `rerankDepth` (1-500) is how many of the
336
+ * first passages the reranker ranks; unset, the first 20. `user` keeps the search to one user's documents and
337
+ * `userPrefix` (ending in `:`) to a group's; both combine with `filter`. An empty `user` or
338
+ * `userPrefix` is a 400, never "every user". `excludeIds` keeps those documents out.
270
339
  */
271
340
  async query(query, options = {}) {
272
- const body = await this.client.request("POST", this.path("/query"), {
273
- query,
274
- top_k: options.topK,
275
- filter: options.filter,
276
- rerank: options.rerank,
277
- rerank_depth: options.rerankDepth,
278
- retrievers: options.retrievers,
279
- user: options.user,
280
- user_prefix: options.userPrefix,
281
- }, options);
341
+ const body = await this.client.request("POST", this.path("/query"), queryBody(query, options), options);
282
342
  return body.results;
283
343
  }
344
+ /**
345
+ * A deep search, page by page: ranks `maxResults` documents once (at least `topK`; at most 1,000,
346
+ * or 5,000 on a custom model's engine) and yields them `topK` at a time. Later pages are read from
347
+ * that ranking (kept 15 minutes) without searching again, so they never repeat or skip a
348
+ * document; past `rerankDepth` results keep retrieval order (`reranked: false`). Pass a page's
349
+ * `nextCursor` as `cursor` to go on from it in another call (`query` is then ignored).
350
+ */
351
+ async *queryPages(query, options) {
352
+ let cursor = options.cursor ?? null;
353
+ let page = cursor
354
+ ? { results: [], next_cursor: cursor }
355
+ : await this.client.request("POST", this.path("/query"), { ...queryBody(query, options), max_results: options.maxResults }, options);
356
+ if (!cursor) {
357
+ cursor = page.next_cursor ?? null;
358
+ yield { results: page.results, nextCursor: cursor };
359
+ }
360
+ while (cursor) {
361
+ page = await this.client.request("POST", this.path("/query"), { cursor, top_k: options.topK }, options);
362
+ cursor = page.next_cursor ?? null;
363
+ yield { results: page.results, nextCursor: cursor };
364
+ }
365
+ }
284
366
  /** One document by id, or null if it does not exist. */
285
367
  async get(id, options) {
286
368
  try {
@@ -314,7 +396,10 @@ export class Namespace {
314
396
  async delete(id, options) {
315
397
  await this.client.request("DELETE", this.path(`/documents/${segment(id)}`), undefined, options);
316
398
  }
317
- /** Delete up to 1000 documents by id in one call. Ids that do not exist are skipped. Returns how many were deleted. */
399
+ /**
400
+ * Delete up to 1000 documents by id in one call. Ids that do not exist are skipped; a namespace that
401
+ * does not exist throws ConareError 404 `namespace_not_found`. Returns how many were deleted.
402
+ */
318
403
  async deleteMany(ids, options) {
319
404
  const out = await this.client.request("POST", this.path("/documents/delete"), { ids }, options);
320
405
  return out.deleted;
@@ -337,34 +422,67 @@ export class Namespace {
337
422
  }
338
423
  }
339
424
  // ---- Sources ---------------------------------------------------------------
340
- /** Apps connected through Conare that keep syncing into a namespace. */
425
+ /** Apps connected through Conare that keep syncing into a namespace, and custom sources you push to. */
341
426
  export class Sources {
342
427
  client;
428
+ /** The documents of a custom source. */
429
+ documents;
343
430
  constructor(client) {
344
431
  this.client = client;
432
+ this.documents = new SourceDocuments(client);
433
+ }
434
+ /**
435
+ * Create a custom source: a set of documents you push into `namespace`, keyed by your own ids.
436
+ * With `user`, `users.delete(user)` deletes it with the user's documents.
437
+ */
438
+ async create(params, options) {
439
+ const body = await this.client.request("POST", "/sources", { type: params.type, namespace: params.namespace, name: params.name, user: params.user }, options);
440
+ return toCustomSource(body);
345
441
  }
346
442
  /**
347
443
  * Start connecting an app. Send the app owner to `connectUrl`; they come back to `redirectUrl`.
348
444
  * For your own users, connect each one into their own namespace, e.g. "user-42".
445
+ * Twenty and Granola (`auth: "apiKey"` in `types()`) take `config` instead: `apiKey`, and for
446
+ * Twenty `baseUrl` when self-hosted. Conare checks the key, the source starts syncing at once,
447
+ * and `connectUrl` is null.
349
448
  */
350
449
  async connect(params, options) {
351
- const body = await this.client.request("POST", "/sources", { type: params.type, namespace: params.namespace, name: params.name, redirect_url: params.redirectUrl }, options);
352
- return { source: toSource(body.source), connectUrl: body.connect_url };
450
+ const body = await this.client.request("POST", "/sources", {
451
+ type: params.type,
452
+ namespace: params.namespace,
453
+ name: params.name,
454
+ redirect_url: params.redirectUrl,
455
+ sync_interval_s: params.syncIntervalSeconds,
456
+ config: params.config && { base_url: params.config.baseUrl, api_key: params.config.apiKey },
457
+ }, options);
458
+ return { source: toSource(body.source), connectUrl: body.connect_url ?? null };
353
459
  }
354
- /** Every connected source. */
460
+ /** Set how often a source syncs: seconds from 300 (5 minutes) to 2592000 (30 days), or null for automatic. */
461
+ async update(id, params, options) {
462
+ return toSource(await this.client.request("PATCH", `/sources/${segment(id)}`, { sync_interval_s: params.syncIntervalSeconds }, options));
463
+ }
464
+ /** Every source: the connected apps, then the custom sources (`kind: "custom"`). */
355
465
  async list(options) {
356
466
  const body = await this.client.request("GET", "/sources", undefined, options);
357
- return body.sources.map(toSource);
467
+ return body.sources.map(toAnySource);
358
468
  }
359
469
  /** One source by id. */
360
470
  async get(id, options) {
361
- return toSource(await this.client.request("GET", `/sources/${segment(id)}`, undefined, options));
471
+ return toAnySource(await this.client.request("GET", `/sources/${segment(id)}`, undefined, options));
362
472
  }
363
- /** Start a sync now. */
364
- async sync(id, options) {
365
- return toSource(await this.client.request("POST", `/sources/${segment(id)}/sync`, undefined, options));
473
+ /**
474
+ * Start a sync now. `full: true` re-reads everything the app holds instead of what changed: documents
475
+ * that changed are rewritten and ones Conare no longer keeps are deleted. It is for Gmail and the apps
476
+ * Conare reads itself (other apps answer 400), and Gmail's rows are billed again (`cost.usdPerMillionRows`).
477
+ */
478
+ async sync(id, options = {}) {
479
+ const { full, ...request } = options;
480
+ return toSource(await this.client.request("POST", `/sources/${segment(id)}/sync`, full ? { full: true } : undefined, request));
366
481
  }
367
- /** Disconnect a source. Pass `deleteDocuments: true` to also delete what it synced. */
482
+ /**
483
+ * Disconnect a source. Pass `deleteDocuments: true` to also delete what it synced. A custom
484
+ * source's documents are deleted by a run, which `runs.get` follows until the source is `deleted`.
485
+ */
368
486
  async delete(id, options = {}) {
369
487
  const qs = options.deleteDocuments ? "?delete_documents=true" : "";
370
488
  await this.client.request("DELETE", `/sources/${segment(id)}${qs}`, undefined, options);
@@ -372,9 +490,376 @@ export class Sources {
372
490
  /** The apps you can connect. */
373
491
  async types(options) {
374
492
  const body = await this.client.request("GET", "/sources/types", undefined, options);
375
- return body.types.map((t) => ({ type: t.type, name: t.name, logoUrl: t.logo_url }));
493
+ return body.types.map((t) => ({
494
+ type: t.type,
495
+ name: t.name,
496
+ logoUrl: t.logo_url,
497
+ ...(t.auth === "api_key" ? { auth: "apiKey" } : {}),
498
+ }));
499
+ }
500
+ }
501
+ // ---- Custom sources --------------------------------------------------------
502
+ /** The documents of a custom source, by source id. */
503
+ export class SourceDocuments {
504
+ client;
505
+ constructor(client) {
506
+ this.client = client;
507
+ }
508
+ /**
509
+ * Push documents (sent 100 at a time): what each write did, in order, once it is stored. Pushes
510
+ * of one source may run concurrently. With `runId`, they belong to that snapshot run.
511
+ */
512
+ async put(sourceId, documents, options = {}) {
513
+ const all = Array.isArray(documents) ? documents : [documents];
514
+ const out = [];
515
+ for (let i = 0; i < all.length; i += BATCH_SIZE) {
516
+ const body = await this.client.request("PUT", `/sources/${segment(sourceId)}/documents`, { run_id: options.runId, documents: all.slice(i, i + BATCH_SIZE).map(toWireCustomDocument) }, options);
517
+ out.push(...body.results.map(toPushResult));
518
+ }
519
+ return out;
520
+ }
521
+ /**
522
+ * Which documents need a push: `need` are those the source does not hold with that `tag`,
523
+ * `excluded` those deleted with `exclude`. With `runId`, each one counts as seen by the run.
524
+ */
525
+ async check(sourceId, documents, options = {}) {
526
+ const out = { need: [], excluded: [] };
527
+ for (let i = 0; i < documents.length; i += CHECK_BATCH) {
528
+ const body = await this.client.request("POST", `/sources/${segment(sourceId)}/documents/check`, { run_id: options.runId, documents: documents.slice(i, i + CHECK_BATCH).map((d) => ({ external_id: d.externalId, tag: d.tag })) }, { ...options, idempotencyKey: stepKey(options.idempotencyKey, i / CHECK_BATCH) });
529
+ out.need.push(...body.need);
530
+ out.excluded.push(...body.excluded);
531
+ }
532
+ return out;
533
+ }
534
+ /** Every document of the source in key order, page by page. `limit` is the page size: 1-100, default 50. */
535
+ async *list(sourceId, options = {}) {
536
+ let cursor = null;
537
+ do {
538
+ const params = new URLSearchParams();
539
+ if (options.limit)
540
+ params.set("limit", String(options.limit));
541
+ if (cursor)
542
+ params.set("cursor", cursor);
543
+ const qs = params.toString();
544
+ const page = await this.client.request("GET", `/sources/${segment(sourceId)}/documents${qs ? `?${qs}` : ""}`, undefined, options);
545
+ yield* page.data.map(toCustomDocument);
546
+ cursor = page.next_cursor;
547
+ } while (cursor);
548
+ }
549
+ /** One document with its text and metadata, by its `key` (or an external id that is its own key), or null. */
550
+ async get(sourceId, key, options) {
551
+ try {
552
+ return toCustomDocument(await this.client.request("GET", `/sources/${segment(sourceId)}/documents/${segment(key)}`, undefined, options));
553
+ }
554
+ catch (err) {
555
+ if (err instanceof ConareError && err.status === 404 && err.code === "document_not_found")
556
+ return null;
557
+ throw err;
558
+ }
559
+ }
560
+ /**
561
+ * Delete documents by external id (1,000 a call). A tombstone at `seq` makes older pushes of each
562
+ * `stale` (one already writing too); one holding a higher `seq` is `kept`; `exclude` keeps it out until
563
+ * restored.
564
+ */
565
+ async delete(sourceId, externalIds, options = {}) {
566
+ const out = { deleted: 0, kept: 0, excluded: 0 };
567
+ for (let i = 0; i < externalIds.length; i += CHECK_BATCH) {
568
+ const body = await this.client.request("POST", `/sources/${segment(sourceId)}/documents/delete`, { external_ids: externalIds.slice(i, i + CHECK_BATCH), exclude: options.exclude, seq: options.seq }, { ...options, idempotencyKey: stepKey(options.idempotencyKey, i / CHECK_BATCH) });
569
+ out.deleted += body.deleted;
570
+ out.kept += body.kept;
571
+ out.excluded += body.excluded;
572
+ }
573
+ return out;
574
+ }
575
+ /** Let excluded documents be pushed again. Returns how many were excluded. */
576
+ async restore(sourceId, externalIds, options) {
577
+ let restored = 0;
578
+ for (let i = 0; i < externalIds.length; i += CHECK_BATCH) {
579
+ const body = await this.client.request("POST", `/sources/${segment(sourceId)}/documents/restore`, { external_ids: externalIds.slice(i, i + CHECK_BATCH) }, { ...options, idempotencyKey: stepKey(options?.idempotencyKey, i / CHECK_BATCH) });
580
+ restored += body.restored;
581
+ }
582
+ return restored;
376
583
  }
377
584
  }
585
+ /**
586
+ * An open snapshot run: push or check the source's whole set through it, then complete it. The
587
+ * documents it never saw are deleted, unless that is over 10% (and over 1,000) at once: then the run
588
+ * is `held` until a second run at least 24 h later agrees.
589
+ */
590
+ export class SnapshotRun {
591
+ client;
592
+ sourceId;
593
+ run;
594
+ constructor(client, sourceId, run) {
595
+ this.client = client;
596
+ this.sourceId = sourceId;
597
+ this.run = run;
598
+ }
599
+ get id() {
600
+ return this.run.id;
601
+ }
602
+ put(documents, options = {}) {
603
+ return this.client.sources.documents.put(this.sourceId, documents, { ...options, runId: this.run.id });
604
+ }
605
+ check(documents, options = {}) {
606
+ return this.client.sources.documents.check(this.sourceId, documents, { ...options, runId: this.run.id });
607
+ }
608
+ /**
609
+ * Stop taking pushes and sweep. Waits up to `wait` seconds (default 100) for the run to finish,
610
+ * then follows it until it did (`runs.get`); `allowMassDelete` applies a sweep of any size.
611
+ */
612
+ async complete(options = {}) {
613
+ const wait = options.wait ?? 100;
614
+ const body = await this.client.request("POST", `/runs/${segment(this.run.id)}/complete?wait=${wait}`, { allow_mass_delete: options.allowMassDelete }, { timeout: (wait + 30) * 1000, ...options });
615
+ let run = toRun(body.run);
616
+ while (!run.finishedAt) {
617
+ await sleep(options.poll ?? 5_000, options.signal);
618
+ run = await this.client.runs.get(run.id, options);
619
+ }
620
+ return run;
621
+ }
622
+ }
623
+ export class Runs {
624
+ client;
625
+ constructor(client) {
626
+ this.client = client;
627
+ }
628
+ /**
629
+ * Open a snapshot run of a custom source (one active run at a time). `expected`, your count of
630
+ * the set, blocks the sweep of a run that saw under 90% of it; a run with no push for
631
+ * `idleTimeoutS` (60-86,400, default 3,600) is canceled.
632
+ */
633
+ async open(sourceId, params = {}, options) {
634
+ const body = await this.client.request("POST", `/sources/${segment(sourceId)}/runs`, { mode: "snapshot", expected: params.expected, idle_timeout_s: params.idleTimeoutS }, options);
635
+ return new SnapshotRun(this.client, sourceId, toRun(body));
636
+ }
637
+ async get(id, options) {
638
+ return toRun(await this.client.request("GET", `/runs/${segment(id)}`, undefined, options));
639
+ }
640
+ }
641
+ export class Imports {
642
+ client;
643
+ constructor(client) {
644
+ this.client = client;
645
+ }
646
+ /**
647
+ * Write a file of JSON lines (one `CustomDocumentInput` a line, snake_case, up to 1 GiB) into a
648
+ * custom source: it is uploaded in parts, each checked by its MD5, then imported by a run, which
649
+ * `runs.get` follows. `snapshot` also deletes what the file does not hold.
650
+ */
651
+ async create(sourceId, file, params = {}, options = {}) {
652
+ const bytes = typeof file === "string"
653
+ ? new TextEncoder().encode(file)
654
+ : file instanceof Uint8Array
655
+ ? file
656
+ : file instanceof ArrayBuffer
657
+ ? new Uint8Array(file)
658
+ : new Uint8Array(await file.arrayBuffer());
659
+ const upload = await this.client.request("POST", "/uploads", { bytes: bytes.length, filename: params.filename }, options);
660
+ // Each step is its own request: with the caller's key, its own key derived from it.
661
+ const key = options.idempotencyKey;
662
+ for (let n = 1; n <= upload.parts; n++) {
663
+ const part = bytes.subarray((n - 1) * upload.part_size, n * upload.part_size);
664
+ await this.client.request("PUT", `/uploads/${segment(upload.id)}/parts/${n}`, part, { timeout: 300_000, ...options, idempotencyKey: stepKey(key, `part-${n}`) }, { "Content-MD5": base64(md5(part)) });
665
+ }
666
+ await this.client.request("POST", `/uploads/${segment(upload.id)}/complete`, { purpose: "import" }, { ...options, idempotencyKey: stepKey(key, "complete") });
667
+ const body = await this.client.request("POST", `/sources/${segment(sourceId)}/imports`, { upload: upload.id, mode: params.mode ?? "delta", expected: params.expected, allow_mass_delete: params.allowMassDelete }, { ...options, idempotencyKey: stepKey(key, "import") });
668
+ return toRun(body.run);
669
+ }
670
+ }
671
+ export class Users {
672
+ client;
673
+ constructor(client) {
674
+ this.client = client;
675
+ }
676
+ /**
677
+ * Delete everything Conare holds of a user: their documents in every namespace and their
678
+ * sources. A purge run does it (writes for the user are refused meanwhile); it finishes once a
679
+ * second check 10 minutes after the first finds nothing. Asking again returns the same run.
680
+ */
681
+ async delete(user, options) {
682
+ const body = await this.client.request("DELETE", `/users/${segment(user)}`, undefined, options);
683
+ return toRun(body.run);
684
+ }
685
+ /** `delete` for every user starting with `prefix` (at least 3 characters, ending in `:`). */
686
+ async deletePrefix(prefix, options) {
687
+ const body = await this.client.request("DELETE", `/users?prefix=${encodeURIComponent(prefix)}`, undefined, options);
688
+ return toRun(body.run);
689
+ }
690
+ }
691
+ export class Events {
692
+ client;
693
+ constructor(client) {
694
+ this.client = client;
695
+ }
696
+ /**
697
+ * The events after `cursor`, oldest first (100 by default, at most 1,000): `seq` counts up by one
698
+ * with no gap, so pass `nextCursor` as the next `cursor`. `types` takes groups such as `"run.*"`.
699
+ */
700
+ async list(params = {}, options) {
701
+ const q = new URLSearchParams();
702
+ if (params.cursor)
703
+ q.set("cursor", params.cursor);
704
+ if (params.types?.length)
705
+ q.set("types", params.types.join(","));
706
+ if (params.userPrefix)
707
+ q.set("user_prefix", params.userPrefix);
708
+ if (params.limit)
709
+ q.set("limit", String(params.limit));
710
+ const qs = q.toString();
711
+ const body = await this.client.request("GET", `/events${qs ? `?${qs}` : ""}`, undefined, options);
712
+ return {
713
+ data: body.data.map((e) => ({
714
+ id: e.id,
715
+ seq: e.seq,
716
+ type: e.type,
717
+ sourceId: e.source_id,
718
+ runId: e.run_id,
719
+ user: e.user,
720
+ data: e.data,
721
+ createdAt: new Date(e.created_at),
722
+ })),
723
+ nextCursor: body.next_cursor,
724
+ };
725
+ }
726
+ }
727
+ function toAnySource(s) {
728
+ return s.type === "custom" ? toCustomSource(s) : toSource(s);
729
+ }
730
+ function toCustomSource(s) {
731
+ return {
732
+ id: s.id,
733
+ kind: "custom",
734
+ type: "custom",
735
+ namespace: s.namespace,
736
+ user: s.user,
737
+ name: s.name,
738
+ status: s.status,
739
+ health: s.health,
740
+ display: s.display,
741
+ sync: { state: s.sync.state, runId: s.sync.run_id, phase: s.sync.phase },
742
+ documents: s.documents,
743
+ documentsVerifiedAt: s.documents_verified_at ? new Date(s.documents_verified_at) : null,
744
+ createdAt: new Date(s.created_at),
745
+ updatedAt: new Date(s.updated_at),
746
+ };
747
+ }
748
+ function toWireCustomDocument(d) {
749
+ return {
750
+ external_id: d.externalId,
751
+ text: d.text,
752
+ title: d.title,
753
+ url: d.url,
754
+ event_at: d.eventAt,
755
+ metadata: d.metadata,
756
+ user: d.user,
757
+ seq: d.seq,
758
+ tag: d.tag,
759
+ deleted: d.deleted,
760
+ };
761
+ }
762
+ function toPushResult(r) {
763
+ const out = { externalId: r.external_id, key: r.key, result: r.result };
764
+ if (r.code !== undefined)
765
+ out.code = r.code;
766
+ if (r.message !== undefined)
767
+ out.message = r.message;
768
+ if (r.stored_seq !== undefined)
769
+ out.storedSeq = r.stored_seq;
770
+ if (r.version !== undefined)
771
+ out.version = r.version;
772
+ if (r.chunks !== undefined)
773
+ out.chunks = r.chunks;
774
+ if (r.chunks_embedded !== undefined)
775
+ out.chunksEmbedded = r.chunks_embedded;
776
+ return out;
777
+ }
778
+ function toCustomDocument(d) {
779
+ const out = {
780
+ externalId: d.external_id,
781
+ key: d.key,
782
+ tag: d.tag,
783
+ seq: d.seq,
784
+ user: d.user,
785
+ version: d.version,
786
+ updatedAt: d.updated_at ? new Date(d.updated_at) : null,
787
+ };
788
+ if (d.text !== undefined)
789
+ out.text = d.text;
790
+ if (d.metadata !== undefined)
791
+ out.metadata = d.metadata;
792
+ return out;
793
+ }
794
+ function toRun(r) {
795
+ return {
796
+ id: r.id,
797
+ sourceId: r.source_id,
798
+ kind: r.kind,
799
+ state: r.state,
800
+ phase: r.phase,
801
+ attempt: r.attempt ?? 0,
802
+ sweep: r.sweep,
803
+ sweepReason: r.sweep_reason,
804
+ expected: r.expected,
805
+ counts: r.counts ?? {},
806
+ error: r.error,
807
+ progress: r.progress
808
+ ? { done: r.progress.done, expected: r.progress.expected, ratePerS: r.progress.rate_per_s, etaS: r.progress.eta_s }
809
+ : null,
810
+ createdAt: new Date(r.created_at),
811
+ startedAt: r.started_at ? new Date(r.started_at) : null,
812
+ finishedAt: r.finished_at ? new Date(r.finished_at) : null,
813
+ };
814
+ }
815
+ /** A random Idempotency-Key for one call (kept across its retries). */
816
+ function base64(bytes) {
817
+ let bin = "";
818
+ for (const b of bytes)
819
+ bin += String.fromCharCode(b);
820
+ return btoa(bin);
821
+ }
822
+ // MD5 (RFC 1321), for an upload part's Content-MD5: WebCrypto has no MD5, and the SDK imports nothing.
823
+ const MD5_S = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
824
+ const MD5_K = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0);
825
+ function md5(data) {
826
+ const padded = new Uint8Array(((data.length + 8) >> 6) * 64 + 64);
827
+ padded.set(data);
828
+ padded[data.length] = 0x80;
829
+ const view = new DataView(padded.buffer);
830
+ view.setUint32(padded.length - 8, (data.length * 8) >>> 0, true);
831
+ view.setUint32(padded.length - 4, Math.floor(data.length / 2 ** 29), true);
832
+ let a0 = 0x67452301, b0 = 0xefcdab89, c0 = 0x98badcfe, d0 = 0x10325476;
833
+ const m = new Uint32Array(16);
834
+ for (let off = 0; off < padded.length; off += 64) {
835
+ for (let j = 0; j < 16; j++)
836
+ m[j] = view.getUint32(off + j * 4, true);
837
+ let a = a0, b = b0, c = c0, d = d0;
838
+ for (let i = 0; i < 64; i++) {
839
+ let f, g;
840
+ if (i < 16)
841
+ [f, g] = [(b & c) | (~b & d), i];
842
+ else if (i < 32)
843
+ [f, g] = [(d & b) | (~d & c), (5 * i + 1) % 16];
844
+ else if (i < 48)
845
+ [f, g] = [b ^ c ^ d, (3 * i + 5) % 16];
846
+ else
847
+ [f, g] = [c ^ (b | ~d), (7 * i) % 16];
848
+ const sum = (a + f + MD5_K[i] + m[g]) >>> 0;
849
+ const shift = MD5_S[(i >> 4) * 4 + (i % 4)];
850
+ [a, d, c] = [d, c, b];
851
+ b = (b + ((sum << shift) | (sum >>> (32 - shift)))) >>> 0;
852
+ }
853
+ a0 = (a0 + a) >>> 0;
854
+ b0 = (b0 + b) >>> 0;
855
+ c0 = (c0 + c) >>> 0;
856
+ d0 = (d0 + d) >>> 0;
857
+ }
858
+ const out = new Uint8Array(16);
859
+ const ov = new DataView(out.buffer);
860
+ [a0, b0, c0, d0].forEach((w, i) => ov.setUint32(i * 4, w, true));
861
+ return out;
862
+ }
378
863
  function toSource(s) {
379
864
  return {
380
865
  id: s.id,
@@ -387,6 +872,26 @@ function toSource(s) {
387
872
  lastSyncedAt: s.last_synced_at ? new Date(s.last_synced_at) : null,
388
873
  createdAt: new Date(s.created_at),
389
874
  ...(s.progress ? { recordsPulled: s.progress.records_pulled } : {}),
875
+ syncIntervalSeconds: s.sync_interval_s ?? null,
876
+ syncIntervalAuto: s.sync_interval_auto ?? true,
877
+ nextSyncAt: s.next_sync_at ? new Date(s.next_sync_at) : null,
878
+ ...(s.resync ? { resyncNote: s.resync.message } : {}),
879
+ cost: s.cost
880
+ ? {
881
+ rowsPerRun: s.cost.rows_per_run,
882
+ windowSeconds: s.cost.window_s,
883
+ reads: s.cost.reads,
884
+ autoIntervalSeconds: s.cost.auto_interval_s,
885
+ usdPerMillionRows: s.cost.usd_per_million_rows,
886
+ options: s.cost.options.map((o) => ({
887
+ intervalSeconds: o.interval_s,
888
+ auto: o.auto,
889
+ rowsMonth: o.rows_month,
890
+ usdMonth: o.usd_month,
891
+ })),
892
+ rowsBilled: s.cost.rows_billed,
893
+ }
894
+ : null,
390
895
  };
391
896
  }
392
897
  function toError(res, text) {
@@ -401,6 +906,14 @@ function toError(res, text) {
401
906
  return new ConareError(res.status, error?.code ?? `http_${res.status}`, error?.message ?? (res.statusText || `HTTP ${res.status}`), error?.request_id ?? requestId);
402
907
  }
403
908
  const ID_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
909
+ /**
910
+ * The Idempotency-Key of step `step` of a call that sends several requests, from the caller's
911
+ * `key`: the key itself for the first (0), `<key>:<step>` after; none when the caller gave none
912
+ * (each request then makes its own).
913
+ */
914
+ function stepKey(key, step) {
915
+ return key && step !== 0 ? `${key}:${step}` : key;
916
+ }
404
917
  /** "idk_" and 32 random hex characters: one write call's Idempotency-Key. */
405
918
  function newIdempotencyKey() {
406
919
  const bytes = new Uint8Array(16);