conare 0.17.0 → 0.19.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/README.md CHANGED
@@ -44,15 +44,20 @@ await docs.add({ id, text, metadata }); // one document
44
44
  await docs.add([...]); // or many; sent 100 at a time. Returns the ids.
45
45
  await docs.write({ id, text, ifVersion: 7 }); // add, only if the document is at version 7 (0: only if
46
46
  // it does not exist), else 409 version_conflict.
47
- // Returns [{ id, version }]
48
- await docs.get("refunds"); // { id, text, metadata, updatedAt, version } or null
47
+ // Returns [{ id, version, result, chunks, chunksEmbedded }]:
48
+ // result "unchanged" when Conare already held it as sent
49
+ await docs.add({ id, text, user: "tenant-7:u_42", seq: 1759698843000 }); // a user's document; a lower seq
50
+ // than stored is "stale" and writes nothing
51
+ await docs.query("refunds", { userPrefix: "tenant-7:" }); // one user's documents (user) or a group's (userPrefix)
52
+ await docs.get("refunds"); // { id, text, metadata, updatedAt, version, user?, seq? } or null
49
53
  for await (const doc of docs.list()) {} // every document, page by page ({ limit } per page: 1-100, default 50)
50
54
  await docs.delete("refunds"); // 404 document_not_found if it does not exist
51
55
  await docs.deleteMany(["a", "b"]); // up to 1000 ids in one call; missing ids are skipped. Returns the count
52
56
  await docs.deleteWhere({ team: "support" }); // every document matching the filter, whole documents. Returns the count
53
57
  await docs.uploadFile(bytes, "report.pdf"); // a PDF (one document per page) or an .xlsx (Markdown tables per sheet),
54
58
  // up to 20 MiB. The same name (or { id }) again replaces it.
55
- // Returns { fileId, type, ids, pages, sheets, pagesWithoutText }
59
+ // Returns { fileId, type, ids, pages, sheets, pagesOcr, pagesWithoutText, ocrPending }:
60
+ // scanned pages are OCR'd after the answer (ocrPending; { wait: true } reads them first)
56
61
  await docs.drop(); // delete the namespace and its documents (succeeds if already emptied; 404 namespace_not_found if never written)
57
62
  await docs.create({ sparse: true }); // create it with a sparse (SPLADE) index, before its first write
58
63
 
@@ -107,7 +112,7 @@ await conare.rerank("refund window", ["a", "b"], { topK: 1 }); // [{ index, sc
107
112
 
108
113
  `rerank` takes 1-100 documents of 1-24,000 characters each (the query at most 8,192 characters, all
109
114
  together at most 256,000); more than 100 is a 400 `invalid_request`. More than 20 go through a
110
- tournament of 20-document windows that settles the exact order of the best `topK` (at most 20). A
115
+ tournament: windows of 20 documents, then one final window that reads the best 20 together and sets their order. A
111
116
  document no window read before the one-second budget ended, or whose window failed, is listed by
112
117
  index in `.unscored` and is not in the results; its score from another call would not compare.
113
118
 
@@ -137,9 +142,11 @@ await conare.sources.delete(source.id, { deleteDocuments: true });
137
142
 
138
143
  Every failure is a `ConareError` with `status`, `code`, `message` and `requestId`
139
144
  (`status` is 0 when no response arrived: `timeout`, `connection_error`). 429, 5xx and network
140
- errors are retried twice with backoff, honouring `Retry-After`. `sources.connect()` is retried only
141
- on 429 and 503, and `add()` gives every document without an id one of its own first, so a retry
142
- never creates anything twice.
145
+ errors are retried twice with backoff, honouring `Retry-After`. Every write carries an
146
+ `Idempotency-Key`, the same on each of its retries: the API answers a retry with the first answer
147
+ and does nothing again, so a retry never creates anything twice and a conditional write's retry is
148
+ not a `version_conflict`. Pass `{ idempotencyKey }` to make a call you repeat later (a restarted
149
+ job) the same call; within 24 hours its repeat gets the first answer.
143
150
 
144
151
  ```ts
145
152
  import { ConareError } from "conare";
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.17.0";
1
+ export declare const VERSION = "0.19.0";
2
2
  /** A metadata value: string, number, boolean or an array of strings. */
3
3
  export type MetadataValue = string | number | boolean | string[];
4
4
  export type Metadata = Record<string, MetadataValue>;
@@ -39,6 +39,35 @@ export interface DocumentInput {
39
39
  * ConareError 409 `version_conflict`. Checked atomically with the write.
40
40
  */
41
41
  ifVersion?: number;
42
+ /**
43
+ * Who the document belongs to: 1-128 characters of [A-Za-z0-9._:@-], starting with a letter or
44
+ * digit, at most 8 `:`. Group users with `:` (`tenant-7:u_42`) and query a group with `userPrefix`.
45
+ */
46
+ user?: string;
47
+ /**
48
+ * Your sequence number for the document (a source timestamp, a byte length), 0 to 2^53. A write
49
+ * with a lower `seq` than stored is `stale` and writes nothing. Without it, the last write wins and
50
+ * the stored `seq` stays.
51
+ */
52
+ seq?: number;
53
+ }
54
+ /** What a write did with one document. */
55
+ export type WriteOutcome = "created" | "updated" | "unchanged" | "stale";
56
+ export interface WriteResult {
57
+ id: string;
58
+ /** The document's version after the write; null when the server did not answer one. */
59
+ version: number | null;
60
+ /**
61
+ * `unchanged`: Conare already held the document as sent, so nothing was embedded or written and
62
+ * its version stayed, unless the write raised `seq` (stored with a new version: always keep
63
+ * `version`). `stale`: it holds a higher `seq` (`storedSeq`); nothing was written.
64
+ * Absent from a server older than results.
65
+ */
66
+ result?: WriteOutcome;
67
+ /** The document's passages, and those this write embedded (only changed ones are). */
68
+ chunks?: number;
69
+ chunksEmbedded?: number;
70
+ storedSeq?: number;
42
71
  }
43
72
  /** What `uploadFile` stored. */
44
73
  export interface FileUpload {
@@ -50,24 +79,33 @@ export interface FileUpload {
50
79
  pages: number | null;
51
80
  /** A workbook's sheets (null for a PDF). */
52
81
  sheets: number | null;
53
- /** PDF pages read by OCR because they had no text layer (scans, images); stored like the rest. */
82
+ /** PDF pages read by OCR before the answer (`wait: true`); stored like the rest. */
54
83
  pagesOcr: number;
55
84
  /** PDF pages with no text even after OCR (blank, or OCR could not read them): not stored. */
56
85
  pagesWithoutText: number[];
86
+ /** PDF pages OCR reads after the answer (without `wait`): each is stored, marked `ocr`, within about a minute. */
87
+ ocrPending: number[];
57
88
  }
58
89
  export interface Document {
59
90
  id: string;
60
91
  text: string;
61
92
  metadata: Metadata;
62
93
  updatedAt: Date;
63
- /** Changes on every write of the document and only grows: pass it as `ifVersion`. */
94
+ /**
95
+ * Changes when a write stores something new and only grows (an `unchanged` write keeps it unless
96
+ * it raises `seq`): pass it as `ifVersion`.
97
+ */
64
98
  version: number;
99
+ user?: string;
100
+ seq?: number;
65
101
  }
66
102
  export interface DocumentSummary {
67
103
  id: string;
68
104
  metadata: Metadata;
69
105
  updatedAt: Date;
70
106
  version: number;
107
+ user?: string;
108
+ seq?: number;
71
109
  }
72
110
  export interface QueryResult {
73
111
  id: string;
@@ -78,6 +116,8 @@ export interface QueryResult {
78
116
  /** The reranking model scored this result (false past its window, with `rerank: false`, or when it failed). */
79
117
  reranked: boolean;
80
118
  metadata: Metadata;
119
+ /** The document's user, when it has one. */
120
+ user?: string;
81
121
  }
82
122
  /** What a query fuses: the embedding model, BM25 keywords, or the learned-sparse (SPLADE) model. */
83
123
  export type Retriever = "vector" | "keyword" | "sparse";
@@ -105,6 +145,8 @@ export interface Source {
105
145
  documents: number;
106
146
  lastSyncedAt: Date | null;
107
147
  createdAt: Date;
148
+ /** While syncing: records read from the app so far in the run in flight. */
149
+ recordsPulled?: number;
108
150
  }
109
151
  export interface SourceType {
110
152
  type: string;
@@ -127,6 +169,16 @@ export interface RequestOptions {
127
169
  signal?: AbortSignal;
128
170
  /** Overrides the client timeout for this call, in milliseconds. */
129
171
  timeout?: number;
172
+ /**
173
+ * The `Idempotency-Key` sent with every request but a GET (the write routes honour it). By
174
+ * default the SDK makes one per call and sends it on each retry of the call; pass your own to make a call you repeat later (a
175
+ * job restarted after a crash) the same call: within 24 hours its repeat gets the first answer and
176
+ * writes nothing. A key is 1-255 visible ASCII characters, kept per API key; `write()` and `add()`
177
+ * send batch `n` after the first as `<key>:<n>` and leave documents without an id to the API, which
178
+ * derives their ids from the key; `deleteWhere()` sends round `n` after the first as `<key>:<n>`.
179
+ * The same key with another request is a 422 `idempotency_key_reused`.
180
+ */
181
+ idempotencyKey?: string;
130
182
  }
131
183
  /** Every failure the SDK throws. `status` is 0 when no response arrived. */
132
184
  export declare class ConareError extends Error {
@@ -190,36 +242,39 @@ export declare class Namespace {
190
242
  }>;
191
243
  /**
192
244
  * Add or replace documents. Accepts one or many; sends them in batches of 100. Returns the ids.
193
- * A document without an id gets one here, so a retried batch replaces instead of duplicating.
245
+ * A document without an id gets one here, and each batch carries an `Idempotency-Key` reused on
246
+ * its retries, so a retried batch never writes twice.
194
247
  */
195
248
  add(documents: DocumentInput | DocumentInput[], options?: RequestOptions): Promise<string[]>;
196
249
  /**
197
- * `add` that returns each document's new version, to pass as `ifVersion` on its next write.
198
- * A conditional write retried after a lost response can answer 409 `version_conflict` for its
199
- * own first attempt: `get()` the document to tell. `version` is null when the server did not
200
- * answer one (a server older than versions): never pass it as `ifVersion`.
250
+ * `add` that returns what the write did with each document: its new version, to pass as
251
+ * `ifVersion` on its next write, and its `result` (`unchanged` when Conare already held it as
252
+ * sent: nothing was embedded or written). A conditional write retried after a lost response gets
253
+ * its first answer (the retry carries the batch's `Idempotency-Key`), not a `version_conflict`
254
+ * from its own first attempt. `version` is null when the server did not answer one (a server older than versions): never
255
+ * pass it as `ifVersion`.
201
256
  */
202
- write(documents: DocumentInput | DocumentInput[], options?: RequestOptions): Promise<{
203
- id: string;
204
- version: number | null;
205
- }[]>;
257
+ write(documents: DocumentInput | DocumentInput[], options?: RequestOptions): Promise<WriteResult[]>;
206
258
  /**
207
259
  * Store a PDF or an Excel workbook (.xlsx), at most 20 MiB: one document per PDF page with a
208
260
  * text layer (`<fileId>:page-3`) and Markdown tables per worksheet (`<fileId>:Sheet1-1`), each
209
261
  * with `file`, `file_id`, `file_type` and `page` or `sheet` metadata. `fileId` defaults to the
210
262
  * name in id characters; uploading the same one again replaces every document it made. Pages
211
- * without a text layer (scans, images) are read by OCR and counted in `pagesOcr`; pages with no
212
- * text even then are listed in `pagesWithoutText` and not stored.
263
+ * without a text layer (scans, images) are read by OCR: by default after the answer
264
+ * (`ocrPending`, stored within about a minute), with `wait: true` before it (`pagesOcr`). Pages
265
+ * with no text even then are listed in `pagesWithoutText` and not stored.
213
266
  */
214
267
  uploadFile(file: Blob | Uint8Array | ArrayBuffer, name: string, options?: RequestOptions & {
215
268
  id?: string;
269
+ wait?: boolean;
216
270
  }): Promise<FileUpload>;
217
271
  /**
218
272
  * Hybrid search, reranked. One result per document: its best passage. `retrievers` picks what
219
273
  * the search fuses (default `["vector", "keyword"]`); `"sparse"` needs a namespace created with
220
274
  * a sparse index. `rerankDepth` (1-100) has the reranker rank every passage among the first
221
- * that many in a tournament of 20-passage windows (exact order for the first `topK`, at most
222
- * 20); unset, it reads one window of 20.
275
+ * that many in windows of 20 passages, then reads the best 20 of them together in one final
276
+ * window that sets their order; unset, it reads one window of 20. `user` keeps the search to one user's documents and
277
+ * `userPrefix` (ending in `:`) to a group's; both combine with `filter`.
223
278
  */
224
279
  query(query: string, options?: RequestOptions & {
225
280
  topK?: number;
@@ -227,6 +282,8 @@ export declare class Namespace {
227
282
  rerank?: boolean;
228
283
  rerankDepth?: number;
229
284
  retrievers?: Retriever[];
285
+ user?: string;
286
+ userPrefix?: string;
230
287
  }): Promise<QueryResult[]>;
231
288
  /** One document by id, or null if it does not exist. */
232
289
  get(id: string, options?: RequestOptions): Promise<Document | null>;
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.17.0";
2
+ export const VERSION = "0.19.0";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
5
  // ---- Errors ----------------------------------------------------------------
@@ -74,7 +74,7 @@ export class Conare {
74
74
  }
75
75
  /** Embed texts. Use type "query" for search queries and "document" (default) for stored text. */
76
76
  async embed(input, options = {}) {
77
- const body = await this.request("POST", "/embed", { input: Array.isArray(input) ? input : [input], type: options.type ?? "document" }, options, true);
77
+ const body = await this.request("POST", "/embed", { input: Array.isArray(input) ? input : [input], type: options.type ?? "document" }, options);
78
78
  return body.embeddings;
79
79
  }
80
80
  /**
@@ -83,24 +83,26 @@ export class Conare {
83
83
  * Check `unscored`: documents left unread are missing from the results.
84
84
  */
85
85
  async rerank(query, documents, options = {}) {
86
- const body = await this.request("POST", "/rerank", { query, documents, top_k: options.topK }, options, true);
86
+ const body = await this.request("POST", "/rerank", { query, documents, top_k: options.topK }, options);
87
87
  const results = body.results.map((r) => ({ index: r.index, score: r.score, document: documents[r.index] ?? "" }));
88
88
  return Object.assign(results, { unscored: body.unscored ?? [] });
89
89
  }
90
90
  /**
91
- * @internal Sends one API request. An idempotent request (every GET and DELETE, and the POSTs
92
- * that cannot create anything twice) is retried on 429, 5xx and network errors; any other only
93
- * on 429 and 503, where the API did not act on it.
91
+ * @internal Sends one API request. Every request but a GET carries an `Idempotency-Key` (the
92
+ * caller's, or one made here), the same on each of its attempts: the API answers a repeat with
93
+ * the first answer and does nothing again. So every request is retried on 429, 5xx, 409
94
+ * `idempotency_in_progress` (the first attempt is still running) and network errors.
94
95
  */
95
- async request(method, path, body, options = {}, idempotent = method !== "POST") {
96
+ async request(method, path, body, options = {}) {
97
+ const key = method === "GET" ? undefined : (options.idempotencyKey ?? newIdempotencyKey());
96
98
  for (let attempt = 0;; attempt++) {
97
99
  let res;
98
100
  let text;
99
101
  try {
100
- [res, text] = await this.send(method, path, body, options);
102
+ [res, text] = await this.send(method, path, body, options, key);
101
103
  }
102
104
  catch (err) {
103
- if (err instanceof ConareError && idempotent && attempt < this.maxRetries) {
105
+ if (err instanceof ConareError && attempt < this.maxRetries) {
104
106
  await sleep(retryDelay(attempt, null), options.signal);
105
107
  continue;
106
108
  }
@@ -114,16 +116,17 @@ export class Conare {
114
116
  throw new ConareError(res.status, "invalid_response", "The response was not JSON.", res.headers.get("x-request-id"));
115
117
  }
116
118
  }
117
- const retryable = res.status === 429 || res.status === 503 || (idempotent && res.status >= 500);
119
+ const err = toError(res, text);
120
+ const retryable = res.status === 429 || res.status >= 500 || err.code === "idempotency_in_progress";
118
121
  if (retryable && attempt < this.maxRetries) {
119
122
  await sleep(retryDelay(attempt, res.headers.get("retry-after")), options.signal);
120
123
  continue;
121
124
  }
122
- throw toError(res, text);
125
+ throw err;
123
126
  }
124
127
  }
125
128
  // One attempt, body included, under the timeout and the caller's signal.
126
- async send(method, path, body, options) {
129
+ async send(method, path, body, options, idempotencyKey) {
127
130
  const controller = new AbortController();
128
131
  const timeout = options.timeout ?? this.timeout;
129
132
  const timer = setTimeout(() => controller.abort(), timeout);
@@ -140,6 +143,7 @@ export class Conare {
140
143
  Authorization: `Bearer ${this.apiKey}`,
141
144
  Accept: "application/json",
142
145
  ...(body === undefined ? {} : { "Content-Type": raw ? "application/octet-stream" : "application/json" }),
146
+ ...(idempotencyKey === undefined ? {} : { "Idempotency-Key": idempotencyKey }),
143
147
  },
144
148
  body: body === undefined ? undefined : raw ? body : JSON.stringify(body),
145
149
  signal: controller.signal,
@@ -178,36 +182,54 @@ export class Namespace {
178
182
  * other setting is a 409. Returns whether it has a sparse index.
179
183
  */
180
184
  async create(options = {}) {
181
- const body = await this.client.request("POST", "/namespaces", { name: this.name, sparse: options.sparse ?? false }, options, true);
185
+ const body = await this.client.request("POST", "/namespaces", { name: this.name, sparse: options.sparse ?? false }, options);
182
186
  return { sparse: body.sparse };
183
187
  }
184
188
  /**
185
189
  * Add or replace documents. Accepts one or many; sends them in batches of 100. Returns the ids.
186
- * A document without an id gets one here, so a retried batch replaces instead of duplicating.
190
+ * A document without an id gets one here, and each batch carries an `Idempotency-Key` reused on
191
+ * its retries, so a retried batch never writes twice.
187
192
  */
188
193
  async add(documents, options) {
189
194
  return (await this.write(documents, options)).map((d) => d.id);
190
195
  }
191
196
  /**
192
- * `add` that returns each document's new version, to pass as `ifVersion` on its next write.
193
- * A conditional write retried after a lost response can answer 409 `version_conflict` for its
194
- * own first attempt: `get()` the document to tell. `version` is null when the server did not
195
- * answer one (a server older than versions): never pass it as `ifVersion`.
197
+ * `add` that returns what the write did with each document: its new version, to pass as
198
+ * `ifVersion` on its next write, and its `result` (`unchanged` when Conare already held it as
199
+ * sent: nothing was embedded or written). A conditional write retried after a lost response gets
200
+ * its first answer (the retry carries the batch's `Idempotency-Key`), not a `version_conflict`
201
+ * from its own first attempt. `version` is null when the server did not answer one (a server older than versions): never
202
+ * pass it as `ifVersion`.
196
203
  */
197
204
  async write(documents, options) {
198
205
  const all = Array.isArray(documents) ? documents : [documents];
199
206
  const out = [];
200
207
  for (let i = 0; i < all.length; i += BATCH_SIZE) {
201
208
  const batch = all.slice(i, i + BATCH_SIZE);
209
+ const key = options?.idempotencyKey;
210
+ // With the caller's key, the API derives a missing id from it: the same on a repeat of the call.
202
211
  const body = await this.client.request("POST", this.path("/documents"), {
203
212
  documents: batch.map((d) => ({
204
- id: d.id ?? newDocumentId(),
213
+ id: d.id ?? (key ? undefined : newDocumentId()),
205
214
  text: d.text,
206
215
  metadata: d.metadata,
216
+ user: d.user,
217
+ seq: d.seq,
207
218
  if_version: d.ifVersion,
208
219
  })),
209
- }, options, true);
210
- body.ids.forEach((id, j) => out.push({ id, version: body.versions?.[j] ?? null }));
220
+ }, { ...options, idempotencyKey: key && i > 0 ? `${key}:${i / BATCH_SIZE}` : key });
221
+ body.ids.forEach((id, j) => {
222
+ const r = body.results?.[j];
223
+ const result = { id, version: body.versions?.[j] ?? null };
224
+ if (r) {
225
+ result.result = r.result;
226
+ result.chunks = r.chunks;
227
+ result.chunksEmbedded = r.chunks_embedded;
228
+ if (r.stored_seq !== undefined)
229
+ result.storedSeq = r.stored_seq;
230
+ }
231
+ out.push(result);
232
+ });
211
233
  }
212
234
  return out;
213
235
  }
@@ -216,12 +238,17 @@ export class Namespace {
216
238
  * text layer (`<fileId>:page-3`) and Markdown tables per worksheet (`<fileId>:Sheet1-1`), each
217
239
  * with `file`, `file_id`, `file_type` and `page` or `sheet` metadata. `fileId` defaults to the
218
240
  * name in id characters; uploading the same one again replaces every document it made. Pages
219
- * without a text layer (scans, images) are read by OCR and counted in `pagesOcr`; pages with no
220
- * text even then are listed in `pagesWithoutText` and not stored.
241
+ * without a text layer (scans, images) are read by OCR: by default after the answer
242
+ * (`ocrPending`, stored within about a minute), with `wait: true` before it (`pagesOcr`). Pages
243
+ * with no text even then are listed in `pagesWithoutText` and not stored.
221
244
  */
222
245
  async uploadFile(file, name, options = {}) {
223
- const query = new URLSearchParams({ name, ...(options.id ? { id: options.id } : {}) });
224
- const body = await this.client.request("POST", this.path(`/files?${query}`), file, { timeout: 120_000, ...options }, true);
246
+ const query = new URLSearchParams({
247
+ name,
248
+ ...(options.id ? { id: options.id } : {}),
249
+ ...(options.wait ? { wait: "true" } : {}),
250
+ });
251
+ const body = await this.client.request("POST", this.path(`/files?${query}`), file, { timeout: 120_000, ...options });
225
252
  return {
226
253
  fileId: body.file_id,
227
254
  type: body.type,
@@ -230,24 +257,35 @@ export class Namespace {
230
257
  sheets: body.sheets ?? null,
231
258
  pagesOcr: body.pages_ocr ?? 0,
232
259
  pagesWithoutText: body.pages_without_text ?? [],
260
+ ocrPending: body.ocr_pending ?? [],
233
261
  };
234
262
  }
235
263
  /**
236
264
  * Hybrid search, reranked. One result per document: its best passage. `retrievers` picks what
237
265
  * the search fuses (default `["vector", "keyword"]`); `"sparse"` needs a namespace created with
238
266
  * a sparse index. `rerankDepth` (1-100) has the reranker rank every passage among the first
239
- * that many in a tournament of 20-passage windows (exact order for the first `topK`, at most
240
- * 20); unset, it reads one window of 20.
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`.
241
270
  */
242
271
  async query(query, options = {}) {
243
- const body = await this.client.request("POST", this.path("/query"), { query, top_k: options.topK, filter: options.filter, rerank: options.rerank, rerank_depth: options.rerankDepth, retrievers: options.retrievers }, options, true);
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);
244
282
  return body.results;
245
283
  }
246
284
  /** One document by id, or null if it does not exist. */
247
285
  async get(id, options) {
248
286
  try {
249
287
  const d = await this.client.request("GET", this.path(`/documents/${segment(id)}`), undefined, options);
250
- return { id: d.id, text: d.text, metadata: d.metadata, updatedAt: new Date(d.updated_at), version: d.version };
288
+ return { id: d.id, text: d.text, metadata: d.metadata, updatedAt: new Date(d.updated_at), version: d.version, user: d.user, seq: d.seq };
251
289
  }
252
290
  catch (err) {
253
291
  if (err instanceof ConareError && err.status === 404)
@@ -267,7 +305,7 @@ export class Namespace {
267
305
  const qs = params.toString();
268
306
  const page = await this.client.request("GET", this.path(`/documents${qs ? `?${qs}` : ""}`), undefined, options);
269
307
  for (const d of page.documents) {
270
- yield { id: d.id, metadata: d.metadata, updatedAt: new Date(d.updated_at), version: d.version };
308
+ yield { id: d.id, metadata: d.metadata, updatedAt: new Date(d.updated_at), version: d.version, user: d.user, seq: d.seq };
271
309
  }
272
310
  cursor = page.next_cursor;
273
311
  } while (cursor);
@@ -284,8 +322,10 @@ export class Namespace {
284
322
  /** Delete every document matching filter (at least one condition), calling until none match. Returns how many were deleted. */
285
323
  async deleteWhere(filter, options) {
286
324
  let deleted = 0;
287
- for (;;) {
288
- const out = await this.client.request("POST", this.path("/documents/delete"), { filter }, options);
325
+ const key = options?.idempotencyKey;
326
+ for (let round = 0;; round++) {
327
+ // Each round is its own call (the same body deletes the next batch): its own key.
328
+ const out = await this.client.request("POST", this.path("/documents/delete"), { filter }, { ...options, idempotencyKey: key && round > 0 ? `${key}:${round}` : key });
289
329
  deleted += out.deleted;
290
330
  if (!out.more)
291
331
  return deleted;
@@ -322,7 +362,7 @@ export class Sources {
322
362
  }
323
363
  /** Start a sync now. */
324
364
  async sync(id, options) {
325
- return toSource(await this.client.request("POST", `/sources/${segment(id)}/sync`, undefined, options, true));
365
+ return toSource(await this.client.request("POST", `/sources/${segment(id)}/sync`, undefined, options));
326
366
  }
327
367
  /** Disconnect a source. Pass `deleteDocuments: true` to also delete what it synced. */
328
368
  async delete(id, options = {}) {
@@ -346,6 +386,7 @@ function toSource(s) {
346
386
  documents: s.documents,
347
387
  lastSyncedAt: s.last_synced_at ? new Date(s.last_synced_at) : null,
348
388
  createdAt: new Date(s.created_at),
389
+ ...(s.progress ? { recordsPulled: s.progress.records_pulled } : {}),
349
390
  };
350
391
  }
351
392
  function toError(res, text) {
@@ -360,6 +401,12 @@ function toError(res, text) {
360
401
  return new ConareError(res.status, error?.code ?? `http_${res.status}`, error?.message ?? (res.statusText || `HTTP ${res.status}`), error?.request_id ?? requestId);
361
402
  }
362
403
  const ID_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
404
+ /** "idk_" and 32 random hex characters: one write call's Idempotency-Key. */
405
+ function newIdempotencyKey() {
406
+ const bytes = new Uint8Array(16);
407
+ globalThis.crypto.getRandomValues(bytes);
408
+ return "idk_" + Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
409
+ }
363
410
  /** "doc_" and 20 random base62 characters, the shape the API generates. */
364
411
  function newDocumentId() {
365
412
  const bytes = new Uint8Array(20);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -26,6 +26,6 @@
26
26
  "engines": { "node": ">=18" },
27
27
  "devDependencies": {
28
28
  "@types/bun": "1.4.2",
29
- "typescript": "5.9.3"
29
+ "typescript": "6.0.3"
30
30
  }
31
31
  }