@anyformat/sdk 0.2.2 → 1.0.0-rc.2

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.js CHANGED
@@ -1,3 +1,46 @@
1
+ // package.json
2
+ var package_default = {
3
+ name: "@anyformat/sdk",
4
+ version: "1.0.0-rc.2",
5
+ description: "TypeScript SDK for the AnyFormat API",
6
+ license: "MIT",
7
+ author: "Anyformat <info@anyformat.ai>",
8
+ type: "module",
9
+ main: "./dist/index.cjs",
10
+ module: "./dist/index.js",
11
+ types: "./dist/index.d.ts",
12
+ exports: {
13
+ ".": {
14
+ types: "./dist/index.d.ts",
15
+ import: "./dist/index.js",
16
+ require: "./dist/index.cjs"
17
+ }
18
+ },
19
+ files: [
20
+ "dist"
21
+ ],
22
+ engines: {
23
+ node: ">=18"
24
+ },
25
+ scripts: {
26
+ "gen:spec": 'ROOT=$(unset GIT_DIR && git rev-parse --show-toplevel) && cd "$ROOT/anyformat/services/api" && uv run python "$ROOT/anyformat/libs/public/sdk-js/scripts/dump_openapi.py" "$ROOT/anyformat/libs/public/sdk-js/openapi/v2.json" --surface v2 && uv run python "$ROOT/anyformat/libs/public/sdk-js/scripts/dump_openapi.py" "$ROOT/anyformat/libs/public/sdk-js/openapi/v3.json" --surface v3',
27
+ "gen:client": "openapi-ts",
28
+ gen: "bun run gen:spec && bun run gen:client",
29
+ "gen:check": "bun run gen && git diff --exit-code -- openapi src/sdk",
30
+ build: "tsup",
31
+ typecheck: "tsc --noEmit",
32
+ test: "vitest run",
33
+ prepublishOnly: "bun run build"
34
+ },
35
+ devDependencies: {
36
+ "@hey-api/openapi-ts": "^0.99.0",
37
+ "@types/node": "^25.9.1",
38
+ tsup: "^8.3.0",
39
+ typescript: "^5.6.0",
40
+ vitest: "^4.1.7"
41
+ }
42
+ };
43
+
1
44
  // src/builder.ts
2
45
  import { readFileSync } from "fs";
3
46
  import { basename } from "path";
@@ -41,8 +84,8 @@ var Result = class {
41
84
  }
42
85
  raw;
43
86
  _parse;
44
- get collectionId() {
45
- return this.raw.collection_id;
87
+ get documentPacketId() {
88
+ return this.raw.document_packet_id;
46
89
  }
47
90
  get extractions() {
48
91
  return this.raw.extractions ?? [];
@@ -59,13 +102,22 @@ var Result = class {
59
102
  return this._parse;
60
103
  }
61
104
  /**
62
- * Convenience accessor for a top-level scalar field on the first
63
- * extraction (linear workflows). Returns `undefined` for missing fields
64
- * or list-valued fields — read `extractions` directly for those.
105
+ * Convenience accessor for a top-level field on the untagged (linear)
106
+ * extraction. Returns the scalar `ExtractedField` for a scalar field, or
107
+ * the array of row records (`ExtractedRows`) for a list/object field such
108
+ * as `line_items`. `undefined` only when the field is absent.
109
+ *
110
+ * Parameterise with the declared schema type to type a scalar's `.value`:
111
+ * `result.field<number>("total").value` is `number | null`.
65
112
  */
66
113
  field(name) {
67
- const value = this.extractions[0]?.fields?.[name];
68
- return value !== void 0 && !Array.isArray(value) ? value : void 0;
114
+ const untagged = this.extractions.find(
115
+ (e) => e.split_name == null && e.partition == null
116
+ );
117
+ const value = untagged?.fields?.[name];
118
+ if (value === void 0) return void 0;
119
+ if (Array.isArray(value)) return value;
120
+ return value;
69
121
  }
70
122
  };
71
123
 
@@ -78,39 +130,116 @@ var APIError = class extends AnyformatError {
78
130
  this.status = status;
79
131
  this.body = body;
80
132
  this.name = new.target.name;
133
+ if (body && typeof body === "object") {
134
+ const envelope = body;
135
+ if (typeof envelope.error_code === "string") this.errorCode = envelope.error_code;
136
+ if (envelope.detail !== void 0) this.detail = envelope.detail;
137
+ if (typeof envelope.retryable === "boolean") this.retryable = envelope.retryable;
138
+ if (typeof envelope.request_id === "string") this.requestId = envelope.request_id;
139
+ if (envelope.params && typeof envelope.params === "object") {
140
+ this.params = envelope.params;
141
+ }
142
+ }
81
143
  }
82
144
  status;
83
145
  body;
146
+ /** Stable identifier for programmatic handling, e.g. `PAYMENT_REQUIRED`. */
147
+ errorCode;
148
+ /** Developer-facing explanation; not surfaced in `message` (ADR platform/0053 §2). Often a `ValidationItem[]`. */
149
+ detail;
150
+ /** Named substitutions the `error` summary refers to, e.g. `{ required_scope }`. */
151
+ params;
152
+ /** Whether the API says retrying the same request can succeed. */
153
+ retryable;
154
+ /** Correlation id to quote in support requests. */
155
+ requestId;
84
156
  };
85
- var BadRequest = class extends APIError {
157
+ var BadRequestError = class extends APIError {
86
158
  };
87
- var Unauthorized = class extends APIError {
159
+ var UnauthorizedError = class extends APIError {
88
160
  };
89
- var Forbidden = class extends APIError {
161
+ var PaymentRequiredError = class extends APIError {
90
162
  };
91
- var NotFound = class extends APIError {
163
+ var ForbiddenError = class extends APIError {
92
164
  };
93
- var RateLimited = class extends APIError {
165
+ var NotFoundError = class extends APIError {
166
+ };
167
+ var RateLimitedError = class extends APIError {
168
+ constructor(status, message, body, retryAfter) {
169
+ super(status, message, body);
170
+ this.retryAfter = retryAfter;
171
+ }
172
+ retryAfter;
94
173
  };
95
174
  var ServerError = class extends APIError {
96
175
  };
97
- var SDKTimeout = class extends AnyformatError {
176
+ function parseRetryAfter(raw) {
177
+ if (raw == null || raw.trim() === "") return void 0;
178
+ const seconds = Number(raw);
179
+ if (!Number.isNaN(seconds)) return seconds;
180
+ const when = Date.parse(raw);
181
+ if (Number.isNaN(when)) return void 0;
182
+ return Math.max((when - Date.now()) / 1e3, 0);
183
+ }
184
+ var InsufficientScopeError = class extends ForbiddenError {
185
+ };
186
+ var TermsAcceptanceRequiredError = class extends ForbiddenError {
187
+ };
188
+ var WorkflowNameConflictError = class extends APIError {
189
+ };
190
+ var SDKTimeoutError = class extends AnyformatError {
191
+ };
192
+ var RunFailedError = class extends AnyformatError {
193
+ constructor(runId, status) {
194
+ super(`Run ${runId} ended with status "${status}"`);
195
+ this.runId = runId;
196
+ this.status = status;
197
+ this.name = new.target.name;
198
+ }
199
+ runId;
200
+ status;
201
+ };
202
+ var ExtractionFailedError = class extends RunFailedError {
203
+ constructor(runId) {
204
+ super(runId, "error");
205
+ }
206
+ };
207
+ var ExtractionCancelledError = class extends RunFailedError {
208
+ constructor(runId) {
209
+ super(runId, "cancelled");
210
+ }
98
211
  };
99
212
  var WorkflowBuilderError = class extends AnyformatError {
100
213
  };
101
- function toApiError(status, body) {
102
- const message = `AnyFormat API error (${status})`;
214
+ function messageFrom(status, body) {
215
+ const fallback = `AnyFormat API error (${status})`;
216
+ if (!body || typeof body !== "object") return fallback;
217
+ const envelope = body;
218
+ return typeof envelope.error === "string" && envelope.error ? envelope.error : fallback;
219
+ }
220
+ var BY_ERROR_CODE = {
221
+ insufficient_api_key_scope: InsufficientScopeError,
222
+ terms_acceptance_required: TermsAcceptanceRequiredError,
223
+ WORKFLOW_NAME_CONFLICT: WorkflowNameConflictError
224
+ };
225
+ function toApiError(status, body, headers) {
226
+ const message = messageFrom(status, body);
227
+ const errorCode = body && typeof body === "object" && typeof body.error_code === "string" ? body.error_code : void 0;
228
+ const ByCode = errorCode ? BY_ERROR_CODE[errorCode] : void 0;
229
+ if (ByCode) return new ByCode(status, message, body);
103
230
  switch (status) {
104
231
  case 400:
105
- return new BadRequest(status, message, body);
232
+ return new BadRequestError(status, message, body);
106
233
  case 401:
107
- return new Unauthorized(status, message, body);
234
+ return new UnauthorizedError(status, message, body);
235
+ case 402:
236
+ return new PaymentRequiredError(status, message, body);
108
237
  case 403:
109
- return new Forbidden(status, message, body);
238
+ return new ForbiddenError(status, message, body);
110
239
  case 404:
111
- return new NotFound(status, message, body);
240
+ return new NotFoundError(status, message, body);
112
241
  case 429:
113
- return new RateLimited(status, message, body);
242
+ return new RateLimitedError(status, message, body, parseRetryAfter(headers?.get("Retry-After")));
114
243
  default:
115
244
  return status >= 500 ? new ServerError(status, message, body) : new APIError(status, message, body);
116
245
  }
@@ -170,7 +299,7 @@ function createSseClient({
170
299
  ...options
171
300
  }) {
172
301
  let lastEventId;
173
- const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
302
+ const sleep2 = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
174
303
  const createStream = async function* () {
175
304
  let retryDelay = sseDefaultRetryDelay ?? 3e3;
176
305
  let attempt = 0;
@@ -274,7 +403,7 @@ function createSseClient({
274
403
  break;
275
404
  }
276
405
  const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
277
- await sleep(backoff);
406
+ await sleep2(backoff);
278
407
  }
279
408
  }
280
409
  };
@@ -927,46 +1056,115 @@ var createClient = (config = {}) => {
927
1056
  };
928
1057
 
929
1058
  // src/sdk/client.gen.ts
930
- var client = createClient(createConfig({ baseUrl: "https://api-dev.anyformat.ai" }));
1059
+ var client = createClient(createConfig({ baseUrl: "https://api.anyformat.dev" }));
931
1060
 
932
1061
  // src/sdk/sdk.gen.ts
933
- var v2ListWorkflows = (options) => (options?.client ?? client).get({
1062
+ var v3DeleteDocumentPacket = (options) => (options.client ?? client).delete({
1063
+ security: [{ scheme: "bearer", type: "http" }],
1064
+ url: "/v3/document-packets/{document_packet_id}/",
1065
+ ...options
1066
+ });
1067
+ var v3GetDocumentPacket = (options) => (options.client ?? client).get({
1068
+ security: [{ scheme: "bearer", type: "http" }],
1069
+ url: "/v3/document-packets/{document_packet_id}/",
1070
+ ...options
1071
+ });
1072
+ var v3RunDocumentPacket = (options) => (options.client ?? client).post({
934
1073
  security: [{ scheme: "bearer", type: "http" }],
935
- url: "/v2/workflows/",
1074
+ url: "/v3/document-packets/{document_packet_id}/run/",
936
1075
  ...options
937
1076
  });
938
- var v2CreateWorkflow = (options) => (options.client ?? client).post({
1077
+ var v3Parse = (options) => (options.client ?? client).post({
1078
+ ...formDataBodySerializer,
939
1079
  security: [{ scheme: "bearer", type: "http" }],
940
- url: "/v2/workflows/",
1080
+ url: "/v3/parse/",
1081
+ ...options,
1082
+ headers: {
1083
+ "Content-Type": null,
1084
+ ...options.headers
1085
+ }
1086
+ });
1087
+ var v3GetRun = (options) => (options.client ?? client).get({
1088
+ security: [{ scheme: "bearer", type: "http" }],
1089
+ url: "/v3/runs/{run_id}/",
1090
+ ...options
1091
+ });
1092
+ var v3ListWorkflows = (options) => (options?.client ?? client).get({
1093
+ security: [{ scheme: "bearer", type: "http" }],
1094
+ url: "/v3/workflows/",
1095
+ ...options
1096
+ });
1097
+ var v3CreateWorkflow = (options) => (options.client ?? client).post({
1098
+ security: [{ scheme: "bearer", type: "http" }],
1099
+ url: "/v3/workflows/",
941
1100
  ...options,
942
1101
  headers: {
943
1102
  "Content-Type": "application/json",
944
1103
  ...options.headers
945
1104
  }
946
1105
  });
947
- var v2DeleteWorkflow = (options) => (options.client ?? client).delete({
1106
+ var v3DeleteWorkflow = (options) => (options.client ?? client).delete({
1107
+ security: [{ scheme: "bearer", type: "http" }],
1108
+ url: "/v3/workflows/{workflow_id}/",
1109
+ ...options
1110
+ });
1111
+ var v3GetWorkflow = (options) => (options.client ?? client).get({
948
1112
  security: [{ scheme: "bearer", type: "http" }],
949
- url: "/v2/workflows/{workflow_id}/",
1113
+ url: "/v3/workflows/{workflow_id}/",
950
1114
  ...options
951
1115
  });
952
- var v2UpdateWorkflow = (options) => (options.client ?? client).put({
1116
+ var v3UpdateWorkflow = (options) => (options.client ?? client).patch({
953
1117
  security: [{ scheme: "bearer", type: "http" }],
954
- url: "/v2/workflows/{workflow_id}/",
1118
+ url: "/v3/workflows/{workflow_id}/",
955
1119
  ...options,
956
1120
  headers: {
957
1121
  "Content-Type": "application/json",
958
1122
  ...options.headers
959
1123
  }
960
1124
  });
961
- var v2GetFileResults = (options) => (options.client ?? client).get({
1125
+ var v3UploadToDataset = (options) => (options.client ?? client).post({
1126
+ ...formDataBodySerializer,
962
1127
  security: [{ scheme: "bearer", type: "http" }],
963
- url: "/v2/workflows/{workflow_id}/files/{collection_id}/results/",
1128
+ url: "/v3/workflows/{workflow_id}/dataset/upload/",
1129
+ ...options,
1130
+ headers: {
1131
+ "Content-Type": null,
1132
+ ...options.headers
1133
+ }
1134
+ });
1135
+ var v3ListWorkflowDocumentPackets = (options) => (options.client ?? client).get({
1136
+ security: [{ scheme: "bearer", type: "http" }],
1137
+ url: "/v3/workflows/{workflow_id}/document-packets/",
1138
+ ...options
1139
+ });
1140
+ var v3ListWorkflowRuns = (options) => (options.client ?? client).get({
1141
+ security: [{ scheme: "bearer", type: "http" }],
1142
+ url: "/v3/workflows/{workflow_id}/runs/",
964
1143
  ...options
965
1144
  });
966
- var v2RunWorkflow = (options) => (options.client ?? client).post({
1145
+ var v3UploadToWorkflow = (options) => (options.client ?? client).post({
967
1146
  ...formDataBodySerializer,
968
1147
  security: [{ scheme: "bearer", type: "http" }],
969
- url: "/v2/workflows/{workflow_id}/run/",
1148
+ url: "/v3/workflows/{workflow_id}/upload/",
1149
+ ...options,
1150
+ headers: {
1151
+ "Content-Type": null,
1152
+ ...options.headers
1153
+ }
1154
+ });
1155
+ var v3UploadFromUrl = (options) => (options.client ?? client).post({
1156
+ security: [{ scheme: "bearer", type: "http" }],
1157
+ url: "/v3/workflows/{workflow_id}/upload/from-url/",
1158
+ ...options,
1159
+ headers: {
1160
+ "Content-Type": "application/json",
1161
+ ...options.headers
1162
+ }
1163
+ });
1164
+ var v3UploadAndRunWorkflow = (options) => (options.client ?? client).post({
1165
+ ...formDataBodySerializer,
1166
+ security: [{ scheme: "bearer", type: "http" }],
1167
+ url: "/v3/workflows/{workflow_id}/upload/run/",
970
1168
  ...options,
971
1169
  headers: {
972
1170
  "Content-Type": null,
@@ -975,36 +1173,129 @@ var v2RunWorkflow = (options) => (options.client ?? client).post({
975
1173
  });
976
1174
 
977
1175
  // src/run.ts
1176
+ function isTransientStatus(status) {
1177
+ return status === 429 || status >= 500;
1178
+ }
1179
+ var RETRY_BASE_MS = 1e3;
1180
+ var RETRY_MAX_MS = 3e4;
1181
+ function retryDelayMs(response, attempt) {
1182
+ const retryAfter = parseRetryAfter(response?.headers?.get("Retry-After"));
1183
+ if (retryAfter !== void 0) return Math.min(retryAfter * 1e3, RETRY_MAX_MS);
1184
+ const base = Math.min(RETRY_BASE_MS * 2 ** attempt, RETRY_MAX_MS);
1185
+ return base * (0.75 + Math.random() * 0.5);
1186
+ }
1187
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
978
1188
  var Run = class {
979
1189
  /** @internal */
980
- constructor(client2, workflowId, id) {
1190
+ constructor(client2, id, workflowId, documentPacketId, status = "queued") {
981
1191
  this.client = client2;
982
- this.workflowId = workflowId;
983
1192
  this.id = id;
1193
+ this.workflowId = workflowId;
1194
+ this.documentPacketId = documentPacketId;
1195
+ this.status = status;
984
1196
  }
985
1197
  client;
986
- workflowId;
987
1198
  id;
1199
+ workflowId;
1200
+ documentPacketId;
1201
+ /** Status at trigger time, refreshed on every `wait()` poll. */
1202
+ status;
988
1203
  async wait(opts = {}) {
989
1204
  const timeoutMs = opts.timeoutMs ?? 3e5;
990
1205
  const pollMs = opts.pollMs ?? 3e3;
991
1206
  const deadline = Date.now() + timeoutMs;
992
- while (Date.now() < deadline) {
993
- const results = await v2GetFileResults({
994
- client: this.client,
995
- path: { workflow_id: this.workflowId, collection_id: this.id }
996
- });
997
- if (!results.error) return new Result(results.data);
998
- if (results.response?.status !== 412) {
999
- throw toApiError(results.response?.status ?? 500, results.error);
1207
+ let transientFailures = 0;
1208
+ for (; ; ) {
1209
+ const res = await v3GetRun({ client: this.client, path: { run_id: this.id } });
1210
+ if (res.error) {
1211
+ const status = res.response?.status ?? 500;
1212
+ if (!isTransientStatus(status)) throw toApiError(status, res.error, res.response?.headers);
1213
+ const remainingMs = deadline - Date.now();
1214
+ if (remainingMs <= 0) {
1215
+ throw new SDKTimeoutError(`Extraction did not complete within ${timeoutMs}ms`);
1216
+ }
1217
+ await sleep(Math.min(retryDelayMs(res.response, transientFailures), remainingMs));
1218
+ transientFailures += 1;
1219
+ continue;
1220
+ }
1221
+ transientFailures = 0;
1222
+ const detail = res.data;
1223
+ this.status = detail.status;
1224
+ if (detail.status === "processed") {
1225
+ if (!detail.results) {
1226
+ throw new AnyformatError(`Run ${this.id} is processed but the API returned no results`);
1227
+ }
1228
+ return new Result(detail.results);
1000
1229
  }
1001
- await new Promise((resolve) => setTimeout(resolve, pollMs));
1230
+ if (detail.status === "error") throw new ExtractionFailedError(this.id);
1231
+ if (detail.status === "cancelled") throw new ExtractionCancelledError(this.id);
1232
+ if (Date.now() >= deadline) {
1233
+ throw new SDKTimeoutError(`Extraction did not complete within ${timeoutMs}ms`);
1234
+ }
1235
+ await sleep(pollMs);
1002
1236
  }
1003
- throw new SDKTimeout(`Extraction did not complete within ${timeoutMs}ms`);
1237
+ }
1238
+ };
1239
+
1240
+ // src/upload.ts
1241
+ var DatasetUpload = class {
1242
+ /** @internal */
1243
+ constructor(workflowId, documentPacketId, files, groundTruthSaved) {
1244
+ this.workflowId = workflowId;
1245
+ this.documentPacketId = documentPacketId;
1246
+ this.files = files;
1247
+ this.groundTruthSaved = groundTruthSaved;
1248
+ }
1249
+ workflowId;
1250
+ documentPacketId;
1251
+ files;
1252
+ groundTruthSaved;
1253
+ };
1254
+ var Upload = class {
1255
+ /** @internal */
1256
+ constructor(client2, workflowId, documentPacketId, files) {
1257
+ this.client = client2;
1258
+ this.workflowId = workflowId;
1259
+ this.documentPacketId = documentPacketId;
1260
+ this.files = files;
1261
+ }
1262
+ client;
1263
+ workflowId;
1264
+ documentPacketId;
1265
+ files;
1266
+ /** Trigger extraction on the staged packet and return a pending `Run`. */
1267
+ async run(opts = {}) {
1268
+ const res = await v3RunDocumentPacket({
1269
+ client: this.client,
1270
+ path: { document_packet_id: this.documentPacketId },
1271
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1272
+ });
1273
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1274
+ const data = res.data;
1275
+ return new Run(this.client, data.run_id, data.workflow_id, data.document_packet_id, data.status);
1004
1276
  }
1005
1277
  };
1006
1278
 
1007
1279
  // src/workflow.ts
1280
+ var MAX_FILES_PER_PACKET = 100;
1281
+ function normalizeFiles(files, op) {
1282
+ const list = files == null ? [] : Array.isArray(files) ? files : [files];
1283
+ if (list.length === 0) {
1284
+ throw new WorkflowBuilderError(`${op}() requires at least one named file`);
1285
+ }
1286
+ if (list.length > MAX_FILES_PER_PACKET) {
1287
+ throw new WorkflowBuilderError(`${op}() accepts at most ${MAX_FILES_PER_PACKET} files per document packet`);
1288
+ }
1289
+ for (const file of list) {
1290
+ const filename = file.name;
1291
+ if (typeof filename !== "string" || filename.length === 0) {
1292
+ throw new WorkflowBuilderError(
1293
+ `${op}() needs a named file so the server can detect its type \u2014 pass a File, e.g. new File([bytes], "invoice.pdf"), not a bare Blob`
1294
+ );
1295
+ }
1296
+ }
1297
+ return list;
1298
+ }
1008
1299
  var Workflow = class {
1009
1300
  /** @internal */
1010
1301
  constructor(client2, id, name) {
@@ -1015,29 +1306,90 @@ var Workflow = class {
1015
1306
  client;
1016
1307
  id;
1017
1308
  name;
1018
- /** Submit a document against this workflow and return a pending `Run`. */
1019
- async run(file = null, opts = {}) {
1020
- if (file === null && !opts.text) {
1021
- throw new WorkflowBuilderError("run() requires a document \u2014 pass a file or non-empty opts.text");
1022
- }
1023
- if (file !== null && opts.text !== void 0) {
1024
- throw new WorkflowBuilderError("run() accepts either a file or text, not both");
1025
- }
1026
- if (file !== null) {
1027
- const filename = file.name;
1028
- if (typeof filename !== "string" || filename.length === 0) {
1029
- throw new WorkflowBuilderError(
1030
- 'run() needs a named file so the server can detect its type \u2014 pass a File, e.g. new File([bytes], "invoice.pdf"), not a bare Blob'
1031
- );
1032
- }
1309
+ /** Upload 1..100 files as one document packet and run it. Returns a pending `Run`. */
1310
+ async run(files = null, opts = {}) {
1311
+ const list = normalizeFiles(files, "run");
1312
+ const submitted = await v3UploadAndRunWorkflow({
1313
+ client: this.client,
1314
+ path: { workflow_id: this.id },
1315
+ body: { files: list, ...opts.onConflict ? { on_conflict: opts.onConflict } : {} },
1316
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1317
+ });
1318
+ if (submitted.error) throw toApiError(submitted.response?.status ?? 500, submitted.error, submitted.response?.headers);
1319
+ const data = submitted.data;
1320
+ return new Run(this.client, data.run_id, data.workflow_id, data.document_packet_id, data.status);
1321
+ }
1322
+ /**
1323
+ * Stage 1..100 files as one document packet WITHOUT running it (no credits
1324
+ * spent). Returns an `Upload`; call `.run()` on it to start extraction.
1325
+ */
1326
+ async upload(files = null, opts = {}) {
1327
+ const list = normalizeFiles(files, "upload");
1328
+ const staged = await v3UploadToWorkflow({
1329
+ client: this.client,
1330
+ path: { workflow_id: this.id },
1331
+ body: { files: list, ...opts.onConflict ? { on_conflict: opts.onConflict } : {} },
1332
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1333
+ });
1334
+ if (staged.error) throw toApiError(staged.response?.status ?? 500, staged.error, staged.response?.headers);
1335
+ const data = staged.data;
1336
+ return new Upload(this.client, data.workflow_id, data.document_packet_id, data.files);
1337
+ }
1338
+ /**
1339
+ * Upload 1..100 files as ONE document (+ optional ground truth) into the
1340
+ * workflow's dataset, as one document packet. Atomic: any rejected file or a
1341
+ * ground-truth failure fails the call and stores nothing. By default a
1342
+ * colliding filename fails with `409`; pass `onConflict: "rename"` to
1343
+ * auto-rename instead.
1344
+ */
1345
+ async uploadToDataset(files = null, opts = {}) {
1346
+ const list = normalizeFiles(files, "uploadToDataset");
1347
+ const registered = await v3UploadToDataset({
1348
+ client: this.client,
1349
+ path: { workflow_id: this.id },
1350
+ body: {
1351
+ files: list,
1352
+ ...opts.groundTruth != null ? { ground_truth: JSON.stringify(opts.groundTruth) } : {},
1353
+ ...opts.onConflict ? { on_conflict: opts.onConflict } : {}
1354
+ },
1355
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1356
+ });
1357
+ if (registered.error) throw toApiError(registered.response?.status ?? 500, registered.error, registered.response?.headers);
1358
+ const data = registered.data;
1359
+ return new DatasetUpload(this.id, data.document_packet_id, data.files, data.ground_truth_saved);
1360
+ }
1361
+ /**
1362
+ * Client-orchestrated bulk dataset upload: one atomic call per document,
1363
+ * in order. There is no batch endpoint — each document is bounded and
1364
+ * independently retryable. On failure the call rejects; documents already
1365
+ * uploaded stay registered.
1366
+ */
1367
+ async uploadDocumentsToDataset(documents) {
1368
+ const uploaded = [];
1369
+ for (const doc of documents) {
1370
+ uploaded.push(
1371
+ await this.uploadToDataset(doc.files, {
1372
+ groundTruth: doc.groundTruth,
1373
+ idempotencyKey: doc.idempotencyKey,
1374
+ onConflict: doc.onConflict
1375
+ })
1376
+ );
1033
1377
  }
1034
- const submitted = await v2RunWorkflow({
1378
+ return uploaded;
1379
+ }
1380
+ /**
1381
+ * Import 1..10 HTTPS URLs server-side into one document packet, atomically.
1382
+ * Returns an `Upload`; call `.run()` on it to start extraction.
1383
+ */
1384
+ async uploadFromUrls(urls, opts = {}) {
1385
+ const staged = await v3UploadFromUrl({
1035
1386
  client: this.client,
1036
1387
  path: { workflow_id: this.id },
1037
- body: { file, text: opts.text ?? null }
1388
+ body: { urls, ...opts.onConflict ? { on_conflict: opts.onConflict } : {} }
1038
1389
  });
1039
- if (submitted.error) throw toApiError(submitted.response?.status ?? 500, submitted.error);
1040
- return new Run(this.client, this.id, submitted.data.id);
1390
+ if (staged.error) throw toApiError(staged.response?.status ?? 500, staged.error, staged.response?.headers);
1391
+ const data = staged.data;
1392
+ return new Upload(this.client, data.workflow_id, data.document_packet_id, data.files);
1041
1393
  }
1042
1394
  };
1043
1395
 
@@ -1067,13 +1419,16 @@ var WorkflowBuilder = class {
1067
1419
  }
1068
1420
  parse(opts = {}) {
1069
1421
  this.require(this.parseNode === null, "parse() can only be called once");
1422
+ const o = opts;
1070
1423
  this.parseNode = {
1071
1424
  type: "parse",
1072
- id: opts.id ?? this.nextId("parse"),
1073
- mode: opts.mode ?? "standard",
1074
- ...opts.promptHint !== void 0 ? { prompt_hint: opts.promptHint } : {},
1075
- figure_enhancement: opts.figureEnhancement ?? false,
1076
- cache: opts.cache ?? true
1425
+ id: o.id ?? this.nextId("parse"),
1426
+ mode: o.mode ?? "standard",
1427
+ ...o.promptHint !== void 0 ? { prompt_hint: o.promptHint } : {},
1428
+ figure_enhancement: o.figureEnhancement ?? false,
1429
+ cache: o.cache ?? true,
1430
+ ...o.effort !== void 0 ? { effort: o.effort } : {},
1431
+ ...o.scannedPages !== void 0 ? { scanned_pages: o.scannedPages } : {}
1077
1432
  };
1078
1433
  return this;
1079
1434
  }
@@ -1120,9 +1475,12 @@ var WorkflowBuilder = class {
1120
1475
  const node = {
1121
1476
  type: "extract",
1122
1477
  id: opts.id ?? this.nextId("extract"),
1478
+ ...opts.mode !== void 0 ? { mode: opts.mode } : {},
1123
1479
  extraction_schema: { fields },
1124
1480
  ...lookupFileUploads.length > 0 ? { lookup_file_uploads: lookupFileUploads } : {},
1125
- ...opts.lookupSuggestion !== void 0 ? { lookup_suggestion: opts.lookupSuggestion } : {}
1481
+ ...opts.lookupSuggestion !== void 0 ? { lookup_suggestion: opts.lookupSuggestion } : {},
1482
+ ...opts.lookupReasoningEffort !== void 0 ? { lookup_reasoning_effort: opts.lookupReasoningEffort } : {},
1483
+ ...opts.useImages !== void 0 ? { use_images: opts.useImages } : {}
1126
1484
  };
1127
1485
  this.extracts.push([node, branchId]);
1128
1486
  return this;
@@ -1204,21 +1562,22 @@ var WorkflowBuilder = class {
1204
1562
  }
1205
1563
  return { name: this.name, description: this.description, nodes, edges };
1206
1564
  }
1207
- /** Persist the workflow and return a handle you can `.run(file)` on. */
1565
+ /** Persist the workflow and return a handle you can `.run(files)` on. */
1208
1566
  async create() {
1209
- const res = await v2CreateWorkflow({ client: this.client, body: this.build() });
1210
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1567
+ const res = await v3CreateWorkflow({ client: this.client, body: this.build() });
1568
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1211
1569
  return new Workflow(this.client, res.data.id, res.data.name);
1212
1570
  }
1213
- /** Replace an existing workflow's definition and return a handle you can `.run(file)` on. */
1571
+ /** Replace an existing workflow's typed graph and return a handle you can `.run(files)` on. */
1214
1572
  async update(workflowId) {
1215
- const res = await v2UpdateWorkflow({ client: this.client, path: { workflow_id: workflowId }, body: this.build() });
1216
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1573
+ const res = await v3UpdateWorkflow({ client: this.client, path: { workflow_id: workflowId }, body: this.build() });
1574
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1217
1575
  return new Workflow(this.client, res.data.id, res.data.name);
1218
1576
  }
1219
1577
  };
1220
1578
 
1221
1579
  // src/client.ts
1580
+ var SDK_USER_AGENT = `anyformat-typescript-sdk-${package_default.version}`;
1222
1581
  var Anyformat = class {
1223
1582
  /** @internal */
1224
1583
  _client;
@@ -1228,66 +1587,234 @@ var Anyformat = class {
1228
1587
  baseUrl: opts.baseUrl ?? "https://api.anyformat.ai",
1229
1588
  auth: opts.apiKey,
1230
1589
  // Identifies the caller in our logs (Datadog facet). Plain HTTP callers
1231
- // send no such header and are logged as origin "api".
1232
- headers: { "x-anyformat-origin": "js-sdk" }
1590
+ // send no such header and are logged as origin "api". User-Agent is
1591
+ // ignored by browsers (forbidden header) but used by Node fetch.
1592
+ headers: {
1593
+ "x-anyformat-origin": "js-sdk",
1594
+ "User-Agent": SDK_USER_AGENT
1595
+ }
1233
1596
  })
1234
1597
  );
1235
1598
  }
1236
1599
  workflow(name, description) {
1237
1600
  return new WorkflowBuilder(this._client, name, description);
1238
1601
  }
1239
- async listWorkflows(opts) {
1240
- const res = await v2ListWorkflows({
1602
+ async listWorkflows(opts = {}) {
1603
+ const res = await v3ListWorkflows({
1604
+ client: this._client,
1605
+ query: { limit: opts.limit, cursor: opts.cursor }
1606
+ });
1607
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1608
+ return {
1609
+ items: res.data.items.map((r) => new Workflow(this._client, r.id, r.name)),
1610
+ nextCursor: res.data.next_cursor ?? null
1611
+ };
1612
+ }
1613
+ /** Retrieve a workflow with its complete typed graph inline (round-trippable into `updateWorkflow`). */
1614
+ async getWorkflow(workflowId) {
1615
+ const res = await v3GetWorkflow({ client: this._client, path: { workflow_id: workflowId } });
1616
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1617
+ return res.data;
1618
+ }
1619
+ /**
1620
+ * Replace a workflow's typed graph (atomic). Accepts the shape `getWorkflow`
1621
+ * returns — echo each field's `persistent_id` unchanged (including across
1622
+ * renames) to keep the field's identity; omit it for new fields.
1623
+ */
1624
+ async updateWorkflow(workflowId, definition) {
1625
+ const res = await v3UpdateWorkflow({
1241
1626
  client: this._client,
1242
- query: { page: opts?.page, page_size: opts?.pageSize, status: opts?.status }
1627
+ path: { workflow_id: workflowId },
1628
+ // The PATCH body forbids unknown keys, so a fetched detail's read-only
1629
+ // fields (id, timestamps) must not be forwarded.
1630
+ body: {
1631
+ name: definition.name,
1632
+ description: definition.description,
1633
+ nodes: definition.nodes,
1634
+ edges: definition.edges
1635
+ }
1243
1636
  });
1244
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1245
- return res.data.results.map((r) => new Workflow(this._client, r.id, r.name ?? ""));
1637
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1638
+ return res.data;
1246
1639
  }
1247
1640
  async deleteWorkflow(workflowId) {
1248
- const res = await v2DeleteWorkflow({
1641
+ const res = await v3DeleteWorkflow({
1249
1642
  client: this._client,
1250
1643
  path: { workflow_id: workflowId }
1251
1644
  });
1252
- if (res.error) throw toApiError(res.response?.status ?? 500, res.error);
1645
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1253
1646
  return workflowId;
1254
1647
  }
1648
+ /** Stage 1..100 files as one document packet without running it. Returns an `Upload`. */
1649
+ upload(workflowId, files, opts = {}) {
1650
+ return new Workflow(this._client, workflowId, "").upload(files, opts);
1651
+ }
1652
+ /** Upload 1..100 files (+ optional ground truth) as one dataset collection. Returns a `DatasetUpload`. */
1653
+ uploadToDataset(workflowId, files, opts = {}) {
1654
+ return new Workflow(this._client, workflowId, "").uploadToDataset(files, opts);
1655
+ }
1656
+ /** Bulk-upload documents into a workflow's dataset, one atomic call per document. */
1657
+ uploadDocumentsToDataset(workflowId, documents) {
1658
+ return new Workflow(this._client, workflowId, "").uploadDocumentsToDataset(documents);
1659
+ }
1660
+ async getDocumentPacket(documentPacketId) {
1661
+ const res = await v3GetDocumentPacket({
1662
+ client: this._client,
1663
+ path: { document_packet_id: documentPacketId }
1664
+ });
1665
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1666
+ return res.data;
1667
+ }
1668
+ /** Delete a document packet and all its files. Irreversible. */
1669
+ async deleteDocumentPacket(documentPacketId) {
1670
+ const res = await v3DeleteDocumentPacket({
1671
+ client: this._client,
1672
+ path: { document_packet_id: documentPacketId }
1673
+ });
1674
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1675
+ return documentPacketId;
1676
+ }
1677
+ /** Run (or re-run) a document packet on the latest version of its workflow. */
1678
+ async runDocumentPacket(documentPacketId, opts = {}) {
1679
+ const res = await v3RunDocumentPacket({
1680
+ client: this._client,
1681
+ path: { document_packet_id: documentPacketId },
1682
+ ...opts.idempotencyKey ? { headers: { "Idempotency-Key": opts.idempotencyKey } } : {}
1683
+ });
1684
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1685
+ const data = res.data;
1686
+ return new Run(this._client, data.run_id, data.workflow_id, data.document_packet_id, data.status);
1687
+ }
1688
+ async listDocumentPackets(workflowId, opts = {}) {
1689
+ const res = await v3ListWorkflowDocumentPackets({
1690
+ client: this._client,
1691
+ path: { workflow_id: workflowId },
1692
+ query: { limit: opts.limit, cursor: opts.cursor }
1693
+ });
1694
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1695
+ return { items: res.data.items, nextCursor: res.data.next_cursor ?? null };
1696
+ }
1697
+ async listRuns(workflowId, opts = {}) {
1698
+ const res = await v3ListWorkflowRuns({
1699
+ client: this._client,
1700
+ path: { workflow_id: workflowId },
1701
+ query: { limit: opts.limit, cursor: opts.cursor }
1702
+ });
1703
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1704
+ return { items: res.data.items, nextCursor: res.data.next_cursor ?? null };
1705
+ }
1706
+ /**
1707
+ * Every workflow, following `nextCursor` across pages so no rows are silently
1708
+ * truncated. Lazy — each page is fetched on demand as the iterator advances.
1709
+ */
1710
+ async *iterWorkflows(opts = {}) {
1711
+ let cursor;
1712
+ for (; ; ) {
1713
+ const page = await this.listWorkflows({ limit: opts.limit, cursor });
1714
+ yield* page.items;
1715
+ if (page.nextCursor === null) return;
1716
+ cursor = page.nextCursor;
1717
+ }
1718
+ }
1719
+ /** Every document packet of a workflow, following `nextCursor` across pages. Lazy. */
1720
+ async *iterDocumentPackets(workflowId, opts = {}) {
1721
+ let cursor;
1722
+ for (; ; ) {
1723
+ const page = await this.listDocumentPackets(workflowId, { limit: opts.limit, cursor });
1724
+ yield* page.items;
1725
+ if (page.nextCursor === null) return;
1726
+ cursor = page.nextCursor;
1727
+ }
1728
+ }
1729
+ /** Every run of a workflow, following `nextCursor` across pages. Lazy. */
1730
+ async *iterRuns(workflowId, opts = {}) {
1731
+ let cursor;
1732
+ for (; ; ) {
1733
+ const page = await this.listRuns(workflowId, { limit: opts.limit, cursor });
1734
+ yield* page.items;
1735
+ if (page.nextCursor === null) return;
1736
+ cursor = page.nextCursor;
1737
+ }
1738
+ }
1739
+ /** Retrieve one run: lifecycle status plus results inline once `processed`. */
1740
+ async getRun(runId) {
1741
+ const res = await v3GetRun({ client: this._client, path: { run_id: runId } });
1742
+ if (res.error) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1743
+ return res.data;
1744
+ }
1745
+ /**
1746
+ * Parse a document with the platform's atomic parse operation (fast lite
1747
+ * parse). Returns the run id; poll `getParseMarkdown(runId)` for the parsed
1748
+ * markdown.
1749
+ */
1750
+ async parse(file) {
1751
+ const res = await v3Parse({ client: this._client, body: { file } });
1752
+ if (res.error !== void 0) throw toApiError(res.response?.status ?? 500, res.error, res.response?.headers);
1753
+ return res.data.run_id;
1754
+ }
1755
+ /**
1756
+ * Poll a parse run. Returns the parsed markdown once the run is `processed`,
1757
+ * or `null` while it is still queued or in progress.
1758
+ */
1759
+ async getParseMarkdown(runId) {
1760
+ const run = await this.getRun(runId);
1761
+ if (run.status === "processed") {
1762
+ const markdown = run.results?.parse?.markdown;
1763
+ if (markdown == null) throw new AnyformatError(`Run ${runId} is processed but the API returned no results`);
1764
+ return markdown;
1765
+ }
1766
+ if (run.status === "error") throw new ExtractionFailedError(runId);
1767
+ if (run.status === "cancelled") throw new ExtractionCancelledError(runId);
1768
+ return null;
1769
+ }
1255
1770
  };
1256
1771
 
1257
1772
  // src/schema.ts
1258
- function withLookup(base, opts) {
1259
- if (opts?.lookup) return { ...base, lookup: true };
1260
- return base;
1773
+ function withOpts(base, opts) {
1774
+ return {
1775
+ ...base,
1776
+ ...opts?.source && opts.source !== "extraction" ? { source: opts.source } : {},
1777
+ ...opts?.persistentId !== void 0 ? { persistent_id: opts.persistentId } : {}
1778
+ };
1261
1779
  }
1262
1780
  var Schema = {
1263
- string: (name, description, opts) => withLookup({ data_type: "string", name, description }, opts),
1264
- integer: (name, description, opts) => withLookup({ data_type: "integer", name, description }, opts),
1265
- float: (name, description, opts) => withLookup({ data_type: "float", name, description }, opts),
1266
- boolean: (name, description, opts) => withLookup({ data_type: "boolean", name, description }, opts),
1267
- date: (name, description, opts) => withLookup({ data_type: "date", name, description }, opts),
1268
- datetime: (name, description, opts) => withLookup({ data_type: "datetime", name, description }, opts),
1269
- enum: (name, description, options, opts) => withLookup({ data_type: "enum", name, description, enum_options: options }, opts),
1270
- multiSelect: (name, description, options, opts) => withLookup({ data_type: "multi_select", name, description, enum_options: options }, opts),
1271
- object: (name, description, fields, opts) => withLookup({ data_type: "object", name, description, nested_fields: fields }, opts),
1781
+ string: (name, description, opts) => withOpts({ data_type: "string", name, description }, opts),
1782
+ integer: (name, description, opts) => withOpts({ data_type: "integer", name, description }, opts),
1783
+ float: (name, description, opts) => withOpts({ data_type: "float", name, description }, opts),
1784
+ boolean: (name, description, opts) => withOpts({ data_type: "boolean", name, description }, opts),
1785
+ date: (name, description, opts) => withOpts({ data_type: "date", name, description }, opts),
1786
+ datetime: (name, description, opts) => withOpts({ data_type: "datetime", name, description }, opts),
1787
+ enum: (name, description, options, opts) => withOpts({ data_type: "enum", name, description, enum_options: options }, opts),
1788
+ multiSelect: (name, description, options, opts) => withOpts({ data_type: "multi_select", name, description, enum_options: options }, opts),
1789
+ object: (name, description, fields, opts) => withOpts({ data_type: "object", name, description, nested_fields: fields }, opts),
1272
1790
  option: (name, description) => ({ name, description })
1273
1791
  };
1274
1792
  export {
1275
1793
  APIError,
1276
1794
  Anyformat,
1277
1795
  AnyformatError,
1278
- BadRequest,
1279
- Forbidden,
1280
- NotFound,
1796
+ BadRequestError,
1797
+ DatasetUpload,
1798
+ ExtractionCancelledError,
1799
+ ExtractionFailedError,
1800
+ ForbiddenError,
1801
+ InsufficientScopeError,
1802
+ NotFoundError,
1281
1803
  ParseView,
1282
- RateLimited,
1804
+ PaymentRequiredError,
1805
+ RateLimitedError,
1283
1806
  Result,
1284
1807
  Run,
1285
- SDKTimeout,
1808
+ RunFailedError,
1809
+ SDKTimeoutError,
1286
1810
  Schema,
1287
1811
  ServerError,
1288
- Unauthorized,
1812
+ TermsAcceptanceRequiredError,
1813
+ UnauthorizedError,
1814
+ Upload,
1289
1815
  Workflow,
1290
1816
  WorkflowBuilder,
1291
- WorkflowBuilderError
1817
+ WorkflowBuilderError,
1818
+ WorkflowNameConflictError
1292
1819
  };
1293
1820
  //# sourceMappingURL=index.js.map