@format.dev/client 0.0.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -20
- package/dist/index.cjs +309 -0
- package/dist/index.d.cts +148 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +148 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +309 -0
- package/dist/index.mjs.map +1 -0
- package/dist/web.cjs +288 -0
- package/dist/web.d.cts +119 -0
- package/dist/web.d.cts.map +1 -0
- package/dist/web.d.mts +119 -0
- package/dist/web.d.mts.map +1 -0
- package/dist/web.mjs +287 -0
- package/dist/web.mjs.map +1 -0
- package/package.json +73 -34
- package/index.d.ts +0 -2
- package/index.js +0 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import { Readable } from "node:stream";
|
|
2
|
+
import { File, FormData } from "formdata-node";
|
|
3
|
+
import { FormDataEncoder } from "form-data-encoder";
|
|
4
|
+
import { Readable as Readable$1 } from "stream";
|
|
5
|
+
|
|
6
|
+
//#region package.json
|
|
7
|
+
var version = "0.1.1";
|
|
8
|
+
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/constants.ts
|
|
11
|
+
const REGION_MAP = { GLOBAL: "https://api.format.dev" };
|
|
12
|
+
const API_PREFIX = "/v1";
|
|
13
|
+
const CLIENT_IDENTIFIER = `@format.dev/client/${version}`;
|
|
14
|
+
const DEFAULTS = { baseUrl: REGION_MAP.GLOBAL };
|
|
15
|
+
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/helpers.ts
|
|
18
|
+
function isWebReadable(x) {
|
|
19
|
+
return typeof globalThis.ReadableStream !== "undefined" && x != null && typeof x.getReader === "function";
|
|
20
|
+
}
|
|
21
|
+
function isBlobLike(x) {
|
|
22
|
+
return x != null && typeof x === "object" && typeof x.arrayBuffer === "function" && typeof x.stream === "function" && typeof x.size === "number" && typeof x.type === "string";
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The API origin requests go to. `environmentBaseUrl` is the `FORMAT_BASE_URL`
|
|
26
|
+
* the Node build reads from its environment. The web build does not read
|
|
27
|
+
* environment variables, so it passes nothing.
|
|
28
|
+
*/
|
|
29
|
+
function resolveBaseUrl(opts, environmentBaseUrl) {
|
|
30
|
+
return (opts.baseUrl ?? (opts.region ? REGION_MAP[opts.region] : void 0) ?? environmentBaseUrl ?? DEFAULTS.baseUrl).replace(/\/+$/, "");
|
|
31
|
+
}
|
|
32
|
+
/** The render endpoint under an API origin. The origin carries no version, so the prefix is added here. */
|
|
33
|
+
function renderUrl(baseUrl) {
|
|
34
|
+
return `${baseUrl}${API_PREFIX}/render`;
|
|
35
|
+
}
|
|
36
|
+
/** The `tags` form field: trimmed, empty tags dropped, duplicates removed, sent as a JSON array. */
|
|
37
|
+
function serializeTags(tags) {
|
|
38
|
+
return JSON.stringify(Array.from(new Set(tags.map((t) => t.trim()).filter(Boolean))));
|
|
39
|
+
}
|
|
40
|
+
function parseFilenameFromContentDisposition(header) {
|
|
41
|
+
if (!header) return;
|
|
42
|
+
const mExt = header.match(/filename\*\s*=\s*([^;]+)/i);
|
|
43
|
+
if (mExt) {
|
|
44
|
+
const v = mExt[1].trim();
|
|
45
|
+
const m = /^([A-Za-z0-9._-]+)''(.+)$/.exec(v);
|
|
46
|
+
if (m) {
|
|
47
|
+
const value = stripQuotes(m[2]);
|
|
48
|
+
try {
|
|
49
|
+
return decodeURIComponent(value);
|
|
50
|
+
} catch {
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const mQuoted = header.match(/filename\s*=\s*"([^"]*)"/i);
|
|
56
|
+
if (mQuoted) return mQuoted[1];
|
|
57
|
+
const mBare = header.match(/filename\s*=\s*([^;]+)/i);
|
|
58
|
+
if (mBare) return mBare[1].trim();
|
|
59
|
+
}
|
|
60
|
+
function parseContentType(header) {
|
|
61
|
+
if (!header) return;
|
|
62
|
+
const [mime] = header.split(";", 1);
|
|
63
|
+
return mime?.trim().toLowerCase();
|
|
64
|
+
}
|
|
65
|
+
async function safeJson(body) {
|
|
66
|
+
try {
|
|
67
|
+
return JSON.parse(body);
|
|
68
|
+
} catch {
|
|
69
|
+
return { raw: body };
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function timeoutSignal(ms, reason = /* @__PURE__ */ new Error("Timeout")) {
|
|
73
|
+
if (AbortSignal.timeout) return AbortSignal.timeout(ms);
|
|
74
|
+
const ac = new AbortController();
|
|
75
|
+
setTimeout(() => ac.abort(reason), ms);
|
|
76
|
+
return ac.signal;
|
|
77
|
+
}
|
|
78
|
+
function anySignal(signals) {
|
|
79
|
+
if (AbortSignal.any) return AbortSignal.any(signals);
|
|
80
|
+
const ac = new AbortController();
|
|
81
|
+
const aborted = signals.find((signal) => signal.aborted);
|
|
82
|
+
if (aborted) {
|
|
83
|
+
ac.abort(aborted.reason);
|
|
84
|
+
return ac.signal;
|
|
85
|
+
}
|
|
86
|
+
const onAbort = (event) => {
|
|
87
|
+
for (const signal of signals) signal.removeEventListener("abort", onAbort);
|
|
88
|
+
ac.abort(event.target.reason);
|
|
89
|
+
};
|
|
90
|
+
for (const s of signals) s.addEventListener("abort", onAbort, { once: true });
|
|
91
|
+
return ac.signal;
|
|
92
|
+
}
|
|
93
|
+
function getAbortErrorOrElse(signal, cause) {
|
|
94
|
+
return signal?.aborted ? signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("Aborted with unknown reason") : new Error(cause instanceof Error ? cause.message : "Unknown internal error", { cause });
|
|
95
|
+
}
|
|
96
|
+
function concatUint8Array(parts, total) {
|
|
97
|
+
if (parts.length === 1 && parts[0].byteLength === total) return parts[0];
|
|
98
|
+
let offset = 0;
|
|
99
|
+
const out = new Uint8Array(total);
|
|
100
|
+
for (const p of parts) {
|
|
101
|
+
out.set(p, offset);
|
|
102
|
+
offset += p.byteLength;
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The key a client sends, or a thrown error naming how to supply one.
|
|
108
|
+
* `environmentApiKey` is the `FORMAT_API_KEY` the Node build reads from its
|
|
109
|
+
* environment. The web build passes nothing, so its callers have to
|
|
110
|
+
* pass `apiKey` explicitly.
|
|
111
|
+
*/
|
|
112
|
+
function resolveApiKey(explicitApiKey, environmentApiKey, howToSupply) {
|
|
113
|
+
if (explicitApiKey) return explicitApiKey;
|
|
114
|
+
if (environmentApiKey) return environmentApiKey;
|
|
115
|
+
throw new Error(`Format API key is required. ${howToSupply ?? "Pass `apiKey` explicitly."}`);
|
|
116
|
+
}
|
|
117
|
+
function stripQuotes(input) {
|
|
118
|
+
if (input.length >= 2 && input[0] === "\"" && input[input.length - 1] === "\"") return input.slice(1, -1);
|
|
119
|
+
return input;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region src/node-assets.ts
|
|
124
|
+
function toFileLike(webStream, name, type) {
|
|
125
|
+
return {
|
|
126
|
+
name,
|
|
127
|
+
type,
|
|
128
|
+
[Symbol.toStringTag]: "File",
|
|
129
|
+
stream() {
|
|
130
|
+
return webStream;
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
function isNodeReadable(x) {
|
|
135
|
+
return x != null && typeof x.pipe === "function" && typeof x.read === "function";
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Normalize assets into something FormData#set accepts (File or File-like)
|
|
139
|
+
* whilst retaining multipart streaming where possible
|
|
140
|
+
*/
|
|
141
|
+
function assetsToFormDataValue(input, filename = "assets.zip", mime = "application/zip") {
|
|
142
|
+
if (isBlobLike(input)) return new File([input], filename, { type: mime });
|
|
143
|
+
if (input instanceof Uint8Array || input instanceof ArrayBuffer || Buffer?.isBuffer?.(input)) return new File([input], filename, { type: mime });
|
|
144
|
+
if (isWebReadable(input)) return toFileLike(input, filename, mime);
|
|
145
|
+
if (isNodeReadable(input)) return toFileLike(Readable$1.toWeb(input), filename, mime);
|
|
146
|
+
throw new TypeError("Unsupported assets type");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
//#endregion
|
|
150
|
+
//#region src/error.ts
|
|
151
|
+
/**
|
|
152
|
+
* Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.
|
|
153
|
+
*/
|
|
154
|
+
var FormatError = class extends Error {
|
|
155
|
+
constructor(status, detail) {
|
|
156
|
+
super(`Format API: Error ${status}`);
|
|
157
|
+
this.status = status;
|
|
158
|
+
this.detail = detail;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
//#endregion
|
|
163
|
+
//#region src/response.ts
|
|
164
|
+
/**
|
|
165
|
+
* The error a non-2xx response becomes.
|
|
166
|
+
*
|
|
167
|
+
* Reads at most about 1MB of the body, so an unexpectedly large error response
|
|
168
|
+
* cannot exhaust memory, and parses it as JSON where it can. A body that is not
|
|
169
|
+
* JSON arrives as `{ raw: body }`.
|
|
170
|
+
*/
|
|
171
|
+
async function formatErrorFrom(res) {
|
|
172
|
+
const status = res.status ?? 0;
|
|
173
|
+
let size = 0;
|
|
174
|
+
const limit = 1e6;
|
|
175
|
+
const chunks = [];
|
|
176
|
+
const reader = res.body?.getReader();
|
|
177
|
+
try {
|
|
178
|
+
if (reader) while (size < limit) {
|
|
179
|
+
const { done, value } = await reader.read();
|
|
180
|
+
if (done || !value?.length) break;
|
|
181
|
+
chunks.push(value);
|
|
182
|
+
size += value.byteLength;
|
|
183
|
+
}
|
|
184
|
+
} finally {
|
|
185
|
+
try {
|
|
186
|
+
await reader?.cancel();
|
|
187
|
+
} catch {}
|
|
188
|
+
}
|
|
189
|
+
const buf = concatUint8Array(chunks, size);
|
|
190
|
+
return new FormatError(status, await safeJson(new TextDecoder("utf-8", { fatal: false }).decode(buf)));
|
|
191
|
+
}
|
|
192
|
+
/** What a successful response says about the PDF, read from its headers. */
|
|
193
|
+
function responseDetails(res) {
|
|
194
|
+
const rawContentLength = res.headers.get("content-length");
|
|
195
|
+
const contentType = parseContentType(res.headers.get("content-type"));
|
|
196
|
+
return {
|
|
197
|
+
filename: parseFilenameFromContentDisposition(res.headers.get("content-disposition")),
|
|
198
|
+
contentLength: rawContentLength ? parseInt(rawContentLength) : void 0,
|
|
199
|
+
contentType,
|
|
200
|
+
traceparent: res.headers.get("traceparent") || void 0,
|
|
201
|
+
isPdf: contentType === "application/pdf"
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Assign to the Response itself: a Proxy breaks the native methods' brand
|
|
206
|
+
* checks in browsers and Node 24.
|
|
207
|
+
*/
|
|
208
|
+
function augmentResponse(res) {
|
|
209
|
+
return Object.assign(res, responseDetails(res));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
//#endregion
|
|
213
|
+
//#region src/document-assets.ts
|
|
214
|
+
/**
|
|
215
|
+
* A compiled document cannot cancel its asset lookup. Reject promptly on abort
|
|
216
|
+
* and cancel any stream that arrives afterwards so its source can release it.
|
|
217
|
+
*/
|
|
218
|
+
async function documentAssets(doc, signal) {
|
|
219
|
+
if (signal.aborted) throw getAbortErrorOrElse(signal);
|
|
220
|
+
const pending = doc.getAssetsWebStream();
|
|
221
|
+
return new Promise((resolve, reject) => {
|
|
222
|
+
const onAbort = () => {
|
|
223
|
+
signal.removeEventListener("abort", onAbort);
|
|
224
|
+
reject(getAbortErrorOrElse(signal));
|
|
225
|
+
};
|
|
226
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
227
|
+
if (signal.aborted) onAbort();
|
|
228
|
+
pending.then((stream) => {
|
|
229
|
+
signal.removeEventListener("abort", onAbort);
|
|
230
|
+
if (signal.aborted) {
|
|
231
|
+
stream?.cancel(signal.reason).catch(() => {});
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
resolve(stream);
|
|
235
|
+
}, (error) => {
|
|
236
|
+
signal.removeEventListener("abort", onAbort);
|
|
237
|
+
reject(error);
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
//#endregion
|
|
243
|
+
//#region src/client.ts
|
|
244
|
+
const USER_AGENT = `${CLIENT_IDENTIFIER} (${process.platform}) node ${process.version}`;
|
|
245
|
+
var FormatClient = class {
|
|
246
|
+
baseUrl;
|
|
247
|
+
renderTimeoutMs;
|
|
248
|
+
apiKey;
|
|
249
|
+
constructor(opts = {}) {
|
|
250
|
+
this.apiKey = resolveApiKey(opts.apiKey, process.env.FORMAT_API_KEY, "Pass `apiKey` explicitly or set `FORMAT_API_KEY` in your environment.");
|
|
251
|
+
this.baseUrl = resolveBaseUrl(opts, process.env.FORMAT_BASE_URL);
|
|
252
|
+
this.renderTimeoutMs = opts.renderTimeoutMs ?? 12e4;
|
|
253
|
+
}
|
|
254
|
+
async pdf(doc, options) {
|
|
255
|
+
const renderTimeoutSignal = timeoutSignal(this.renderTimeoutMs);
|
|
256
|
+
const combinedSignal = options?.signal ? anySignal([options.signal, renderTimeoutSignal]) : renderTimeoutSignal;
|
|
257
|
+
const isFormatDoc = typeof doc !== "string";
|
|
258
|
+
const html = isFormatDoc ? doc.html : doc;
|
|
259
|
+
const form = new FormData();
|
|
260
|
+
form.set("html", html);
|
|
261
|
+
if (options?.tags) form.set("tags", serializeTags(options.tags));
|
|
262
|
+
let assets = options?.assets;
|
|
263
|
+
if (!assets && isFormatDoc) assets = await documentAssets(doc, combinedSignal);
|
|
264
|
+
if (assets) form.set("assets", assetsToFormDataValue(assets));
|
|
265
|
+
const encoder = new FormDataEncoder(form);
|
|
266
|
+
const headers = {
|
|
267
|
+
...encoder.headers,
|
|
268
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
269
|
+
"User-Agent": USER_AGENT,
|
|
270
|
+
"X-Format-Client": CLIENT_IDENTIFIER
|
|
271
|
+
};
|
|
272
|
+
let res;
|
|
273
|
+
if (combinedSignal.aborted) throw getAbortErrorOrElse(combinedSignal);
|
|
274
|
+
try {
|
|
275
|
+
res = await fetch(renderUrl(this.baseUrl), {
|
|
276
|
+
method: "POST",
|
|
277
|
+
headers,
|
|
278
|
+
body: Readable.toWeb(Readable.from(encoder)),
|
|
279
|
+
signal: combinedSignal,
|
|
280
|
+
duplex: "half",
|
|
281
|
+
credentials: "omit"
|
|
282
|
+
});
|
|
283
|
+
} catch (err) {
|
|
284
|
+
throw getAbortErrorOrElse(combinedSignal, err);
|
|
285
|
+
}
|
|
286
|
+
if (!res.ok) throw await formatErrorFrom(res);
|
|
287
|
+
const toFile = async (filePath, options$1) => {
|
|
288
|
+
if (res.bodyUsed) throw new Error("Response body already consumed");
|
|
289
|
+
if (!res.body) throw new Error("Response body is empty");
|
|
290
|
+
const [{ pipeline }, { createWriteStream }, fs, path] = await Promise.all([
|
|
291
|
+
import("node:stream/promises"),
|
|
292
|
+
import("node:fs"),
|
|
293
|
+
import("node:fs/promises"),
|
|
294
|
+
import("node:path")
|
|
295
|
+
]);
|
|
296
|
+
await fs.mkdir(path.dirname(filePath), { recursive: true });
|
|
297
|
+
await pipeline(Readable.fromWeb(res.body), createWriteStream(filePath, { mode: options$1?.mode }));
|
|
298
|
+
return {
|
|
299
|
+
path: filePath,
|
|
300
|
+
bytes: (await fs.stat(filePath)).size
|
|
301
|
+
};
|
|
302
|
+
};
|
|
303
|
+
return Object.assign(augmentResponse(res), { toFile });
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
//#endregion
|
|
308
|
+
export { FormatClient, FormatError };
|
|
309
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["REGION_MAP: Record<FormatRegion, string>","FormDataFile","Readable","status: number","detail: unknown","chunks: Uint8Array[]","res: Response","options"],"sources":["../package.json","../src/constants.ts","../src/helpers.ts","../src/node-assets.ts","../src/error.ts","../src/response.ts","../src/document-assets.ts","../src/client.ts"],"sourcesContent":["{\n\t\"name\": \"@format.dev/client\",\n\t\"version\": \"0.1.1\",\n\t\"license\": \"MIT\",\n\t\"description\": \"The JavaScript client for the Format API.\",\n\t\"author\": \"the format.dev developers\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/format-hq/format-js.git\",\n\t\t\"directory\": \"packages/client\"\n\t},\n\t\"type\": \"module\",\n\t\"main\": \"./dist/index.cjs\",\n\t\"module\": \"./dist/index.mjs\",\n\t\"types\": \"./dist/index.d.mts\",\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"browser\": {\n\t\t\t\t\"types\": {\n\t\t\t\t\t\"import\": \"./dist/web.d.mts\",\n\t\t\t\t\t\"require\": \"./dist/web.d.cts\"\n\t\t\t\t},\n\t\t\t\t\"import\": \"./dist/web.mjs\",\n\t\t\t\t\"require\": \"./dist/web.cjs\",\n\t\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t\t},\n\t\t\t\"types\": {\n\t\t\t\t\"import\": \"./dist/index.d.mts\",\n\t\t\t\t\"require\": \"./dist/index.d.cts\"\n\t\t\t},\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"require\": \"./dist/index.cjs\",\n\t\t\t\"default\": \"./dist/index.mjs\"\n\t\t},\n\t\t\"./web\": {\n\t\t\t\"types\": {\n\t\t\t\t\"import\": \"./dist/web.d.mts\",\n\t\t\t\t\"require\": \"./dist/web.d.cts\"\n\t\t\t},\n\t\t\t\"import\": \"./dist/web.mjs\",\n\t\t\t\"require\": \"./dist/web.cjs\",\n\t\t\t\"default\": \"./dist/web.mjs\"\n\t\t}\n\t},\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"LICENSE\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"sideEffects\": false,\n\t\"scripts\": {\n\t\t\"clean\": \"rimraf dist\",\n\t\t\"build\": \"tsdown\",\n\t\t\"dev\": \"tsdown --watch\",\n\t\t\"typecheck\": \"tsc -p tsconfig.json --noEmit && tsc -p tsconfig.web.json --noEmit\"\n\t},\n\t\"dependencies\": {\n\t\t\"@format.dev/types\": \"workspace:*\",\n\t\t\"form-data-encoder\": \"^4.1.0\",\n\t\t\"formdata-node\": \"^6.0.3\",\n\t\t\"is-stream\": \"^4.0.1\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@types/node\": \"^24.2.1\",\n\t\t\"rimraf\": \"^6.0.1\",\n\t\t\"tsdown\": \"0.17.0-beta.6\",\n\t\t\"typescript\": \"^5\"\n\t},\n\t\"engines\": {\n\t\t\"node\": \">=18.17.0\"\n\t}\n}\n","import type { FormatRegion } from './types'\nimport { version } from '../package.json'\n\nexport const REGION_MAP: Record<FormatRegion, string> = {\n\tGLOBAL: 'https://api.format.dev'\n\t// US: 'https://us.api.format.dev',\n\t// EU: 'https://eu.api.format.dev'\n} as const\n\n// API version prefix used by renderUrl() in helpers.ts. Keep it in sync with the API route.\nexport const API_PREFIX = '/v1'\n\nexport const CLIENT_IDENTIFIER = `@format.dev/client/${version}`\n\n// Shared by the Node and web builds, so nothing here may read `process` or any\n// other Node global. The Node build adds its own User-Agent in client.ts.\nexport const DEFAULTS = {\n\tbaseUrl: REGION_MAP.GLOBAL\n} as const\n","// Shared by both builds. Keep Node imports and globals in the Node entry.\nimport { API_PREFIX, DEFAULTS, REGION_MAP } from './constants'\nimport type { FormatOptions } from './types'\n\nexport function isWebReadable(x: any): x is ReadableStream<Uint8Array> {\n\treturn typeof globalThis.ReadableStream !== 'undefined' && x != null && typeof (x as any).getReader === 'function'\n}\n\nexport function isBlobLike(x: any): x is Blob {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === 'object' &&\n\t\ttypeof (x as any).arrayBuffer === 'function' &&\n\t\ttypeof (x as any).stream === 'function' &&\n\t\ttypeof (x as any).size === 'number' &&\n\t\ttypeof (x as any).type === 'string'\n\t)\n}\n\n/**\n * The API origin requests go to. `environmentBaseUrl` is the `FORMAT_BASE_URL`\n * the Node build reads from its environment. The web build does not read\n * environment variables, so it passes nothing.\n */\nexport function resolveBaseUrl(opts: FormatOptions, environmentBaseUrl?: string) {\n\tconst baseUrl =\n\t\topts.baseUrl ?? (opts.region ? REGION_MAP[opts.region] : undefined) ?? environmentBaseUrl ?? DEFAULTS.baseUrl\n\n\treturn baseUrl.replace(/\\/+$/, '') // strip trailing slash\n}\n\n/** The render endpoint under an API origin. The origin carries no version, so the prefix is added here. */\nexport function renderUrl(baseUrl: string): string {\n\treturn `${baseUrl}${API_PREFIX}/render`\n}\n\n/** The `tags` form field: trimmed, empty tags dropped, duplicates removed, sent as a JSON array. */\nexport function serializeTags(tags: string[]): string {\n\treturn JSON.stringify(Array.from(new Set(tags.map(t => t.trim()).filter(Boolean))))\n}\n\n// extract suggested filename from Content-Disposition\nexport function parseFilenameFromContentDisposition(header: string | null): string | undefined {\n\tif (!header) return\n\n\t// RFC 5987: filename*=UTF-8''file%20name.pdf\n\tconst mExt = header.match(/filename\\*\\s*=\\s*([^;]+)/i)\n\tif (mExt) {\n\t\tconst v = mExt[1].trim()\n\t\tconst m = /^([A-Za-z0-9._-]+)''(.+)$/.exec(v) // charset'lang'value\n\t\tif (m) {\n\t\t\tconst value = stripQuotes(m[2])\n\t\t\ttry {\n\t\t\t\treturn decodeURIComponent(value)\n\t\t\t} catch {\n\t\t\t\treturn value\n\t\t\t}\n\t\t}\n\t}\n\n\t// quoted filename=\"a;b.pdf\"\n\tconst mQuoted = header.match(/filename\\s*=\\s*\"([^\"]*)\"/i)\n\tif (mQuoted) return mQuoted[1]\n\n\t// bare filename=a.pdf\n\tconst mBare = header.match(/filename\\s*=\\s*([^;]+)/i)\n\tif (mBare) return mBare[1].trim()\n\n\treturn\n}\n\n// parse and normalize MIME (strip params, lowercase)\nexport function parseContentType(header: string | null): string | undefined {\n\tif (!header) {\n\t\treturn\n\t}\n\n\tconst [mime] = header.split(';', 1)\n\treturn mime?.trim().toLowerCase()\n}\n\nexport async function safeJson(body: string) {\n\ttry {\n\t\treturn JSON.parse(body)\n\t} catch {\n\t\treturn { raw: body }\n\t}\n}\n\nexport function firstHeader(header: string | string[] | null): string | undefined {\n\treturn Array.isArray(header) ? header[0] : header || undefined\n}\n\nexport function timeoutSignal(ms: number, reason = new Error('Timeout')): AbortSignal {\n\tif ((AbortSignal as any).timeout) {\n\t\treturn AbortSignal.timeout(ms)\n\t}\n\n\tconst ac = new AbortController()\n\n\tsetTimeout(() => ac.abort(reason), ms)\n\n\treturn ac.signal\n}\n\nexport function anySignal(signals: AbortSignal[]): AbortSignal {\n\tif ((AbortSignal as any).any) {\n\t\treturn AbortSignal.any(signals)\n\t}\n\n\tconst ac = new AbortController()\n\tconst aborted = signals.find(signal => signal.aborted)\n\tif (aborted) {\n\t\tac.abort(aborted.reason)\n\t\treturn ac.signal\n\t}\n\n\tconst onAbort = (event: Event) => {\n\t\tfor (const signal of signals) signal.removeEventListener('abort', onAbort)\n\t\tac.abort((event.target as AbortSignal).reason)\n\t}\n\n\tfor (const s of signals) {\n\t\ts.addEventListener('abort', onAbort, { once: true })\n\t}\n\n\treturn ac.signal\n}\n\nexport function getAbortErrorOrElse(signal: AbortSignal | undefined, cause?: unknown): Error {\n\treturn signal?.aborted\n\t\t? signal.reason instanceof Error\n\t\t\t? signal.reason\n\t\t\t: new Error('Aborted with unknown reason')\n\t\t: new Error(cause instanceof Error ? cause.message : 'Unknown internal error', { cause })\n}\n\nexport function concatUint8Array(parts: Uint8Array[], total: number): Uint8Array {\n\tif (parts.length === 1 && parts[0].byteLength === total) {\n\t\treturn parts[0]\n\t}\n\n\tlet offset = 0\n\tconst out = new Uint8Array(total)\n\n\tfor (const p of parts) {\n\t\tout.set(p, offset)\n\t\toffset += p.byteLength\n\t}\n\n\treturn out\n}\n\n/**\n * The key a client sends, or a thrown error naming how to supply one.\n * `environmentApiKey` is the `FORMAT_API_KEY` the Node build reads from its\n * environment. The web build passes nothing, so its callers have to\n * pass `apiKey` explicitly.\n */\nexport function resolveApiKey(\n\texplicitApiKey: string | undefined,\n\tenvironmentApiKey?: string,\n\thowToSupply?: string\n): string {\n\tif (explicitApiKey) {\n\t\treturn explicitApiKey\n\t}\n\n\tif (environmentApiKey) {\n\t\treturn environmentApiKey\n\t}\n\n\tthrow new Error(`Format API key is required. ${howToSupply ?? 'Pass `apiKey` explicitly.'}`)\n}\n\nfunction stripQuotes(input: string): string {\n\tif (input.length >= 2 && input[0] === '\"' && input[input.length - 1] === '\"') return input.slice(1, -1)\n\treturn input\n}\n","// Asset normalisation for the Node build only. It imports Node's stream module\n// and formdata-node, which the web build must never bundle.\nimport { Readable } from 'stream'\nimport { File as FormDataFile } from 'formdata-node'\nimport { isBlobLike, isWebReadable } from './helpers'\nimport type { AssetLike } from './node-types'\n\ntype FileLike = {\n\tname: string\n\ttype: string\n\treadonly [Symbol.toStringTag]: 'File'\n\tstream(): ReadableStream<Uint8Array>\n}\n\ntype FileLikeForFormData = FormDataFile | FileLike\n\nfunction toFileLike(webStream: ReadableStream<Uint8Array>, name: string, type: string): FileLike {\n\treturn {\n\t\tname,\n\t\ttype,\n\t\t[Symbol.toStringTag]: 'File' as const,\n\t\tstream() {\n\t\t\treturn webStream\n\t\t}\n\t}\n}\n\nfunction isNodeReadable(x: any): x is Readable {\n\treturn x != null && typeof (x as any).pipe === 'function' && typeof (x as any).read === 'function'\n}\n\n/**\n * Normalize assets into something FormData#set accepts (File or File-like)\n * whilst retaining multipart streaming where possible\n */\nexport function assetsToFormDataValue(\n\tinput: AssetLike,\n\tfilename = 'assets.zip',\n\tmime = 'application/zip'\n): FileLikeForFormData {\n\t// blob - wrap as File to ensure a filename\n\tif (isBlobLike(input)) {\n\t\treturn new FormDataFile([input as any], filename, { type: mime })\n\t}\n\n\t// bytes\n\tif (input instanceof Uint8Array || input instanceof ArrayBuffer || Buffer?.isBuffer?.(input)) {\n\t\treturn new FormDataFile([input], filename, { type: mime })\n\t}\n\n\t// web ReadableStream\n\tif (isWebReadable(input)) {\n\t\treturn toFileLike(input, filename, mime)\n\t}\n\n\t// node Readable\n\tif (isNodeReadable(input)) {\n\t\tconst webStream = Readable.toWeb(input) as unknown as ReadableStream<Uint8Array>\n\t\treturn toFileLike(webStream, filename, mime)\n\t}\n\n\tthrow new TypeError('Unsupported assets type')\n}\n","/**\n * Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.\n */\nexport class FormatError extends Error {\n\tconstructor(\n\t\t/** HTTP status code from the API response. */\n\t\tpublic status: number,\n\t\t/** Parsed error response body. Typically a JSON object with error details, or `{ raw: string }` if the body couldn't be parsed. */\n\t\tpublic detail: unknown\n\t) {\n\t\tsuper(`Format API: Error ${status}`)\n\t}\n}\n","// Response handling shared by the Node and web builds.\nimport { FormatError } from './error'\nimport { concatUint8Array, parseContentType, parseFilenameFromContentDisposition, safeJson } from './helpers'\nimport type { FormatResponse } from './types'\n\n/**\n * The error a non-2xx response becomes.\n *\n * Reads at most about 1MB of the body, so an unexpectedly large error response\n * cannot exhaust memory, and parses it as JSON where it can. A body that is not\n * JSON arrives as `{ raw: body }`.\n */\nexport async function formatErrorFrom(res: Response): Promise<FormatError> {\n\tconst status = res.status ?? 0\n\n\t// read at most ~1MB of error body to avoid unbounded memory usage\n\tlet size = 0\n\tconst limit = 1_000_000\n\tconst chunks: Uint8Array[] = []\n\tconst reader = res.body?.getReader()\n\n\ttry {\n\t\tif (reader) {\n\t\t\twhile (size < limit) {\n\t\t\t\tconst { done, value } = await reader.read()\n\t\t\t\tif (done || !value?.length) break\n\t\t\t\tchunks.push(value)\n\t\t\t\tsize += value.byteLength\n\t\t\t}\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tawait reader?.cancel()\n\t\t} catch {\n\t\t\t// ignore\n\t\t}\n\t}\n\n\t// avoid Buffer.concat so we are web/browser-friendly\n\tconst buf = concatUint8Array(chunks, size)\n\tconst body = new TextDecoder('utf-8', { fatal: false }).decode(buf)\n\tconst detail = await safeJson(body)\n\n\treturn new FormatError(status, detail)\n}\n\n/** What a successful response says about the PDF, read from its headers. */\nfunction responseDetails(res: Response): Omit<FormatResponse, keyof Response> {\n\tconst rawContentLength = res.headers.get('content-length')\n\tconst contentType = parseContentType(res.headers.get('content-type'))\n\n\treturn {\n\t\tfilename: parseFilenameFromContentDisposition(res.headers.get('content-disposition')),\n\t\tcontentLength: rawContentLength ? parseInt(rawContentLength) : undefined,\n\t\tcontentType,\n\t\ttraceparent: res.headers.get('traceparent') || undefined,\n\t\tisPdf: contentType === 'application/pdf'\n\t}\n}\n\n/**\n * Assign to the Response itself: a Proxy breaks the native methods' brand\n * checks in browsers and Node 24.\n */\nexport function augmentResponse(res: Response): FormatResponse {\n\treturn Object.assign(res, responseDetails(res))\n}\n","import { getAbortErrorOrElse } from './helpers'\nimport type { FormatDocument } from './types'\n\n/**\n * A compiled document cannot cancel its asset lookup. Reject promptly on abort\n * and cancel any stream that arrives afterwards so its source can release it.\n */\nexport async function documentAssets(\n\tdoc: FormatDocument,\n\tsignal: AbortSignal\n): Promise<ReadableStream<Uint8Array> | undefined> {\n\tif (signal.aborted) throw getAbortErrorOrElse(signal)\n\tconst pending = doc.getAssetsWebStream()\n\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = () => {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\treject(getAbortErrorOrElse(signal))\n\t\t}\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\tif (signal.aborted) onAbort()\n\t\tpending.then(\n\t\t\tstream => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tvoid stream?.cancel(signal.reason).catch(() => {})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tresolve(stream)\n\t\t\t},\n\t\t\terror => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\treject(error)\n\t\t\t}\n\t\t)\n\t})\n}\n","import { Readable } from 'node:stream'\nimport { FormData } from 'formdata-node'\nimport { FormDataEncoder } from 'form-data-encoder'\nimport {\n\tanySignal,\n\tgetAbortErrorOrElse,\n\trenderUrl,\n\tresolveBaseUrl,\n\ttimeoutSignal,\n\tresolveApiKey,\n\tserializeTags\n} from './helpers'\nimport { assetsToFormDataValue } from './node-assets'\nimport { augmentResponse, formatErrorFrom } from './response'\nimport { CLIENT_IDENTIFIER } from './constants'\nimport { documentAssets } from './document-assets'\nimport type { FormatOptions, FormatDocument, FormatPdfOptions, FormatResponse, WriteStreamOptions } from './node-types'\n\nconst USER_AGENT = `${CLIENT_IDENTIFIER} (${process.platform}) node ${process.version}`\n\nexport class FormatClient {\n\tprivate readonly baseUrl: string\n\tprivate readonly renderTimeoutMs: number\n\tprivate readonly apiKey: string\n\n\tconstructor(opts: FormatOptions = {}) {\n\t\tthis.apiKey = resolveApiKey(\n\t\t\topts.apiKey,\n\t\t\tprocess.env.FORMAT_API_KEY,\n\t\t\t'Pass `apiKey` explicitly or set `FORMAT_API_KEY` in your environment.'\n\t\t)\n\t\tthis.baseUrl = resolveBaseUrl(opts, process.env.FORMAT_BASE_URL)\n\t\tthis.renderTimeoutMs = opts.renderTimeoutMs ?? 120_000\n\t}\n\n\tasync pdf(doc: string | FormatDocument, options?: FormatPdfOptions): Promise<FormatResponse> {\n\t\tconst renderTimeoutSignal = timeoutSignal(this.renderTimeoutMs)\n\t\tconst combinedSignal = options?.signal ? anySignal([options.signal, renderTimeoutSignal]) : renderTimeoutSignal\n\n\t\t// `doc` is either raw document model HTML (hand-authored / non-studio flows) or a\n\t\t// FormatDocument from studio's compile output\n\t\tconst isFormatDoc = typeof doc !== 'string'\n\t\tconst html = isFormatDoc ? doc.html : doc\n\n\t\tconst form = new FormData()\n\t\tform.set('html', html)\n\n\t\tif (options?.tags) {\n\t\t\tform.set('tags', serializeTags(options.tags))\n\t\t}\n\n\t\t// `getAssetsWebStream()` is the single source of truth: a stream means\n\t\t// attach it, `undefined` means this render has no assets, and a throw\n\t\t// (e.g. the rendered HTML references assets the bundle can't supply)\n\t\t// propagates to the caller with full context.\n\t\tlet assets = options?.assets\n\t\tif (!assets && isFormatDoc) {\n\t\t\tassets = await documentAssets(doc, combinedSignal)\n\t\t}\n\n\t\tif (assets) {\n\t\t\tform.set('assets', assetsToFormDataValue(assets))\n\t\t}\n\n\t\tconst encoder = new FormDataEncoder(form)\n\t\tconst headers = {\n\t\t\t...encoder.headers,\n\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t'User-Agent': USER_AGENT,\n\t\t\t'X-Format-Client': CLIENT_IDENTIFIER\n\t\t}\n\n\t\tlet res: Response\n\t\tif (combinedSignal.aborted) throw getAbortErrorOrElse(combinedSignal)\n\n\t\ttry {\n\t\t\tres = await fetch(renderUrl(this.baseUrl), {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders,\n\t\t\t\tbody: Readable.toWeb(Readable.from(encoder)) as any,\n\t\t\t\tsignal: combinedSignal,\n\t\t\t\tduplex: 'half' as any,\n\t\t\t\t// Node 24 otherwise reports a streamed upload's 401 as \"fetch failed\".\n\t\t\t\t// This leaves the explicit Authorization header intact.\n\t\t\t\tcredentials: 'omit'\n\t\t\t} as any)\n\t\t} catch (err) {\n\t\t\tthrow getAbortErrorOrElse(combinedSignal, err)\n\t\t}\n\n\t\tif (!res.ok) {\n\t\t\tthrow await formatErrorFrom(res)\n\t\t}\n\n\t\tconst toFile = async (filePath: string, options?: WriteStreamOptions) => {\n\t\t\tif (res.bodyUsed) {\n\t\t\t\tthrow new Error('Response body already consumed')\n\t\t\t}\n\n\t\t\tif (!res.body) {\n\t\t\t\tthrow new Error('Response body is empty')\n\t\t\t}\n\n\t\t\tconst [{ pipeline }, { createWriteStream }, fs, path] = await Promise.all([\n\t\t\t\timport('node:stream/promises'),\n\t\t\t\timport('node:fs'),\n\t\t\t\timport('node:fs/promises'),\n\t\t\t\timport('node:path')\n\t\t\t])\n\n\t\t\tawait fs.mkdir(path.dirname(filePath), { recursive: true })\n\t\t\tconst nodeReadable = Readable.fromWeb(res.body as any)\n\t\t\tconst outStream = createWriteStream(filePath, { mode: options?.mode })\n\t\t\tawait pipeline(nodeReadable, outStream)\n\t\t\tconst stats = await fs.stat(filePath)\n\t\t\treturn { path: filePath, bytes: stats.size }\n\t\t}\n\n\t\treturn Object.assign(augmentResponse(res), { toFile })\n\t}\n}\n"],"mappings":";;;;;;cAEY;;;;ACCZ,MAAaA,aAA2C,EACvD,QAAQ,0BAGR;AAGD,MAAa,aAAa;AAE1B,MAAa,oBAAoB,sBAAsB;AAIvD,MAAa,WAAW,EACvB,SAAS,WAAW,QACpB;;;;ACdD,SAAgB,cAAc,GAAyC;AACtE,QAAO,OAAO,WAAW,mBAAmB,eAAe,KAAK,QAAQ,OAAQ,EAAU,cAAc;;AAGzG,SAAgB,WAAW,GAAmB;AAC7C,QACC,KAAK,QACL,OAAO,MAAM,YACb,OAAQ,EAAU,gBAAgB,cAClC,OAAQ,EAAU,WAAW,cAC7B,OAAQ,EAAU,SAAS,YAC3B,OAAQ,EAAU,SAAS;;;;;;;AAS7B,SAAgB,eAAe,MAAqB,oBAA6B;AAIhF,SAFC,KAAK,YAAY,KAAK,SAAS,WAAW,KAAK,UAAU,WAAc,sBAAsB,SAAS,SAExF,QAAQ,QAAQ,GAAG;;;AAInC,SAAgB,UAAU,SAAyB;AAClD,QAAO,GAAG,UAAU,WAAW;;;AAIhC,SAAgB,cAAc,MAAwB;AACrD,QAAO,KAAK,UAAU,MAAM,KAAK,IAAI,IAAI,KAAK,KAAI,MAAK,EAAE,MAAM,CAAC,CAAC,OAAO,QAAQ,CAAC,CAAC,CAAC;;AAIpF,SAAgB,oCAAoC,QAA2C;AAC9F,KAAI,CAAC,OAAQ;CAGb,MAAM,OAAO,OAAO,MAAM,4BAA4B;AACtD,KAAI,MAAM;EACT,MAAM,IAAI,KAAK,GAAG,MAAM;EACxB,MAAM,IAAI,4BAA4B,KAAK,EAAE;AAC7C,MAAI,GAAG;GACN,MAAM,QAAQ,YAAY,EAAE,GAAG;AAC/B,OAAI;AACH,WAAO,mBAAmB,MAAM;WACzB;AAC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ants.ts
|
|
7
|
+
const REGION_MAP = { GLOBAL: "https://api.format.dev" };
|
|
8
|
+
const API_PREFIX = "/v1";
|
|
9
|
+
const CLIENT_IDENTIFIER = `@format.dev/client/${version}`;
|
|
10
|
+
const DEFAULTS = { baseUrl: REGION_MAP.GLOBAL };
|
|
11
|
+
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/helpers.ts
|
|
14
|
+
function isWebReadable(x) {
|
|
15
|
+
return typeof globalThis.ReadableStream !== "undefined" && x != null && typeof x.getReader === "function";
|
|
16
|
+
}
|
|
17
|
+
function isBlobLike(x) {
|
|
18
|
+
return x != null && typeof x === "object" && typeof x.arrayBuffer === "function" && typeof x.stream === "function" && typeof x.size === "number" && typeof x.type === "string";
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The API origin requests go to. `environmentBaseUrl` is the `FORMAT_BASE_URL`
|
|
22
|
+
* the Node build reads from its environment. The web build does not read
|
|
23
|
+
* environment variables, so it passes nothing.
|
|
24
|
+
*/
|
|
25
|
+
function resolveBaseUrl(opts, environmentBaseUrl) {
|
|
26
|
+
return (opts.baseUrl ?? (opts.region ? REGION_MAP[opts.region] : void 0) ?? environmentBaseUrl ?? DEFAULTS.baseUrl).replace(/\/+$/, "");
|
|
27
|
+
}
|
|
28
|
+
/** The render endpoint under an API origin. The origin carries no version, so the prefix is added here. */
|
|
29
|
+
function renderUrl(baseUrl) {
|
|
30
|
+
return `${baseUrl}${API_PREFIX}/render`;
|
|
31
|
+
}
|
|
32
|
+
/** The `tags` form field: trimmed, empty tags dropped, duplicates removed, sent as a JSON array. */
|
|
33
|
+
function serializeTags(tags) {
|
|
34
|
+
return JSON.stringify(Array.from(new Set(tags.map((t) => t.trim()).filter(Boolean))));
|
|
35
|
+
}
|
|
36
|
+
function parseFilenameFromContentDisposition(header) {
|
|
37
|
+
if (!header) return;
|
|
38
|
+
const mExt = header.match(/filename\*\s*=\s*([^;]+)/i);
|
|
39
|
+
if (mExt) {
|
|
40
|
+
const v = mExt[1].trim();
|
|
41
|
+
const m = /^([A-Za-z0-9._-]+)''(.+)$/.exec(v);
|
|
42
|
+
if (m) {
|
|
43
|
+
const value = stripQuotes(m[2]);
|
|
44
|
+
try {
|
|
45
|
+
return decodeURIComponent(value);
|
|
46
|
+
} catch {
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const mQuoted = header.match(/filename\s*=\s*"([^"]*)"/i);
|
|
52
|
+
if (mQuoted) return mQuoted[1];
|
|
53
|
+
const mBare = header.match(/filename\s*=\s*([^;]+)/i);
|
|
54
|
+
if (mBare) return mBare[1].trim();
|
|
55
|
+
}
|
|
56
|
+
function parseContentType(header) {
|
|
57
|
+
if (!header) return;
|
|
58
|
+
const [mime] = header.split(";", 1);
|
|
59
|
+
return mime?.trim().toLowerCase();
|
|
60
|
+
}
|
|
61
|
+
async function safeJson(body) {
|
|
62
|
+
try {
|
|
63
|
+
return JSON.parse(body);
|
|
64
|
+
} catch {
|
|
65
|
+
return { raw: body };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function timeoutSignal(ms, reason = /* @__PURE__ */ new Error("Timeout")) {
|
|
69
|
+
if (AbortSignal.timeout) return AbortSignal.timeout(ms);
|
|
70
|
+
const ac = new AbortController();
|
|
71
|
+
setTimeout(() => ac.abort(reason), ms);
|
|
72
|
+
return ac.signal;
|
|
73
|
+
}
|
|
74
|
+
function anySignal(signals) {
|
|
75
|
+
if (AbortSignal.any) return AbortSignal.any(signals);
|
|
76
|
+
const ac = new AbortController();
|
|
77
|
+
const aborted = signals.find((signal) => signal.aborted);
|
|
78
|
+
if (aborted) {
|
|
79
|
+
ac.abort(aborted.reason);
|
|
80
|
+
return ac.signal;
|
|
81
|
+
}
|
|
82
|
+
const onAbort = (event) => {
|
|
83
|
+
for (const signal of signals) signal.removeEventListener("abort", onAbort);
|
|
84
|
+
ac.abort(event.target.reason);
|
|
85
|
+
};
|
|
86
|
+
for (const s of signals) s.addEventListener("abort", onAbort, { once: true });
|
|
87
|
+
return ac.signal;
|
|
88
|
+
}
|
|
89
|
+
function getAbortErrorOrElse(signal, cause) {
|
|
90
|
+
return signal?.aborted ? signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("Aborted with unknown reason") : new Error(cause instanceof Error ? cause.message : "Unknown internal error", { cause });
|
|
91
|
+
}
|
|
92
|
+
function concatUint8Array(parts, total) {
|
|
93
|
+
if (parts.length === 1 && parts[0].byteLength === total) return parts[0];
|
|
94
|
+
let offset = 0;
|
|
95
|
+
const out = new Uint8Array(total);
|
|
96
|
+
for (const p of parts) {
|
|
97
|
+
out.set(p, offset);
|
|
98
|
+
offset += p.byteLength;
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* The key a client sends, or a thrown error naming how to supply one.
|
|
104
|
+
* `environmentApiKey` is the `FORMAT_API_KEY` the Node build reads from its
|
|
105
|
+
* environment. The web build passes nothing, so its callers have to
|
|
106
|
+
* pass `apiKey` explicitly.
|
|
107
|
+
*/
|
|
108
|
+
function resolveApiKey(explicitApiKey, environmentApiKey, howToSupply) {
|
|
109
|
+
if (explicitApiKey) return explicitApiKey;
|
|
110
|
+
if (environmentApiKey) return environmentApiKey;
|
|
111
|
+
throw new Error(`Format API key is required. ${howToSupply ?? "Pass `apiKey` explicitly."}`);
|
|
112
|
+
}
|
|
113
|
+
function stripQuotes(input) {
|
|
114
|
+
if (input.length >= 2 && input[0] === "\"" && input[input.length - 1] === "\"") return input.slice(1, -1);
|
|
115
|
+
return input;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
//#endregion
|
|
119
|
+
//#region src/error.ts
|
|
120
|
+
/**
|
|
121
|
+
* Thrown when the Format API returns a non-2xx response. Contains the HTTP status code and parsed error body.
|
|
122
|
+
*/
|
|
123
|
+
var FormatError = class extends Error {
|
|
124
|
+
constructor(status, detail) {
|
|
125
|
+
super(`Format API: Error ${status}`);
|
|
126
|
+
this.status = status;
|
|
127
|
+
this.detail = detail;
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
//#endregion
|
|
132
|
+
//#region src/response.ts
|
|
133
|
+
/**
|
|
134
|
+
* The error a non-2xx response becomes.
|
|
135
|
+
*
|
|
136
|
+
* Reads at most about 1MB of the body, so an unexpectedly large error response
|
|
137
|
+
* cannot exhaust memory, and parses it as JSON where it can. A body that is not
|
|
138
|
+
* JSON arrives as `{ raw: body }`.
|
|
139
|
+
*/
|
|
140
|
+
async function formatErrorFrom(res) {
|
|
141
|
+
const status = res.status ?? 0;
|
|
142
|
+
let size = 0;
|
|
143
|
+
const limit = 1e6;
|
|
144
|
+
const chunks = [];
|
|
145
|
+
const reader = res.body?.getReader();
|
|
146
|
+
try {
|
|
147
|
+
if (reader) while (size < limit) {
|
|
148
|
+
const { done, value } = await reader.read();
|
|
149
|
+
if (done || !value?.length) break;
|
|
150
|
+
chunks.push(value);
|
|
151
|
+
size += value.byteLength;
|
|
152
|
+
}
|
|
153
|
+
} finally {
|
|
154
|
+
try {
|
|
155
|
+
await reader?.cancel();
|
|
156
|
+
} catch {}
|
|
157
|
+
}
|
|
158
|
+
const buf = concatUint8Array(chunks, size);
|
|
159
|
+
return new FormatError(status, await safeJson(new TextDecoder("utf-8", { fatal: false }).decode(buf)));
|
|
160
|
+
}
|
|
161
|
+
/** What a successful response says about the PDF, read from its headers. */
|
|
162
|
+
function responseDetails(res) {
|
|
163
|
+
const rawContentLength = res.headers.get("content-length");
|
|
164
|
+
const contentType = parseContentType(res.headers.get("content-type"));
|
|
165
|
+
return {
|
|
166
|
+
filename: parseFilenameFromContentDisposition(res.headers.get("content-disposition")),
|
|
167
|
+
contentLength: rawContentLength ? parseInt(rawContentLength) : void 0,
|
|
168
|
+
contentType,
|
|
169
|
+
traceparent: res.headers.get("traceparent") || void 0,
|
|
170
|
+
isPdf: contentType === "application/pdf"
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Assign to the Response itself: a Proxy breaks the native methods' brand
|
|
175
|
+
* checks in browsers and Node 24.
|
|
176
|
+
*/
|
|
177
|
+
function augmentResponse(res) {
|
|
178
|
+
return Object.assign(res, responseDetails(res));
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
//#endregion
|
|
182
|
+
//#region src/document-assets.ts
|
|
183
|
+
/**
|
|
184
|
+
* A compiled document cannot cancel its asset lookup. Reject promptly on abort
|
|
185
|
+
* and cancel any stream that arrives afterwards so its source can release it.
|
|
186
|
+
*/
|
|
187
|
+
async function documentAssets(doc, signal) {
|
|
188
|
+
if (signal.aborted) throw getAbortErrorOrElse(signal);
|
|
189
|
+
const pending = doc.getAssetsWebStream();
|
|
190
|
+
return new Promise((resolve, reject) => {
|
|
191
|
+
const onAbort = () => {
|
|
192
|
+
signal.removeEventListener("abort", onAbort);
|
|
193
|
+
reject(getAbortErrorOrElse(signal));
|
|
194
|
+
};
|
|
195
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
196
|
+
if (signal.aborted) onAbort();
|
|
197
|
+
pending.then((stream) => {
|
|
198
|
+
signal.removeEventListener("abort", onAbort);
|
|
199
|
+
if (signal.aborted) {
|
|
200
|
+
stream?.cancel(signal.reason).catch(() => {});
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
resolve(stream);
|
|
204
|
+
}, (error) => {
|
|
205
|
+
signal.removeEventListener("abort", onAbort);
|
|
206
|
+
reject(error);
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
//#endregion
|
|
212
|
+
//#region src/web-client.ts
|
|
213
|
+
const ASSETS_FILENAME = "assets.zip";
|
|
214
|
+
const ASSETS_TYPE = "application/zip";
|
|
215
|
+
async function readStream(stream, signal) {
|
|
216
|
+
const reader = stream.getReader();
|
|
217
|
+
const onAbort = () => void reader.cancel(signal.reason).catch(() => {});
|
|
218
|
+
const chunks = [];
|
|
219
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
220
|
+
try {
|
|
221
|
+
if (signal.aborted) {
|
|
222
|
+
onAbort();
|
|
223
|
+
throw getAbortErrorOrElse(signal);
|
|
224
|
+
}
|
|
225
|
+
for (;;) {
|
|
226
|
+
const { done, value } = await reader.read();
|
|
227
|
+
if (signal.aborted) throw getAbortErrorOrElse(signal);
|
|
228
|
+
if (done) return chunks;
|
|
229
|
+
chunks.push(new Uint8Array(value));
|
|
230
|
+
}
|
|
231
|
+
} finally {
|
|
232
|
+
signal.removeEventListener("abort", onAbort);
|
|
233
|
+
reader.releaseLock();
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/** The assets archive as a Blob for native FormData. */
|
|
237
|
+
async function assetsToBlob(input, signal) {
|
|
238
|
+
if (isBlobLike(input)) return input.type === ASSETS_TYPE ? input : new Blob([input], { type: ASSETS_TYPE });
|
|
239
|
+
if (input instanceof ArrayBuffer) return new Blob([input], { type: ASSETS_TYPE });
|
|
240
|
+
if (ArrayBuffer.isView(input)) return new Blob([new Uint8Array(input)], { type: ASSETS_TYPE });
|
|
241
|
+
if (isWebReadable(input)) return new Blob(await readStream(input, signal), { type: ASSETS_TYPE });
|
|
242
|
+
throw new TypeError("Unsupported assets type. Pass a Blob, an ArrayBuffer, a Uint8Array or a ReadableStream.");
|
|
243
|
+
}
|
|
244
|
+
var FormatClient = class {
|
|
245
|
+
baseUrl;
|
|
246
|
+
renderTimeoutMs;
|
|
247
|
+
apiKey;
|
|
248
|
+
constructor(opts) {
|
|
249
|
+
this.apiKey = resolveApiKey(opts?.apiKey);
|
|
250
|
+
this.baseUrl = resolveBaseUrl(opts);
|
|
251
|
+
this.renderTimeoutMs = opts.renderTimeoutMs ?? 12e4;
|
|
252
|
+
}
|
|
253
|
+
async pdf(doc, options) {
|
|
254
|
+
const renderTimeoutSignal = timeoutSignal(this.renderTimeoutMs);
|
|
255
|
+
const combinedSignal = options?.signal ? anySignal([options.signal, renderTimeoutSignal]) : renderTimeoutSignal;
|
|
256
|
+
const isFormatDoc = typeof doc !== "string";
|
|
257
|
+
const html = isFormatDoc ? doc.html : doc;
|
|
258
|
+
const form = new FormData();
|
|
259
|
+
form.set("html", html);
|
|
260
|
+
if (options?.tags) form.set("tags", serializeTags(options.tags));
|
|
261
|
+
let assets = options?.assets;
|
|
262
|
+
if (!assets && isFormatDoc) assets = await documentAssets(doc, combinedSignal);
|
|
263
|
+
if (assets) form.set("assets", await assetsToBlob(assets, combinedSignal), ASSETS_FILENAME);
|
|
264
|
+
if (combinedSignal.aborted) throw getAbortErrorOrElse(combinedSignal);
|
|
265
|
+
let res;
|
|
266
|
+
try {
|
|
267
|
+
res = await fetch(renderUrl(this.baseUrl), {
|
|
268
|
+
method: "POST",
|
|
269
|
+
headers: {
|
|
270
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
271
|
+
"X-Format-Client": CLIENT_IDENTIFIER
|
|
272
|
+
},
|
|
273
|
+
body: form,
|
|
274
|
+
signal: combinedSignal,
|
|
275
|
+
credentials: "omit",
|
|
276
|
+
mode: "cors"
|
|
277
|
+
});
|
|
278
|
+
} catch (err) {
|
|
279
|
+
throw getAbortErrorOrElse(combinedSignal, err);
|
|
280
|
+
}
|
|
281
|
+
if (!res.ok) throw await formatErrorFrom(res);
|
|
282
|
+
return augmentResponse(res);
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
//#endregion
|
|
287
|
+
exports.FormatClient = FormatClient;
|
|
288
|
+
exports.FormatError = FormatError;
|