@anyformat/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1237 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ APIError: () => APIError,
24
+ Anyformat: () => Anyformat,
25
+ AnyformatError: () => AnyformatError,
26
+ BadRequest: () => BadRequest,
27
+ Forbidden: () => Forbidden,
28
+ NotFound: () => NotFound,
29
+ RateLimited: () => RateLimited,
30
+ Result: () => Result,
31
+ Run: () => Run,
32
+ SDKTimeout: () => SDKTimeout,
33
+ Schema: () => Schema,
34
+ ServerError: () => ServerError,
35
+ Unauthorized: () => Unauthorized,
36
+ WorkflowBuilder: () => WorkflowBuilder,
37
+ WorkflowBuilderError: () => WorkflowBuilderError
38
+ });
39
+ module.exports = __toCommonJS(index_exports);
40
+
41
+ // src/result.ts
42
+ var Result = class {
43
+ constructor(raw) {
44
+ this.raw = raw;
45
+ }
46
+ raw;
47
+ get collectionId() {
48
+ return this.raw.collection_id;
49
+ }
50
+ get extractions() {
51
+ return this.raw.extractions ?? [];
52
+ }
53
+ /**
54
+ * Convenience accessor for a top-level scalar field on the first
55
+ * extraction (linear workflows). Returns `undefined` for missing fields
56
+ * or list-valued fields — read `extractions` directly for those.
57
+ */
58
+ field(name) {
59
+ const value = this.extractions[0]?.fields?.[name];
60
+ return value !== void 0 && !Array.isArray(value) ? value : void 0;
61
+ }
62
+ };
63
+
64
+ // src/errors.ts
65
+ var AnyformatError = class extends Error {
66
+ };
67
+ var APIError = class extends AnyformatError {
68
+ constructor(status, message, body) {
69
+ super(message);
70
+ this.status = status;
71
+ this.body = body;
72
+ this.name = new.target.name;
73
+ }
74
+ status;
75
+ body;
76
+ };
77
+ var BadRequest = class extends APIError {
78
+ };
79
+ var Unauthorized = class extends APIError {
80
+ };
81
+ var Forbidden = class extends APIError {
82
+ };
83
+ var NotFound = class extends APIError {
84
+ };
85
+ var RateLimited = class extends APIError {
86
+ };
87
+ var ServerError = class extends APIError {
88
+ };
89
+ var SDKTimeout = class extends AnyformatError {
90
+ };
91
+ var WorkflowBuilderError = class extends AnyformatError {
92
+ };
93
+ function toApiError(status, body) {
94
+ const message = `AnyFormat API error (${status})`;
95
+ switch (status) {
96
+ case 400:
97
+ return new BadRequest(status, message, body);
98
+ case 401:
99
+ return new Unauthorized(status, message, body);
100
+ case 403:
101
+ return new Forbidden(status, message, body);
102
+ case 404:
103
+ return new NotFound(status, message, body);
104
+ case 429:
105
+ return new RateLimited(status, message, body);
106
+ default:
107
+ return status >= 500 ? new ServerError(status, message, body) : new APIError(status, message, body);
108
+ }
109
+ }
110
+
111
+ // src/sdk/core/bodySerializer.gen.ts
112
+ var serializeFormDataPair = (data, key, value) => {
113
+ if (typeof value === "string" || value instanceof Blob) {
114
+ data.append(key, value);
115
+ } else if (value instanceof Date) {
116
+ data.append(key, value.toISOString());
117
+ } else {
118
+ data.append(key, JSON.stringify(value));
119
+ }
120
+ };
121
+ var formDataBodySerializer = {
122
+ bodySerializer: (body) => {
123
+ const data = new FormData();
124
+ Object.entries(body).forEach(([key, value]) => {
125
+ if (value === void 0 || value === null) {
126
+ return;
127
+ }
128
+ if (Array.isArray(value)) {
129
+ value.forEach((v) => serializeFormDataPair(data, key, v));
130
+ } else {
131
+ serializeFormDataPair(data, key, value);
132
+ }
133
+ });
134
+ return data;
135
+ }
136
+ };
137
+ var jsonBodySerializer = {
138
+ bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value)
139
+ };
140
+
141
+ // src/sdk/core/params.gen.ts
142
+ var extraPrefixesMap = {
143
+ $body_: "body",
144
+ $headers_: "headers",
145
+ $path_: "path",
146
+ $query_: "query"
147
+ };
148
+ var extraPrefixes = Object.entries(extraPrefixesMap);
149
+
150
+ // src/sdk/core/serverSentEvents.gen.ts
151
+ function createSseClient({
152
+ onRequest,
153
+ onSseError,
154
+ onSseEvent,
155
+ responseTransformer,
156
+ responseValidator,
157
+ sseDefaultRetryDelay,
158
+ sseMaxRetryAttempts,
159
+ sseMaxRetryDelay,
160
+ sseSleepFn,
161
+ url,
162
+ ...options
163
+ }) {
164
+ let lastEventId;
165
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
166
+ const createStream = async function* () {
167
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
168
+ let attempt = 0;
169
+ const signal = options.signal ?? new AbortController().signal;
170
+ while (true) {
171
+ if (signal.aborted) break;
172
+ attempt++;
173
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
174
+ if (lastEventId !== void 0) {
175
+ headers.set("Last-Event-ID", lastEventId);
176
+ }
177
+ try {
178
+ const requestInit = {
179
+ redirect: "follow",
180
+ ...options,
181
+ body: options.serializedBody,
182
+ headers,
183
+ signal
184
+ };
185
+ let request = new Request(url, requestInit);
186
+ if (onRequest) {
187
+ request = await onRequest(url, requestInit);
188
+ }
189
+ const _fetch = options.fetch ?? globalThis.fetch;
190
+ const response = await _fetch(request);
191
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
192
+ if (!response.body) throw new Error("No body in SSE response");
193
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
194
+ let buffer = "";
195
+ const abortHandler = () => {
196
+ try {
197
+ reader.cancel();
198
+ } catch {
199
+ }
200
+ };
201
+ signal.addEventListener("abort", abortHandler);
202
+ try {
203
+ while (true) {
204
+ const { done, value } = await reader.read();
205
+ if (done) break;
206
+ buffer += value;
207
+ buffer = buffer.replace(/\r\n?/g, "\n");
208
+ const chunks = buffer.split("\n\n");
209
+ buffer = chunks.pop() ?? "";
210
+ for (const chunk of chunks) {
211
+ const lines = chunk.split("\n");
212
+ const dataLines = [];
213
+ let eventName;
214
+ for (const line of lines) {
215
+ if (line.startsWith("data:")) {
216
+ dataLines.push(line.replace(/^data:\s*/, ""));
217
+ } else if (line.startsWith("event:")) {
218
+ eventName = line.replace(/^event:\s*/, "");
219
+ } else if (line.startsWith("id:")) {
220
+ lastEventId = line.replace(/^id:\s*/, "");
221
+ } else if (line.startsWith("retry:")) {
222
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
223
+ if (!Number.isNaN(parsed)) {
224
+ retryDelay = parsed;
225
+ }
226
+ }
227
+ }
228
+ let data;
229
+ let parsedJson = false;
230
+ if (dataLines.length) {
231
+ const rawData = dataLines.join("\n");
232
+ try {
233
+ data = JSON.parse(rawData);
234
+ parsedJson = true;
235
+ } catch {
236
+ data = rawData;
237
+ }
238
+ }
239
+ if (parsedJson) {
240
+ if (responseValidator) {
241
+ await responseValidator(data);
242
+ }
243
+ if (responseTransformer) {
244
+ data = await responseTransformer(data);
245
+ }
246
+ }
247
+ onSseEvent?.({
248
+ data,
249
+ event: eventName,
250
+ id: lastEventId,
251
+ retry: retryDelay
252
+ });
253
+ if (dataLines.length) {
254
+ yield data;
255
+ }
256
+ }
257
+ }
258
+ } finally {
259
+ signal.removeEventListener("abort", abortHandler);
260
+ reader.releaseLock();
261
+ }
262
+ break;
263
+ } catch (error) {
264
+ onSseError?.(error);
265
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
266
+ break;
267
+ }
268
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
269
+ await sleep(backoff);
270
+ }
271
+ }
272
+ };
273
+ const stream = createStream();
274
+ return { stream };
275
+ }
276
+
277
+ // src/sdk/core/pathSerializer.gen.ts
278
+ var separatorArrayExplode = (style) => {
279
+ switch (style) {
280
+ case "label":
281
+ return ".";
282
+ case "matrix":
283
+ return ";";
284
+ case "simple":
285
+ return ",";
286
+ default:
287
+ return "&";
288
+ }
289
+ };
290
+ var separatorArrayNoExplode = (style) => {
291
+ switch (style) {
292
+ case "form":
293
+ return ",";
294
+ case "pipeDelimited":
295
+ return "|";
296
+ case "spaceDelimited":
297
+ return "%20";
298
+ default:
299
+ return ",";
300
+ }
301
+ };
302
+ var separatorObjectExplode = (style) => {
303
+ switch (style) {
304
+ case "label":
305
+ return ".";
306
+ case "matrix":
307
+ return ";";
308
+ case "simple":
309
+ return ",";
310
+ default:
311
+ return "&";
312
+ }
313
+ };
314
+ var serializeArrayParam = ({
315
+ allowReserved,
316
+ explode,
317
+ name,
318
+ style,
319
+ value
320
+ }) => {
321
+ if (!explode) {
322
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
323
+ switch (style) {
324
+ case "label":
325
+ return `.${joinedValues2}`;
326
+ case "matrix":
327
+ return `;${name}=${joinedValues2}`;
328
+ case "simple":
329
+ return joinedValues2;
330
+ default:
331
+ return `${name}=${joinedValues2}`;
332
+ }
333
+ }
334
+ const separator = separatorArrayExplode(style);
335
+ const joinedValues = value.map((v) => {
336
+ if (style === "label" || style === "simple") {
337
+ return allowReserved ? v : encodeURIComponent(v);
338
+ }
339
+ return serializePrimitiveParam({
340
+ allowReserved,
341
+ name,
342
+ value: v
343
+ });
344
+ }).join(separator);
345
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
346
+ };
347
+ var serializePrimitiveParam = ({
348
+ allowReserved,
349
+ name,
350
+ value
351
+ }) => {
352
+ if (value === void 0 || value === null) {
353
+ return "";
354
+ }
355
+ if (typeof value === "object") {
356
+ throw new Error(
357
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
358
+ );
359
+ }
360
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
361
+ };
362
+ var serializeObjectParam = ({
363
+ allowReserved,
364
+ explode,
365
+ name,
366
+ style,
367
+ value,
368
+ valueOnly
369
+ }) => {
370
+ if (value instanceof Date) {
371
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
372
+ }
373
+ if (style !== "deepObject" && !explode) {
374
+ let values = [];
375
+ Object.entries(value).forEach(([key, v]) => {
376
+ values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
377
+ });
378
+ const joinedValues2 = values.join(",");
379
+ switch (style) {
380
+ case "form":
381
+ return `${name}=${joinedValues2}`;
382
+ case "label":
383
+ return `.${joinedValues2}`;
384
+ case "matrix":
385
+ return `;${name}=${joinedValues2}`;
386
+ default:
387
+ return joinedValues2;
388
+ }
389
+ }
390
+ const separator = separatorObjectExplode(style);
391
+ const joinedValues = Object.entries(value).map(
392
+ ([key, v]) => serializePrimitiveParam({
393
+ allowReserved,
394
+ name: style === "deepObject" ? `${name}[${key}]` : key,
395
+ value: v
396
+ })
397
+ ).join(separator);
398
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
399
+ };
400
+
401
+ // src/sdk/core/utils.gen.ts
402
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
403
+ var defaultPathSerializer = ({ path, url: _url }) => {
404
+ let url = _url;
405
+ const matches = _url.match(PATH_PARAM_RE);
406
+ if (matches) {
407
+ for (const match of matches) {
408
+ let explode = false;
409
+ let name = match.substring(1, match.length - 1);
410
+ let style = "simple";
411
+ if (name.endsWith("*")) {
412
+ explode = true;
413
+ name = name.substring(0, name.length - 1);
414
+ }
415
+ if (name.startsWith(".")) {
416
+ name = name.substring(1);
417
+ style = "label";
418
+ } else if (name.startsWith(";")) {
419
+ name = name.substring(1);
420
+ style = "matrix";
421
+ }
422
+ const value = path[name];
423
+ if (value === void 0 || value === null) {
424
+ continue;
425
+ }
426
+ if (Array.isArray(value)) {
427
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
428
+ continue;
429
+ }
430
+ if (typeof value === "object") {
431
+ url = url.replace(
432
+ match,
433
+ serializeObjectParam({
434
+ explode,
435
+ name,
436
+ style,
437
+ value,
438
+ valueOnly: true
439
+ })
440
+ );
441
+ continue;
442
+ }
443
+ if (style === "matrix") {
444
+ url = url.replace(
445
+ match,
446
+ `;${serializePrimitiveParam({
447
+ name,
448
+ value
449
+ })}`
450
+ );
451
+ continue;
452
+ }
453
+ const replaceValue = encodeURIComponent(
454
+ style === "label" ? `.${value}` : value
455
+ );
456
+ url = url.replace(match, replaceValue);
457
+ }
458
+ }
459
+ return url;
460
+ };
461
+ var getUrl = ({
462
+ baseUrl,
463
+ path,
464
+ query,
465
+ querySerializer,
466
+ url: _url
467
+ }) => {
468
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
469
+ let url = (baseUrl ?? "") + pathUrl;
470
+ if (path) {
471
+ url = defaultPathSerializer({ path, url });
472
+ }
473
+ let search = query ? querySerializer(query) : "";
474
+ if (search.startsWith("?")) {
475
+ search = search.substring(1);
476
+ }
477
+ if (search) {
478
+ url += `?${search}`;
479
+ }
480
+ return url;
481
+ };
482
+ function getValidRequestBody(options) {
483
+ const hasBody = options.body !== void 0;
484
+ const isSerializedBody = hasBody && options.bodySerializer;
485
+ if (isSerializedBody) {
486
+ if ("serializedBody" in options) {
487
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
488
+ return hasSerializedBody ? options.serializedBody : null;
489
+ }
490
+ return options.body !== "" ? options.body : null;
491
+ }
492
+ if (hasBody) {
493
+ return options.body;
494
+ }
495
+ return void 0;
496
+ }
497
+
498
+ // src/sdk/core/auth.gen.ts
499
+ var getAuthToken = async (auth, callback) => {
500
+ const token = typeof callback === "function" ? await callback(auth) : callback;
501
+ if (!token) {
502
+ return;
503
+ }
504
+ if (auth.scheme === "bearer") {
505
+ return `Bearer ${token}`;
506
+ }
507
+ if (auth.scheme === "basic") {
508
+ return `Basic ${btoa(token)}`;
509
+ }
510
+ return token;
511
+ };
512
+
513
+ // src/sdk/client/utils.gen.ts
514
+ var createQuerySerializer = ({
515
+ parameters = {},
516
+ ...args
517
+ } = {}) => {
518
+ const querySerializer = (queryParams) => {
519
+ const search = [];
520
+ if (queryParams && typeof queryParams === "object") {
521
+ for (const name in queryParams) {
522
+ const value = queryParams[name];
523
+ if (value === void 0 || value === null) {
524
+ continue;
525
+ }
526
+ const options = parameters[name] || args;
527
+ if (Array.isArray(value)) {
528
+ const serializedArray = serializeArrayParam({
529
+ allowReserved: options.allowReserved,
530
+ explode: true,
531
+ name,
532
+ style: "form",
533
+ value,
534
+ ...options.array
535
+ });
536
+ if (serializedArray) search.push(serializedArray);
537
+ } else if (typeof value === "object") {
538
+ const serializedObject = serializeObjectParam({
539
+ allowReserved: options.allowReserved,
540
+ explode: true,
541
+ name,
542
+ style: "deepObject",
543
+ value,
544
+ ...options.object
545
+ });
546
+ if (serializedObject) search.push(serializedObject);
547
+ } else {
548
+ const serializedPrimitive = serializePrimitiveParam({
549
+ allowReserved: options.allowReserved,
550
+ name,
551
+ value
552
+ });
553
+ if (serializedPrimitive) search.push(serializedPrimitive);
554
+ }
555
+ }
556
+ }
557
+ return search.join("&");
558
+ };
559
+ return querySerializer;
560
+ };
561
+ var getParseAs = (contentType) => {
562
+ if (!contentType) {
563
+ return "stream";
564
+ }
565
+ const cleanContent = contentType.split(";")[0]?.trim();
566
+ if (!cleanContent) {
567
+ return;
568
+ }
569
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
570
+ return "json";
571
+ }
572
+ if (cleanContent === "multipart/form-data") {
573
+ return "formData";
574
+ }
575
+ if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
576
+ return "blob";
577
+ }
578
+ if (cleanContent.startsWith("text/")) {
579
+ return "text";
580
+ }
581
+ return;
582
+ };
583
+ var checkForExistence = (options, name) => {
584
+ if (!name) {
585
+ return false;
586
+ }
587
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
588
+ return true;
589
+ }
590
+ return false;
591
+ };
592
+ async function setAuthParams(options) {
593
+ for (const auth of options.security ?? []) {
594
+ if (checkForExistence(options, auth.name)) {
595
+ continue;
596
+ }
597
+ const token = await getAuthToken(auth, options.auth);
598
+ if (!token) {
599
+ continue;
600
+ }
601
+ const name = auth.name ?? "Authorization";
602
+ switch (auth.in) {
603
+ case "query":
604
+ if (!options.query) {
605
+ options.query = {};
606
+ }
607
+ options.query[name] = token;
608
+ break;
609
+ case "cookie":
610
+ options.headers.append("Cookie", `${name}=${token}`);
611
+ break;
612
+ case "header":
613
+ default:
614
+ options.headers.set(name, token);
615
+ break;
616
+ }
617
+ }
618
+ }
619
+ var buildUrl = (options) => getUrl({
620
+ baseUrl: options.baseUrl,
621
+ path: options.path,
622
+ query: options.query,
623
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
624
+ url: options.url
625
+ });
626
+ var mergeConfigs = (a, b) => {
627
+ const config = { ...a, ...b };
628
+ if (config.baseUrl?.endsWith("/")) {
629
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
630
+ }
631
+ config.headers = mergeHeaders(a.headers, b.headers);
632
+ return config;
633
+ };
634
+ var headersEntries = (headers) => {
635
+ const entries = [];
636
+ headers.forEach((value, key) => {
637
+ entries.push([key, value]);
638
+ });
639
+ return entries;
640
+ };
641
+ var mergeHeaders = (...headers) => {
642
+ const mergedHeaders = new Headers();
643
+ for (const header of headers) {
644
+ if (!header) {
645
+ continue;
646
+ }
647
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
648
+ for (const [key, value] of iterator) {
649
+ if (value === null) {
650
+ mergedHeaders.delete(key);
651
+ } else if (Array.isArray(value)) {
652
+ for (const v of value) {
653
+ mergedHeaders.append(key, v);
654
+ }
655
+ } else if (value !== void 0) {
656
+ mergedHeaders.set(
657
+ key,
658
+ typeof value === "object" ? JSON.stringify(value) : value
659
+ );
660
+ }
661
+ }
662
+ }
663
+ return mergedHeaders;
664
+ };
665
+ var Interceptors = class {
666
+ fns = [];
667
+ clear() {
668
+ this.fns = [];
669
+ }
670
+ eject(id) {
671
+ const index = this.getInterceptorIndex(id);
672
+ if (this.fns[index]) {
673
+ this.fns[index] = null;
674
+ }
675
+ }
676
+ exists(id) {
677
+ const index = this.getInterceptorIndex(id);
678
+ return Boolean(this.fns[index]);
679
+ }
680
+ getInterceptorIndex(id) {
681
+ if (typeof id === "number") {
682
+ return this.fns[id] ? id : -1;
683
+ }
684
+ return this.fns.indexOf(id);
685
+ }
686
+ update(id, fn) {
687
+ const index = this.getInterceptorIndex(id);
688
+ if (this.fns[index]) {
689
+ this.fns[index] = fn;
690
+ return id;
691
+ }
692
+ return false;
693
+ }
694
+ use(fn) {
695
+ this.fns.push(fn);
696
+ return this.fns.length - 1;
697
+ }
698
+ };
699
+ var createInterceptors = () => ({
700
+ error: new Interceptors(),
701
+ request: new Interceptors(),
702
+ response: new Interceptors()
703
+ });
704
+ var defaultQuerySerializer = createQuerySerializer({
705
+ allowReserved: false,
706
+ array: {
707
+ explode: true,
708
+ style: "form"
709
+ },
710
+ object: {
711
+ explode: true,
712
+ style: "deepObject"
713
+ }
714
+ });
715
+ var defaultHeaders = {
716
+ "Content-Type": "application/json"
717
+ };
718
+ var createConfig = (override = {}) => ({
719
+ ...jsonBodySerializer,
720
+ headers: defaultHeaders,
721
+ parseAs: "auto",
722
+ querySerializer: defaultQuerySerializer,
723
+ ...override
724
+ });
725
+
726
+ // src/sdk/client/client.gen.ts
727
+ var createClient = (config = {}) => {
728
+ let _config = mergeConfigs(createConfig(), config);
729
+ const getConfig = () => ({ ..._config });
730
+ const setConfig = (config2) => {
731
+ _config = mergeConfigs(_config, config2);
732
+ return getConfig();
733
+ };
734
+ const interceptors = createInterceptors();
735
+ const beforeRequest = async (options) => {
736
+ const opts = {
737
+ ..._config,
738
+ ...options,
739
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
740
+ headers: mergeHeaders(_config.headers, options.headers),
741
+ serializedBody: void 0
742
+ };
743
+ if (opts.security) {
744
+ await setAuthParams(opts);
745
+ }
746
+ if (opts.requestValidator) {
747
+ await opts.requestValidator(opts);
748
+ }
749
+ if (opts.body !== void 0 && opts.bodySerializer) {
750
+ opts.serializedBody = opts.bodySerializer(opts.body);
751
+ }
752
+ if (opts.body === void 0 || opts.serializedBody === "") {
753
+ opts.headers.delete("Content-Type");
754
+ }
755
+ const resolvedOpts = opts;
756
+ const url = buildUrl(resolvedOpts);
757
+ return { opts: resolvedOpts, url };
758
+ };
759
+ const request = async (options) => {
760
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
761
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
762
+ let request2;
763
+ let response;
764
+ try {
765
+ const { opts, url } = await beforeRequest(options);
766
+ const requestInit = {
767
+ redirect: "follow",
768
+ ...opts,
769
+ body: getValidRequestBody(opts)
770
+ };
771
+ request2 = new Request(url, requestInit);
772
+ for (const fn of interceptors.request.fns) {
773
+ if (fn) {
774
+ request2 = await fn(request2, opts);
775
+ }
776
+ }
777
+ const _fetch = opts.fetch;
778
+ response = await _fetch(request2);
779
+ for (const fn of interceptors.response.fns) {
780
+ if (fn) {
781
+ response = await fn(response, request2, opts);
782
+ }
783
+ }
784
+ const result = {
785
+ request: request2,
786
+ response
787
+ };
788
+ if (response.ok) {
789
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
790
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
791
+ let emptyData;
792
+ switch (parseAs) {
793
+ case "arrayBuffer":
794
+ case "blob":
795
+ case "text":
796
+ emptyData = await response[parseAs]();
797
+ break;
798
+ case "formData":
799
+ emptyData = new FormData();
800
+ break;
801
+ case "stream":
802
+ emptyData = response.body;
803
+ break;
804
+ case "json":
805
+ default:
806
+ emptyData = {};
807
+ break;
808
+ }
809
+ return opts.responseStyle === "data" ? emptyData : {
810
+ data: emptyData,
811
+ ...result
812
+ };
813
+ }
814
+ let data;
815
+ switch (parseAs) {
816
+ case "arrayBuffer":
817
+ case "blob":
818
+ case "formData":
819
+ case "text":
820
+ data = await response[parseAs]();
821
+ break;
822
+ case "json": {
823
+ const text = await response.text();
824
+ data = text ? JSON.parse(text) : {};
825
+ break;
826
+ }
827
+ case "stream":
828
+ return opts.responseStyle === "data" ? response.body : {
829
+ data: response.body,
830
+ ...result
831
+ };
832
+ }
833
+ if (parseAs === "json") {
834
+ if (opts.responseValidator) {
835
+ await opts.responseValidator(data);
836
+ }
837
+ if (opts.responseTransformer) {
838
+ data = await opts.responseTransformer(data);
839
+ }
840
+ }
841
+ return opts.responseStyle === "data" ? data : {
842
+ data,
843
+ ...result
844
+ };
845
+ }
846
+ const textError = await response.text();
847
+ let jsonError;
848
+ try {
849
+ jsonError = JSON.parse(textError);
850
+ } catch {
851
+ }
852
+ throw jsonError ?? textError;
853
+ } catch (error) {
854
+ let finalError = error;
855
+ for (const fn of interceptors.error.fns) {
856
+ if (fn) {
857
+ finalError = await fn(finalError, response, request2, options);
858
+ }
859
+ }
860
+ finalError = finalError || {};
861
+ if (throwOnError) {
862
+ throw finalError;
863
+ }
864
+ return responseStyle === "data" ? void 0 : {
865
+ error: finalError,
866
+ request: request2,
867
+ response
868
+ };
869
+ }
870
+ };
871
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
872
+ const makeSseFn = (method) => async (options) => {
873
+ const { opts, url } = await beforeRequest(options);
874
+ return createSseClient({
875
+ ...opts,
876
+ body: opts.body,
877
+ method,
878
+ onRequest: async (url2, init) => {
879
+ let request2 = new Request(url2, init);
880
+ for (const fn of interceptors.request.fns) {
881
+ if (fn) {
882
+ request2 = await fn(request2, opts);
883
+ }
884
+ }
885
+ return request2;
886
+ },
887
+ serializedBody: getValidRequestBody(opts),
888
+ url
889
+ });
890
+ };
891
+ const _buildUrl = (options) => buildUrl({ ..._config, ...options });
892
+ return {
893
+ buildUrl: _buildUrl,
894
+ connect: makeMethodFn("CONNECT"),
895
+ delete: makeMethodFn("DELETE"),
896
+ get: makeMethodFn("GET"),
897
+ getConfig,
898
+ head: makeMethodFn("HEAD"),
899
+ interceptors,
900
+ options: makeMethodFn("OPTIONS"),
901
+ patch: makeMethodFn("PATCH"),
902
+ post: makeMethodFn("POST"),
903
+ put: makeMethodFn("PUT"),
904
+ request,
905
+ setConfig,
906
+ sse: {
907
+ connect: makeSseFn("CONNECT"),
908
+ delete: makeSseFn("DELETE"),
909
+ get: makeSseFn("GET"),
910
+ head: makeSseFn("HEAD"),
911
+ options: makeSseFn("OPTIONS"),
912
+ patch: makeSseFn("PATCH"),
913
+ post: makeSseFn("POST"),
914
+ put: makeSseFn("PUT"),
915
+ trace: makeSseFn("TRACE")
916
+ },
917
+ trace: makeMethodFn("TRACE")
918
+ };
919
+ };
920
+
921
+ // src/sdk/client.gen.ts
922
+ var client = createClient(createConfig({ baseUrl: "https://api-dev.anyformat.ai" }));
923
+
924
+ // src/sdk/sdk.gen.ts
925
+ var v2CreateWorkflow = (options) => (options.client ?? client).post({
926
+ security: [{ scheme: "bearer", type: "http" }],
927
+ url: "/v2/workflows/",
928
+ ...options,
929
+ headers: {
930
+ "Content-Type": "application/json",
931
+ ...options.headers
932
+ }
933
+ });
934
+ var v2GetFileResults = (options) => (options.client ?? client).get({
935
+ security: [{ scheme: "bearer", type: "http" }],
936
+ url: "/v2/workflows/{workflow_id}/files/{collection_id}/results/",
937
+ ...options
938
+ });
939
+ var v2RunWorkflow = (options) => (options.client ?? client).post({
940
+ ...formDataBodySerializer,
941
+ security: [{ scheme: "bearer", type: "http" }],
942
+ url: "/v2/workflows/{workflow_id}/run/",
943
+ ...options,
944
+ headers: {
945
+ "Content-Type": null,
946
+ ...options.headers
947
+ }
948
+ });
949
+
950
+ // src/run.ts
951
+ var Run = class {
952
+ constructor(client2, request, file, text) {
953
+ this.client = client2;
954
+ this.request = request;
955
+ this.file = file;
956
+ this.text = text;
957
+ }
958
+ client;
959
+ request;
960
+ file;
961
+ text;
962
+ workflowId = null;
963
+ collectionId = null;
964
+ /**
965
+ * Create the workflow and submit the document — exactly once per `Run`.
966
+ * Memoized so that retrying `wait()` after an `SDKTimeout` resumes polling
967
+ * the in-flight run instead of creating a duplicate workflow + submission.
968
+ */
969
+ async submit() {
970
+ if (this.collectionId !== null) return;
971
+ const created = await v2CreateWorkflow({ client: this.client, body: this.request });
972
+ if (created.error) throw toApiError(created.response?.status ?? 500, created.error);
973
+ this.workflowId = created.data.id;
974
+ const submitted = await v2RunWorkflow({
975
+ client: this.client,
976
+ path: { workflow_id: this.workflowId },
977
+ body: { file: this.file, text: this.text }
978
+ });
979
+ if (submitted.error) throw toApiError(submitted.response?.status ?? 500, submitted.error);
980
+ this.collectionId = submitted.data.id;
981
+ }
982
+ async wait(opts = {}) {
983
+ const timeoutMs = opts.timeoutMs ?? 12e4;
984
+ const pollMs = opts.pollMs ?? 2e3;
985
+ await this.submit();
986
+ const deadline = Date.now() + timeoutMs;
987
+ while (Date.now() < deadline) {
988
+ const results = await v2GetFileResults({
989
+ client: this.client,
990
+ path: { workflow_id: this.workflowId, collection_id: this.collectionId }
991
+ });
992
+ if (!results.error) return new Result(results.data);
993
+ if (results.response?.status !== 412) {
994
+ throw toApiError(results.response?.status ?? 500, results.error);
995
+ }
996
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
997
+ }
998
+ throw new SDKTimeout(`Extraction did not complete within ${timeoutMs}ms`);
999
+ }
1000
+ };
1001
+
1002
+ // src/builder.ts
1003
+ var WorkflowBuilder = class {
1004
+ constructor(client2, name, description) {
1005
+ this.client = client2;
1006
+ this.name = name;
1007
+ this.description = description;
1008
+ }
1009
+ client;
1010
+ name;
1011
+ description;
1012
+ parseNode = null;
1013
+ classifyNode = null;
1014
+ splitNode = null;
1015
+ splitRouteFrom = null;
1016
+ extracts = [];
1017
+ validates = [];
1018
+ idCounters = {};
1019
+ nextId(kind) {
1020
+ this.idCounters[kind] = (this.idCounters[kind] ?? 0) + 1;
1021
+ return `${kind}_${this.idCounters[kind]}`;
1022
+ }
1023
+ require(condition, message) {
1024
+ if (!condition) throw new WorkflowBuilderError(message);
1025
+ }
1026
+ parse(opts = {}) {
1027
+ this.require(this.parseNode === null, "parse() can only be called once");
1028
+ this.parseNode = {
1029
+ type: "parse",
1030
+ id: opts.id ?? this.nextId("parse"),
1031
+ mode: opts.mode ?? "standard",
1032
+ ...opts.promptHint !== void 0 ? { prompt_hint: opts.promptHint } : {},
1033
+ figure_enhancement: opts.figureEnhancement ?? false
1034
+ };
1035
+ return this;
1036
+ }
1037
+ classify(categories, opts = {}) {
1038
+ this.require(this.parseNode !== null, "classify() requires parse() first");
1039
+ this.require(this.classifyNode === null, "classify() can only be called once");
1040
+ this.require(categories.length > 0, "classify() requires at least one category");
1041
+ this.classifyNode = { type: "classify", id: opts.id ?? this.nextId("classify"), categories };
1042
+ return this;
1043
+ }
1044
+ split(rules, opts = {}) {
1045
+ this.require(this.parseNode !== null, "split() requires parse() first");
1046
+ this.require(this.splitNode === null, "split() can only be called once");
1047
+ this.require(rules.length > 0, "split() requires at least one rule");
1048
+ this.require(
1049
+ !(opts.routeFrom !== void 0 && this.classifyNode === null),
1050
+ "routeFrom is only valid after classify()"
1051
+ );
1052
+ this.require(
1053
+ !(this.classifyNode !== null && opts.routeFrom === void 0),
1054
+ "split(rules, { routeFrom }) is required when chaining after classify() \u2014 specify which classify branch routes into the splitter"
1055
+ );
1056
+ this.splitRouteFrom = this.normalizeClassifyBranch(opts.routeFrom, "routeFrom");
1057
+ this.splitNode = { type: "splitter", id: opts.id ?? this.nextId("split"), rules };
1058
+ return this;
1059
+ }
1060
+ extract(fields, opts = {}) {
1061
+ this.require(this.parseNode !== null, "extract() requires parse() first");
1062
+ this.require(fields.length > 0, "extract() requires at least one field");
1063
+ const hasRouter = this.classifyNode !== null || this.splitNode !== null;
1064
+ this.require(
1065
+ !(hasRouter && opts.branch === void 0),
1066
+ "extract(fields, { branch }) is required when classify() or split() is used"
1067
+ );
1068
+ this.require(
1069
+ !(!hasRouter && opts.branch !== void 0),
1070
+ "extract(fields, { branch }) is only valid after classify() or split()"
1071
+ );
1072
+ const branchId = this.normalizeExtractBranch(opts.branch);
1073
+ const node = {
1074
+ type: "extract",
1075
+ id: opts.id ?? this.nextId("extract"),
1076
+ extraction_schema: { fields }
1077
+ };
1078
+ this.extracts.push([node, branchId]);
1079
+ return this;
1080
+ }
1081
+ validate(rules, opts = {}) {
1082
+ this.require(this.parseNode !== null, "validate() requires parse() first");
1083
+ this.require(this.extracts.length > 0, "validate() requires extract() first");
1084
+ this.require(rules.length > 0, "validate() requires at least one rule");
1085
+ let sourceExtractId;
1086
+ if (opts.branch !== void 0) {
1087
+ const branchId = this.normalizeExtractBranch(opts.branch);
1088
+ const matching = this.extracts.filter(([, b]) => b === branchId);
1089
+ this.require(matching.length > 0, `validate(branch) did not match any extract`);
1090
+ sourceExtractId = matching[matching.length - 1][0].id;
1091
+ } else {
1092
+ sourceExtractId = this.extracts[this.extracts.length - 1][0].id;
1093
+ }
1094
+ const node = { type: "validate", id: opts.id ?? this.nextId("validate"), rules };
1095
+ this.validates.push([node, sourceExtractId]);
1096
+ return this;
1097
+ }
1098
+ normalizeClassifyBranch(value, kwarg) {
1099
+ if (value === void 0) return null;
1100
+ const categories = this.classifyNode?.categories ?? [];
1101
+ if (typeof value !== "string") {
1102
+ if (!categories.some((c) => c.id === value.id)) {
1103
+ throw new WorkflowBuilderError(`${kwarg}=${value.id} is not one of the registered classify categories`);
1104
+ }
1105
+ return value.id;
1106
+ }
1107
+ if (!categories.some((c) => c.id === value)) {
1108
+ throw new WorkflowBuilderError(`${kwarg}=${value} does not match any classify category id`);
1109
+ }
1110
+ return value;
1111
+ }
1112
+ normalizeExtractBranch(value) {
1113
+ if (value === void 0) return null;
1114
+ const router = this.splitNode?.rules ?? this.classifyNode?.categories ?? [];
1115
+ if (typeof value !== "string") {
1116
+ if (!router.some((item) => item.id === value.id)) {
1117
+ const expected = this.splitNode ? "splitter rule" : "classify category";
1118
+ throw new WorkflowBuilderError(`branch=${value.id} is not one of the registered ${expected} objects`);
1119
+ }
1120
+ return value.id;
1121
+ }
1122
+ if (!router.some((item) => item.id === value)) {
1123
+ throw new WorkflowBuilderError(`branch=${value} does not match any router id`);
1124
+ }
1125
+ return value;
1126
+ }
1127
+ /** Assemble the wire request (branch-routed edges). Pure — no network. */
1128
+ build() {
1129
+ if (this.parseNode === null) throw new WorkflowBuilderError("build() requires parse()");
1130
+ const parseId = this.parseNode.id;
1131
+ const nodes = [this.parseNode];
1132
+ const edges = [];
1133
+ if (this.classifyNode !== null) {
1134
+ nodes.push(this.classifyNode);
1135
+ edges.push({ source: parseId, target: this.classifyNode.id });
1136
+ }
1137
+ if (this.splitNode !== null) {
1138
+ nodes.push(this.splitNode);
1139
+ if (this.classifyNode !== null) {
1140
+ edges.push({ source: this.classifyNode.id, target: this.splitNode.id, branch: this.splitRouteFrom });
1141
+ } else {
1142
+ edges.push({ source: parseId, target: this.splitNode.id });
1143
+ }
1144
+ }
1145
+ const routerId = this.splitNode?.id ?? this.classifyNode?.id ?? null;
1146
+ for (const [node, branchId] of this.extracts) {
1147
+ nodes.push(node);
1148
+ edges.push(
1149
+ routerId === null ? { source: parseId, target: node.id } : { source: routerId, target: node.id, branch: branchId }
1150
+ );
1151
+ }
1152
+ for (const [node, sourceExtractId] of this.validates) {
1153
+ nodes.push(node);
1154
+ edges.push({ source: sourceExtractId, target: node.id });
1155
+ }
1156
+ return { name: this.name, description: this.description, nodes, edges };
1157
+ }
1158
+ /** Persist the workflow and return its id. */
1159
+ async create() {
1160
+ const res = await v2CreateWorkflow({ client: this.client, body: this.build() });
1161
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1162
+ return res.data.id;
1163
+ }
1164
+ /** Create the workflow, submit a document, and return a pending `Run`. */
1165
+ run(file = null, opts = {}) {
1166
+ this.require(
1167
+ !(file === null && opts.text === void 0),
1168
+ "run() requires a document \u2014 pass a file or opts.text"
1169
+ );
1170
+ return new Run(this.client, this.build(), file, opts.text ?? null);
1171
+ }
1172
+ };
1173
+
1174
+ // src/client.ts
1175
+ var Anyformat = class {
1176
+ /** @internal */
1177
+ _client;
1178
+ constructor(opts) {
1179
+ this._client = createClient(
1180
+ createConfig({
1181
+ baseUrl: opts.baseUrl ?? "https://api.anyformat.ai",
1182
+ auth: opts.apiKey
1183
+ })
1184
+ );
1185
+ }
1186
+ workflow(name, description) {
1187
+ return new WorkflowBuilder(this._client, name, description);
1188
+ }
1189
+ };
1190
+
1191
+ // src/schema.ts
1192
+ var Schema = {
1193
+ string: (name, description) => ({ data_type: "string", name, description }),
1194
+ integer: (name, description) => ({ data_type: "integer", name, description }),
1195
+ float: (name, description) => ({ data_type: "float", name, description }),
1196
+ boolean: (name, description) => ({ data_type: "boolean", name, description }),
1197
+ date: (name, description) => ({ data_type: "date", name, description }),
1198
+ datetime: (name, description) => ({ data_type: "datetime", name, description }),
1199
+ enum: (name, description, options) => ({
1200
+ data_type: "enum",
1201
+ name,
1202
+ description,
1203
+ enum_options: options
1204
+ }),
1205
+ multiSelect: (name, description, options) => ({
1206
+ data_type: "multi_select",
1207
+ name,
1208
+ description,
1209
+ enum_options: options
1210
+ }),
1211
+ object: (name, description, fields) => ({
1212
+ data_type: "object",
1213
+ name,
1214
+ description,
1215
+ nested_fields: fields
1216
+ }),
1217
+ option: (name, description) => ({ name, description })
1218
+ };
1219
+ // Annotate the CommonJS export names for ESM import in node:
1220
+ 0 && (module.exports = {
1221
+ APIError,
1222
+ Anyformat,
1223
+ AnyformatError,
1224
+ BadRequest,
1225
+ Forbidden,
1226
+ NotFound,
1227
+ RateLimited,
1228
+ Result,
1229
+ Run,
1230
+ SDKTimeout,
1231
+ Schema,
1232
+ ServerError,
1233
+ Unauthorized,
1234
+ WorkflowBuilder,
1235
+ WorkflowBuilderError
1236
+ });
1237
+ //# sourceMappingURL=index.cjs.map