conare 0.22.0 → 0.23.1
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 +14 -0
- package/dist/cli/github/sync.js +34 -3
- package/dist/cli/scrub.js +12 -0
- package/dist/index.d.ts +167 -12
- package/dist/index.js +101 -19
- 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.
|
|
@@ -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
|
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;
|
|
@@ -54,8 +59,20 @@ export async function syncRepo(opts) {
|
|
|
54
59
|
for (const ns of [opts.namespaces.github, opts.namespaces.docs])
|
|
55
60
|
await refuseOtherRepo(ns, info.full_name);
|
|
56
61
|
// ---- threads ----
|
|
57
|
-
|
|
58
|
-
|
|
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
|
+
}
|
|
59
76
|
report.threads.changed = issues.length;
|
|
60
77
|
log(`${repo}: ${issues.length} threads ${since ? `updated since ${since}` : "(first run)"}`);
|
|
61
78
|
const comments = await threadComments(gh, repo, issues, !since || issues.length > PER_THREAD_LIMIT);
|
|
@@ -66,7 +83,7 @@ export async function syncRepo(opts) {
|
|
|
66
83
|
report.threads.failed = threadResult.rejected.length;
|
|
67
84
|
report.rejected.push(...threadResult.rejected);
|
|
68
85
|
if (threadResult.rejected.length === 0 && issues.length > 0) {
|
|
69
|
-
next
|
|
86
|
+
next[mark] = issues.reduce((max, i) => (i.updated_at > max ? i.updated_at : max), since ?? "");
|
|
70
87
|
}
|
|
71
88
|
// ---- docs ----
|
|
72
89
|
const head = await gh.json(`/repos/${repo}/git/ref/heads/${encodeURIComponent(info.default_branch)}`);
|
|
@@ -163,6 +180,20 @@ async function refuseOtherRepo(ns, fullName) {
|
|
|
163
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.`);
|
|
164
181
|
}
|
|
165
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
|
+
}
|
|
166
197
|
/** One entry per thread number, its newest version (a thread updated mid-listing can appear twice). */
|
|
167
198
|
export function latestPerThread(issues) {
|
|
168
199
|
const byNumber = new Map();
|
package/dist/cli/scrub.js
CHANGED
|
@@ -39,7 +39,19 @@ const RULES = [
|
|
|
39
39
|
re: /\bsk-[A-Za-z0-9][A-Za-z0-9_-]{19,}/g,
|
|
40
40
|
accept: (s) => hasDigit(s) && (/[A-Z]/.test(s) || s.length >= 35),
|
|
41
41
|
},
|
|
42
|
+
// Stripe and WorkOS secret and restricted keys (sk_live_, sk_test_, rk_…), Stripe webhook secrets.
|
|
43
|
+
{ kind: "api_key", re: /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{20,}/g, accept: hasDigit },
|
|
44
|
+
{ kind: "webhook_secret", re: /\bwhsec_[A-Za-z0-9+/=]{24,}/g, accept: hasDigit },
|
|
42
45
|
{ kind: "github_token", re: /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})/g },
|
|
46
|
+
{ kind: "gitlab_token", re: /\bglpat-[A-Za-z0-9_-]{20,}/g },
|
|
47
|
+
{ kind: "npm_token", re: /\bnpm_[A-Za-z0-9]{36}\b/g, accept: hasDigit },
|
|
48
|
+
{ kind: "pypi_token", re: /\bpypi-AgE[A-Za-z0-9_-]{50,}/g },
|
|
49
|
+
{ kind: "sendgrid_key", re: /\bSG\.[A-Za-z0-9_-]{20,24}\.[A-Za-z0-9_-]{40,46}/g },
|
|
50
|
+
// Google OAuth access tokens (ya29.…) and refresh tokens (1//0…).
|
|
51
|
+
{ kind: "google_oauth_token", re: /\bya29\.[A-Za-z0-9_-]{20,}/g },
|
|
52
|
+
{ kind: "google_oauth_token", re: /(?<![\w/])1\/\/0[A-Za-z0-9_-]{30,}/g },
|
|
53
|
+
// A GCP service-account key file's private_key_id (40 hex); its private_key is a PEM block.
|
|
54
|
+
{ kind: "private_key_id", re: /(\bprivate_key_id["']?\s*[:=]\s*["']?)([a-f0-9]{40})\b/g, label: true },
|
|
43
55
|
{ kind: "aws_access_key", re: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g },
|
|
44
56
|
{ kind: "slack_token", re: /\bxox[abposr]-[A-Za-z0-9-]{10,}/g },
|
|
45
57
|
{ kind: "google_api_key", re: /\bAIza[0-9A-Za-z_-]{35}/g },
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const VERSION = "0.
|
|
1
|
+
export declare const VERSION = "0.23.1";
|
|
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>;
|
|
@@ -71,10 +71,109 @@ export interface WriteResult {
|
|
|
71
71
|
storedSeq?: number;
|
|
72
72
|
}
|
|
73
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";
|
|
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
|
+
}
|
|
75
170
|
/** What `uploadFile` stored. */
|
|
76
171
|
export interface FileUpload {
|
|
77
172
|
fileId: string;
|
|
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[];
|
|
78
177
|
/** The type it was read as: an image of any format is `image`. */
|
|
79
178
|
type: "pdf" | "xlsx" | "docx" | "pptx" | "csv" | "tsv" | "txt" | "md" | "image";
|
|
80
179
|
/** The documents it made, in reading order. */
|
|
@@ -91,6 +190,8 @@ export interface FileUpload {
|
|
|
91
190
|
pagesOcr: number;
|
|
92
191
|
/** Pictures of a Word document or deck read by OCR before the answer (`wait: true`), each a document of its own. */
|
|
93
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[];
|
|
94
195
|
/** PDF pages with no text even after OCR (blank, or OCR could not read them): not stored. */
|
|
95
196
|
pagesWithoutText: number[];
|
|
96
197
|
/**
|
|
@@ -98,6 +199,21 @@ export interface FileUpload {
|
|
|
98
199
|
* `getFile(fileId)` says when OCR ended and which of them it could not read.
|
|
99
200
|
*/
|
|
100
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;
|
|
101
217
|
}
|
|
102
218
|
/** What `getFile` reads: an upload's outcome, with OCR after the answer folded in as it ends. */
|
|
103
219
|
export interface FileStatus extends FileUpload {
|
|
@@ -152,6 +268,8 @@ export interface QueryOptions extends RequestOptions {
|
|
|
152
268
|
userPrefix?: string;
|
|
153
269
|
/** Documents (ids) no result may be: up to 10,000. */
|
|
154
270
|
excludeIds?: string[];
|
|
271
|
+
/** 2 searches again from the best results, for answers that span documents (not with `queryPages`). */
|
|
272
|
+
hops?: 1 | 2;
|
|
155
273
|
}
|
|
156
274
|
/** One page of `Namespace.queryPages`. */
|
|
157
275
|
export interface QueryPage {
|
|
@@ -368,6 +486,12 @@ export interface ConareOptions {
|
|
|
368
486
|
* be its own. Make one client per organization.
|
|
369
487
|
*/
|
|
370
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;
|
|
371
495
|
}
|
|
372
496
|
/** An organization the key acts for (`organizations()`). */
|
|
373
497
|
export interface Organization {
|
|
@@ -425,12 +549,17 @@ export interface StoredFile {
|
|
|
425
549
|
pagesText: number;
|
|
426
550
|
/** Pages read by OCR with text. */
|
|
427
551
|
pagesOcr: number;
|
|
428
|
-
/**
|
|
552
|
+
/** Every page this parse stored no text for: blank, read as empty, unreadable, or without a text layer and not read by OCR. */
|
|
429
553
|
pagesWithoutText: number[];
|
|
430
554
|
/** Pages waiting for OCR. */
|
|
431
555
|
ocrPending: number;
|
|
432
556
|
/** Pages OCR could not read after its retries; each keeps what an earlier upload stored for it. */
|
|
433
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
|
+
}[];
|
|
434
563
|
documents: number;
|
|
435
564
|
/** Parts the write refused, each with why. */
|
|
436
565
|
rejected: {
|
|
@@ -440,6 +569,8 @@ export interface StoredFile {
|
|
|
440
569
|
}[];
|
|
441
570
|
/** The locator fields its documents carry: page, sheet, rows, slide, heading, part, frame. */
|
|
442
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[];
|
|
443
574
|
chunksEmbedded: number;
|
|
444
575
|
/** The file's latest parse. */
|
|
445
576
|
run: {
|
|
@@ -491,6 +622,7 @@ export declare class Conare {
|
|
|
491
622
|
private readonly timeout;
|
|
492
623
|
private readonly maxRetries;
|
|
493
624
|
private readonly fetchFn;
|
|
625
|
+
private gzip;
|
|
494
626
|
constructor(options?: ConareOptions);
|
|
495
627
|
/** A handle to one namespace. Nothing is sent until you call a method; the first write creates it. */
|
|
496
628
|
namespace(name: string): Namespace;
|
|
@@ -525,6 +657,19 @@ export declare class Conare {
|
|
|
525
657
|
rerank(query: string, documents: string[], options?: RequestOptions & {
|
|
526
658
|
topK?: number;
|
|
527
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>;
|
|
528
673
|
private send;
|
|
529
674
|
}
|
|
530
675
|
/** One namespace: a named set of documents, e.g. "docs" or "user-42". */
|
|
@@ -572,15 +717,16 @@ export declare class Namespace {
|
|
|
572
717
|
* `sheet` metadata. Slides with no text are listed in `slidesWithoutText`. `fileId` defaults to the
|
|
573
718
|
* name in id characters (a name with characters outside ASCII also gets 8 hex digits of its hash, so
|
|
574
719
|
* such names do not collide); uploading the same one again replaces every document it made, and two
|
|
575
|
-
* uploads of one id run one at a time.
|
|
576
|
-
*
|
|
577
|
-
*
|
|
578
|
-
*
|
|
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`.
|
|
579
727
|
*/
|
|
580
|
-
uploadFile(file: Blob | Uint8Array | ArrayBuffer, name: string, options?: RequestOptions & {
|
|
728
|
+
uploadFile(file: Blob | Uint8Array | ArrayBuffer, name: string, options?: RequestOptions & ParseOptions & {
|
|
581
729
|
id?: string;
|
|
582
|
-
wait?: boolean;
|
|
583
|
-
type?: FileType;
|
|
584
730
|
}): Promise<FileUpload>;
|
|
585
731
|
/**
|
|
586
732
|
* An upload's outcome: the last upload of `fileId` here in the last 7 days. While OCR reads after the
|
|
@@ -623,8 +769,17 @@ export declare class Namespace {
|
|
|
623
769
|
deleteMany(ids: string[], options?: RequestOptions): Promise<number>;
|
|
624
770
|
/** Delete every document matching filter (at least one condition), calling until none match. Returns how many were deleted. */
|
|
625
771
|
deleteWhere(filter: Filter, options?: RequestOptions): Promise<number>;
|
|
626
|
-
/**
|
|
627
|
-
|
|
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
|
+
}>;
|
|
628
783
|
}
|
|
629
784
|
/** Apps connected through Conare that keep syncing into a namespace, and custom sources you push to. */
|
|
630
785
|
export declare class Sources {
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,51 @@
|
|
|
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.1";
|
|
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,
|
|
@@ -14,6 +54,7 @@ function toFileUpload(body) {
|
|
|
14
54
|
slidesWithoutText: body.slides_without_text ?? [],
|
|
15
55
|
pagesOcr: body.pages_ocr ?? 0,
|
|
16
56
|
imagesOcr: body.images_ocr ?? 0,
|
|
57
|
+
imagesWithoutText: body.images_without_text ?? [],
|
|
17
58
|
pagesWithoutText: body.pages_without_text ?? [],
|
|
18
59
|
ocrPending: body.ocr_pending ?? [],
|
|
19
60
|
};
|
|
@@ -60,6 +101,7 @@ function queryBody(query, options) {
|
|
|
60
101
|
user: options.user,
|
|
61
102
|
user_prefix: options.userPrefix,
|
|
62
103
|
exclude_ids: options.excludeIds,
|
|
104
|
+
hops: options.hops,
|
|
63
105
|
};
|
|
64
106
|
}
|
|
65
107
|
/** The largest file `files.upload` sends in one request; a larger one (up to 512 MiB) goes in parts. */
|
|
@@ -69,7 +111,8 @@ function toStoredFile(f) {
|
|
|
69
111
|
id: f.id, name: f.name, namespace: f.namespace, user: f.user, sourceId: f.source_id, type: f.type, declared: f.declared,
|
|
70
112
|
bytes: f.bytes, sha256: f.sha256, metadata: f.metadata ?? {}, state: f.state, pages: f.pages, pagesText: f.pages_text,
|
|
71
113
|
pagesOcr: f.pages_ocr, pagesWithoutText: f.pages_without_text ?? [], ocrPending: f.ocr_pending, ocrFailed: f.ocr_failed ?? [],
|
|
72
|
-
documents: f.documents, rejected: f.rejected ?? [], locators: f.locators ?? [], chunksEmbedded: f.chunks_embedded ?? 0,
|
|
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 ?? [],
|
|
73
116
|
run: { id: f.run.id, kind: f.run.kind, state: f.run.state, phase: f.run.phase, error: f.run.error,
|
|
74
117
|
...(f.run.retry_at ? { retryAt: new Date(f.run.retry_at) } : {}) },
|
|
75
118
|
error: f.error ?? null, updatedAt: new Date(f.updated_at),
|
|
@@ -104,6 +147,7 @@ export class Conare {
|
|
|
104
147
|
timeout;
|
|
105
148
|
maxRetries;
|
|
106
149
|
fetchFn;
|
|
150
|
+
gzip;
|
|
107
151
|
constructor(options = {}) {
|
|
108
152
|
const apiKey = options.apiKey ?? env("CONARE_API_KEY");
|
|
109
153
|
if (!apiKey) {
|
|
@@ -120,6 +164,7 @@ export class Conare {
|
|
|
120
164
|
this.maxRetries = options.maxRetries ?? 2;
|
|
121
165
|
this.fetchFn = options.fetch ?? ((url, init) => fetch(url, init));
|
|
122
166
|
this.organization = options.organization || undefined;
|
|
167
|
+
this.gzip = (options.gzip ?? true) && typeof CompressionStream !== "undefined";
|
|
123
168
|
this.sources = new Sources(this);
|
|
124
169
|
this.runs = new Runs(this);
|
|
125
170
|
this.imports = new Imports(this);
|
|
@@ -173,6 +218,21 @@ export class Conare {
|
|
|
173
218
|
const results = body.results.map((r) => ({ index: r.index, score: r.score, document: documents[r.index] ?? "" }));
|
|
174
219
|
return Object.assign(results, { unscored: body.unscored ?? [] });
|
|
175
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
|
+
}
|
|
176
236
|
/**
|
|
177
237
|
* @internal Sends one API request. Every request but a GET carries an `Idempotency-Key` (the
|
|
178
238
|
* caller's, or one made here), the same on each of its attempts: the API answers a repeat with
|
|
@@ -220,22 +280,33 @@ export class Conare {
|
|
|
220
280
|
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
221
281
|
if (options.signal?.aborted)
|
|
222
282
|
controller.abort();
|
|
223
|
-
// 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.
|
|
224
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);
|
|
225
286
|
try {
|
|
226
|
-
const
|
|
287
|
+
const attempt = async (zipped) => this.fetchFn(this.baseURL + path, {
|
|
227
288
|
method,
|
|
228
289
|
headers: {
|
|
229
290
|
Authorization: `Bearer ${this.apiKey}`,
|
|
230
291
|
Accept: "application/json",
|
|
231
292
|
...(body === undefined ? {} : { "Content-Type": raw ? "application/octet-stream" : "application/json" }),
|
|
293
|
+
...(zipped === undefined ? {} : { "Content-Encoding": "gzip" }),
|
|
232
294
|
...(idempotencyKey === undefined ? {} : { "Idempotency-Key": idempotencyKey }),
|
|
233
295
|
...(this.organization === undefined ? {} : { "X-Conare-Org": this.organization }),
|
|
234
296
|
...extra,
|
|
235
297
|
},
|
|
236
|
-
body:
|
|
298
|
+
body: zipped ?? (raw ? body : json),
|
|
237
299
|
signal: controller.signal,
|
|
238
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
|
+
}
|
|
239
310
|
return [res, await res.text()];
|
|
240
311
|
}
|
|
241
312
|
catch (err) {
|
|
@@ -252,6 +323,10 @@ export class Conare {
|
|
|
252
323
|
}
|
|
253
324
|
}
|
|
254
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
|
+
}
|
|
255
330
|
// ---- Namespace -------------------------------------------------------------
|
|
256
331
|
/** One namespace: a named set of documents, e.g. "docs" or "user-42". */
|
|
257
332
|
export class Namespace {
|
|
@@ -335,19 +410,19 @@ export class Namespace {
|
|
|
335
410
|
* `sheet` metadata. Slides with no text are listed in `slidesWithoutText`. `fileId` defaults to the
|
|
336
411
|
* name in id characters (a name with characters outside ASCII also gets 8 hex digits of its hash, so
|
|
337
412
|
* such names do not collide); uploading the same one again replaces every document it made, and two
|
|
338
|
-
* uploads of one id run one at a time.
|
|
339
|
-
*
|
|
340
|
-
*
|
|
341
|
-
*
|
|
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`.
|
|
342
420
|
*/
|
|
343
421
|
async uploadFile(file, name, options = {}) {
|
|
344
|
-
const query = new URLSearchParams({
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
...(options.wait ? { wait: "true" } : {}),
|
|
349
|
-
});
|
|
350
|
-
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 });
|
|
351
426
|
return toFileUpload(body);
|
|
352
427
|
}
|
|
353
428
|
/**
|
|
@@ -446,9 +521,16 @@ export class Namespace {
|
|
|
446
521
|
return deleted;
|
|
447
522
|
}
|
|
448
523
|
}
|
|
449
|
-
/**
|
|
450
|
-
|
|
451
|
-
|
|
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 ?? [] };
|
|
452
534
|
}
|
|
453
535
|
}
|
|
454
536
|
// ---- Sources ---------------------------------------------------------------
|