typizer 0.1.0 → 0.3.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/CHANGELOG.md +76 -0
- package/README.md +273 -134
- package/dist/client.d.ts +323 -0
- package/dist/client.js +629 -0
- package/dist/core.d.ts +109 -0
- package/dist/core.js +339 -0
- package/dist/errors.d.ts +146 -0
- package/dist/errors.js +281 -0
- package/dist/files.d.ts +42 -0
- package/dist/files.js +159 -0
- package/dist/gen/index.d.ts +2 -2
- package/dist/gen/index.js +1 -1
- package/dist/gen/sdk.gen.d.ts +509 -5
- package/dist/gen/sdk.gen.js +893 -4
- package/dist/gen/types.gen.d.ts +4279 -913
- package/dist/index.d.ts +26 -3
- package/dist/index.js +33 -4
- package/dist/pagination.d.ts +30 -0
- package/dist/pagination.js +49 -0
- package/dist/run.d.ts +50 -0
- package/dist/run.js +45 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/dist/webhooks.d.ts +40 -0
- package/dist/webhooks.js +208 -0
- package/package.json +3 -1
package/dist/client.js
ADDED
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `Typizer` client (SPEC.md): one entry point, resources as namespaces, `extract` in one call,
|
|
3
|
+
* retries, idempotency keys, typed errors, pagination and webhooks.
|
|
4
|
+
*/
|
|
5
|
+
import { APIPromise, env, maskKey, newIdempotencyKey, sleep, Transport, userAgent, } from './core.js';
|
|
6
|
+
import { ConfigurationError, RunFailedError, WaitTimeoutError } from './errors.js';
|
|
7
|
+
import { resolveDocument, toBlob } from './files.js';
|
|
8
|
+
import { Page, PagePromise } from './pagination.js';
|
|
9
|
+
import { withRunHelpers } from './run.js';
|
|
10
|
+
import { webhooks } from './webhooks.js';
|
|
11
|
+
export const DEFAULT_BASE_URL = 'https://api.typizer.ru';
|
|
12
|
+
const TERMINAL = new Set(['succeeded', 'failed']);
|
|
13
|
+
function seg(name, value) {
|
|
14
|
+
const s = String(value ?? '');
|
|
15
|
+
if (!s)
|
|
16
|
+
throw new TypeError(`typizer: ${name} is empty`);
|
|
17
|
+
return encodeURIComponent(s);
|
|
18
|
+
}
|
|
19
|
+
function iso(v) {
|
|
20
|
+
return v instanceof Date ? v.toISOString() : v;
|
|
21
|
+
}
|
|
22
|
+
function schemaValue(schema) {
|
|
23
|
+
if (typeof schema === 'string') {
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(schema);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
throw new TypeError('typizer: schema is not valid JSON');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (!schema || typeof schema !== 'object')
|
|
32
|
+
throw new TypeError('typizer: schema must be an object');
|
|
33
|
+
return schema;
|
|
34
|
+
}
|
|
35
|
+
function idOf(v) {
|
|
36
|
+
return typeof v === 'string' ? v : v?.id;
|
|
37
|
+
}
|
|
38
|
+
/** Drops unset fields: optional parameters are never sent (SPEC §3). */
|
|
39
|
+
function compact(obj) {
|
|
40
|
+
return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
|
|
41
|
+
}
|
|
42
|
+
/** The Typizer API client. One per application: it is safe to share and reuses connections. */
|
|
43
|
+
export class TypizerClient {
|
|
44
|
+
/** Webhook signature verification, without a client: `Typizer.webhooks.verify(body, headers, secret)`. */
|
|
45
|
+
static webhooks = webhooks;
|
|
46
|
+
runs;
|
|
47
|
+
files;
|
|
48
|
+
typizers;
|
|
49
|
+
catalog;
|
|
50
|
+
batches;
|
|
51
|
+
webhookEndpoints;
|
|
52
|
+
/** Same as the static `Typizer.webhooks`. */
|
|
53
|
+
webhooks = webhooks;
|
|
54
|
+
#options;
|
|
55
|
+
#apiKey;
|
|
56
|
+
#baseUrl;
|
|
57
|
+
/** @internal */
|
|
58
|
+
_transport;
|
|
59
|
+
constructor(options = {}, shared) {
|
|
60
|
+
const apiKey = options.apiKey ?? env('TYPIZER_API_KEY');
|
|
61
|
+
if (!apiKey || /\s/.test(apiKey)) {
|
|
62
|
+
throw new ConfigurationError(apiKey
|
|
63
|
+
? 'typizer: the API key must not contain spaces'
|
|
64
|
+
: 'typizer: no API key: pass new Typizer({ apiKey }) or set TYPIZER_API_KEY (keys: https://my.typizer.ru)');
|
|
65
|
+
}
|
|
66
|
+
const baseUrl = (options.baseUrl ?? env('TYPIZER_BASE_URL') ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
67
|
+
const envLevel = env('TYPIZER_LOG')?.toLowerCase();
|
|
68
|
+
const logLevel = options.logLevel ??
|
|
69
|
+
(envLevel === 'debug' || envLevel === 'info' || envLevel === 'warn' || envLevel === 'off'
|
|
70
|
+
? envLevel
|
|
71
|
+
: envLevel === 'warning'
|
|
72
|
+
? 'warn'
|
|
73
|
+
: 'warn');
|
|
74
|
+
this.#options = options;
|
|
75
|
+
this.#apiKey = apiKey;
|
|
76
|
+
this.#baseUrl = baseUrl;
|
|
77
|
+
const cfg = {
|
|
78
|
+
apiKey,
|
|
79
|
+
baseUrl,
|
|
80
|
+
timeout: options.timeout ?? 75_000,
|
|
81
|
+
maxRetries: options.maxRetries ?? 2,
|
|
82
|
+
maxRetryDelay: options.maxRetryDelay ?? 60_000,
|
|
83
|
+
fetch: options.fetch,
|
|
84
|
+
proxy: options.proxy,
|
|
85
|
+
defaultHeaders: Object.fromEntries(Object.entries(options.defaultHeaders ?? {}).filter(([k]) => k.toLowerCase() !== 'authorization')),
|
|
86
|
+
userAgent: userAgent(options.appInfo),
|
|
87
|
+
logger: options.logger ?? console,
|
|
88
|
+
logLevel,
|
|
89
|
+
};
|
|
90
|
+
this._transport = new Transport(cfg, shared ?? { maintenance: new Set() });
|
|
91
|
+
this.runs = new Runs(this);
|
|
92
|
+
this.files = new Files(this);
|
|
93
|
+
this.typizers = new Typizers(this);
|
|
94
|
+
this.catalog = new Catalog(this);
|
|
95
|
+
this.batches = new Batches(this);
|
|
96
|
+
this.webhookEndpoints = new WebhookEndpoints(this);
|
|
97
|
+
Object.defineProperty(this, '_transport', { enumerable: false });
|
|
98
|
+
}
|
|
99
|
+
/** A copy with other settings that shares the connections and state. */
|
|
100
|
+
withOptions(options) {
|
|
101
|
+
return new TypizerClient({ ...this.#options, apiKey: this.#apiKey, baseUrl: this.#baseUrl, ...options }, this._transport.shared);
|
|
102
|
+
}
|
|
103
|
+
/** @internal */
|
|
104
|
+
_call(req, opts = {}, map) {
|
|
105
|
+
return new APIPromise(this._send(req, opts, map));
|
|
106
|
+
}
|
|
107
|
+
/** @internal */
|
|
108
|
+
async _send(req, opts = {}, map) {
|
|
109
|
+
const r = await this._transport.request(typeof req === 'function' ? await req() : req, opts);
|
|
110
|
+
return { ...r, data: map ? map(r.data) : r.data };
|
|
111
|
+
}
|
|
112
|
+
/** @internal */
|
|
113
|
+
_list(path, query, cursorParam, opts = {}, map) {
|
|
114
|
+
const fetchPage = (cursor) => new PagePromise((async () => {
|
|
115
|
+
const r = await this._transport.request({ method: 'GET', path, query: cursor ? { ...query, [cursorParam]: cursor } : query }, opts);
|
|
116
|
+
const body = r.data ?? {};
|
|
117
|
+
const data = (body.data ?? []).map((item) => (map ? map(item) : item));
|
|
118
|
+
return { ...r, data: new Page({ ...body, data }, fetchPage) };
|
|
119
|
+
})());
|
|
120
|
+
return fetchPage();
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Processes a document and waits for the result — the main task in one call (SPEC §4):
|
|
124
|
+
* `const run = await client.extract({ file: 'invoice.pdf', schema })`.
|
|
125
|
+
*
|
|
126
|
+
* Pass exactly one of `schema`, `catalog`, `typizer`. A local file goes in the same request.
|
|
127
|
+
* Returns the succeeded run; a failed run is a `RunFailedError`, a run still going after
|
|
128
|
+
* `timeout` (300 s) a `WaitTimeoutError` (the run goes on and is billed).
|
|
129
|
+
*/
|
|
130
|
+
extract(params, options = {}) {
|
|
131
|
+
return new APIPromise((async () => {
|
|
132
|
+
const start = Date.now();
|
|
133
|
+
const deadline = start + (params.timeout ?? 300_000);
|
|
134
|
+
const signal = params.signal ?? options.signal;
|
|
135
|
+
const idempotencyKey = params.idempotencyKey ?? options.idempotencyKey ?? newIdempotencyKey();
|
|
136
|
+
const wait = Math.max(0, Math.min(60, Math.floor((deadline - Date.now()) / 1000)));
|
|
137
|
+
const req = await this.runs._request('extract', params, wait);
|
|
138
|
+
const created = await this._transport.request({ ...req, deadline }, { ...options, idempotencyKey, signal });
|
|
139
|
+
const run = await this.runs._poll(withRunHelpers(created.data), start, deadline, params.pollInterval, {
|
|
140
|
+
...options,
|
|
141
|
+
idempotencyKey: undefined,
|
|
142
|
+
signal,
|
|
143
|
+
});
|
|
144
|
+
if (run.status === 'failed')
|
|
145
|
+
throw new RunFailedError(run);
|
|
146
|
+
return { ...created, data: run };
|
|
147
|
+
})());
|
|
148
|
+
}
|
|
149
|
+
/** Who the API key belongs to (`GET /v1/me`). */
|
|
150
|
+
me(options) {
|
|
151
|
+
return this._call({ method: 'GET', path: '/v1/me' }, options);
|
|
152
|
+
}
|
|
153
|
+
/** Pages on the balance (`GET /v1/balance`). */
|
|
154
|
+
balance(options) {
|
|
155
|
+
return this._call({ method: 'GET', path: '/v1/balance' }, options);
|
|
156
|
+
}
|
|
157
|
+
/** Usage by day, typizer or key (`GET /v1/usage`). */
|
|
158
|
+
usage(params = {}, options) {
|
|
159
|
+
return this._call({
|
|
160
|
+
method: 'GET',
|
|
161
|
+
path: '/v1/usage',
|
|
162
|
+
query: { from: params.from, to: params.to, group_by: params.groupBy },
|
|
163
|
+
}, options);
|
|
164
|
+
}
|
|
165
|
+
/** The key's organization (`GET /v1/organization`). */
|
|
166
|
+
organization(options) {
|
|
167
|
+
return this._call({ method: 'GET', path: '/v1/organization' }, options);
|
|
168
|
+
}
|
|
169
|
+
/** Service status and maintenance (`GET /v1/status`). */
|
|
170
|
+
status(options) {
|
|
171
|
+
return this._call({ method: 'GET', path: '/v1/status' }, options);
|
|
172
|
+
}
|
|
173
|
+
toJSON() {
|
|
174
|
+
return { apiKey: maskKey(this.#apiKey), baseUrl: this.#baseUrl };
|
|
175
|
+
}
|
|
176
|
+
toString() {
|
|
177
|
+
return `Typizer(${maskKey(this.#apiKey)}, ${this.#baseUrl})`;
|
|
178
|
+
}
|
|
179
|
+
[Symbol.for('nodejs.util.inspect.custom')]() {
|
|
180
|
+
return `Typizer { apiKey: '${maskKey(this.#apiKey)}', baseUrl: '${this.#baseUrl}' }`;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
class Resource {
|
|
184
|
+
c;
|
|
185
|
+
constructor(client) {
|
|
186
|
+
this.c = client;
|
|
187
|
+
Object.defineProperty(this, 'c', { enumerable: false });
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** `client.runs`: documents processed by a schema. */
|
|
191
|
+
export class Runs extends Resource {
|
|
192
|
+
/** @internal Builds the request that creates a run (argument errors before the network). */
|
|
193
|
+
async _request(method, params, wait) {
|
|
194
|
+
const sources = [
|
|
195
|
+
params.schema !== undefined,
|
|
196
|
+
params.catalog !== undefined,
|
|
197
|
+
params.typizer !== undefined,
|
|
198
|
+
].filter(Boolean).length;
|
|
199
|
+
if (sources !== 1) {
|
|
200
|
+
throw new TypeError(`typizer: ${method}: pass exactly one of schema, catalog and typizer`);
|
|
201
|
+
}
|
|
202
|
+
if (params.instructions !== undefined && params.schema === undefined) {
|
|
203
|
+
throw new TypeError(`typizer: ${method}: instructions go only with schema`);
|
|
204
|
+
}
|
|
205
|
+
const schema = params.schema !== undefined ? schemaValue(params.schema) : undefined;
|
|
206
|
+
const doc = await resolveDocument(method, params);
|
|
207
|
+
const typizerId = params.typizer !== undefined ? idOf(params.typizer) : undefined;
|
|
208
|
+
const path = typizerId ? `/v1/typizers/${seg('typizer', typizerId)}/runs` : '/v1/extract';
|
|
209
|
+
const req = { method: 'POST', path, query: {} };
|
|
210
|
+
if (wait !== undefined) {
|
|
211
|
+
const w = Math.max(0, Math.min(60, Math.floor(wait)));
|
|
212
|
+
req.query = { wait: w };
|
|
213
|
+
req.minTimeout = (w + 15) * 1000;
|
|
214
|
+
}
|
|
215
|
+
const fields = compact({
|
|
216
|
+
schema,
|
|
217
|
+
catalog: params.catalog,
|
|
218
|
+
instructions: params.instructions,
|
|
219
|
+
webhook_url: params.webhookUrl,
|
|
220
|
+
metadata: params.metadata,
|
|
221
|
+
format: params.format,
|
|
222
|
+
mode: params.mode,
|
|
223
|
+
});
|
|
224
|
+
if (doc.kind === 'local') {
|
|
225
|
+
const form = new FormData();
|
|
226
|
+
for (const [k, v] of Object.entries(fields)) {
|
|
227
|
+
form.append(k, typeof v === 'string' ? v : JSON.stringify(v));
|
|
228
|
+
}
|
|
229
|
+
form.append('file', doc.blob, doc.filename);
|
|
230
|
+
req.form = form;
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
req.json = { ...fields, ...(doc.kind === 'url' ? { url: doc.url } : { file_id: doc.id }) };
|
|
234
|
+
}
|
|
235
|
+
return req;
|
|
236
|
+
}
|
|
237
|
+
/** @internal The polling loop of SPEC §4.4. */
|
|
238
|
+
async _poll(run, start, deadline, pollInterval, options) {
|
|
239
|
+
let interval = pollInterval ?? 1000;
|
|
240
|
+
let current = run;
|
|
241
|
+
while (!TERMINAL.has(String(current.status))) {
|
|
242
|
+
const now = Date.now();
|
|
243
|
+
if (now >= deadline)
|
|
244
|
+
throw new WaitTimeoutError(current, now - start);
|
|
245
|
+
await sleep(Math.min(interval, deadline - now), options.signal);
|
|
246
|
+
interval = Math.min(interval * 1.5, 5000);
|
|
247
|
+
const r = await this.c._transport.request({ method: 'GET', path: `/v1/runs/${seg('id', current.id)}`, deadline }, options);
|
|
248
|
+
current = withRunHelpers(r.data);
|
|
249
|
+
}
|
|
250
|
+
return current;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Starts a run without waiting (unless `wait` asks the server to hold the request up to 60 s):
|
|
254
|
+
* `POST /v1/extract`, or `POST /v1/typizers/{id}/runs` with `typizer`.
|
|
255
|
+
*/
|
|
256
|
+
create(params, options = {}) {
|
|
257
|
+
return this.c._call(() => this._request('runs.create', params, params.wait), {
|
|
258
|
+
...options,
|
|
259
|
+
idempotencyKey: params.idempotencyKey ?? options.idempotencyKey,
|
|
260
|
+
signal: params.signal ?? options.signal,
|
|
261
|
+
}, (raw) => withRunHelpers(raw));
|
|
262
|
+
}
|
|
263
|
+
/** A run (`GET /v1/runs/{id}`). */
|
|
264
|
+
get(id, options) {
|
|
265
|
+
return this.c._call(() => Promise.resolve({ method: 'GET', path: `/v1/runs/${seg('id', id)}` }), options, (raw) => withRunHelpers(raw));
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Waits for a run to finish and returns it — `succeeded` or `failed` (only a wait that runs
|
|
269
|
+
* out throws: `WaitTimeoutError`).
|
|
270
|
+
*/
|
|
271
|
+
wait(id, params = {}, options = {}) {
|
|
272
|
+
return new APIPromise((async () => {
|
|
273
|
+
const start = Date.now();
|
|
274
|
+
const deadline = start + (params.timeout ?? 300_000);
|
|
275
|
+
const opts = { ...options, signal: params.signal ?? options.signal };
|
|
276
|
+
const first = await this.c._transport.request({ method: 'GET', path: `/v1/runs/${seg('id', id)}`, deadline }, opts);
|
|
277
|
+
const run = await this._poll(withRunHelpers(first.data), start, deadline, params.pollInterval, opts);
|
|
278
|
+
return { ...first, data: run };
|
|
279
|
+
})());
|
|
280
|
+
}
|
|
281
|
+
/** Runs, newest first; `for await` walks all pages (`GET /v1/runs`). */
|
|
282
|
+
list(params = {}, options) {
|
|
283
|
+
return this.c._list('/v1/runs', {
|
|
284
|
+
limit: params.limit,
|
|
285
|
+
status: params.status,
|
|
286
|
+
typizer_id: params.typizerId,
|
|
287
|
+
batch_id: params.batchId,
|
|
288
|
+
source: params.source,
|
|
289
|
+
created_after: iso(params.createdAfter),
|
|
290
|
+
created_before: iso(params.createdBefore),
|
|
291
|
+
}, 'starting_after', options, (raw) => withRunHelpers(raw));
|
|
292
|
+
}
|
|
293
|
+
/** The result in a file format (`GET /v1/runs/{id}/output`): a `Response` to read or stream. */
|
|
294
|
+
output(id, params = {}, options) {
|
|
295
|
+
return this.c._call(() => Promise.resolve({
|
|
296
|
+
method: 'GET',
|
|
297
|
+
path: `/v1/runs/${seg('id', id)}/output`,
|
|
298
|
+
query: { format: params.format },
|
|
299
|
+
download: true,
|
|
300
|
+
}), options);
|
|
301
|
+
}
|
|
302
|
+
/** Runs a failed run again (`POST /v1/runs/{id}/retry`). */
|
|
303
|
+
retry(id, options) {
|
|
304
|
+
return this.c._call(() => Promise.resolve({ method: 'POST', path: `/v1/runs/${seg('id', id)}/retry` }), options, (raw) => withRunHelpers(raw));
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/** `client.files`: uploaded documents. */
|
|
308
|
+
export class Files extends Resource {
|
|
309
|
+
/** Uploads a document (`POST /v1/files`); usually not needed — `extract` takes the file itself. */
|
|
310
|
+
upload(file, params = {}, options) {
|
|
311
|
+
return this.c._call(async () => {
|
|
312
|
+
const { blob, filename } = await toBlob(file, params.filename);
|
|
313
|
+
const form = new FormData();
|
|
314
|
+
form.append('file', blob, filename);
|
|
315
|
+
return { method: 'POST', path: '/v1/files', form };
|
|
316
|
+
}, options);
|
|
317
|
+
}
|
|
318
|
+
get(id, options) {
|
|
319
|
+
return this.c._call(() => Promise.resolve({ method: 'GET', path: `/v1/files/${seg('id', id)}` }), options);
|
|
320
|
+
}
|
|
321
|
+
delete(id, options) {
|
|
322
|
+
return this.c._call(() => Promise.resolve({ method: 'DELETE', path: `/v1/files/${seg('id', id)}` }), options);
|
|
323
|
+
}
|
|
324
|
+
/** The file's bytes: a `Response` to read or stream. */
|
|
325
|
+
content(id, options) {
|
|
326
|
+
return this.c._call(() => Promise.resolve({
|
|
327
|
+
method: 'GET',
|
|
328
|
+
path: `/v1/files/${seg('id', id)}/content`,
|
|
329
|
+
download: true,
|
|
330
|
+
}), options);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
class TypizerVersions extends Resource {
|
|
334
|
+
list(typizerId, params = {}, options) {
|
|
335
|
+
return this.c._list(`/v1/typizers/${seg('typizerId', typizerId)}/versions`, { limit: params.limit }, 'starting_after', options);
|
|
336
|
+
}
|
|
337
|
+
get(typizerId, version, options) {
|
|
338
|
+
return this.c._call(() => Promise.resolve({
|
|
339
|
+
method: 'GET',
|
|
340
|
+
path: `/v1/typizers/${seg('typizerId', typizerId)}/versions/${seg('version', version)}`,
|
|
341
|
+
}), options);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
class TypizerCatalogUpdate extends Resource {
|
|
345
|
+
/** What a catalog update would change (`GET /v1/typizers/{id}/catalog_update`). */
|
|
346
|
+
get(typizerId, params = {}, options) {
|
|
347
|
+
return this.c._call(() => Promise.resolve({
|
|
348
|
+
method: 'GET',
|
|
349
|
+
path: `/v1/typizers/${seg('typizerId', typizerId)}/catalog_update`,
|
|
350
|
+
query: { version: params.version },
|
|
351
|
+
}), options);
|
|
352
|
+
}
|
|
353
|
+
/** Applies a catalog update (`POST /v1/typizers/{id}/catalog_update`). */
|
|
354
|
+
apply(typizerId, params, options) {
|
|
355
|
+
return this.c._call(() => Promise.resolve({
|
|
356
|
+
method: 'POST',
|
|
357
|
+
path: `/v1/typizers/${seg('typizerId', typizerId)}/catalog_update`,
|
|
358
|
+
json: compact({ version: params.version, paths: params.paths }),
|
|
359
|
+
}), options);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
function typizerBody(p) {
|
|
363
|
+
return compact({
|
|
364
|
+
name: p.name,
|
|
365
|
+
description: p.description,
|
|
366
|
+
schema: p.schema !== undefined ? schemaValue(p.schema) : undefined,
|
|
367
|
+
instructions: p.instructions,
|
|
368
|
+
default_format: p.defaultFormat,
|
|
369
|
+
mode: p.mode,
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
/** `client.typizers`: saved schemas. */
|
|
373
|
+
export class Typizers extends Resource {
|
|
374
|
+
versions = new TypizerVersions(this.c);
|
|
375
|
+
catalogUpdate = new TypizerCatalogUpdate(this.c);
|
|
376
|
+
create(params, options) {
|
|
377
|
+
return this.c._call(() => Promise.resolve({ method: 'POST', path: '/v1/typizers', json: typizerBody(params) }), options);
|
|
378
|
+
}
|
|
379
|
+
get(id, options) {
|
|
380
|
+
return this.c._call(() => Promise.resolve({ method: 'GET', path: `/v1/typizers/${seg('id', id)}` }), options);
|
|
381
|
+
}
|
|
382
|
+
update(id, params, options) {
|
|
383
|
+
return this.c._call(() => Promise.resolve({
|
|
384
|
+
method: 'PATCH',
|
|
385
|
+
path: `/v1/typizers/${seg('id', id)}`,
|
|
386
|
+
json: typizerBody(params),
|
|
387
|
+
}), options);
|
|
388
|
+
}
|
|
389
|
+
delete(id, options) {
|
|
390
|
+
return this.c._call(() => Promise.resolve({ method: 'DELETE', path: `/v1/typizers/${seg('id', id)}` }), options);
|
|
391
|
+
}
|
|
392
|
+
list(params = {}, options) {
|
|
393
|
+
return this.c._list('/v1/typizers', { limit: params.limit }, 'starting_after', options);
|
|
394
|
+
}
|
|
395
|
+
/** Drafts a schema from a description and/or a sample file (`POST /v1/typizers/generate`). */
|
|
396
|
+
generate(params, options) {
|
|
397
|
+
return this.c._call(() => Promise.resolve({
|
|
398
|
+
method: 'POST',
|
|
399
|
+
path: '/v1/typizers/generate',
|
|
400
|
+
json: compact({ description: params.description, file_id: params.fileId }),
|
|
401
|
+
}), options);
|
|
402
|
+
}
|
|
403
|
+
/** The typizer's XSD (`GET /v1/typizers/{id}/xsd`): a `Response`. */
|
|
404
|
+
xsd(id, options) {
|
|
405
|
+
return this.c._call(() => Promise.resolve({
|
|
406
|
+
method: 'GET',
|
|
407
|
+
path: `/v1/typizers/${seg('id', id)}/xsd`,
|
|
408
|
+
download: true,
|
|
409
|
+
}), options);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
function splitRef(ref) {
|
|
413
|
+
const at = ref.indexOf('@');
|
|
414
|
+
return at < 0 ? [ref, undefined] : [ref.slice(0, at), ref.slice(at + 1) || undefined];
|
|
415
|
+
}
|
|
416
|
+
class CatalogPublishers extends Resource {
|
|
417
|
+
get(slug, options) {
|
|
418
|
+
return this.c._call(() => Promise.resolve({
|
|
419
|
+
method: 'GET',
|
|
420
|
+
path: `/v1/catalog/publishers/${seg('slug', slug)}`,
|
|
421
|
+
}), options);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
/** `client.catalog`: ready-made schemas (official and community). */
|
|
425
|
+
export class Catalog extends Resource {
|
|
426
|
+
publishers = new CatalogPublishers(this.c);
|
|
427
|
+
list(params = {}, options) {
|
|
428
|
+
return this.c._list('/v1/catalog', {
|
|
429
|
+
q: params.q,
|
|
430
|
+
category: params.category,
|
|
431
|
+
kind: params.kind,
|
|
432
|
+
publisher: params.publisher,
|
|
433
|
+
favorites: params.favorites,
|
|
434
|
+
sort: params.sort,
|
|
435
|
+
limit: params.limit,
|
|
436
|
+
}, 'cursor', options);
|
|
437
|
+
}
|
|
438
|
+
/** A catalog schema: `schet-faktura`, `schet-faktura@1`, `cat_…`, `acme/akt-sverki@1.2.0`. */
|
|
439
|
+
get(ref, params = {}, options) {
|
|
440
|
+
return this.c._call(() => Promise.resolve(this.#getReq(ref, params.version)), options);
|
|
441
|
+
}
|
|
442
|
+
#getReq(ref, version) {
|
|
443
|
+
const [name, refVersion] = splitRef(ref);
|
|
444
|
+
if (!name)
|
|
445
|
+
throw new TypeError('typizer: empty catalog reference');
|
|
446
|
+
const query = { version: version ?? refVersion };
|
|
447
|
+
const slash = name.indexOf('/');
|
|
448
|
+
if (slash >= 0) {
|
|
449
|
+
return {
|
|
450
|
+
method: 'GET',
|
|
451
|
+
path: `/v1/catalog/${seg('publisher', name.slice(0, slash))}/${seg('slug', name.slice(slash + 1))}`,
|
|
452
|
+
query,
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
return { method: 'GET', path: `/v1/catalog/${seg('entry', name)}`, query };
|
|
456
|
+
}
|
|
457
|
+
/** A community `publisher/slug` is looked up first (one more request); a slug or `cat_…` is used as is. */
|
|
458
|
+
async #entry(ref, options) {
|
|
459
|
+
const [name, version] = splitRef(ref);
|
|
460
|
+
if (!name)
|
|
461
|
+
throw new TypeError('typizer: empty catalog reference');
|
|
462
|
+
if (!name.includes('/'))
|
|
463
|
+
return [name, version];
|
|
464
|
+
const entry = await this.c._transport.request(this.#getReq(name), {
|
|
465
|
+
...options,
|
|
466
|
+
idempotencyKey: undefined,
|
|
467
|
+
});
|
|
468
|
+
return [entry.data.id, version];
|
|
469
|
+
}
|
|
470
|
+
/** Every version of a catalog schema (not paginated). */
|
|
471
|
+
versions(ref, options) {
|
|
472
|
+
return new APIPromise((async () => {
|
|
473
|
+
const [id] = await this.#entry(ref, options);
|
|
474
|
+
const r = await this.c._transport.request({ method: 'GET', path: `/v1/catalog/${seg('entry', id)}/versions` }, options);
|
|
475
|
+
return { ...r, data: r.data?.data ?? [] };
|
|
476
|
+
})());
|
|
477
|
+
}
|
|
478
|
+
/** Adds a catalog schema to your typizers as it is. */
|
|
479
|
+
install(ref, params = {}, options) {
|
|
480
|
+
return this.#install('install', ref, params, options);
|
|
481
|
+
}
|
|
482
|
+
/** Creates your own typizer from a catalog schema, to change it. */
|
|
483
|
+
fork(ref, params = {}, options) {
|
|
484
|
+
return this.#install('fork', ref, params, options);
|
|
485
|
+
}
|
|
486
|
+
#install(action, ref, params, options) {
|
|
487
|
+
return this.c._call(async () => {
|
|
488
|
+
const [id, version] = await this.#entry(ref, options);
|
|
489
|
+
return {
|
|
490
|
+
method: 'POST',
|
|
491
|
+
path: `/v1/catalog/${seg('entry', id)}/${action}`,
|
|
492
|
+
json: compact({ version: params.version ?? version, name: params.name }),
|
|
493
|
+
};
|
|
494
|
+
}, options);
|
|
495
|
+
}
|
|
496
|
+
favorite(ref, options) {
|
|
497
|
+
return this.c._call(async () => {
|
|
498
|
+
const [id] = await this.#entry(ref, options);
|
|
499
|
+
return { method: 'PUT', path: `/v1/catalog/${seg('entry', id)}/favorite` };
|
|
500
|
+
}, options);
|
|
501
|
+
}
|
|
502
|
+
unfavorite(ref, options) {
|
|
503
|
+
return this.c._call(async () => {
|
|
504
|
+
const [id] = await this.#entry(ref, options);
|
|
505
|
+
return { method: 'DELETE', path: `/v1/catalog/${seg('entry', id)}/favorite` };
|
|
506
|
+
}, options);
|
|
507
|
+
}
|
|
508
|
+
/** Reports a catalog schema to the moderators. */
|
|
509
|
+
report(ref, params, options) {
|
|
510
|
+
return this.c._call(async () => {
|
|
511
|
+
if (!params?.reason)
|
|
512
|
+
throw new TypeError('typizer: catalog.report: reason is required');
|
|
513
|
+
const [id, version] = await this.#entry(ref, options);
|
|
514
|
+
return {
|
|
515
|
+
method: 'POST',
|
|
516
|
+
path: `/v1/catalog/${seg('entry', id)}/reports`,
|
|
517
|
+
json: compact({
|
|
518
|
+
reason: params.reason,
|
|
519
|
+
details: params.details,
|
|
520
|
+
version: params.version ?? version,
|
|
521
|
+
}),
|
|
522
|
+
};
|
|
523
|
+
}, options);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
/** `client.batches`: one typizer over many files. */
|
|
527
|
+
export class Batches extends Resource {
|
|
528
|
+
create(params, options) {
|
|
529
|
+
return this.c._call(async () => {
|
|
530
|
+
const typizerId = idOf(params.typizer);
|
|
531
|
+
if (!typizerId)
|
|
532
|
+
throw new TypeError('typizer: batches.create: typizer is required');
|
|
533
|
+
const hasFiles = Boolean(params.files?.length);
|
|
534
|
+
if (hasFiles === Boolean(params.fileIds?.length)) {
|
|
535
|
+
throw new TypeError('typizer: batches.create: pass either files or fileIds');
|
|
536
|
+
}
|
|
537
|
+
if (!hasFiles) {
|
|
538
|
+
return {
|
|
539
|
+
method: 'POST',
|
|
540
|
+
path: '/v1/batches',
|
|
541
|
+
json: compact({
|
|
542
|
+
typizer_id: typizerId,
|
|
543
|
+
file_ids: params.fileIds,
|
|
544
|
+
format: params.format,
|
|
545
|
+
mode: params.mode,
|
|
546
|
+
metadata: params.metadata,
|
|
547
|
+
}),
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
const form = new FormData();
|
|
551
|
+
form.append('typizer_id', typizerId);
|
|
552
|
+
if (params.format)
|
|
553
|
+
form.append('format', params.format);
|
|
554
|
+
if (params.mode)
|
|
555
|
+
form.append('mode', params.mode);
|
|
556
|
+
if (params.metadata)
|
|
557
|
+
form.append('metadata', JSON.stringify(params.metadata));
|
|
558
|
+
for (const f of params.files ?? []) {
|
|
559
|
+
const item = f && typeof f === 'object' && 'file' in f && !(f instanceof Blob)
|
|
560
|
+
? f
|
|
561
|
+
: { file: f };
|
|
562
|
+
const { blob, filename } = await toBlob(item.file, item.filename);
|
|
563
|
+
form.append('files', blob, filename);
|
|
564
|
+
}
|
|
565
|
+
return { method: 'POST', path: '/v1/batches', form };
|
|
566
|
+
}, options);
|
|
567
|
+
}
|
|
568
|
+
get(id, options) {
|
|
569
|
+
return this.c._call(() => Promise.resolve({ method: 'GET', path: `/v1/batches/${seg('id', id)}` }), options);
|
|
570
|
+
}
|
|
571
|
+
list(params = {}, options) {
|
|
572
|
+
return this.c._list('/v1/batches', { limit: params.limit }, 'starting_after', options);
|
|
573
|
+
}
|
|
574
|
+
/** All results of a batch in one file (`GET /v1/batches/{id}/export`): a `Response`. */
|
|
575
|
+
export(id, params = {}, options) {
|
|
576
|
+
return this.c._call(() => Promise.resolve({
|
|
577
|
+
method: 'GET',
|
|
578
|
+
path: `/v1/batches/${seg('id', id)}/export`,
|
|
579
|
+
query: { format: params.format },
|
|
580
|
+
download: true,
|
|
581
|
+
}), options);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
class WebhookDeliveries extends Resource {
|
|
585
|
+
list(endpointId, params = {}, options) {
|
|
586
|
+
return this.c._list(`/v1/webhook_endpoints/${seg('endpointId', endpointId)}/deliveries`, { limit: params.limit }, 'starting_after', options);
|
|
587
|
+
}
|
|
588
|
+
retry(deliveryId, options) {
|
|
589
|
+
return this.c._call(() => Promise.resolve({
|
|
590
|
+
method: 'POST',
|
|
591
|
+
path: `/v1/webhook_deliveries/${seg('deliveryId', deliveryId)}/retry`,
|
|
592
|
+
}), options);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
/** `client.webhookEndpoints`: where Typizer sends webhooks. */
|
|
596
|
+
export class WebhookEndpoints extends Resource {
|
|
597
|
+
deliveries = new WebhookDeliveries(this.c);
|
|
598
|
+
/** Creates an endpoint; `secret` comes only in this response (a replay returns `secret: null`). */
|
|
599
|
+
create(params, options) {
|
|
600
|
+
return this.c._call(() => Promise.resolve({
|
|
601
|
+
method: 'POST',
|
|
602
|
+
path: '/v1/webhook_endpoints',
|
|
603
|
+
json: compact({ url: params.url, events: params.events }),
|
|
604
|
+
}), options);
|
|
605
|
+
}
|
|
606
|
+
get(id, options) {
|
|
607
|
+
return this.c._call(() => Promise.resolve({ method: 'GET', path: `/v1/webhook_endpoints/${seg('id', id)}` }), options);
|
|
608
|
+
}
|
|
609
|
+
update(id, params, options) {
|
|
610
|
+
return this.c._call(() => Promise.resolve({
|
|
611
|
+
method: 'PATCH',
|
|
612
|
+
path: `/v1/webhook_endpoints/${seg('id', id)}`,
|
|
613
|
+
json: compact({ url: params.url, events: params.events, status: params.status }),
|
|
614
|
+
}), options);
|
|
615
|
+
}
|
|
616
|
+
delete(id, options) {
|
|
617
|
+
return this.c._call(() => Promise.resolve({ method: 'DELETE', path: `/v1/webhook_endpoints/${seg('id', id)}` }), options);
|
|
618
|
+
}
|
|
619
|
+
list(params = {}, options) {
|
|
620
|
+
return this.c._list('/v1/webhook_endpoints', { limit: params.limit }, 'starting_after', options);
|
|
621
|
+
}
|
|
622
|
+
/** Sends a test event to the endpoint. */
|
|
623
|
+
test(id, options) {
|
|
624
|
+
return this.c._call(() => Promise.resolve({
|
|
625
|
+
method: 'POST',
|
|
626
|
+
path: `/v1/webhook_endpoints/${seg('id', id)}/test`,
|
|
627
|
+
}), options);
|
|
628
|
+
}
|
|
629
|
+
}
|