@cardonjs/backups 0.0.0-stage → 0.3.3

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.
Files changed (49) hide show
  1. package/FORMAT.md +147 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1237 -2
  4. package/dist/copy.d.ts +175 -0
  5. package/dist/copy.d.ts.map +1 -0
  6. package/dist/copy.js +863 -0
  7. package/dist/copy.js.map +1 -0
  8. package/dist/encryption.d.ts +203 -0
  9. package/dist/encryption.d.ts.map +1 -0
  10. package/dist/encryption.js +609 -0
  11. package/dist/encryption.js.map +1 -0
  12. package/dist/export.d.ts +201 -0
  13. package/dist/export.d.ts.map +1 -0
  14. package/dist/export.js +447 -0
  15. package/dist/export.js.map +1 -0
  16. package/dist/index.d.ts +14 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +14 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/keys.d.ts +28 -0
  21. package/dist/keys.d.ts.map +1 -0
  22. package/dist/keys.js +97 -0
  23. package/dist/keys.js.map +1 -0
  24. package/dist/metadata.d.ts +49 -0
  25. package/dist/metadata.d.ts.map +1 -0
  26. package/dist/metadata.js +51 -0
  27. package/dist/metadata.js.map +1 -0
  28. package/dist/restore.d.ts +97 -0
  29. package/dist/restore.d.ts.map +1 -0
  30. package/dist/restore.js +276 -0
  31. package/dist/restore.js.map +1 -0
  32. package/dist/retention.d.ts +153 -0
  33. package/dist/retention.d.ts.map +1 -0
  34. package/dist/retention.js +295 -0
  35. package/dist/retention.js.map +1 -0
  36. package/dist/run.d.ts +94 -0
  37. package/dist/run.d.ts.map +1 -0
  38. package/dist/run.js +129 -0
  39. package/dist/run.js.map +1 -0
  40. package/dist/sniff.d.ts +15 -0
  41. package/dist/sniff.d.ts.map +1 -0
  42. package/dist/sniff.js +47 -0
  43. package/dist/sniff.js.map +1 -0
  44. package/dist/workflow.d.ts +102 -0
  45. package/dist/workflow.d.ts.map +1 -0
  46. package/dist/workflow.js +298 -0
  47. package/dist/workflow.js.map +1 -0
  48. package/llms.txt +249 -0
  49. package/package.json +76 -3
@@ -0,0 +1,201 @@
1
+ /**
2
+ * The client of Cloudflare's D1 export endpoint: the only module that talks to the REST API. It
3
+ * follows Cloudflare's documentation, what Wrangler 4.116 sends and reads, and what a real run
4
+ * answered; everything that depends on the API's shape is in this file.
5
+ *
6
+ * Observed on Cloudflare on 2026-11-20 (shapes only, logged by a wrapper around `fetch`; twice,
7
+ * identically, for a 15 MB database):
8
+ *
9
+ * - **Start**, body `{ output_format: "polling" }`: HTTP 200, envelope
10
+ * `{ errors: [], messages, result, success: true }`; `result` is
11
+ * `{ at_bookmark, messages, status: "active", success, type: "export" }`, its `messages` like
12
+ * `["Generating <database-id>-<bookmark>.sql", "Uploaded part 2", "Uploaded part 1"]`.
13
+ * - **First poll** (10 s later), body `{ output_format, current_bookmark }`: HTTP 200; `result` is
14
+ * `{ at_bookmark, messages, result: { filename, signed_url }, status: "complete", success,
15
+ * type }`. The signed URL is **nested** in `result.result` (where Wrangler reads it; there was
16
+ * no `result.signed_url`), and `at_bookmark` is the start's.
17
+ * - **A second poll with the same bookmark**: HTTP 200, envelope `success: true`, `errors: []`,
18
+ * but `result` is `{ error: "Not currently exporting anything.", success: false }` (no
19
+ * `status`, no `at_bookmark`). **A completed export hands out its signed URL once**: the poll
20
+ * that first reports `complete` is the only one carrying it, so whoever receives that answer
21
+ * must download from it, and never poll again for it. That answer is `not_exporting` here; an
22
+ * export Cloudflare cancelled (not polled in time) is assumed to answer the same.
23
+ *
24
+ * A poll's answer whose `at_bookmark` differs from the polled bookmark is about another export
25
+ * (never observed; possible if Cloudflare tracks one export per database): `export_lost`, never
26
+ * `pending` or `ready`.
27
+ *
28
+ * The API token goes only to `https://api.cloudflare.com`, in the `Authorization` header. The
29
+ * signed URL of a ready export is never returned: it stays in the closure of `download()`, which
30
+ * fetches it without credentials. Neither appears in a result, an error or a log line.
31
+ */
32
+ type Fetch = (input: string, init: RequestInit) => Promise<Response>;
33
+ export interface D1ExportOptions {
34
+ /** The Cloudflare account id (32 hex characters). */
35
+ readonly accountId: string;
36
+ /** The D1 database's id (a UUID, `database_id` in the Wrangler config). */
37
+ readonly databaseId: string;
38
+ /**
39
+ * An API token with the D1 Write permission (the export endpoint requires it: an export locks
40
+ * the database). A secret: never logged or returned. Assume it can read, change and delete
41
+ * every D1 database of the account: keep it in a Worker that does nothing but backups.
42
+ */
43
+ readonly apiToken: string;
44
+ /**
45
+ * The format of the dump. `"d1"` (default) can be loaded back into D1. `"sqlite3"` asks
46
+ * Cloudflare for `dump_options.compatibility: "sqlite3_cli_only"`, needed for databases with
47
+ * virtual tables (FTS5); that dump loads into the `sqlite3` CLI only, never into D1.
48
+ */
49
+ readonly format?: "d1" | "sqlite3";
50
+ /**
51
+ * Hosts the signed URL may point to, exact (`example.com`) or by suffix (`*.example.com`).
52
+ * By default any public DNS name over https is accepted: the URL comes from an authenticated
53
+ * answer of `api.cloudflare.com`. Set it once you know the host your account gets.
54
+ */
55
+ readonly signedUrlHosts?: readonly string[];
56
+ /**
57
+ * Per API request. Default 30 000 ms. The download is bounded by `copyExport`'s
58
+ * `timeoutMs` (the whole copy) instead.
59
+ */
60
+ readonly timeoutMs?: number;
61
+ /**
62
+ * For tests: the `fetch` to use. Default: the global one. It receives the API token (in a
63
+ * header) and the signed URL: never log inside it.
64
+ */
65
+ readonly fetch?: Fetch;
66
+ }
67
+ /** Why an export call failed. `retryable` says whether the same call may succeed later. */
68
+ export type ExportFailureReason =
69
+ /**
70
+ * 401 or 403, or Cloudflare's error code 10000: the token is wrong, expired or lacks the
71
+ * permission (a D1 Read token is not enough: export needs D1 Write).
72
+ */
73
+ "unauthorized"
74
+ /** 404: no such account or database for this token. */
75
+ | "not_found"
76
+ /** Another 4xx, or `success: false`: Cloudflare refused the request. */
77
+ | "rejected"
78
+ /** 429. */
79
+ | "rate_limited"
80
+ /** 5xx. */
81
+ | "unavailable"
82
+ /** The request did not complete (connection, DNS). */
83
+ | "network"
84
+ /** No answer within `timeoutMs`. */
85
+ | "timeout"
86
+ /** An answer this client does not understand: never read as a success. */
87
+ | "malformed"
88
+ /** Cloudflare reports the export itself failed (`status: "error"`). */
89
+ | "export_failed"
90
+ /**
91
+ * Cloudflare answers `"Not currently exporting anything."` (a `result` with that exact
92
+ * `error` and no `status`): the completion was already handed out to an earlier poll, or the
93
+ * export was cancelled. Polling again cannot help; a new export can (`start`).
94
+ */
95
+ | "not_exporting"
96
+ /**
97
+ * A `result` with an `error` and no `status`, with another text than the one above, or a
98
+ * poll's answer whose `at_bookmark` is not the polled bookmark (an answer about another export
99
+ * of the database): treated the same way (no export running for this bookmark; start a new
100
+ * one), never as ready or pending.
101
+ */
102
+ | "export_lost"
103
+ /** The signed URL is not one this client will fetch (see `signedUrlHosts`). */
104
+ | "signed_url_refused";
105
+ export interface ExportFailure {
106
+ readonly status: "failed";
107
+ readonly reason: ExportFailureReason;
108
+ readonly retryable: boolean;
109
+ /** The HTTP status, when there was an answer. */
110
+ readonly httpStatus?: number;
111
+ }
112
+ export interface ExportPending {
113
+ readonly status: "pending";
114
+ /** Pass it to the next `poll`. */
115
+ readonly bookmark: string;
116
+ }
117
+ export type DownloadFailureReason =
118
+ /**
119
+ * 401, 403, 404 or 410: the signed URL expired or was refused. Polling again gives no new one
120
+ * (the completion is handed out once): a retry needs a new export.
121
+ */
122
+ "expired"
123
+ /** The download's `signal` aborted (its deadline passed). */
124
+ | "timeout"
125
+ /** A 3xx: redirects are never followed. */
126
+ | "redirected" | "unavailable" | "rate_limited" | "network"
127
+ /** Any other status. */
128
+ | "refused";
129
+ export type DownloadResult = {
130
+ readonly ok: true;
131
+ readonly body: ReadableStream<Uint8Array>;
132
+ /**
133
+ * The byte length when the answer states it (`Content-Length`, no `Content-Encoding`),
134
+ * else `null`.
135
+ */
136
+ readonly length: number | null;
137
+ } | {
138
+ readonly ok: false;
139
+ readonly reason: DownloadFailureReason;
140
+ readonly retryable: boolean;
141
+ readonly httpStatus?: number;
142
+ };
143
+ export interface DownloadOptions {
144
+ /**
145
+ * Aborts the request (an aborted request is `timeout`). The body is not watched here: whoever
146
+ * reads it (`copyExport`) bounds the reading with the same signal.
147
+ */
148
+ readonly signal?: AbortSignal;
149
+ }
150
+ /**
151
+ * The answer that reported the export complete. **Cloudflare hands out the signed URL once**:
152
+ * a later poll with the same bookmark answers `not_exporting`. Download from this answer (pass
153
+ * it to `copyExport`) and never poll again for the same export.
154
+ */
155
+ export interface ExportReady {
156
+ readonly status: "ready";
157
+ /** The bookmark the export is at. */
158
+ readonly bookmark: string;
159
+ /**
160
+ * Fetches the dump from the signed URL Cloudflare returned: GET, no credentials, no redirects.
161
+ * The URL itself is never exposed (it grants access to every row until it expires). Call it
162
+ * right away: the URL is valid for a limited time.
163
+ */
164
+ download(options?: DownloadOptions): Promise<DownloadResult>;
165
+ }
166
+ /**
167
+ * How many times one backup run (a Workflow instance, a `runBackup` call) starts a new export
168
+ * after Cloudflare answered that none is running (`isRestartable`), before it gives up.
169
+ */
170
+ export declare const MAX_RESTARTS = 2;
171
+ /**
172
+ * Whether a failed answer means "no export is running for this bookmark" (`not_exporting`,
173
+ * `export_lost`): polling again cannot help, starting a new export can.
174
+ */
175
+ export declare function isRestartable(reason: ExportFailureReason): boolean;
176
+ export type ExportStartResult = ExportPending | ExportReady | ExportFailure;
177
+ export type ExportPollResult = ExportPending | ExportReady | ExportFailure;
178
+ export interface D1Exporter {
179
+ readonly accountId: string;
180
+ readonly databaseId: string;
181
+ readonly format: "d1" | "sqlite3";
182
+ /** Starts an export. Each call starts a new one: keep the bookmark it returns. */
183
+ start(): Promise<ExportStartResult>;
184
+ /**
185
+ * Asks how the export at `bookmark` is going. A `ready` answer is the only one that carries
186
+ * the dump (see `ExportReady`): after it, the same bookmark answers `not_exporting`.
187
+ */
188
+ poll(bookmark: string): Promise<ExportPollResult>;
189
+ }
190
+ /** Whether `value` has the shape of a D1 database id (a lowercase UUID). */
191
+ export declare function isValidDatabaseId(value: unknown): value is string;
192
+ /** Whether `value` is a valid bookmark (what `poll` and the metadata accept). */
193
+ export declare function isValidBookmark(value: unknown): value is string;
194
+ /**
195
+ * Builds the client. Throws a `TypeError` (never including a value) when an option is invalid:
196
+ * the ids must have Cloudflare's shapes, so they cannot change the host or the path of the
197
+ * request.
198
+ */
199
+ export declare function d1Export(options: D1ExportOptions): D1Exporter;
200
+ export {};
201
+ //# sourceMappingURL=export.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"export.d.ts","sourceRoot":"","sources":["../src/export.ts"],"names":[],"mappings":"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"}
package/dist/export.js ADDED
@@ -0,0 +1,447 @@
1
+ /**
2
+ * The client of Cloudflare's D1 export endpoint: the only module that talks to the REST API. It
3
+ * follows Cloudflare's documentation, what Wrangler 4.116 sends and reads, and what a real run
4
+ * answered; everything that depends on the API's shape is in this file.
5
+ *
6
+ * Observed on Cloudflare on 2026-11-20 (shapes only, logged by a wrapper around `fetch`; twice,
7
+ * identically, for a 15 MB database):
8
+ *
9
+ * - **Start**, body `{ output_format: "polling" }`: HTTP 200, envelope
10
+ * `{ errors: [], messages, result, success: true }`; `result` is
11
+ * `{ at_bookmark, messages, status: "active", success, type: "export" }`, its `messages` like
12
+ * `["Generating <database-id>-<bookmark>.sql", "Uploaded part 2", "Uploaded part 1"]`.
13
+ * - **First poll** (10 s later), body `{ output_format, current_bookmark }`: HTTP 200; `result` is
14
+ * `{ at_bookmark, messages, result: { filename, signed_url }, status: "complete", success,
15
+ * type }`. The signed URL is **nested** in `result.result` (where Wrangler reads it; there was
16
+ * no `result.signed_url`), and `at_bookmark` is the start's.
17
+ * - **A second poll with the same bookmark**: HTTP 200, envelope `success: true`, `errors: []`,
18
+ * but `result` is `{ error: "Not currently exporting anything.", success: false }` (no
19
+ * `status`, no `at_bookmark`). **A completed export hands out its signed URL once**: the poll
20
+ * that first reports `complete` is the only one carrying it, so whoever receives that answer
21
+ * must download from it, and never poll again for it. That answer is `not_exporting` here; an
22
+ * export Cloudflare cancelled (not polled in time) is assumed to answer the same.
23
+ *
24
+ * A poll's answer whose `at_bookmark` differs from the polled bookmark is about another export
25
+ * (never observed; possible if Cloudflare tracks one export per database): `export_lost`, never
26
+ * `pending` or `ready`.
27
+ *
28
+ * The API token goes only to `https://api.cloudflare.com`, in the `Authorization` header. The
29
+ * signed URL of a ready export is never returned: it stays in the closure of `download()`, which
30
+ * fetches it without credentials. Neither appears in a result, an error or a log line.
31
+ */
32
+ const API_ORIGIN = "https://api.cloudflare.com";
33
+ /** Cloudflare account ids: 32 lowercase hex characters. */
34
+ const ACCOUNT_ID = /^[0-9a-f]{32}$/;
35
+ /** D1 database ids: a UUID. */
36
+ const DATABASE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
37
+ /** Visible ASCII only: a value that fits an HTTP header without surprises. */
38
+ const TOKEN = /^[\x21-\x7e]{1,1024}$/;
39
+ /** D1 bookmarks look like `00000085-0000024c-00004c6d-8e61…`; accept a little more, bounded. */
40
+ const BOOKMARK = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/;
41
+ /** The longest API answer read: export answers are a few hundred bytes. */
42
+ const MAX_ANSWER_BYTES = 1024 * 1024;
43
+ const MAX_SIGNED_URL_LENGTH = 8192;
44
+ const DEFAULT_TIMEOUT_MS = 30_000;
45
+ /** What Cloudflare answers a poll once the export's completion was handed out (observed). */
46
+ const NOT_EXPORTING = "Not currently exporting anything.";
47
+ /**
48
+ * How many times one backup run (a Workflow instance, a `runBackup` call) starts a new export
49
+ * after Cloudflare answered that none is running (`isRestartable`), before it gives up.
50
+ */
51
+ export const MAX_RESTARTS = 2;
52
+ /**
53
+ * Whether a failed answer means "no export is running for this bookmark" (`not_exporting`,
54
+ * `export_lost`): polling again cannot help, starting a new export can.
55
+ */
56
+ export function isRestartable(reason) {
57
+ return reason === "not_exporting" || reason === "export_lost";
58
+ }
59
+ function failed(reason, retryable, httpStatus) {
60
+ return httpStatus === undefined
61
+ ? { status: "failed", reason, retryable }
62
+ : { status: "failed", reason, retryable, httpStatus };
63
+ }
64
+ /** Whether `value` has the shape of a D1 database id (a lowercase UUID). */
65
+ export function isValidDatabaseId(value) {
66
+ return typeof value === "string" && DATABASE_ID.test(value);
67
+ }
68
+ /** Whether `value` is a valid bookmark (what `poll` and the metadata accept). */
69
+ export function isValidBookmark(value) {
70
+ return typeof value === "string" && BOOKMARK.test(value);
71
+ }
72
+ function isObject(value) {
73
+ return typeof value === "object" && value !== null && !Array.isArray(value);
74
+ }
75
+ const IPV4 = /^\d{1,3}(?:\.\d{1,3}){3}$/;
76
+ function hostAllowed(host, allowed) {
77
+ if (allowed === undefined)
78
+ return true;
79
+ return allowed.some((entry) => entry.startsWith("*.")
80
+ ? host.endsWith(entry.slice(1)) && host.length > entry.length - 1
81
+ : host === entry);
82
+ }
83
+ /**
84
+ * The signed URL as a `URL`, or `null` when this client will not fetch it: https only, the
85
+ * default port, no user or password, a DNS name with a dot (no IP literal, no `localhost`), and
86
+ * one of `signedUrlHosts` when given.
87
+ */
88
+ function checkSignedUrl(value, allowed) {
89
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_SIGNED_URL_LENGTH) {
90
+ return null;
91
+ }
92
+ let url;
93
+ try {
94
+ url = new URL(value);
95
+ }
96
+ catch {
97
+ return null;
98
+ }
99
+ const host = url.hostname.toLowerCase();
100
+ if (url.protocol !== "https:" ||
101
+ url.port !== "" ||
102
+ url.username !== "" ||
103
+ url.password !== "" ||
104
+ host.startsWith("[") ||
105
+ IPV4.test(host) ||
106
+ !host.includes(".") ||
107
+ host.endsWith(".") ||
108
+ host === "localhost" ||
109
+ host.endsWith(".localhost")) {
110
+ return null;
111
+ }
112
+ return hostAllowed(host, allowed) ? url : null;
113
+ }
114
+ function assertHostList(value) {
115
+ if (value === undefined)
116
+ return;
117
+ const entry = /^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]{2,63}$/;
118
+ if (!Array.isArray(value) ||
119
+ value.length === 0 ||
120
+ !value.every((host) => typeof host === "string" && entry.test(host))) {
121
+ throw new TypeError('d1Export: signedUrlHosts must be a non-empty list of lowercase hosts ("example.com" or "*.example.com").');
122
+ }
123
+ }
124
+ /** Reads at most `limit` bytes of `response`'s body; `null` when it is longer. */
125
+ async function readBounded(response, limit) {
126
+ if (response.body === null)
127
+ return "";
128
+ const reader = response.body.getReader();
129
+ const chunks = [];
130
+ let total = 0;
131
+ for (;;) {
132
+ const { done, value } = await reader.read();
133
+ if (done)
134
+ break;
135
+ total += value.byteLength;
136
+ if (total > limit) {
137
+ await reader.cancel().catch(() => undefined);
138
+ return null;
139
+ }
140
+ chunks.push(value);
141
+ }
142
+ const bytes = new Uint8Array(total);
143
+ let offset = 0;
144
+ for (const chunk of chunks) {
145
+ bytes.set(chunk, offset);
146
+ offset += chunk.byteLength;
147
+ }
148
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes);
149
+ }
150
+ function failureForStatus(status) {
151
+ if (status === 401 || status === 403)
152
+ return failed("unauthorized", false, status);
153
+ if (status === 404)
154
+ return failed("not_found", false, status);
155
+ if (status === 429)
156
+ return failed("rate_limited", true, status);
157
+ if (status >= 500 && status <= 599)
158
+ return failed("unavailable", true, status);
159
+ return failed("rejected", false, status);
160
+ }
161
+ /** Cloudflare's API error code for an authentication failure (a token without the permission). */
162
+ const AUTH_ERROR_CODE = 10000;
163
+ /** Whether an API answer lists error code 10000. Only codes are read, never messages. */
164
+ function hasAuthError(text) {
165
+ if (text === null)
166
+ return false;
167
+ let parsed;
168
+ try {
169
+ parsed = JSON.parse(text);
170
+ }
171
+ catch {
172
+ return false;
173
+ }
174
+ if (!isObject(parsed) || !Array.isArray(parsed.errors))
175
+ return false;
176
+ return parsed.errors.some((entry) => isObject(entry) && entry.code === AUTH_ERROR_CODE);
177
+ }
178
+ /**
179
+ * `promise`, or a rejection as soon as `signal` aborts (for a `fetch` that ignores signals). A
180
+ * value that arrives after the abort goes to `discard`.
181
+ */
182
+ function raceAbort(promise, signal, discard) {
183
+ if (signal === undefined)
184
+ return promise;
185
+ return new Promise((resolve, reject) => {
186
+ const onAbort = () => reject(new DOMException("aborted", "AbortError"));
187
+ signal.addEventListener("abort", onAbort, { once: true });
188
+ promise.then((value) => {
189
+ signal.removeEventListener("abort", onAbort);
190
+ if (signal.aborted)
191
+ discard(value);
192
+ else
193
+ resolve(value);
194
+ }, (error) => {
195
+ signal.removeEventListener("abort", onAbort);
196
+ reject(error);
197
+ });
198
+ });
199
+ }
200
+ function isAbort(error) {
201
+ return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
202
+ }
203
+ /**
204
+ * Builds the client. Throws a `TypeError` (never including a value) when an option is invalid:
205
+ * the ids must have Cloudflare's shapes, so they cannot change the host or the path of the
206
+ * request.
207
+ */
208
+ export function d1Export(options) {
209
+ if (typeof options !== "object" || options === null) {
210
+ throw new TypeError("d1Export: options { accountId, databaseId, apiToken } are required.");
211
+ }
212
+ const { accountId, databaseId, apiToken, signedUrlHosts } = options;
213
+ const format = options.format ?? "d1";
214
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
215
+ if (typeof accountId !== "string" || !ACCOUNT_ID.test(accountId)) {
216
+ throw new TypeError("d1Export: accountId must be a Cloudflare account id (32 hex characters).");
217
+ }
218
+ if (typeof databaseId !== "string" || !DATABASE_ID.test(databaseId)) {
219
+ throw new TypeError("d1Export: databaseId must be the D1 database id (a lowercase UUID).");
220
+ }
221
+ if (typeof apiToken !== "string" || !TOKEN.test(apiToken)) {
222
+ throw new TypeError("d1Export: apiToken must be a non-empty API token (visible ASCII, no spaces).");
223
+ }
224
+ if (format !== "d1" && format !== "sqlite3") {
225
+ throw new TypeError('d1Export: format must be "d1" or "sqlite3".');
226
+ }
227
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 300_000) {
228
+ throw new TypeError("d1Export: timeoutMs must be a whole number from 1000 to 300000.");
229
+ }
230
+ assertHostList(signedUrlHosts);
231
+ if (options.fetch !== undefined && typeof options.fetch !== "function") {
232
+ throw new TypeError("d1Export: fetch must be a function.");
233
+ }
234
+ const injected = options.fetch;
235
+ const doFetch = injected ?? ((input, init) => fetch(input, init));
236
+ const hosts = signedUrlHosts === undefined ? undefined : [...signedUrlHosts];
237
+ const endpoint = new URL(`/client/v4/accounts/${accountId}/d1/database/${databaseId}/export`, API_ORIGIN);
238
+ // Belt and braces: the shapes above already make this impossible.
239
+ if (endpoint.origin !== API_ORIGIN)
240
+ throw new TypeError("d1Export: invalid endpoint.");
241
+ const endpointHref = endpoint.href;
242
+ const dumpOptions = format === "sqlite3" ? { compatibility: "sqlite3_cli_only" } : undefined;
243
+ function downloader(url) {
244
+ const href = url.href;
245
+ return async (options) => {
246
+ const signal = options?.signal;
247
+ if (signal !== undefined && !(signal instanceof AbortSignal)) {
248
+ throw new TypeError("download: signal must be an AbortSignal.");
249
+ }
250
+ if (signal?.aborted)
251
+ return { ok: false, reason: "timeout", retryable: true };
252
+ let response;
253
+ try {
254
+ // No headers, no credentials: the URL is the capability. Redirects are not followed, so
255
+ // the request goes only to the host checked above.
256
+ const init = signal === undefined
257
+ ? { method: "GET", redirect: "manual" }
258
+ : { method: "GET", redirect: "manual", signal };
259
+ response = await raceAbort(doFetch(href, init), signal, (late) => {
260
+ late.body?.cancel().catch(() => undefined);
261
+ });
262
+ }
263
+ catch {
264
+ return signal?.aborted
265
+ ? { ok: false, reason: "timeout", retryable: true }
266
+ : { ok: false, reason: "network", retryable: true };
267
+ }
268
+ const status = response.status;
269
+ if (status !== 200) {
270
+ await response.body?.cancel().catch(() => undefined);
271
+ if ((status >= 300 && status <= 399) || status === 0) {
272
+ return { ok: false, reason: "redirected", retryable: false, httpStatus: status };
273
+ }
274
+ if (status === 401 || status === 403 || status === 404 || status === 410) {
275
+ return { ok: false, reason: "expired", retryable: true, httpStatus: status };
276
+ }
277
+ if (status === 429) {
278
+ return { ok: false, reason: "rate_limited", retryable: true, httpStatus: status };
279
+ }
280
+ if (status >= 500 && status <= 599) {
281
+ return { ok: false, reason: "unavailable", retryable: true, httpStatus: status };
282
+ }
283
+ return { ok: false, reason: "refused", retryable: false, httpStatus: status };
284
+ }
285
+ if (response.body === null) {
286
+ return { ok: true, body: new Response("").body, length: 0 };
287
+ }
288
+ const encoding = (response.headers.get("content-encoding") ?? "identity").trim();
289
+ const declared = response.headers.get("content-length");
290
+ const length = encoding.toLowerCase() === "identity" && declared !== null && /^\d{1,15}$/.test(declared)
291
+ ? Number(declared)
292
+ : null;
293
+ return { ok: true, body: response.body, length };
294
+ };
295
+ }
296
+ /** Parses an export answer strictly; anything unexpected is `malformed`. */
297
+ function parse(text, polled) {
298
+ if (text === null)
299
+ return failed("malformed", true, 200);
300
+ let envelope;
301
+ try {
302
+ envelope = JSON.parse(text);
303
+ }
304
+ catch {
305
+ return failed("malformed", true, 200);
306
+ }
307
+ if (!isObject(envelope) || typeof envelope.success !== "boolean") {
308
+ return failed("malformed", true, 200);
309
+ }
310
+ if (envelope.success !== true) {
311
+ return hasAuthError(text)
312
+ ? failed("unauthorized", false, 200)
313
+ : failed("rejected", false, 200);
314
+ }
315
+ const result = envelope.result;
316
+ if (!isObject(result))
317
+ return failed("malformed", true, 200);
318
+ if (result.success !== undefined && typeof result.success !== "boolean") {
319
+ return failed("malformed", true, 200);
320
+ }
321
+ const status = result.status;
322
+ if (status !== undefined &&
323
+ status !== "active" &&
324
+ status !== "complete" &&
325
+ status !== "error") {
326
+ return failed("malformed", true, 200);
327
+ }
328
+ // Any `error` key counts, `error: null` included: this fails closed on purpose. Never
329
+ // observed so far; if Cloudflare started sending `error: null` on every answer, an `active`
330
+ // or `complete` answer would be `malformed` (and one without a status `export_lost`): every
331
+ // backup would fail loudly, after its retries, instead of a dump being taken from an answer
332
+ // that may report an error. Accepting `null` would then be a one-line change here.
333
+ if (result.error !== undefined) {
334
+ // Observed: `{ error: "Not currently exporting anything.", success: false }`, no status,
335
+ // for a poll after the completion was handed out. The text is matched exactly; any other
336
+ // error without a status is still "no export running", never ready.
337
+ if (status === undefined) {
338
+ return result.error === NOT_EXPORTING
339
+ ? failed("not_exporting", false, 200)
340
+ : failed("export_lost", false, 200);
341
+ }
342
+ // An error next to "active" or "complete" is a shape nobody has seen: never ready.
343
+ if (status !== "error")
344
+ return failed("malformed", true, 200);
345
+ }
346
+ const atBookmark = result.at_bookmark;
347
+ // A poll's answer must be about the export it polled. Observed: the completed export's
348
+ // `at_bookmark` is the start's. If Cloudflare tracks one export per database, a poll could
349
+ // be answered about another export of the same database (a manual `wrangler d1 export`, a
350
+ // second backup instance): that answer is not this export's, whatever it says (pending,
351
+ // ready, failed), so its dump is never downloaded. `export_lost`: this export is not running
352
+ // any more as far as the answer tells; a restart starts a new one, whose answers are checked
353
+ // the same way, at most `MAX_RESTARTS` times.
354
+ if (polled !== undefined && isValidBookmark(atBookmark) && atBookmark !== polled) {
355
+ return failed("export_lost", false, 200);
356
+ }
357
+ if (result.success === false || status === "error")
358
+ return failed("export_failed", false, 200);
359
+ if (atBookmark !== undefined && !isValidBookmark(atBookmark)) {
360
+ return failed("malformed", true, 200);
361
+ }
362
+ // The real API puts the signed URL in `result.result.signed_url` (observed on 2026-11-20,
363
+ // and where Wrangler reads it); Cloudflare's Workflows example reads `result.signed_url`.
364
+ // Either is accepted; both present must agree.
365
+ const nested = isObject(result.result) ? result.result.signed_url : undefined;
366
+ if (result.result !== undefined && result.result !== null && !isObject(result.result)) {
367
+ return failed("malformed", true, 200);
368
+ }
369
+ const top = result.signed_url;
370
+ if (nested !== undefined && top !== undefined && nested !== top) {
371
+ return failed("malformed", true, 200);
372
+ }
373
+ const signed = nested ?? top;
374
+ const bookmark = atBookmark ?? polled;
375
+ if (signed === undefined || signed === null) {
376
+ if (status === "complete")
377
+ return failed("malformed", true, 200);
378
+ return bookmark === undefined
379
+ ? failed("malformed", true, 200)
380
+ : { status: "pending", bookmark };
381
+ }
382
+ if (status === "active" || bookmark === undefined)
383
+ return failed("malformed", true, 200);
384
+ const url = checkSignedUrl(signed, hosts);
385
+ if (url === null)
386
+ return failed("signed_url_refused", false, 200);
387
+ return { status: "ready", bookmark, download: downloader(url) };
388
+ }
389
+ async function call(polled) {
390
+ const body = { output_format: "polling" };
391
+ if (dumpOptions !== undefined)
392
+ body.dump_options = dumpOptions;
393
+ if (polled !== undefined)
394
+ body.current_bookmark = polled;
395
+ let response;
396
+ try {
397
+ response = await doFetch(endpointHref, {
398
+ method: "POST",
399
+ redirect: "manual",
400
+ headers: {
401
+ authorization: `Bearer ${apiToken}`,
402
+ "content-type": "application/json",
403
+ accept: "application/json",
404
+ },
405
+ body: JSON.stringify(body),
406
+ signal: AbortSignal.timeout(timeoutMs),
407
+ });
408
+ }
409
+ catch (error) {
410
+ return isAbort(error) ? failed("timeout", true) : failed("network", true);
411
+ }
412
+ if (response.status !== 200) {
413
+ if (response.status >= 400 && response.status <= 499) {
414
+ // Cloudflare's code 10000 ("Authentication error") is a refused token, whatever the status.
415
+ const text = await readBounded(response, MAX_ANSWER_BYTES).catch(() => null);
416
+ if (hasAuthError(text))
417
+ return failed("unauthorized", false, response.status);
418
+ return failureForStatus(response.status);
419
+ }
420
+ await response.body?.cancel().catch(() => undefined);
421
+ return response.status >= 300 && response.status <= 399
422
+ ? failed("malformed", true, response.status)
423
+ : failureForStatus(response.status);
424
+ }
425
+ let text;
426
+ try {
427
+ text = await readBounded(response, MAX_ANSWER_BYTES);
428
+ }
429
+ catch (error) {
430
+ return isAbort(error) ? failed("timeout", true) : failed("malformed", true, 200);
431
+ }
432
+ return parse(text, polled);
433
+ }
434
+ return {
435
+ accountId,
436
+ databaseId,
437
+ format,
438
+ start: () => call(undefined),
439
+ async poll(bookmark) {
440
+ if (!isValidBookmark(bookmark)) {
441
+ throw new TypeError("d1Export: poll needs the bookmark returned by start or poll.");
442
+ }
443
+ return call(bookmark);
444
+ },
445
+ };
446
+ }
447
+ //# sourceMappingURL=export.js.map