conare 0.21.0 → 0.23.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 +44 -7
- package/dist/cli/args.js +13 -1
- package/dist/cli/github/sync.js +57 -3
- package/dist/cli/main.js +10 -4
- package/dist/cli/upload.js +3 -2
- package/dist/index.d.ts +300 -17
- package/dist/index.js +258 -35
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -33,6 +33,7 @@ new Conare() // CONARE_API_KEY from the enviro
|
|
|
33
33
|
new Conare({ apiKey, baseURL, timeout: 60_000, maxRetries: 2 })
|
|
34
34
|
await conare.organizations() // [{ id, name, role }]: the organizations the key acts for
|
|
35
35
|
new Conare({ organization: "org_…" }) // acts for that one (X-Conare-Org)
|
|
36
|
+
new Conare({ gzip: false }) // JSON bodies of 8 KiB or more go gzip by default
|
|
36
37
|
```
|
|
37
38
|
|
|
38
39
|
Every method also takes `{ signal, timeout }` as its last option.
|
|
@@ -60,9 +61,9 @@ for await (const doc of docs.list()) {} // every document, page by page (
|
|
|
60
61
|
await docs.delete("refunds"); // 404 document_not_found if it does not exist
|
|
61
62
|
await docs.deleteMany(["a", "b"]); // up to 1000 ids in one call; missing ids are skipped. Returns the count
|
|
62
63
|
await docs.deleteWhere({ team: "support" }); // every document matching the filter, whole documents. Returns the count
|
|
63
|
-
await docs.uploadFile(bytes, "report.pdf"); // a PDF (one document per page)
|
|
64
|
-
// up to 20 MiB. The same name (or { id }) again replaces it.
|
|
65
|
-
// Returns { fileId, type, ids, pages, sheets, pagesOcr, pagesWithoutText, ocrPending }:
|
|
64
|
+
await docs.uploadFile(bytes, "report.pdf"); // a PDF (one document per page), a .docx (Markdown), a .pptx (one per slide)
|
|
65
|
+
// or an .xlsx (Markdown tables per sheet), up to 20 MiB. The same name (or { id }) again replaces it.
|
|
66
|
+
// Returns { fileId, type, ids, pages, sheets, slides, slidesWithoutText, pagesOcr, pagesWithoutText, ocrPending }:
|
|
66
67
|
// scanned pages are OCR'd after the answer (ocrPending; { wait: true } reads them first)
|
|
67
68
|
await docs.getFile("report.pdf"); // that upload's outcome, OCR after the answer included (kept 7 days)
|
|
68
69
|
await docs.drop(); // delete the namespace and its documents (succeeds if already emptied; 404 namespace_not_found if never written)
|
|
@@ -78,7 +79,7 @@ Namespace names: 1-64 characters of `a-z 0-9 _ -`. Ids: up to 256 characters of
|
|
|
78
79
|
|
|
79
80
|
```ts
|
|
80
81
|
await docs.query("how do refunds work?", {
|
|
81
|
-
topK: 10, // 1-
|
|
82
|
+
topK: 10, // 1-500, default 10
|
|
82
83
|
filter: { team: "support" }, // optional metadata filter
|
|
83
84
|
rerank: true, // default true
|
|
84
85
|
retrievers: ["vector", "keyword"], // default; one of them alone searches with it alone
|
|
@@ -91,7 +92,7 @@ fuses: `"vector"` (the embedding model) and `"keyword"` (BM25; alone, BM25 alone
|
|
|
91
92
|
rerank window (or of a query not reranked); the two scales do not compare.
|
|
92
93
|
|
|
93
94
|
Filters match metadata values: `{ key: value }` means equals (or, for an array value,
|
|
94
|
-
contains). Operators: `$eq`, `$in` and the ranges below. Combine with `$and` and `$or`:
|
|
95
|
+
contains). Operators: `$eq`, `$in`, `$ne`, `$nin` (queries only) and the ranges below. Combine with `$and` and `$or`:
|
|
95
96
|
|
|
96
97
|
```ts
|
|
97
98
|
{ $or: [{ team: "support" }, { year: { $in: [2024, 2025] } }] }
|
|
@@ -106,7 +107,7 @@ compare numbers, string bounds compare strings by their UTF-8 bytes, so ISO date
|
|
|
106
107
|
{ published_at: { $gte: "2025-06-01" } }
|
|
107
108
|
```
|
|
108
109
|
|
|
109
|
-
|
|
110
|
+
`$ne` and `$nin` work in queries; a delete by filter with one answers 400 `invalid_filter`.
|
|
110
111
|
|
|
111
112
|
### Embed and rerank
|
|
112
113
|
|
|
@@ -126,6 +127,19 @@ together at most 256,000); more than 100 is a 400 `invalid_request`. A document
|
|
|
126
127
|
one-second budget ended, or whose read failed, is listed by index in `.unscored` and is not in the
|
|
127
128
|
results; its score from another call would not compare.
|
|
128
129
|
|
|
130
|
+
### Parse
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
const out = await conare.parse(bytes, { name: "report.pdf", pages: "1-20", layout: true });
|
|
134
|
+
// { id, state: "done", markdown: "<!-- page 1 -->\n\n# Report...", parts: [{ locator: { page: 1 }, markdown, ocr, confidence, blocks }], withoutText }
|
|
135
|
+
await conare.parse({ url: "https://example.com/deck.pptx" }); // fetched by the API
|
|
136
|
+
await conare.parse(locked, { name: "minutes.pdf", password: "..." });
|
|
137
|
+
if (out.state === "parsing") await conare.getParse(out.id); // OCR outlived `wait` (default 60 s): the result, kept 24 h
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
`parse` reads a file with the same parser as `uploadFile` and stores nothing; any key can call it, a models-only key
|
|
141
|
+
too. `uploadFile` takes the same options and answers the same `markdown`, `parts` and `withoutText` beside `ids`.
|
|
142
|
+
|
|
129
143
|
### Sources
|
|
130
144
|
|
|
131
145
|
Connect an app such as HubSpot or Gmail. It keeps syncing into one namespace, and each record
|
|
@@ -189,6 +203,26 @@ await conare.events.list({ cursor: "0", types: ["run.*"] }); // { data: [{ seq,
|
|
|
189
203
|
`sources.list()` and `sources.get()` answer custom sources too, with `kind: "custom"`. These
|
|
190
204
|
calls send an `Idempotency-Key` when they create or delete something, so their retries are safe.
|
|
191
205
|
|
|
206
|
+
### Files
|
|
207
|
+
|
|
208
|
+
A PDF, Word document, PowerPoint deck, Excel workbook, CSV, text or image file becomes documents, one
|
|
209
|
+
per page, sheet part, slide or Word part, each citing where it came from (`page`; `sheet` and `rows`;
|
|
210
|
+
`slide`; `heading` and `part`) in its metadata. Parsing runs in the background; every page without a
|
|
211
|
+
usable text layer (a scan, an image) is read by OCR, and a page OCR could not read is listed in
|
|
212
|
+
`ocrFailed`, never left out silently. Declare the `type` when you know it: the file is parsed as that
|
|
213
|
+
type, and bytes of another type are a `ConareError` 415 `type_mismatch`.
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
const { file } = await conare.files.upload({ file: bytes, name: "Q3 report.pdf", namespace: "kb", type: "pdf",
|
|
217
|
+
metadata: { deal: "acme" } }); // up to 64 MiB in one request, up to 512 MiB in 16 MiB parts
|
|
218
|
+
const [ready] = await conare.files.waitUntilReady({ namespace: "kb", ids: [file.id] });
|
|
219
|
+
// { state: "ready", pages, pagesText, pagesOcr, pagesWithoutText, ocrFailed, documents, locators, ... }
|
|
220
|
+
await conare.files.status({ namespace: "kb", ids: [file.id] });
|
|
221
|
+
await conare.files.reparse(file.id, { namespace: "kb" }); // again, from the stored original
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
The same bytes and metadata again answer `result: "unchanged"`: nothing is parsed or embedded.
|
|
225
|
+
|
|
192
226
|
### Errors
|
|
193
227
|
|
|
194
228
|
Every failure is a `ConareError` with `status`, `code`, `message` and `requestId`
|
|
@@ -276,7 +310,10 @@ review comments; bots other than `greptile-apps[bot]` and `claude[bot]` are left
|
|
|
276
310
|
the default branch into `<repo>-docs` (id: the path with `/` as `:`; metadata `kind: "doc"`,
|
|
277
311
|
`path`, `title`, `author`, `date`, `url`). Later runs read only threads updated since the last one
|
|
278
312
|
and files whose content changed; docs whose file was deleted are deleted. `--state <file>` sets
|
|
279
|
-
where that is kept (default `~/.conare/github-state.json`).
|
|
313
|
+
where that is kept (default `~/.conare/github-state.json`). `<repo>` is the repository's name
|
|
314
|
+
lowercased, with any character other than letters, digits, `_` and `-` as `-` (`vercel/next.js`
|
|
315
|
+
writes `next-js-github`). A namespace that already holds another owner's repository of the same
|
|
316
|
+
name is left alone, and that repository's sync stops with an error.
|
|
280
317
|
|
|
281
318
|
## Development
|
|
282
319
|
|
package/dist/cli/args.js
CHANGED
|
@@ -26,6 +26,16 @@ The key comes from --key, else CONARE_API_KEY, else ~/.conare/sync.json.
|
|
|
26
26
|
Create one at https://conare.ai/console/keys. GitHub: GITHUB_TOKEN, else \`gh auth token\`.
|
|
27
27
|
`;
|
|
28
28
|
const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
29
|
+
/**
|
|
30
|
+
* The name "<name>-github" and "<name>-docs" start with, for owner/repo: the repository's name
|
|
31
|
+
* as a namespace may hold it (1-64 of [a-z0-9_-], starting with a letter or digit): lowercased,
|
|
32
|
+
* any other character as "-", leading "-" and "_" dropped, at most 57 characters so
|
|
33
|
+
* "<name>-github" fits. vercel/next.js -> next-js. null when nothing is left.
|
|
34
|
+
*/
|
|
35
|
+
export function repoNamespace(repo) {
|
|
36
|
+
const name = repo.slice(repo.indexOf("/") + 1).toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").slice(0, 57);
|
|
37
|
+
return name || null;
|
|
38
|
+
}
|
|
29
39
|
export function parseArgs(argv) {
|
|
30
40
|
const args = { help: false, version: false, command: "sessions", dryRun: false, quiet: false, install: false, uninstall: false, repos: [] };
|
|
31
41
|
const rest = [...argv];
|
|
@@ -109,7 +119,9 @@ export function parseArgs(argv) {
|
|
|
109
119
|
// Namespaces are named after the repository alone (<name>-github, <name>-docs).
|
|
110
120
|
const byName = new Map();
|
|
111
121
|
for (const repo of more) {
|
|
112
|
-
const name =
|
|
122
|
+
const name = repoNamespace(repo);
|
|
123
|
+
if (!name)
|
|
124
|
+
return { error: `${repo}: its name makes no namespace name (letters or digits needed).` };
|
|
113
125
|
const other = byName.get(name);
|
|
114
126
|
if (other && other.toLowerCase() !== repo.toLowerCase())
|
|
115
127
|
return { error: `${other} and ${repo} would both write to ${name}-github and ${name}-docs; sync one of them.` };
|
package/dist/cli/github/sync.js
CHANGED
|
@@ -8,6 +8,10 @@
|
|
|
8
8
|
// one back past the page boundary and skip it for good. Each changed thread is rebuilt whole
|
|
9
9
|
// from all of its comments. The first run (or one with more than PER_THREAD_LIMIT changed
|
|
10
10
|
// threads) reads the repository-wide comment listings instead of per-thread ones.
|
|
11
|
+
// A token without Issues: read (GitHub answers 403 for the issues listing; a GitHub App with
|
|
12
|
+
// Pull requests: read still reads every PR's comments) skips the issue threads, says so once,
|
|
13
|
+
// and takes the PR threads from the pulls listing under a watermark of their own, so the issue
|
|
14
|
+
// threads are picked up from the old watermark once the permission exists.
|
|
11
15
|
// Docs: the tree of the branch head; a file is fetched again only when its blob changed; its
|
|
12
16
|
// text and the author and date of the last commit touching it come from GraphQL in batches.
|
|
13
17
|
// A doc id that is in the namespace but no longer made by any file is deleted.
|
|
@@ -16,6 +20,7 @@ import { readFileSync } from "node:fs";
|
|
|
16
20
|
import { ConareError } from "../../index.js";
|
|
17
21
|
import { writePrivate } from "../config.js";
|
|
18
22
|
import { BATCH_BYTES, BATCH_DOCUMENTS, batches, sendBatch } from "../upload.js";
|
|
23
|
+
import { GitHubError } from "./api.js";
|
|
19
24
|
import { commentNumber, docDocument, docId, threadDocument } from "./documents.js";
|
|
20
25
|
/** More changed threads than this: read the repository-wide comment listings. */
|
|
21
26
|
export const PER_THREAD_LIMIT = 100;
|
|
@@ -48,9 +53,26 @@ export async function syncRepo(opts) {
|
|
|
48
53
|
};
|
|
49
54
|
const next = { ...opts.state };
|
|
50
55
|
const info = await gh.json(`/repos/${repo}`);
|
|
56
|
+
// The namespaces are named after the repository alone, so another owner's repository of the
|
|
57
|
+
// same name may fill them: its threads and docs would be overwritten and its docs deleted.
|
|
58
|
+
if (opts.namespaces)
|
|
59
|
+
for (const ns of [opts.namespaces.github, opts.namespaces.docs])
|
|
60
|
+
await refuseOtherRepo(ns, info.full_name);
|
|
51
61
|
// ---- threads ----
|
|
52
|
-
|
|
53
|
-
|
|
62
|
+
let since = opts.state.updatedAt;
|
|
63
|
+
let mark = "updatedAt";
|
|
64
|
+
let issues;
|
|
65
|
+
try {
|
|
66
|
+
issues = latestPerThread(await gh.all(`/repos/${repo}/issues?state=all&sort=updated&direction=desc&per_page=100${since ? `&since=${encodeURIComponent(since)}` : ""}`));
|
|
67
|
+
}
|
|
68
|
+
catch (e) {
|
|
69
|
+
if (!(e instanceof GitHubError) || e.status !== 403)
|
|
70
|
+
throw e;
|
|
71
|
+
log(`${repo}: issue threads skipped: GitHub answered 403 for the issues listing (the token has no Issues: read); PR threads from the pulls listing`);
|
|
72
|
+
mark = "pullsUpdatedAt";
|
|
73
|
+
since = opts.state.pullsUpdatedAt;
|
|
74
|
+
issues = latestPerThread(await pullThreads(gh, repo, since));
|
|
75
|
+
}
|
|
54
76
|
report.threads.changed = issues.length;
|
|
55
77
|
log(`${repo}: ${issues.length} threads ${since ? `updated since ${since}` : "(first run)"}`);
|
|
56
78
|
const comments = await threadComments(gh, repo, issues, !since || issues.length > PER_THREAD_LIMIT);
|
|
@@ -61,7 +83,7 @@ export async function syncRepo(opts) {
|
|
|
61
83
|
report.threads.failed = threadResult.rejected.length;
|
|
62
84
|
report.rejected.push(...threadResult.rejected);
|
|
63
85
|
if (threadResult.rejected.length === 0 && issues.length > 0) {
|
|
64
|
-
next
|
|
86
|
+
next[mark] = issues.reduce((max, i) => (i.updated_at > max ? i.updated_at : max), since ?? "");
|
|
65
87
|
}
|
|
66
88
|
// ---- docs ----
|
|
67
89
|
const head = await gh.json(`/repos/${repo}/git/ref/heads/${encodeURIComponent(info.default_branch)}`);
|
|
@@ -140,6 +162,38 @@ export async function syncRepo(opts) {
|
|
|
140
162
|
}
|
|
141
163
|
return { report, state: next };
|
|
142
164
|
}
|
|
165
|
+
/** Throws when the namespace's first document names another repository (metadata.repo). */
|
|
166
|
+
async function refuseOtherRepo(ns, fullName) {
|
|
167
|
+
let other;
|
|
168
|
+
try {
|
|
169
|
+
for await (const d of ns.list({ limit: 1 })) {
|
|
170
|
+
other = d.metadata?.repo;
|
|
171
|
+
break;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
catch (err) {
|
|
175
|
+
if (err instanceof ConareError && err.status === 404)
|
|
176
|
+
return;
|
|
177
|
+
throw err;
|
|
178
|
+
}
|
|
179
|
+
if (typeof other === "string" && other.toLowerCase() !== fullName.toLowerCase()) {
|
|
180
|
+
throw new Error(`${ns.name} holds ${other}'s documents, which syncing ${fullName} would overwrite and delete (namespaces are named after the repository alone). Sync it with another key.`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/** PR threads updated at or after `since` (all without it), as the issues listing gives them. */
|
|
184
|
+
async function pullThreads(gh, repo, since) {
|
|
185
|
+
const out = [];
|
|
186
|
+
for await (const p of gh.paginate(`/repos/${repo}/pulls?state=all&sort=updated&direction=desc&per_page=100`)) {
|
|
187
|
+
if (since && p.updated_at < since)
|
|
188
|
+
break;
|
|
189
|
+
out.push({
|
|
190
|
+
number: p.number, title: p.title, body: p.body, state: p.state, user: p.user, created_at: p.created_at,
|
|
191
|
+
updated_at: p.updated_at, closed_at: p.closed_at, html_url: p.html_url, labels: p.labels,
|
|
192
|
+
pull_request: { merged_at: p.merged_at ?? null },
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
return out;
|
|
196
|
+
}
|
|
143
197
|
/** One entry per thread number, its newest version (a thread updated mid-listing can appear twice). */
|
|
144
198
|
export function latestPerThread(issues) {
|
|
145
199
|
const byNumber = new Map();
|
package/dist/cli/main.js
CHANGED
|
@@ -8,7 +8,7 @@ import { rmSync } from "node:fs";
|
|
|
8
8
|
import { homedir } from "node:os";
|
|
9
9
|
import { fileURLToPath } from "node:url";
|
|
10
10
|
import { Conare, ConareError, VERSION } from "../index.js";
|
|
11
|
-
import { HELP, parseArgs } from "./args.js";
|
|
11
|
+
import { HELP, parseArgs, repoNamespace } from "./args.js";
|
|
12
12
|
import { readSavedKey, resolvePaths, saveKey } from "./config.js";
|
|
13
13
|
import { GitHub, GitHubError, githubToken } from "./github/api.js";
|
|
14
14
|
import { loadGitHubState, saveGitHubState, syncRepo } from "./github/sync.js";
|
|
@@ -168,11 +168,17 @@ async function syncSessions(args, paths, apiKey, say, fail) {
|
|
|
168
168
|
error = `${report.rejected.length} documents not accepted`;
|
|
169
169
|
}
|
|
170
170
|
catch (err) {
|
|
171
|
-
if (err instanceof ConareError &&
|
|
171
|
+
if (err instanceof ConareError && err.status === 401) {
|
|
172
172
|
error = `The API key was refused (${err.status} ${err.code}).`;
|
|
173
173
|
fail(`${error} Save a valid one: npx conare sync --key sk-conare-…`);
|
|
174
174
|
code = AUTH_FAILED;
|
|
175
175
|
}
|
|
176
|
+
else if (err instanceof ConareError && err.status === 403) {
|
|
177
|
+
// The key is valid but may not write here (a key scoped to other namespaces).
|
|
178
|
+
error = `The API key may not do this: ${err.message} (403 ${err.code}).`;
|
|
179
|
+
fail(error);
|
|
180
|
+
code = INCOMPLETE;
|
|
181
|
+
}
|
|
176
182
|
else {
|
|
177
183
|
const detail = err instanceof ConareError ? `${err.message} (${err.status || err.code}${err.requestId ? `, request ${err.requestId}` : ""})` : String(err);
|
|
178
184
|
error = `Sync stopped: ${detail}`;
|
|
@@ -212,7 +218,7 @@ async function syncGitHub(args, paths, apiKey, say, fail) {
|
|
|
212
218
|
const state = loadGitHubState(stateFile);
|
|
213
219
|
for (const repo of args.repos) {
|
|
214
220
|
const started = Date.now();
|
|
215
|
-
const name =
|
|
221
|
+
const name = repoNamespace(repo); // parseArgs refused a repository without one
|
|
216
222
|
// State written for another key or server starts from nothing (a dry run without a key reuses it).
|
|
217
223
|
const saved = state.repos[repo] ?? {};
|
|
218
224
|
const repoState = account === undefined || saved.account === account ? saved : {};
|
|
@@ -242,7 +248,7 @@ async function syncGitHub(args, paths, apiKey, say, fail) {
|
|
|
242
248
|
}
|
|
243
249
|
}
|
|
244
250
|
catch (err) {
|
|
245
|
-
if (err instanceof ConareError &&
|
|
251
|
+
if (err instanceof ConareError && err.status === 401) {
|
|
246
252
|
fail(`The API key was refused (${err.status} ${err.code}).`);
|
|
247
253
|
return AUTH_FAILED;
|
|
248
254
|
}
|
package/dist/cli/upload.js
CHANGED
|
@@ -29,9 +29,10 @@ export function batches(docs, maxDocs = BATCH_DOCUMENTS, maxBytes = BATCH_BYTES)
|
|
|
29
29
|
out.push(current);
|
|
30
30
|
return out;
|
|
31
31
|
}
|
|
32
|
-
/** A request the API refused because of what one of its documents holds
|
|
32
|
+
/** A request the API refused because of what one of its documents holds; a bad namespace is
|
|
33
|
+
* every document's, so sending each alone would only repeat it. */
|
|
33
34
|
function isDocumentError(err) {
|
|
34
|
-
return err instanceof ConareError && (err.status === 400 || err.status === 413 || err.status === 422);
|
|
35
|
+
return err instanceof ConareError && (err.status === 400 || err.status === 413 || err.status === 422) && err.code !== "invalid_namespace";
|
|
35
36
|
}
|
|
36
37
|
/**
|
|
37
38
|
* Write one batch. When the API refuses the batch for its content, each document is sent
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const VERSION = "0.
|
|
1
|
+
export declare const VERSION = "0.23.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>;
|
|
@@ -70,18 +70,128 @@ export interface WriteResult {
|
|
|
70
70
|
chunksEmbedded?: number;
|
|
71
71
|
storedSeq?: number;
|
|
72
72
|
}
|
|
73
|
+
/** A file type `uploadFile` can declare: the file is read as that type (`jpg` and `tif` are accepted too). */
|
|
74
|
+
export type FileType = "pdf" | "xlsx" | "docx" | "pptx" | "csv" | "tsv" | "txt" | "md" | "png" | "jpeg" | "webp" | "tiff" | "gif" | "bmp" | "heic";
|
|
75
|
+
/**
|
|
76
|
+
* A picture of a Word document or deck that OCR did not turn into text. Every raster picture is read except an
|
|
77
|
+
* icon or a decoration: under 64 pixels on both sides, under 16 pixels on its shorter side, or drawn under half
|
|
78
|
+
* an inch on both sides.
|
|
79
|
+
*/
|
|
80
|
+
export interface PictureWithoutText {
|
|
81
|
+
/** A deck's: the slide it is on. */
|
|
82
|
+
slide?: number;
|
|
83
|
+
/** Its number in reading order (per slide in a deck), as the `image` of its documents would be. */
|
|
84
|
+
image: number;
|
|
85
|
+
/** A Word document's: the headings it sits under. */
|
|
86
|
+
heading?: string;
|
|
87
|
+
/** With `too_small`: its size in pixels. */
|
|
88
|
+
width?: number;
|
|
89
|
+
height?: number;
|
|
90
|
+
/**
|
|
91
|
+
* `too_small`: an icon or a decoration. `not_raster`: a vector picture (EMF, WMF, SVG). `unreadable`: its bytes
|
|
92
|
+
* do not decode. `not_read`: past the most pictures OCR reads in a file, or OCR failed or ran out of time.
|
|
93
|
+
* `no_text`: OCR found no text in it.
|
|
94
|
+
*/
|
|
95
|
+
reason: "too_small" | "not_raster" | "unreadable" | "not_read" | "no_text";
|
|
96
|
+
}
|
|
97
|
+
/** Options of `parse` and `uploadFile`: which pages, a password, the page layout and how long to wait. */
|
|
98
|
+
export interface ParseOptions {
|
|
99
|
+
/** The file's type: it is read as that type. Unset: the bytes say, then the name. */
|
|
100
|
+
type?: FileType;
|
|
101
|
+
/** Pages to read, e.g. `"1-20,25"`: a PDF's pages, an image's frames or a deck's slides. */
|
|
102
|
+
pages?: string;
|
|
103
|
+
/** Opens a password-protected PDF, or an Office file with a password. A missing or wrong one throws 422 `password_protected`. */
|
|
104
|
+
password?: string;
|
|
105
|
+
/** Each part OCR read carries `blocks`, its page's regions. */
|
|
106
|
+
layout?: boolean;
|
|
107
|
+
/**
|
|
108
|
+
* Seconds to wait for OCR before the answer is pending (0-300, default 60; the answer comes within 105 s
|
|
109
|
+
* whatever it says). `true` is 60. On `uploadFile`, `false` answers once the text layers are stored.
|
|
110
|
+
*/
|
|
111
|
+
wait?: number | boolean;
|
|
112
|
+
}
|
|
113
|
+
/** One region of a page as OCR laid it out (`layout: true`). */
|
|
114
|
+
export interface ParseBlock {
|
|
115
|
+
/** `title`, `text`, `list`, `table`, `table_caption`, `image`, `image_caption`, `header`, `footer`, `page_number`, ... */
|
|
116
|
+
type: string;
|
|
117
|
+
/** `[x0, y0, x1, y1]` as shares of the page's width and height from its top left. */
|
|
118
|
+
bbox: [number, number, number, number];
|
|
119
|
+
order: number;
|
|
120
|
+
content: string;
|
|
121
|
+
/** The mean probability of its tokens; null when none was given. */
|
|
122
|
+
conf: number | null;
|
|
123
|
+
}
|
|
124
|
+
/** One part of a parsed file: a page, slide, picture, sheet or Word part. */
|
|
125
|
+
export interface ParsePart {
|
|
126
|
+
/** Where it is: `{ page: 3 }`, `{ slide: 4, image: 1 }`, `{ sheet: "Q3", rows: "2-41" }`, `{ part: 2, heading: "..." }`. */
|
|
127
|
+
locator: Record<string, string | number>;
|
|
128
|
+
markdown: string;
|
|
129
|
+
/** Read by OCR from the page's image, not its text layer. */
|
|
130
|
+
ocr: boolean;
|
|
131
|
+
/** The mean probability (0-1) of the tokens OCR wrote for it; null when OCR did not read it or gave no probabilities. */
|
|
132
|
+
confidence: number | null;
|
|
133
|
+
/** With `layout: true`, on a part OCR read with its layout. */
|
|
134
|
+
blocks?: ParseBlock[];
|
|
135
|
+
}
|
|
136
|
+
/** What of a file holds no text. */
|
|
137
|
+
export interface WithoutText {
|
|
138
|
+
pages: number[];
|
|
139
|
+
slides: number[];
|
|
140
|
+
/** Pictures of a Word or PowerPoint file, each with where it is and why. */
|
|
141
|
+
images: PictureWithoutText[];
|
|
142
|
+
}
|
|
143
|
+
/** A file's text, as `parse` answers it once done. */
|
|
144
|
+
export interface ParseResult {
|
|
145
|
+
id: string;
|
|
146
|
+
state: "done";
|
|
147
|
+
type: FileUpload["type"];
|
|
148
|
+
name: string;
|
|
149
|
+
/** A PDF's pages, an image's frames, a deck's slides or a workbook's sheets (null for other files). */
|
|
150
|
+
pages: number | null;
|
|
151
|
+
/** The whole document: `<!-- page 3 -->`, `<!-- slide 4 -->` and `<!-- sheet "Q3" -->` start each page, slide and sheet. */
|
|
152
|
+
markdown: string;
|
|
153
|
+
parts: ParsePart[];
|
|
154
|
+
withoutText: WithoutText;
|
|
155
|
+
}
|
|
156
|
+
/** A parse OCR was still reading after `wait`: `getParse(id)` answers the result (kept 24 hours). */
|
|
157
|
+
export interface ParsePending {
|
|
158
|
+
id: string;
|
|
159
|
+
state: "parsing";
|
|
160
|
+
}
|
|
161
|
+
/** A parse `getParse` found failed: `error` is what it would have thrown. */
|
|
162
|
+
export interface ParseFailed {
|
|
163
|
+
id: string;
|
|
164
|
+
state: "failed";
|
|
165
|
+
error: {
|
|
166
|
+
code: string;
|
|
167
|
+
message: string;
|
|
168
|
+
};
|
|
169
|
+
}
|
|
73
170
|
/** What `uploadFile` stored. */
|
|
74
171
|
export interface FileUpload {
|
|
75
172
|
fileId: string;
|
|
76
|
-
|
|
173
|
+
/** The whole document as `parse` answers it, once OCR is done (null while `ocr`, or for a file read in the background). */
|
|
174
|
+
markdown: string | null;
|
|
175
|
+
/** Its parts as `parse` answers them (empty while `ocr`, or for a file read in the background). */
|
|
176
|
+
parts: ParsePart[];
|
|
177
|
+
/** The type it was read as: an image of any format is `image`. */
|
|
178
|
+
type: "pdf" | "xlsx" | "docx" | "pptx" | "csv" | "tsv" | "txt" | "md" | "image";
|
|
77
179
|
/** The documents it made, in reading order. */
|
|
78
180
|
ids: string[];
|
|
79
|
-
/** A PDF's pages (null for
|
|
181
|
+
/** A PDF's pages (null for any other file). */
|
|
80
182
|
pages: number | null;
|
|
81
|
-
/** A workbook's sheets (null for
|
|
183
|
+
/** A workbook's sheets (null for any other file). */
|
|
82
184
|
sheets: number | null;
|
|
83
|
-
/**
|
|
185
|
+
/** A deck's slides (null for any other file). */
|
|
186
|
+
slides: number | null;
|
|
187
|
+
/** A deck's slides with no text (pictures only): not stored. */
|
|
188
|
+
slidesWithoutText: number[];
|
|
189
|
+
/** PDF or image pages read by OCR before the answer (`wait: true`); stored like the rest. */
|
|
84
190
|
pagesOcr: number;
|
|
191
|
+
/** Pictures of a Word document or deck read by OCR before the answer (`wait: true`), each a document of its own. */
|
|
192
|
+
imagesOcr: number;
|
|
193
|
+
/** Pictures of a Word document or deck OCR did not turn into text, each with where it is and why. */
|
|
194
|
+
imagesWithoutText: PictureWithoutText[];
|
|
85
195
|
/** PDF pages with no text even after OCR (blank, or OCR could not read them): not stored. */
|
|
86
196
|
pagesWithoutText: number[];
|
|
87
197
|
/**
|
|
@@ -89,6 +199,21 @@ export interface FileUpload {
|
|
|
89
199
|
* `getFile(fileId)` says when OCR ended and which of them it could not read.
|
|
90
200
|
*/
|
|
91
201
|
ocrPending: number[];
|
|
202
|
+
/**
|
|
203
|
+
* `ready`: every document is stored. `ocr`: pages are still being read by OCR (`ocrPending`). `queued`,
|
|
204
|
+
* `parsing`: a large file (over 20 MiB, or over 100 pages for OCR) read in the background; follow it with
|
|
205
|
+
* `getFile(fileId)`. `failed`: the background read failed (`error`).
|
|
206
|
+
*/
|
|
207
|
+
state: "queued" | "parsing" | "ocr" | "ready" | "failed";
|
|
208
|
+
/** Read in the background: the namespace's files source; its documents are `<sourceId>:<fileId>:<part>`. */
|
|
209
|
+
sourceId: string | null;
|
|
210
|
+
/** Everything the file stored no text for, in one place (`pagesWithoutText`, `slidesWithoutText` and `imagesWithoutText` say the same). */
|
|
211
|
+
withoutText: WithoutText;
|
|
212
|
+
/** When `failed`: `{ code, message }`. */
|
|
213
|
+
error: {
|
|
214
|
+
code: string;
|
|
215
|
+
message: string;
|
|
216
|
+
} | null;
|
|
92
217
|
}
|
|
93
218
|
/** What `getFile` reads: an upload's outcome, with OCR after the answer folded in as it ends. */
|
|
94
219
|
export interface FileStatus extends FileUpload {
|
|
@@ -143,6 +268,8 @@ export interface QueryOptions extends RequestOptions {
|
|
|
143
268
|
userPrefix?: string;
|
|
144
269
|
/** Documents (ids) no result may be: up to 10,000. */
|
|
145
270
|
excludeIds?: string[];
|
|
271
|
+
/** 2 searches again from the best results, for answers that span documents (not with `queryPages`). */
|
|
272
|
+
hops?: 1 | 2;
|
|
146
273
|
}
|
|
147
274
|
/** One page of `Namespace.queryPages`. */
|
|
148
275
|
export interface QueryPage {
|
|
@@ -359,6 +486,12 @@ export interface ConareOptions {
|
|
|
359
486
|
* be its own. Make one client per organization.
|
|
360
487
|
*/
|
|
361
488
|
organization?: string;
|
|
489
|
+
/**
|
|
490
|
+
* Send JSON bodies of 8 KiB or more gzip-encoded (`Content-Encoding: gzip`). Default true where the
|
|
491
|
+
* runtime has `CompressionStream` (Node 18+, Bun, browsers). A server that refuses gzip (400 or 415)
|
|
492
|
+
* gets the request again as plain JSON, and no more gzip from this client.
|
|
493
|
+
*/
|
|
494
|
+
gzip?: boolean;
|
|
362
495
|
}
|
|
363
496
|
/** An organization the key acts for (`organizations()`). */
|
|
364
497
|
export interface Organization {
|
|
@@ -392,6 +525,78 @@ export declare class ConareError extends Error {
|
|
|
392
525
|
readonly requestId: string | null;
|
|
393
526
|
constructor(status: number, code: string, message: string, requestId?: string | null);
|
|
394
527
|
}
|
|
528
|
+
/** A file of `files.upload`, as `files.status` reads it. */
|
|
529
|
+
export interface StoredFile {
|
|
530
|
+
/** The file's id in its namespace (and user). */
|
|
531
|
+
id: string;
|
|
532
|
+
name: string;
|
|
533
|
+
namespace: string;
|
|
534
|
+
user: string | null;
|
|
535
|
+
/** The namespace's files source: the file's documents are `<sourceId>:<id>:<part>`. */
|
|
536
|
+
sourceId: string;
|
|
537
|
+
/** What it was parsed as: pdf, xlsx, docx, pptx, csv, tsv, txt, md or image. */
|
|
538
|
+
type: string | null;
|
|
539
|
+
/** Whether the type was declared rather than recognized. */
|
|
540
|
+
declared: boolean;
|
|
541
|
+
bytes: number;
|
|
542
|
+
sha256: string | null;
|
|
543
|
+
metadata: Metadata;
|
|
544
|
+
/** `ocr`: pages are being read by OCR, or wait to be tried again. */
|
|
545
|
+
state: "queued" | "parsing" | "ocr" | "ready" | "failed";
|
|
546
|
+
/** PDF pages, sheets, slides, Word parts or image frames. */
|
|
547
|
+
pages: number;
|
|
548
|
+
/** Pages stored from their text layer. */
|
|
549
|
+
pagesText: number;
|
|
550
|
+
/** Pages read by OCR with text. */
|
|
551
|
+
pagesOcr: number;
|
|
552
|
+
/** Every page this parse stored no text for: blank, read as empty, unreadable, or without a text layer and not read by OCR. */
|
|
553
|
+
pagesWithoutText: number[];
|
|
554
|
+
/** Pages waiting for OCR. */
|
|
555
|
+
ocrPending: number;
|
|
556
|
+
/** Pages OCR could not read after its retries; each keeps what an earlier upload stored for it. */
|
|
557
|
+
ocrFailed: number[];
|
|
558
|
+
/** Pages no reader can open because the file is damaged there, each with why; not tried again. */
|
|
559
|
+
pagesUnreadable: {
|
|
560
|
+
page: number;
|
|
561
|
+
reason: string;
|
|
562
|
+
}[];
|
|
563
|
+
documents: number;
|
|
564
|
+
/** Parts the write refused, each with why. */
|
|
565
|
+
rejected: {
|
|
566
|
+
id: string;
|
|
567
|
+
code: string;
|
|
568
|
+
message: string;
|
|
569
|
+
}[];
|
|
570
|
+
/** The locator fields its documents carry: page, sheet, rows, slide, heading, part, frame. */
|
|
571
|
+
locators: string[];
|
|
572
|
+
/** Pictures of a Word document or deck OCR did not turn into text, each with where it is and why. */
|
|
573
|
+
imagesWithoutText: PictureWithoutText[];
|
|
574
|
+
chunksEmbedded: number;
|
|
575
|
+
/** The file's latest parse. */
|
|
576
|
+
run: {
|
|
577
|
+
id: string;
|
|
578
|
+
kind: "parse" | "reparse";
|
|
579
|
+
state: string;
|
|
580
|
+
phase: string | null;
|
|
581
|
+
error: unknown;
|
|
582
|
+
retryAt?: Date;
|
|
583
|
+
};
|
|
584
|
+
/** When `failed`: `{ code, message }`. */
|
|
585
|
+
error: {
|
|
586
|
+
code: string;
|
|
587
|
+
message: string;
|
|
588
|
+
} | null;
|
|
589
|
+
updatedAt: Date;
|
|
590
|
+
}
|
|
591
|
+
/** What `files.upload` and `files.reparse` answer. */
|
|
592
|
+
export interface FileQueued {
|
|
593
|
+
/** `unchanged`: the same bytes and metadata as the file's last parse; nothing was queued. */
|
|
594
|
+
result?: "unchanged";
|
|
595
|
+
file: StoredFile;
|
|
596
|
+
run?: Run;
|
|
597
|
+
}
|
|
598
|
+
/** The largest file `files.upload` sends in one request; a larger one (up to 512 MiB) goes in parts. */
|
|
599
|
+
export declare const MAX_FILE_REQUEST_BYTES: number;
|
|
395
600
|
/**
|
|
396
601
|
* The Conare client.
|
|
397
602
|
*
|
|
@@ -405,6 +610,8 @@ export declare class Conare {
|
|
|
405
610
|
readonly runs: Runs;
|
|
406
611
|
/** Files of documents written into a custom source. */
|
|
407
612
|
readonly imports: Imports;
|
|
613
|
+
/** Files (PDF, Word, PowerPoint, Excel, CSV, text, images) kept as documents, a page each. */
|
|
614
|
+
readonly files: Files;
|
|
408
615
|
/** Delete everything Conare holds of one of your users. */
|
|
409
616
|
readonly users: Users;
|
|
410
617
|
/** What changed, in order. */
|
|
@@ -415,6 +622,7 @@ export declare class Conare {
|
|
|
415
622
|
private readonly timeout;
|
|
416
623
|
private readonly maxRetries;
|
|
417
624
|
private readonly fetchFn;
|
|
625
|
+
private gzip;
|
|
418
626
|
constructor(options?: ConareOptions);
|
|
419
627
|
/** A handle to one namespace. Nothing is sent until you call a method; the first write creates it. */
|
|
420
628
|
namespace(name: string): Namespace;
|
|
@@ -449,6 +657,19 @@ export declare class Conare {
|
|
|
449
657
|
rerank(query: string, documents: string[], options?: RequestOptions & {
|
|
450
658
|
topK?: number;
|
|
451
659
|
}): Promise<RerankResults>;
|
|
660
|
+
/**
|
|
661
|
+
* Parses a file to Markdown and stores nothing: the same parser, options and result as `uploadFile`.
|
|
662
|
+
* `file` is its bytes, or `{ url }` (an https URL on a public address, fetched by the API). A file OCR
|
|
663
|
+
* reads answers once OCR is done within `wait` seconds (default 60), else `{ id, state: "parsing" }`:
|
|
664
|
+
* `getParse(id)` answers the result (kept 24 hours). Any API key can parse, a models-only key too.
|
|
665
|
+
*/
|
|
666
|
+
parse(file: Blob | Uint8Array | ArrayBuffer | {
|
|
667
|
+
url: string;
|
|
668
|
+
}, options?: RequestOptions & ParseOptions & {
|
|
669
|
+
name?: string;
|
|
670
|
+
}): Promise<ParseResult | ParsePending>;
|
|
671
|
+
/** A parse that answered `state: "parsing"`: still parsing, done with its result, or failed. 404 `parse_not_found` after 24 hours. */
|
|
672
|
+
getParse(id: string, options?: RequestOptions): Promise<ParseResult | ParsePending | ParseFailed>;
|
|
452
673
|
private send;
|
|
453
674
|
}
|
|
454
675
|
/** One namespace: a named set of documents, e.g. "docs" or "user-42". */
|
|
@@ -484,19 +705,28 @@ export declare class Namespace {
|
|
|
484
705
|
*/
|
|
485
706
|
write(documents: DocumentInput | DocumentInput[], options?: RequestOptions): Promise<WriteResult[]>;
|
|
486
707
|
/**
|
|
487
|
-
* Store a PDF
|
|
488
|
-
*
|
|
489
|
-
*
|
|
708
|
+
* Store a PDF, a Word document (.docx), a PowerPoint deck (.pptx), an Excel workbook (.xlsx), a CSV or
|
|
709
|
+
* TSV, a text or Markdown file, or an image (PNG, JPEG, WebP, TIFF), at most 20 MiB. Say its type with
|
|
710
|
+
* `type`: it is read as that type, and bytes of another type are refused (415) rather than misread;
|
|
711
|
+
* without it the type comes from the bytes, then the name. One document per PDF page with a text
|
|
712
|
+
* layer (`<fileId>:page-3`), per image page (read by OCR), a CSV as Markdown tables with its header
|
|
713
|
+
* on every part and the rows each holds in `rows` metadata, a Word document as
|
|
714
|
+
* Markdown (`<fileId>:part-1`, more parts past 240 KiB), one per slide with text (`<fileId>:slide-2`:
|
|
715
|
+
* title, shapes in reading order, tables, speaker notes) and Markdown tables per worksheet
|
|
716
|
+
* (`<fileId>:Sheet1-1`), each with `file`, `file_id`, `file_type` and `page`, `part`, `slide` or
|
|
717
|
+
* `sheet` metadata. Slides with no text are listed in `slidesWithoutText`. `fileId` defaults to the
|
|
490
718
|
* name in id characters (a name with characters outside ASCII also gets 8 hex digits of its hash, so
|
|
491
719
|
* such names do not collide); uploading the same one again replaces every document it made, and two
|
|
492
|
-
* uploads of one id run one at a time.
|
|
493
|
-
*
|
|
494
|
-
*
|
|
495
|
-
*
|
|
720
|
+
* uploads of one id run one at a time. The answer also holds what `parse` answers (`markdown`, `parts`,
|
|
721
|
+
* `withoutText`), and takes its options (`pages`, `password`, `layout`, `wait`). Pages with something on them
|
|
722
|
+
* are read by OCR: the answer waits `wait` seconds for it (default 60); pages it still reads then are in
|
|
723
|
+
* `ocrPending` (`state: "ocr"`, stored within about a minute; `wait: false` answers once the text layers are
|
|
724
|
+
* stored). Pages with no text even then are listed in `withoutText.pages` and not stored. Any file up to 512 MiB
|
|
725
|
+
* goes in this one call: one over 20 MiB, or with more than 100 pages for OCR, is read in the background and
|
|
726
|
+
* answers `state` `queued` or `parsing` (follow it with `getFile`), or `ready` once done within `wait`.
|
|
496
727
|
*/
|
|
497
|
-
uploadFile(file: Blob | Uint8Array | ArrayBuffer, name: string, options?: RequestOptions & {
|
|
728
|
+
uploadFile(file: Blob | Uint8Array | ArrayBuffer, name: string, options?: RequestOptions & ParseOptions & {
|
|
498
729
|
id?: string;
|
|
499
|
-
wait?: boolean;
|
|
500
730
|
}): Promise<FileUpload>;
|
|
501
731
|
/**
|
|
502
732
|
* An upload's outcome: the last upload of `fileId` here in the last 7 days. While OCR reads after the
|
|
@@ -507,7 +737,7 @@ export declare class Namespace {
|
|
|
507
737
|
/**
|
|
508
738
|
* Hybrid search, reranked. One result per document: its best passage; `topK` documents when that
|
|
509
739
|
* many match. `retrievers` picks what the search fuses (default `["vector", "keyword"]`; listed
|
|
510
|
-
* retrievers run as listed, also on a vector-only custom model). `rerankDepth` (1-
|
|
740
|
+
* retrievers run as listed, also on a vector-only custom model). `rerankDepth` (1-1000) is how many of the
|
|
511
741
|
* first passages the reranker ranks; unset, the first 20. `user` keeps the search to one user's documents and
|
|
512
742
|
* `userPrefix` (ending in `:`) to a group's; both combine with `filter`. An empty `user` or
|
|
513
743
|
* `userPrefix` is a 400, never "every user". `excludeIds` keeps those documents out.
|
|
@@ -539,8 +769,17 @@ export declare class Namespace {
|
|
|
539
769
|
deleteMany(ids: string[], options?: RequestOptions): Promise<number>;
|
|
540
770
|
/** Delete every document matching filter (at least one condition), calling until none match. Returns how many were deleted. */
|
|
541
771
|
deleteWhere(filter: Filter, options?: RequestOptions): Promise<number>;
|
|
542
|
-
/**
|
|
543
|
-
|
|
772
|
+
/**
|
|
773
|
+
* Delete the namespace and every document in it, with its files source (the one `files.upload` makes). Succeeds
|
|
774
|
+
* as well when it was already deleted or emptied; throws ConareError 404 `namespace_not_found` for a name never
|
|
775
|
+
* written, and 409 `namespace_has_sources` while another source (an app, a custom or a Cloud Storage source)
|
|
776
|
+
* writes into it, unless `force: true`, which deletes those sources too. Answers the ids of the sources deleted.
|
|
777
|
+
*/
|
|
778
|
+
drop(options?: RequestOptions & {
|
|
779
|
+
force?: boolean;
|
|
780
|
+
}): Promise<{
|
|
781
|
+
sourcesDeleted: string[];
|
|
782
|
+
}>;
|
|
544
783
|
}
|
|
545
784
|
/** Apps connected through Conare that keep syncing into a namespace, and custom sources you push to. */
|
|
546
785
|
export declare class Sources {
|
|
@@ -709,6 +948,50 @@ export declare class Imports {
|
|
|
709
948
|
filename?: string;
|
|
710
949
|
}, options?: RequestOptions): Promise<Run>;
|
|
711
950
|
}
|
|
951
|
+
export declare class Files {
|
|
952
|
+
private readonly client;
|
|
953
|
+
constructor(client: Conare);
|
|
954
|
+
/**
|
|
955
|
+
* Upload a file: it is stored and parsed in the background into a document per page, sheet part,
|
|
956
|
+
* slide or Word part, each citing where it came from; pages without text are read by OCR. Declare
|
|
957
|
+
* its `type` when you know it: it is then parsed as that type, and bytes of another type are a
|
|
958
|
+
* ConareError 415 `type_mismatch`. Up to 64 MiB goes in one request, larger files (up to 512 MiB)
|
|
959
|
+
* in parts of 16 MiB. `wait` (seconds, at most 100) holds the answer until the file is ready.
|
|
960
|
+
*/
|
|
961
|
+
upload(params: {
|
|
962
|
+
file: Blob | Uint8Array | ArrayBuffer | string;
|
|
963
|
+
name: string;
|
|
964
|
+
namespace: string;
|
|
965
|
+
user?: string;
|
|
966
|
+
id?: string;
|
|
967
|
+
type?: FileType;
|
|
968
|
+
metadata?: Metadata;
|
|
969
|
+
wait?: number;
|
|
970
|
+
}, options?: RequestOptions): Promise<FileQueued>;
|
|
971
|
+
/** The files `ids` of a namespace (and user), or, without ids, its first 100 files. */
|
|
972
|
+
status(params: {
|
|
973
|
+
namespace: string;
|
|
974
|
+
user?: string;
|
|
975
|
+
ids?: string[];
|
|
976
|
+
}, options?: RequestOptions): Promise<StoredFile[]>;
|
|
977
|
+
/** Parse a file again from its stored original. */
|
|
978
|
+
reparse(id: string, params: {
|
|
979
|
+
namespace: string;
|
|
980
|
+
user?: string;
|
|
981
|
+
wait?: number;
|
|
982
|
+
}, options?: RequestOptions): Promise<FileQueued>;
|
|
983
|
+
/**
|
|
984
|
+
* Wait until every file of `ids` is ready or failed (polling `status` every `interval` ms), at most
|
|
985
|
+
* `timeout` ms (10 minutes by default): the files as they ended, or a ConareError `timeout`.
|
|
986
|
+
*/
|
|
987
|
+
waitUntilReady(params: {
|
|
988
|
+
namespace: string;
|
|
989
|
+
user?: string;
|
|
990
|
+
ids: string[];
|
|
991
|
+
timeout?: number;
|
|
992
|
+
interval?: number;
|
|
993
|
+
}, options?: RequestOptions): Promise<StoredFile[]>;
|
|
994
|
+
}
|
|
712
995
|
export declare class Users {
|
|
713
996
|
private readonly client;
|
|
714
997
|
constructor(client: Conare);
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,60 @@
|
|
|
1
1
|
// conare: TypeScript client for the Conare API. Zero dependencies; uses global fetch.
|
|
2
|
-
export const VERSION = "0.
|
|
2
|
+
export const VERSION = "0.23.0";
|
|
3
3
|
const DEFAULT_BASE_URL = "https://api.conare.ai";
|
|
4
4
|
const BATCH_SIZE = 100;
|
|
5
|
+
// A JSON body this long or longer goes gzip-encoded: past the first ~14 KB a new connection may send,
|
|
6
|
+
// each doubling of the window costs a round trip, and JSON of documents is 3-4x smaller in gzip.
|
|
7
|
+
const GZIP_MIN_BYTES = 8 * 1024;
|
|
5
8
|
const CHECK_BATCH = 1000;
|
|
9
|
+
function toParse(body) {
|
|
10
|
+
if (body.state === "parsing")
|
|
11
|
+
return { id: body.id, state: "parsing" };
|
|
12
|
+
if (body.state === "failed")
|
|
13
|
+
return { id: body.id, state: "failed", error: body.error ?? { code: "unavailable", message: "the parse failed" } };
|
|
14
|
+
return {
|
|
15
|
+
id: body.id,
|
|
16
|
+
state: "done",
|
|
17
|
+
type: body.type,
|
|
18
|
+
name: body.name,
|
|
19
|
+
pages: body.pages ?? null,
|
|
20
|
+
markdown: body.markdown,
|
|
21
|
+
parts: body.parts,
|
|
22
|
+
withoutText: body.without_text,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/** The query parameters of `ParseOptions`. */
|
|
26
|
+
function parseQuery(options) {
|
|
27
|
+
return {
|
|
28
|
+
...(options.type ? { type: options.type } : {}),
|
|
29
|
+
...(options.pages ? { pages: options.pages } : {}),
|
|
30
|
+
...(options.password ? { password: options.password } : {}),
|
|
31
|
+
...(options.layout ? { layout: "true" } : {}),
|
|
32
|
+
...(options.wait === undefined ? {} : { wait: String(options.wait) }),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
6
35
|
function toFileUpload(body) {
|
|
36
|
+
const pending = body.ocr_pending ?? [];
|
|
7
37
|
return {
|
|
38
|
+
state: body.state ?? (pending.length > 0 ? "ocr" : "ready"),
|
|
39
|
+
sourceId: body.source_id ?? null,
|
|
40
|
+
withoutText: {
|
|
41
|
+
pages: body.without_text?.pages ?? body.pages_without_text ?? [],
|
|
42
|
+
slides: body.without_text?.slides ?? body.slides_without_text ?? [],
|
|
43
|
+
images: body.without_text?.images ?? body.images_without_text ?? [],
|
|
44
|
+
},
|
|
45
|
+
error: body.error ?? null,
|
|
8
46
|
fileId: body.file_id,
|
|
47
|
+
markdown: body.markdown ?? null,
|
|
48
|
+
parts: body.parts ?? [],
|
|
9
49
|
type: body.type,
|
|
10
50
|
ids: body.ids,
|
|
11
51
|
pages: body.pages ?? null,
|
|
12
52
|
sheets: body.sheets ?? null,
|
|
53
|
+
slides: body.slides ?? null,
|
|
54
|
+
slidesWithoutText: body.slides_without_text ?? [],
|
|
13
55
|
pagesOcr: body.pages_ocr ?? 0,
|
|
56
|
+
imagesOcr: body.images_ocr ?? 0,
|
|
57
|
+
imagesWithoutText: body.images_without_text ?? [],
|
|
14
58
|
pagesWithoutText: body.pages_without_text ?? [],
|
|
15
59
|
ocrPending: body.ocr_pending ?? [],
|
|
16
60
|
};
|
|
@@ -57,8 +101,26 @@ function queryBody(query, options) {
|
|
|
57
101
|
user: options.user,
|
|
58
102
|
user_prefix: options.userPrefix,
|
|
59
103
|
exclude_ids: options.excludeIds,
|
|
104
|
+
hops: options.hops,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** The largest file `files.upload` sends in one request; a larger one (up to 512 MiB) goes in parts. */
|
|
108
|
+
export const MAX_FILE_REQUEST_BYTES = 64 * 1024 * 1024;
|
|
109
|
+
function toStoredFile(f) {
|
|
110
|
+
return {
|
|
111
|
+
id: f.id, name: f.name, namespace: f.namespace, user: f.user, sourceId: f.source_id, type: f.type, declared: f.declared,
|
|
112
|
+
bytes: f.bytes, sha256: f.sha256, metadata: f.metadata ?? {}, state: f.state, pages: f.pages, pagesText: f.pages_text,
|
|
113
|
+
pagesOcr: f.pages_ocr, pagesWithoutText: f.pages_without_text ?? [], ocrPending: f.ocr_pending, ocrFailed: f.ocr_failed ?? [],
|
|
114
|
+
pagesUnreadable: f.pages_unreadable ?? [], documents: f.documents, rejected: f.rejected ?? [], locators: f.locators ?? [], chunksEmbedded: f.chunks_embedded ?? 0,
|
|
115
|
+
imagesWithoutText: f.images_without_text ?? [],
|
|
116
|
+
run: { id: f.run.id, kind: f.run.kind, state: f.run.state, phase: f.run.phase, error: f.run.error,
|
|
117
|
+
...(f.run.retry_at ? { retryAt: new Date(f.run.retry_at) } : {}) },
|
|
118
|
+
error: f.error ?? null, updatedAt: new Date(f.updated_at),
|
|
60
119
|
};
|
|
61
120
|
}
|
|
121
|
+
function toFileQueued(body) {
|
|
122
|
+
return { ...(body.result ? { result: body.result } : {}), file: toStoredFile(body.file), ...(body.run ? { run: toRun(body.run) } : {}) };
|
|
123
|
+
}
|
|
62
124
|
// ---- Client ----------------------------------------------------------------
|
|
63
125
|
/**
|
|
64
126
|
* The Conare client.
|
|
@@ -73,6 +135,8 @@ export class Conare {
|
|
|
73
135
|
runs;
|
|
74
136
|
/** Files of documents written into a custom source. */
|
|
75
137
|
imports;
|
|
138
|
+
/** Files (PDF, Word, PowerPoint, Excel, CSV, text, images) kept as documents, a page each. */
|
|
139
|
+
files;
|
|
76
140
|
/** Delete everything Conare holds of one of your users. */
|
|
77
141
|
users;
|
|
78
142
|
/** What changed, in order. */
|
|
@@ -83,6 +147,7 @@ export class Conare {
|
|
|
83
147
|
timeout;
|
|
84
148
|
maxRetries;
|
|
85
149
|
fetchFn;
|
|
150
|
+
gzip;
|
|
86
151
|
constructor(options = {}) {
|
|
87
152
|
const apiKey = options.apiKey ?? env("CONARE_API_KEY");
|
|
88
153
|
if (!apiKey) {
|
|
@@ -99,9 +164,11 @@ export class Conare {
|
|
|
99
164
|
this.maxRetries = options.maxRetries ?? 2;
|
|
100
165
|
this.fetchFn = options.fetch ?? ((url, init) => fetch(url, init));
|
|
101
166
|
this.organization = options.organization || undefined;
|
|
167
|
+
this.gzip = (options.gzip ?? true) && typeof CompressionStream !== "undefined";
|
|
102
168
|
this.sources = new Sources(this);
|
|
103
169
|
this.runs = new Runs(this);
|
|
104
170
|
this.imports = new Imports(this);
|
|
171
|
+
this.files = new Files(this);
|
|
105
172
|
this.users = new Users(this);
|
|
106
173
|
this.events = new Events(this);
|
|
107
174
|
}
|
|
@@ -151,6 +218,21 @@ export class Conare {
|
|
|
151
218
|
const results = body.results.map((r) => ({ index: r.index, score: r.score, document: documents[r.index] ?? "" }));
|
|
152
219
|
return Object.assign(results, { unscored: body.unscored ?? [] });
|
|
153
220
|
}
|
|
221
|
+
/**
|
|
222
|
+
* Parses a file to Markdown and stores nothing: the same parser, options and result as `uploadFile`.
|
|
223
|
+
* `file` is its bytes, or `{ url }` (an https URL on a public address, fetched by the API). A file OCR
|
|
224
|
+
* reads answers once OCR is done within `wait` seconds (default 60), else `{ id, state: "parsing" }`:
|
|
225
|
+
* `getParse(id)` answers the result (kept 24 hours). Any API key can parse, a models-only key too.
|
|
226
|
+
*/
|
|
227
|
+
async parse(file, options = {}) {
|
|
228
|
+
const query = new URLSearchParams({ ...(options.name ? { name: options.name } : {}), ...parseQuery(options) });
|
|
229
|
+
const body = await this.request("POST", `/parse?${query}`, file, { timeout: 120_000, ...options });
|
|
230
|
+
return toParse(body);
|
|
231
|
+
}
|
|
232
|
+
/** A parse that answered `state: "parsing"`: still parsing, done with its result, or failed. 404 `parse_not_found` after 24 hours. */
|
|
233
|
+
async getParse(id, options) {
|
|
234
|
+
return toParse(await this.request("GET", `/parse/${segment(id)}`, undefined, options));
|
|
235
|
+
}
|
|
154
236
|
/**
|
|
155
237
|
* @internal Sends one API request. Every request but a GET carries an `Idempotency-Key` (the
|
|
156
238
|
* caller's, or one made here), the same on each of its attempts: the API answers a repeat with
|
|
@@ -198,22 +280,33 @@ export class Conare {
|
|
|
198
280
|
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
199
281
|
if (options.signal?.aborted)
|
|
200
282
|
controller.abort();
|
|
201
|
-
// A file (uploadFile) goes as its bytes; everything else as JSON.
|
|
283
|
+
// A file (uploadFile) goes as its bytes; everything else as JSON, gzip-encoded when long.
|
|
202
284
|
const raw = body instanceof Uint8Array || body instanceof ArrayBuffer || (typeof Blob !== "undefined" && body instanceof Blob);
|
|
285
|
+
const json = body === undefined || raw ? undefined : JSON.stringify(body);
|
|
203
286
|
try {
|
|
204
|
-
const
|
|
287
|
+
const attempt = async (zipped) => this.fetchFn(this.baseURL + path, {
|
|
205
288
|
method,
|
|
206
289
|
headers: {
|
|
207
290
|
Authorization: `Bearer ${this.apiKey}`,
|
|
208
291
|
Accept: "application/json",
|
|
209
292
|
...(body === undefined ? {} : { "Content-Type": raw ? "application/octet-stream" : "application/json" }),
|
|
293
|
+
...(zipped === undefined ? {} : { "Content-Encoding": "gzip" }),
|
|
210
294
|
...(idempotencyKey === undefined ? {} : { "Idempotency-Key": idempotencyKey }),
|
|
211
295
|
...(this.organization === undefined ? {} : { "X-Conare-Org": this.organization }),
|
|
212
296
|
...extra,
|
|
213
297
|
},
|
|
214
|
-
body:
|
|
298
|
+
body: zipped ?? (raw ? body : json),
|
|
215
299
|
signal: controller.signal,
|
|
216
300
|
});
|
|
301
|
+
const zipped = this.gzip && json !== undefined && json.length >= GZIP_MIN_BYTES ? await gzipText(json) : undefined;
|
|
302
|
+
let res = await attempt(zipped);
|
|
303
|
+
if (zipped !== undefined && (res.status === 400 || res.status === 415)) {
|
|
304
|
+
// A server without gzip (a self-managed install before it) read the bytes as JSON.
|
|
305
|
+
await res.body?.cancel();
|
|
306
|
+
res = await attempt(undefined);
|
|
307
|
+
if (res.ok)
|
|
308
|
+
this.gzip = false;
|
|
309
|
+
}
|
|
217
310
|
return [res, await res.text()];
|
|
218
311
|
}
|
|
219
312
|
catch (err) {
|
|
@@ -230,6 +323,10 @@ export class Conare {
|
|
|
230
323
|
}
|
|
231
324
|
}
|
|
232
325
|
}
|
|
326
|
+
async function gzipText(text) {
|
|
327
|
+
const stream = new Blob([text]).stream().pipeThrough(new CompressionStream("gzip"));
|
|
328
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
329
|
+
}
|
|
233
330
|
// ---- Namespace -------------------------------------------------------------
|
|
234
331
|
/** One namespace: a named set of documents, e.g. "docs" or "user-42". */
|
|
235
332
|
export class Namespace {
|
|
@@ -301,23 +398,31 @@ export class Namespace {
|
|
|
301
398
|
return out;
|
|
302
399
|
}
|
|
303
400
|
/**
|
|
304
|
-
* Store a PDF
|
|
305
|
-
*
|
|
306
|
-
*
|
|
401
|
+
* Store a PDF, a Word document (.docx), a PowerPoint deck (.pptx), an Excel workbook (.xlsx), a CSV or
|
|
402
|
+
* TSV, a text or Markdown file, or an image (PNG, JPEG, WebP, TIFF), at most 20 MiB. Say its type with
|
|
403
|
+
* `type`: it is read as that type, and bytes of another type are refused (415) rather than misread;
|
|
404
|
+
* without it the type comes from the bytes, then the name. One document per PDF page with a text
|
|
405
|
+
* layer (`<fileId>:page-3`), per image page (read by OCR), a CSV as Markdown tables with its header
|
|
406
|
+
* on every part and the rows each holds in `rows` metadata, a Word document as
|
|
407
|
+
* Markdown (`<fileId>:part-1`, more parts past 240 KiB), one per slide with text (`<fileId>:slide-2`:
|
|
408
|
+
* title, shapes in reading order, tables, speaker notes) and Markdown tables per worksheet
|
|
409
|
+
* (`<fileId>:Sheet1-1`), each with `file`, `file_id`, `file_type` and `page`, `part`, `slide` or
|
|
410
|
+
* `sheet` metadata. Slides with no text are listed in `slidesWithoutText`. `fileId` defaults to the
|
|
307
411
|
* name in id characters (a name with characters outside ASCII also gets 8 hex digits of its hash, so
|
|
308
412
|
* 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.
|
|
310
|
-
*
|
|
311
|
-
*
|
|
312
|
-
*
|
|
413
|
+
* uploads of one id run one at a time. The answer also holds what `parse` answers (`markdown`, `parts`,
|
|
414
|
+
* `withoutText`), and takes its options (`pages`, `password`, `layout`, `wait`). Pages with something on them
|
|
415
|
+
* are read by OCR: the answer waits `wait` seconds for it (default 60); pages it still reads then are in
|
|
416
|
+
* `ocrPending` (`state: "ocr"`, stored within about a minute; `wait: false` answers once the text layers are
|
|
417
|
+
* stored). Pages with no text even then are listed in `withoutText.pages` and not stored. Any file up to 512 MiB
|
|
418
|
+
* goes in this one call: one over 20 MiB, or with more than 100 pages for OCR, is read in the background and
|
|
419
|
+
* answers `state` `queued` or `parsing` (follow it with `getFile`), or `ready` once done within `wait`.
|
|
313
420
|
*/
|
|
314
421
|
async uploadFile(file, name, options = {}) {
|
|
315
|
-
const query = new URLSearchParams({
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
});
|
|
320
|
-
const body = await this.client.request("POST", this.path(`/files?${query}`), file, { timeout: 120_000, ...options });
|
|
422
|
+
const query = new URLSearchParams({ name, ...(options.id ? { id: options.id } : {}), ...parseQuery(options) });
|
|
423
|
+
const waitS = typeof options.wait === "number" ? options.wait : options.wait === false ? 0 : 60;
|
|
424
|
+
const timeout = Math.max(120_000, waitS * 1000 + 60_000);
|
|
425
|
+
const body = await this.client.request("POST", this.path(`/files?${query}`), file, { timeout, ...options });
|
|
321
426
|
return toFileUpload(body);
|
|
322
427
|
}
|
|
323
428
|
/**
|
|
@@ -332,7 +437,7 @@ export class Namespace {
|
|
|
332
437
|
/**
|
|
333
438
|
* Hybrid search, reranked. One result per document: its best passage; `topK` documents when that
|
|
334
439
|
* 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-
|
|
440
|
+
* retrievers run as listed, also on a vector-only custom model). `rerankDepth` (1-1000) is how many of the
|
|
336
441
|
* first passages the reranker ranks; unset, the first 20. `user` keeps the search to one user's documents and
|
|
337
442
|
* `userPrefix` (ending in `:`) to a group's; both combine with `filter`. An empty `user` or
|
|
338
443
|
* `userPrefix` is a 400, never "every user". `excludeIds` keeps those documents out.
|
|
@@ -416,9 +521,16 @@ export class Namespace {
|
|
|
416
521
|
return deleted;
|
|
417
522
|
}
|
|
418
523
|
}
|
|
419
|
-
/**
|
|
420
|
-
|
|
421
|
-
|
|
524
|
+
/**
|
|
525
|
+
* Delete the namespace and every document in it, with its files source (the one `files.upload` makes). Succeeds
|
|
526
|
+
* as well when it was already deleted or emptied; throws ConareError 404 `namespace_not_found` for a name never
|
|
527
|
+
* written, and 409 `namespace_has_sources` while another source (an app, a custom or a Cloud Storage source)
|
|
528
|
+
* writes into it, unless `force: true`, which deletes those sources too. Answers the ids of the sources deleted.
|
|
529
|
+
*/
|
|
530
|
+
async drop(options = {}) {
|
|
531
|
+
const { force, ...rest } = options;
|
|
532
|
+
const body = await this.client.request("DELETE", this.path(force ? "?force=true" : ""), undefined, rest);
|
|
533
|
+
return { sourcesDeleted: body?.sources_deleted ?? [] };
|
|
422
534
|
}
|
|
423
535
|
}
|
|
424
536
|
// ---- Sources ---------------------------------------------------------------
|
|
@@ -661,13 +773,95 @@ export class Imports {
|
|
|
661
773
|
const key = options.idempotencyKey;
|
|
662
774
|
for (let n = 1; n <= upload.parts; n++) {
|
|
663
775
|
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":
|
|
776
|
+
await this.client.request("PUT", `/uploads/${segment(upload.id)}/parts/${n}`, part, { timeout: 300_000, ...options, idempotencyKey: stepKey(key, `part-${n}`) }, { "Content-MD5": contentMd5(part) });
|
|
665
777
|
}
|
|
666
778
|
await this.client.request("POST", `/uploads/${segment(upload.id)}/complete`, { purpose: "import" }, { ...options, idempotencyKey: stepKey(key, "complete") });
|
|
667
779
|
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
780
|
return toRun(body.run);
|
|
669
781
|
}
|
|
670
782
|
}
|
|
783
|
+
export class Files {
|
|
784
|
+
client;
|
|
785
|
+
constructor(client) {
|
|
786
|
+
this.client = client;
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* Upload a file: it is stored and parsed in the background into a document per page, sheet part,
|
|
790
|
+
* slide or Word part, each citing where it came from; pages without text are read by OCR. Declare
|
|
791
|
+
* its `type` when you know it: it is then parsed as that type, and bytes of another type are a
|
|
792
|
+
* ConareError 415 `type_mismatch`. Up to 64 MiB goes in one request, larger files (up to 512 MiB)
|
|
793
|
+
* in parts of 16 MiB. `wait` (seconds, at most 100) holds the answer until the file is ready.
|
|
794
|
+
*/
|
|
795
|
+
async upload(params, options = {}) {
|
|
796
|
+
const f = params.file;
|
|
797
|
+
const bytes = typeof f === "string"
|
|
798
|
+
? new TextEncoder().encode(f)
|
|
799
|
+
: f instanceof Uint8Array
|
|
800
|
+
? f
|
|
801
|
+
: f instanceof ArrayBuffer
|
|
802
|
+
? new Uint8Array(f)
|
|
803
|
+
: new Uint8Array(await f.arrayBuffer());
|
|
804
|
+
const timeout = options.timeout ?? 300_000;
|
|
805
|
+
if (bytes.length <= MAX_FILE_REQUEST_BYTES) {
|
|
806
|
+
const q = new URLSearchParams({ namespace: params.namespace, name: params.name });
|
|
807
|
+
if (params.user)
|
|
808
|
+
q.set("user", params.user);
|
|
809
|
+
if (params.id)
|
|
810
|
+
q.set("id", params.id);
|
|
811
|
+
if (params.type)
|
|
812
|
+
q.set("type", params.type);
|
|
813
|
+
if (params.metadata)
|
|
814
|
+
q.set("metadata", JSON.stringify(params.metadata));
|
|
815
|
+
if (params.wait !== undefined)
|
|
816
|
+
q.set("wait", String(params.wait));
|
|
817
|
+
return toFileQueued(await this.client.request("POST", `/files?${q}`, bytes, { ...options, timeout }));
|
|
818
|
+
}
|
|
819
|
+
const upload = await this.client.request("POST", "/uploads", { bytes: bytes.length, filename: params.name, purpose: "file" }, options);
|
|
820
|
+
const key = options.idempotencyKey;
|
|
821
|
+
for (let n = 1; n <= upload.parts; n++) {
|
|
822
|
+
const part = bytes.subarray((n - 1) * upload.part_size, n * upload.part_size);
|
|
823
|
+
await this.client.request("PUT", `/uploads/${segment(upload.id)}/parts/${n}`, part, { timeout: 300_000, ...options, idempotencyKey: stepKey(key, `part-${n}`) }, { "Content-MD5": contentMd5(part) });
|
|
824
|
+
}
|
|
825
|
+
return toFileQueued(await this.client.request("POST", `/uploads/${segment(upload.id)}/complete`, { purpose: "file", namespace: params.namespace, user: params.user, id: params.id, type: params.type, name: params.name,
|
|
826
|
+
metadata: params.metadata, wait: params.wait }, { ...options, timeout, idempotencyKey: stepKey(key, "complete") }));
|
|
827
|
+
}
|
|
828
|
+
/** The files `ids` of a namespace (and user), or, without ids, its first 100 files. */
|
|
829
|
+
async status(params, options = {}) {
|
|
830
|
+
const q = new URLSearchParams({ namespace: params.namespace });
|
|
831
|
+
if (params.user)
|
|
832
|
+
q.set("user", params.user);
|
|
833
|
+
if (params.ids)
|
|
834
|
+
q.set("ids", params.ids.join(","));
|
|
835
|
+
else
|
|
836
|
+
q.set("limit", "100");
|
|
837
|
+
const body = await this.client.request("GET", `/files/status?${q}`, undefined, options);
|
|
838
|
+
return body.data.map(toStoredFile);
|
|
839
|
+
}
|
|
840
|
+
/** Parse a file again from its stored original. */
|
|
841
|
+
async reparse(id, params, options = {}) {
|
|
842
|
+
const q = new URLSearchParams({ namespace: params.namespace });
|
|
843
|
+
if (params.user)
|
|
844
|
+
q.set("user", params.user);
|
|
845
|
+
if (params.wait !== undefined)
|
|
846
|
+
q.set("wait", String(params.wait));
|
|
847
|
+
return toFileQueued(await this.client.request("POST", `/files/${segment(id)}/reparse?${q}`, undefined, { timeout: 300_000, ...options }));
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Wait until every file of `ids` is ready or failed (polling `status` every `interval` ms), at most
|
|
851
|
+
* `timeout` ms (10 minutes by default): the files as they ended, or a ConareError `timeout`.
|
|
852
|
+
*/
|
|
853
|
+
async waitUntilReady(params, options = {}) {
|
|
854
|
+
const deadline = Date.now() + (params.timeout ?? 600_000);
|
|
855
|
+
for (;;) {
|
|
856
|
+
const files = await this.status(params, options);
|
|
857
|
+
if (files.length === params.ids.length && files.every((f) => f.state === "ready" || f.state === "failed"))
|
|
858
|
+
return files;
|
|
859
|
+
if (Date.now() >= deadline)
|
|
860
|
+
throw new ConareError(0, "timeout", `Files still parsing after ${params.timeout ?? 600_000} ms.`);
|
|
861
|
+
await sleep(params.interval ?? 2_000, options.signal);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
671
865
|
export class Users {
|
|
672
866
|
client;
|
|
673
867
|
constructor(client) {
|
|
@@ -819,7 +1013,20 @@ function base64(bytes) {
|
|
|
819
1013
|
bin += String.fromCharCode(b);
|
|
820
1014
|
return btoa(bin);
|
|
821
1015
|
}
|
|
822
|
-
|
|
1016
|
+
let nodeCrypto;
|
|
1017
|
+
function contentMd5(data) {
|
|
1018
|
+
if (nodeCrypto === undefined) {
|
|
1019
|
+
try {
|
|
1020
|
+
const p = globalThis.process;
|
|
1021
|
+
nodeCrypto = p?.getBuiltinModule?.("node:crypto") ?? null;
|
|
1022
|
+
}
|
|
1023
|
+
catch {
|
|
1024
|
+
nodeCrypto = null;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
return nodeCrypto ? nodeCrypto.createHash("md5").update(data).digest("base64") : base64(md5(data));
|
|
1028
|
+
}
|
|
1029
|
+
// MD5 (RFC 1321) in JS, for runtimes without node:crypto.
|
|
823
1030
|
const MD5_S = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
|
|
824
1031
|
const MD5_K = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0);
|
|
825
1032
|
function md5(data) {
|
|
@@ -836,18 +1043,29 @@ function md5(data) {
|
|
|
836
1043
|
m[j] = view.getUint32(off + j * 4, true);
|
|
837
1044
|
let a = a0, b = b0, c = c0, d = d0;
|
|
838
1045
|
for (let i = 0; i < 64; i++) {
|
|
1046
|
+
// Plain assignments: destructuring allocates two arrays a round.
|
|
839
1047
|
let f, g;
|
|
840
|
-
if (i < 16)
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
else if (i <
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
1048
|
+
if (i < 16) {
|
|
1049
|
+
f = (b & c) | (~b & d);
|
|
1050
|
+
g = i;
|
|
1051
|
+
}
|
|
1052
|
+
else if (i < 32) {
|
|
1053
|
+
f = (d & b) | (~d & c);
|
|
1054
|
+
g = (5 * i + 1) % 16;
|
|
1055
|
+
}
|
|
1056
|
+
else if (i < 48) {
|
|
1057
|
+
f = b ^ c ^ d;
|
|
1058
|
+
g = (3 * i + 5) % 16;
|
|
1059
|
+
}
|
|
1060
|
+
else {
|
|
1061
|
+
f = c ^ (b | ~d);
|
|
1062
|
+
g = (7 * i) % 16;
|
|
1063
|
+
}
|
|
848
1064
|
const sum = (a + f + MD5_K[i] + m[g]) >>> 0;
|
|
849
1065
|
const shift = MD5_S[(i >> 4) * 4 + (i % 4)];
|
|
850
|
-
|
|
1066
|
+
a = d;
|
|
1067
|
+
d = c;
|
|
1068
|
+
c = b;
|
|
851
1069
|
b = (b + ((sum << shift) | (sum >>> (32 - shift)))) >>> 0;
|
|
852
1070
|
}
|
|
853
1071
|
a0 = (a0 + a) >>> 0;
|
|
@@ -942,11 +1160,16 @@ function sleep(ms, signal) {
|
|
|
942
1160
|
return new Promise((resolve, reject) => {
|
|
943
1161
|
if (signal?.aborted)
|
|
944
1162
|
return reject(signal.reason);
|
|
945
|
-
const
|
|
946
|
-
signal?.addEventListener("abort", () => {
|
|
1163
|
+
const onAbort = () => {
|
|
947
1164
|
clearTimeout(timer);
|
|
948
1165
|
reject(signal.reason);
|
|
949
|
-
}
|
|
1166
|
+
};
|
|
1167
|
+
// The caller's signal may live for the whole process: its listener goes when the timer fires.
|
|
1168
|
+
const timer = setTimeout(() => {
|
|
1169
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1170
|
+
resolve();
|
|
1171
|
+
}, ms);
|
|
1172
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
950
1173
|
});
|
|
951
1174
|
}
|
|
952
1175
|
function env(name) {
|