cursedbelt-server 4.54.0 → 4.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -71,9 +71,30 @@ export declare function servedRuntime(url: string, { attempts, sleep }?: {
71
71
  * Rows per paged `SELECT`. The fleet's largest table held 290 rows when this was set (collections'
72
72
  * `items`, 2026-09-25) and one `wrangler` call costs ~1 s, so a page this size is one call per
73
73
  * table for every app today. A page D1 refuses — too large a response — is halved and asked
74
- * again, down to one row, before it is a refusal.
74
+ * again, down to one row, before it is a refusal. It is where every table STARTS: small rows grow
75
+ * past it ({@link nextPageRows}).
75
76
  */
76
77
  export declare const PAGE_ROWS = 500;
78
+ /**
79
+ * 🔴 How far a table of small rows grows its pages, and the bytes a grown page may carry.
80
+ *
81
+ * At a fixed {@link PAGE_ROWS} the cost of a pull is its ROW count, ~1.5 s of `bun x wrangler` per
82
+ * 500 rows whatever they hold. Measured 2026-10-29: photos' 171,590-row gazetteer and 40,841
83
+ * `asset_tags` made its backup ~600 calls, 730 s on 2026-10-28, 873 s that night, and then
84
+ * past the recovery backup's 900 s ceiling on both WDElementsBlack runs of 2026-10-29 (exit
85
+ * 143, twice each), so the drive carried a stale photos snapshot. A page of tiny rows is a
86
+ * few KB, so it doubles while the rows it read stay small: to {@link MAX_PAGE_ROWS}, while
87
+ * that many rows of the size just read stay under {@link PAGE_BYTES}. Large rows never grow
88
+ * past {@link PAGE_ROWS}, which is where they were already proven.
89
+ */
90
+ export declare const MAX_PAGE_ROWS = 10000;
91
+ export declare const PAGE_BYTES = 4000000;
92
+ /**
93
+ * The next page's size after one of `limit` rows came back with `rows` rows and `bytes` of SQL
94
+ * literals. It doubles, but never past `cap` (lowered by a refusal: see {@link dumpTable}), and
95
+ * never past {@link PAGE_ROWS} unless rows of this size fit {@link PAGE_BYTES}.
96
+ */
97
+ export declare function nextPageRows(limit: number, rows: number, bytes: number, cap?: number): number;
77
98
  /** One `wrangler` invocation, as {@link pullD1ToSqlite} needs it. Injected so a spec runs none. */
78
99
  export type Wrangler = (args: string[]) => {
79
100
  code: number;
@@ -86,9 +107,17 @@ export type Wrangler = (args: string[]) => {
86
107
  * line until 4.22.0.
87
108
  */
88
109
  export declare const wranglerArgv: (bun?: string) => string[];
110
+ /**
111
+ * 🔴 How long one `wrangler` call may run before it is killed. Without it a call whose connection
112
+ * stalled never returned: measured 2026-10-29, a photos pull logged two `fetch failed` retries and
113
+ * then sat 20 minutes on one call, which inside the recovery backup is the 900 s ceiling's kill and
114
+ * a stale snapshot. A kill reads as `ETIMEDOUT`, which {@link isTransient} waits out and asks again.
115
+ * A healthy page of {@link PAGE_BYTES} answers in seconds.
116
+ */
117
+ export declare const CALL_TIMEOUT_MS = 120000;
89
118
  /**
90
119
  * Run `argv` to completion with its stdout written to a FILE, never a pipe, and return what it
91
- * wrote.
120
+ * wrote — or kill it at `timeoutMs` and say so in a message {@link isTransient} recognizes.
92
121
  *
93
122
  * 🔴 A Bun child that ends with `process.exit()` drops whatever of its stdout the pipe had not
94
123
  * taken yet, at a 64 KiB boundary — and wrangler is a Bun child whenever `node` is not on PATH
@@ -103,6 +132,8 @@ export declare function spawnToFile(argv: string[], options?: {
103
132
  cwd?: string;
104
133
  /** The child's whole environment, or a function of this call's own scratch directory that returns it. */
105
134
  env?: Record<string, string | undefined> | ((scratch: string) => Record<string, string | undefined>);
135
+ /** Kill the child after this long ({@link CALL_TIMEOUT_MS} by default). */
136
+ timeoutMs?: number;
106
137
  }): {
107
138
  code: number;
108
139
  stdout: string;
@@ -105,18 +105,51 @@ export async function servedRuntime(url, { attempts = 3, sleep = (ms) => new Pro
105
105
  * Rows per paged `SELECT`. The fleet's largest table held 290 rows when this was set (collections'
106
106
  * `items`, 2026-09-25) and one `wrangler` call costs ~1 s, so a page this size is one call per
107
107
  * table for every app today. A page D1 refuses — too large a response — is halved and asked
108
- * again, down to one row, before it is a refusal.
108
+ * again, down to one row, before it is a refusal. It is where every table STARTS: small rows grow
109
+ * past it ({@link nextPageRows}).
109
110
  */
110
111
  export const PAGE_ROWS = 500;
112
+ /**
113
+ * 🔴 How far a table of small rows grows its pages, and the bytes a grown page may carry.
114
+ *
115
+ * At a fixed {@link PAGE_ROWS} the cost of a pull is its ROW count, ~1.5 s of `bun x wrangler` per
116
+ * 500 rows whatever they hold. Measured 2026-10-29: photos' 171,590-row gazetteer and 40,841
117
+ * `asset_tags` made its backup ~600 calls, 730 s on 2026-10-28, 873 s that night, and then
118
+ * past the recovery backup's 900 s ceiling on both WDElementsBlack runs of 2026-10-29 (exit
119
+ * 143, twice each), so the drive carried a stale photos snapshot. A page of tiny rows is a
120
+ * few KB, so it doubles while the rows it read stay small: to {@link MAX_PAGE_ROWS}, while
121
+ * that many rows of the size just read stay under {@link PAGE_BYTES}. Large rows never grow
122
+ * past {@link PAGE_ROWS}, which is where they were already proven.
123
+ */
124
+ export const MAX_PAGE_ROWS = 10_000;
125
+ export const PAGE_BYTES = 4_000_000;
126
+ /**
127
+ * The next page's size after one of `limit` rows came back with `rows` rows and `bytes` of SQL
128
+ * literals. It doubles, but never past `cap` (lowered by a refusal: see {@link dumpTable}), and
129
+ * never past {@link PAGE_ROWS} unless rows of this size fit {@link PAGE_BYTES}.
130
+ */
131
+ export function nextPageRows(limit, rows, bytes, cap = MAX_PAGE_ROWS) {
132
+ const perRow = rows > 0 ? bytes / rows : 0;
133
+ const fits = perRow > 0 ? Math.floor(PAGE_BYTES / perRow) : MAX_PAGE_ROWS;
134
+ return Math.max(1, Math.min(cap, limit * 2, Math.max(PAGE_ROWS, fits)));
135
+ }
111
136
  /**
112
137
  * The argv that runs `wrangler`: THIS bun binary's `x`, never a bare `bunx` — a launchd job's
113
138
  * PATH has no `bunx` (task 2112), and vault's and patterns' nightly backups each carried this
114
139
  * line until 4.22.0.
115
140
  */
116
141
  export const wranglerArgv = (bun = process.execPath) => [bun, 'x', 'wrangler'];
142
+ /**
143
+ * 🔴 How long one `wrangler` call may run before it is killed. Without it a call whose connection
144
+ * stalled never returned: measured 2026-10-29, a photos pull logged two `fetch failed` retries and
145
+ * then sat 20 minutes on one call, which inside the recovery backup is the 900 s ceiling's kill and
146
+ * a stale snapshot. A kill reads as `ETIMEDOUT`, which {@link isTransient} waits out and asks again.
147
+ * A healthy page of {@link PAGE_BYTES} answers in seconds.
148
+ */
149
+ export const CALL_TIMEOUT_MS = 120_000;
117
150
  /**
118
151
  * Run `argv` to completion with its stdout written to a FILE, never a pipe, and return what it
119
- * wrote.
152
+ * wrote — or kill it at `timeoutMs` and say so in a message {@link isTransient} recognizes.
120
153
  *
121
154
  * 🔴 A Bun child that ends with `process.exit()` drops whatever of its stdout the pipe had not
122
155
  * taken yet, at a 64 KiB boundary — and wrangler is a Bun child whenever `node` is not on PATH
@@ -133,9 +166,14 @@ export function spawnToFile(argv, options = {}) {
133
166
  let code = 1;
134
167
  try {
135
168
  const env = typeof options.env === 'function' ? options.env(dir) : options.env;
136
- const r = Bun.spawnSync(argv, { cwd: options.cwd, env, stdout: Bun.file(out), stderr: 'pipe' });
137
- code = r.exitCode ?? 1;
169
+ const timeoutMs = options.timeoutMs ?? CALL_TIMEOUT_MS;
170
+ const r = Bun.spawnSync(argv, { cwd: options.cwd, env, stdout: Bun.file(out), stderr: 'pipe', timeout: timeoutMs });
138
171
  const stdout = existsSync(out) ? readFileSync(out, 'utf8') : '';
172
+ if (r.exitedDueToTimeout || r.exitCode === null) {
173
+ code = 124;
174
+ return { code, stdout, stderr: `${argv.slice(0, 4).join(' ')} … did not finish in ${timeoutMs / 1000}s and was killed (ETIMEDOUT)` };
175
+ }
176
+ code = r.exitCode;
139
177
  return { code, stdout, stderr: r.stderr.toString() };
140
178
  }
141
179
  finally {
@@ -299,11 +337,16 @@ export function pageSql(plan, limit, after) {
299
337
  * size back toward {@link PAGE_ROWS}. Before 4.33.1 nothing grew it back: desk's first launchd
300
338
  * backup (2026-09-25) hit a few slow calls early and read its 3,381-row table 15 rows per call —
301
339
  * 225 two-minute calls, on course for hours. Only a refusal at ONE row is fatal.
340
+ *
341
+ * Small rows grow on past {@link PAGE_ROWS} ({@link nextPageRows}). A refusal of a page that
342
+ * large caps the rest of the table at half of it, so a size D1 refused is never asked again;
343
+ * a refusal at or under {@link PAGE_ROWS} caps it there, which is the old behavior exactly.
302
344
  */
303
345
  function dumpTable(caller, database, plan) {
304
346
  const into = `INSERT INTO ${sqlIdent(plan.table)} (${plan.columns.map(sqlIdent).join(', ')}) VALUES (`;
305
347
  const lines = [];
306
348
  let limit = PAGE_ROWS;
349
+ let cap = MAX_PAGE_ROWS;
307
350
  let after = {};
308
351
  for (;;) {
309
352
  let page;
@@ -315,22 +358,26 @@ function dumpTable(caller, database, plan) {
315
358
  if (limit > 1) {
316
359
  const next = Math.max(1, Math.floor(limit / 2));
317
360
  caller.log(`pull D1: \`${plan.table}\` refused a page of ${limit} — asking for ${next}: ${message}`);
361
+ cap = Math.min(cap, Math.max(PAGE_ROWS, next));
318
362
  limit = next;
319
363
  continue;
320
364
  }
321
365
  throw new Error(`could not read \`${plan.table}\` from D1: ${message}`);
322
366
  }
367
+ let bytes = 0;
323
368
  for (const row of page) {
324
369
  const literals = plan.columns.map((_, i) => row[`c${i}`]);
325
370
  if (literals.some((v) => typeof v !== 'string')) {
326
371
  throw new Error(`D1 returned a non-literal value paging \`${plan.table}\` — refusing a snapshot that may not restore`);
327
372
  }
328
- lines.push(`${into}${literals.join(', ')});`);
373
+ const values = literals.join(', ');
374
+ bytes += values.length;
375
+ lines.push(`${into}${values});`);
329
376
  }
330
377
  if (page.length < limit)
331
378
  break;
332
379
  after = plan.key ? { key: Number(page[page.length - 1]?.k) } : { offset: (after.offset ?? 0) + page.length };
333
- limit = Math.min(PAGE_ROWS, limit * 2);
380
+ limit = nextPageRows(limit, page.length, bytes, cap);
334
381
  }
335
382
  return { text: lines.join('\n'), rows: lines.length };
336
383
  }
@@ -414,9 +461,13 @@ export async function pullD1ToSqlite(options) {
414
461
  }
415
462
  }
416
463
  // One table at a time, so a fault is located rather than smeared over the whole load.
464
+ // 🔴 And each table in ONE transaction: bare, every row's INSERT is its own commit and its
465
+ // own journal and sync. Measured 2026-10-29 (forge task 3957), photos' ~400 s load; 3,000
466
+ // rows took 2,881 ms bare and 13 ms in a transaction.
467
+ const load = db.transaction((text) => db.exec(text));
417
468
  for (const { text } of dumps)
418
469
  if (text)
419
- db.exec(text);
470
+ load(text);
420
471
  for (const t of triggers)
421
472
  db.exec(t.sql);
422
473
  if (options.afterLoadSql)
@@ -50,8 +50,16 @@ export interface YtDownload {
50
50
  dir: string;
51
51
  dispose(): Promise<void>;
52
52
  }
53
- /** Fetch one video. `onProgress` gets the fraction of the file received, 0–1. */
54
- export type YtDlpFetch = (videoId: string, onProgress?: (fraction: number) => void) => Promise<YtDownload>;
53
+ /** What one call may add to the profile: a site that needs the owner's sign-in gets his cookies. */
54
+ interface YtDlpCallOptions {
55
+ /** A Netscape-format cookie jar yt-dlp reads (`--cookies`). The caller owns and removes it. */
56
+ cookiesFile?: string;
57
+ }
58
+ /**
59
+ * Fetch one video. `target` is a YouTube video id, or a page URL (`https://…`) of any site yt-dlp
60
+ * reads — Collections' pasted links (forge task 4003). `onProgress` gets the fraction received, 0–1.
61
+ */
62
+ export type YtDlpFetch = (target: string, onProgress?: (fraction: number) => void, options?: YtDlpCallOptions) => Promise<YtDownload>;
55
63
  /**
56
64
  * Why a download failed, sorted by what the owner can do about it.
57
65
  *
@@ -60,9 +68,11 @@ export type YtDlpFetch = (videoId: string, onProgress?: (fraction: number) => vo
60
68
  * · `blocked` — YouTube is refusing this Mac as a bot. Time fixes it, usually.
61
69
  * · `unavailable` — the video itself: private, deleted, region-locked, members-only.
62
70
  * · `too-big` — over the one-download ceiling.
71
+ * · `unsupported` — a pasted page URL yt-dlp has no reader for. Only a URL target gets it: for a
72
+ * YouTube id the same words mean YouTube moved, which `outdated` fixes.
63
73
  * · `failed` — anything else, with yt-dlp's own last error line.
64
74
  */
65
- export type YtDlpFailure = "missing" | "outdated" | "blocked" | "unavailable" | "too-big" | "failed";
75
+ export type YtDlpFailure = "missing" | "outdated" | "blocked" | "unavailable" | "too-big" | "unsupported" | "failed";
66
76
  export declare class YtDlpError extends Error {
67
77
  readonly kind: YtDlpFailure;
68
78
  constructor(message: string, kind: YtDlpFailure);
@@ -79,12 +89,13 @@ export declare const isFinalYtDlpFailure: (kind: YtDlpFailure) => boolean;
79
89
  export declare function parseYtProgress(line: string): number | null;
80
90
  /** The info JSON printed after the file is in place, or `null` for any other line. */
81
91
  export declare function parseYtInfo(line: string): YtInfo | null;
82
- /** Sort a failure by what can be done about it — see {@link YtDlpFailure}. */
83
- export declare function classifyYtDlpFailure(stderr: string): YtDlpFailure;
92
+ /** Sort a failure by what can be done about it — see {@link YtDlpFailure}. `target` is what was fetched. */
93
+ export declare function classifyYtDlpFailure(stderr: string, target?: string): YtDlpFailure;
84
94
  /** The arguments for one download. Exported so a test pins the flags that matter. */
85
- export declare function ytDlpArgs(videoId: string, outDir: string, profile: Pick<YtDlpProfile, "format" | "extraArgs" | "maxFilesize">, options?: {
95
+ export declare function ytDlpArgs(target: string, outDir: string, profile: Pick<YtDlpProfile, "format" | "extraArgs" | "maxFilesize">, options?: {
86
96
  cacheDir?: string;
87
97
  jsRuntime?: string;
98
+ cookiesFile?: string;
88
99
  }): string[];
89
100
  /** Run a program, handing each stdout line over as it arrives. Injected in tests. */
90
101
  export type RunLines = (binary: string, args: string[], onLine: (line: string) => void) => Promise<{
@@ -127,3 +138,4 @@ export interface YtDlpOptions {
127
138
  * and what it leaves as a sentence.
128
139
  */
129
140
  export declare function createYtDlp(options: YtDlpOptions): YtDlpFetch;
141
+ export {};
@@ -14,6 +14,10 @@
14
14
  * a track; Collections ingests a video), and any re-encode (only Collections has one, and only
15
15
  * when no H.264 stream exists).
16
16
  *
17
+ * A target is a YouTube video id or, since forge task 4003, any page URL yt-dlp reads — the
18
+ * links the owner pastes into Collections. A site that hides its videos behind a sign-in (eporner's
19
+ * age check) is handed the owner's own cookie jar per call; reading that jar is the app's business.
20
+ *
17
21
  * ── The file stays on disk ──────────────────────────────────────────────────────────────
18
22
  * A download resolves to a PATH inside a fresh temporary directory, and the caller disposes of
19
23
  * it. A 1080p video is gigabytes, and reading it into memory to hand it over would make the
@@ -57,6 +61,19 @@ export function ytDlpPath(state) {
57
61
  export function ytDlpCacheDir(state) {
58
62
  return join(state, "cache", "yt-dlp");
59
63
  }
64
+ /** Is `target` a page URL rather than a YouTube video id? */
65
+ const isPageUrl = (target) => /^https?:\/\//i.test(target);
66
+ /** The site a target is on, as a sentence names it: `YouTube`, or the URL's host without `www.`. */
67
+ function siteOf(target) {
68
+ if (!isPageUrl(target))
69
+ return "YouTube";
70
+ try {
71
+ return new URL(target).hostname.replace(/^www\./i, "") || "that site";
72
+ }
73
+ catch {
74
+ return "that site";
75
+ }
76
+ }
60
77
  export class YtDlpError extends Error {
61
78
  kind;
62
79
  constructor(message, kind) {
@@ -66,7 +83,7 @@ export class YtDlpError extends Error {
66
83
  }
67
84
  }
68
85
  /** A failure no retry and no update can change — the video's own fault, or the ceiling. */
69
- export const isFinalYtDlpFailure = (kind) => kind === "unavailable" || kind === "too-big";
86
+ export const isFinalYtDlpFailure = (kind) => kind === "unavailable" || kind === "too-big" || kind === "unsupported";
70
87
  // ── Pure: reading what yt-dlp prints ───────────────────────────────────────────────────
71
88
  /**
72
89
  * One progress line, as a fraction — or `null` for any other line.
@@ -109,11 +126,14 @@ const UNAVAILABLE = /video unavailable|this video is unavailable|private video|h
109
126
  const BLOCKED = /confirm you.?re not a bot|sign in to confirm|too many requests|http error 429/i;
110
127
  const OUTDATED = /unable to extract|nsig|n challenge|signature (extraction|function)|precondition check failed|http error 403|requested format is not available|please report this issue|js challenge|player .*(response|js)|unsupported url|jsc/i;
111
128
  const TOO_BIG = /larger than max-filesize|max-filesize/i;
112
- /** Sort a failure by what can be done about it — see {@link YtDlpFailure}. */
113
- export function classifyYtDlpFailure(stderr) {
129
+ const UNSUPPORTED = /unsupported url/i;
130
+ /** Sort a failure by what can be done about it — see {@link YtDlpFailure}. `target` is what was fetched. */
131
+ export function classifyYtDlpFailure(stderr, target = "") {
114
132
  const line = lastYtDlpError(stderr);
115
133
  if (TOO_BIG.test(line))
116
134
  return "too-big";
135
+ if (isPageUrl(target) && UNSUPPORTED.test(line))
136
+ return "unsupported";
117
137
  if (UNAVAILABLE.test(line))
118
138
  return "unavailable";
119
139
  if (BLOCKED.test(line))
@@ -125,29 +145,33 @@ export function classifyYtDlpFailure(stderr) {
125
145
  /** The sentence a downloads table shows. Every kind that has a remedy NAMES it. */
126
146
  function describeYtDlpFailure(kind, detail, context) {
127
147
  const fix = context.fixCommand;
148
+ const site = context.site;
128
149
  switch (kind) {
129
150
  case "missing":
130
151
  return `yt-dlp is not installed on the Mac and installing it failed (${detail}). Run: ${fix}`;
131
152
  case "outdated":
132
- return (`yt-dlp could not read YouTube — it is out of date for a change YouTube made (${detail}). ` +
153
+ return (`yt-dlp could not read ${site} — it is out of date for a change ${site} made (${detail}). ` +
133
154
  (context.updated
134
155
  ? `The agent already updated it and it still fails, so the fix is not released yet; try again in a day, or run: ${fix}`
135
156
  : `Run: ${fix}`));
136
157
  case "blocked":
137
- return `YouTube is refusing this Mac's requests as a bot (${detail}). It usually lifts within hours — try again later. If it persists, update yt-dlp: ${fix}`;
158
+ return `${site} is refusing this Mac's requests as a bot (${detail}). It usually lifts within hours — try again later. If it persists, update yt-dlp: ${fix}`;
138
159
  case "unavailable":
139
- return `YouTube will not play this video to anyone signed out (${detail}), so there is nothing to download.`;
160
+ return `${site} will not play this video to anyone signed out (${detail}), so there is nothing to download.`;
161
+ case "unsupported":
162
+ return `yt-dlp has no reader for ${site} pages (${detail}), so that link cannot be downloaded.`;
140
163
  case "too-big":
141
164
  return `${context.profile.noun} is over this app's ${context.profile.maxFilesize}B ceiling for one download.`;
142
165
  default:
143
- return `yt-dlp failed: ${detail || "no reason given"}. If YouTube links keep failing, update it: ${fix}`;
166
+ return `yt-dlp failed: ${detail || "no reason given"}. If ${site} links keep failing, update it: ${fix}`;
144
167
  }
145
168
  }
146
169
  /** The arguments for one download. Exported so a test pins the flags that matter. */
147
- export function ytDlpArgs(videoId, outDir, profile, options = {}) {
170
+ export function ytDlpArgs(target, outDir, profile, options = {}) {
148
171
  return [
149
172
  ...(options.jsRuntime ? ["--js-runtimes", `bun:${options.jsRuntime}`] : []),
150
173
  ...(options.cacheDir ? ["--cache-dir", options.cacheDir] : []),
174
+ ...(options.cookiesFile ? ["--cookies", options.cookiesFile] : []),
151
175
  "--no-playlist",
152
176
  "-f",
153
177
  profile.format,
@@ -167,7 +191,7 @@ export function ytDlpArgs(videoId, outDir, profile, options = {}) {
167
191
  "-o",
168
192
  join(outDir, "%(id)s.%(ext)s"),
169
193
  "--",
170
- `https://www.youtube.com/watch?v=${videoId}`,
194
+ isPageUrl(target) ? target : `https://www.youtube.com/watch?v=${target}`,
171
195
  ];
172
196
  }
173
197
  const runLines = (binary, args, onLine) => new Promise((resolve, reject) => {
@@ -254,7 +278,7 @@ export function createYtDlp(options) {
254
278
  const label = options.label ?? "[yt-dlp]";
255
279
  const jsRuntime = options.jsRuntime ?? (process.versions.bun ? process.execPath : undefined);
256
280
  let lastUpdate = Number.NEGATIVE_INFINITY;
257
- const describe = (kind, detail, updated) => describeYtDlpFailure(kind, detail, { updated, fixCommand: options.fixCommand, profile: options.profile });
281
+ const describe = (kind, detail, updated, target) => describeYtDlpFailure(kind, detail, { updated, fixCommand: options.fixCommand, profile: options.profile, site: siteOf(target) });
258
282
  const ensureInstalled = async () => {
259
283
  if (await isFile(options.binary))
260
284
  return;
@@ -264,18 +288,19 @@ export function createYtDlp(options) {
264
288
  }
265
289
  catch (error) {
266
290
  const detail = error instanceof Error ? error.message : String(error);
267
- throw new YtDlpError(describe("missing", detail, false), "missing");
291
+ throw new YtDlpError(describe("missing", detail, false, ""), "missing");
268
292
  }
269
293
  };
270
294
  /** One yt-dlp run into a fresh directory. Throws a classified error on failure. */
271
- const attempt = async (videoId, onProgress) => {
295
+ const attempt = async (target, onProgress, call = {}) => {
272
296
  const dir = await mkdtemp(join(options.tmpRoot ?? tmpdir(), "ytdlp-"));
273
297
  const dispose = () => rm(dir, { recursive: true, force: true });
274
298
  try {
275
299
  let info = null;
276
- const { code, stderr } = await run(options.binary, ytDlpArgs(videoId, dir, options.profile, {
300
+ const { code, stderr } = await run(options.binary, ytDlpArgs(target, dir, options.profile, {
277
301
  ...(options.cacheDir ? { cacheDir: options.cacheDir } : {}),
278
302
  ...(jsRuntime ? { jsRuntime } : {}),
303
+ ...(call.cookiesFile ? { cookiesFile: call.cookiesFile } : {}),
279
304
  }), (line) => {
280
305
  const fraction = parseYtProgress(line);
281
306
  if (fraction !== null)
@@ -284,7 +309,7 @@ export function createYtDlp(options) {
284
309
  });
285
310
  const found = info;
286
311
  if (code !== 0 || !found?.filepath) {
287
- const kind = code === 0 ? "failed" : classifyYtDlpFailure(stderr);
312
+ const kind = code === 0 ? "failed" : classifyYtDlpFailure(stderr, target);
288
313
  throw new YtDlpError(code === 0 ? "yt-dlp finished without saying where the file went" : lastYtDlpError(stderr), kind);
289
314
  }
290
315
  if (!(await isFile(found.filepath)))
@@ -297,13 +322,13 @@ export function createYtDlp(options) {
297
322
  throw error;
298
323
  }
299
324
  };
300
- return async (videoId, onProgress) => {
325
+ return async (target, onProgress, call) => {
301
326
  await ensureInstalled();
302
327
  let updated = false;
303
328
  let last = null;
304
329
  for (let tries = 1; tries <= ATTEMPTS + 1; tries++) {
305
330
  try {
306
- return await attempt(videoId, onProgress);
331
+ return await attempt(target, onProgress, call);
307
332
  }
308
333
  catch (error) {
309
334
  last =
@@ -329,6 +354,6 @@ export function createYtDlp(options) {
329
354
  }
330
355
  }
331
356
  const failure = last ?? new YtDlpError("no attempt ran", "failed");
332
- throw new YtDlpError(describe(failure.kind, failure.message, updated), failure.kind);
357
+ throw new YtDlpError(describe(failure.kind, failure.message, updated, target), failure.kind);
333
358
  };
334
359
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.54.0",
3
+ "version": "4.56.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
@@ -417,7 +417,7 @@
417
417
  "@node-rs/argon2": "^2.0.2",
418
418
  "@types/bun": "^1.3.14",
419
419
  "@types/node": "^24",
420
- "cursedbelt": "^5.9.0",
420
+ "cursedbelt": "^5.99.6",
421
421
  "hono": "4.12.28",
422
422
  "kysely": "^0.28.17",
423
423
  "kysely-bun-sqlite": "^0.4.0",
@@ -13,7 +13,7 @@ import {
13
13
  type Wrangler,
14
14
  wranglerArgv,
15
15
  } from './localBackup.js';
16
- import { PAGE_ROWS, pageSql, spawnToFile, tablePlan } from './pullD1.js';
16
+ import { isTransient, PAGE_ROWS, pageSql, spawnToFile, tablePlan } from './pullD1.js';
17
17
 
18
18
  const dirs: string[] = [];
19
19
  const scratch = (): string => {
@@ -199,10 +199,68 @@ describe('pulling D1 down — paged SELECTs, table by table, never an export', (
199
199
  expect((db.query('select count(*) n from items_fts_map').get() as { n: number }).n).toBe(n);
200
200
  db.close();
201
201
  const mapPages = seen.map((a) => a[a.indexOf('--command') + 1] as string).filter((sql) => sql.includes('FROM "items_fts_map"'));
202
- expect(mapPages).toHaveLength(3);
202
+ // 500, then 1,000 small rows: the second page is short, so the table ends there.
203
+ expect(mapPages).toHaveLength(2);
203
204
  expect(mapPages[1]).toContain('WHERE _rowid_ >');
204
205
  });
205
206
 
207
+ test('🔴 a table loads in one transaction, never one commit per row (photos, 2026-10-29: ~400 s of the backup was the load)', async () => {
208
+ const dir = scratch();
209
+ const n = 1_200;
210
+ const source = live(
211
+ `WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${n}) INSERT INTO items SELECT 'i' || i, 'x' FROM s;`,
212
+ );
213
+ await pull(dir, d1(source).run);
214
+ // The header's file change counter (bytes 24–27) counts every commit that wrote the file.
215
+ const header = readFileSync(join(dir, 'pulled.sqlite')).subarray(0, 100);
216
+ const commits = new DataView(header.buffer, header.byteOffset).getUint32(24);
217
+ expect(commits).toBeLessThan(100);
218
+ });
219
+
220
+ /** The LIMIT of every paged SELECT of `table`, in order. */
221
+ const limitsOf = (seen: string[][], table: string): number[] =>
222
+ seen
223
+ .map((a) => a[a.indexOf('--command') + 1] as string)
224
+ .filter((sql) => sql.includes(`FROM "${table}"`))
225
+ .map((sql) => Number(/LIMIT (\d+)/.exec(sql)?.[1]));
226
+
227
+ test('🔴 small rows grow their pages past PAGE_ROWS (photos, 2026-10-29: ~600 calls of 500 rows ran past the 900 s ceiling)', async () => {
228
+ const dir = scratch();
229
+ const n = PAGE_ROWS * 6;
230
+ const source = live(
231
+ `WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${n}) INSERT INTO items_fts_map (item_id, text) SELECT 'i' || i, 't' FROM s; INSERT INTO items VALUES ('i1', 'x');`,
232
+ );
233
+ const { run, seen } = d1(source);
234
+ await pull(dir, run);
235
+ const db = opened(dir);
236
+ expect((db.query('select count(*) n from items_fts_map').get() as { n: number }).n).toBe(n);
237
+ db.close();
238
+ // 500 + 1,000 + a short page of 1,500 — three calls where a fixed page made seven.
239
+ expect(limitsOf(seen, 'items_fts_map')).toEqual([PAGE_ROWS, PAGE_ROWS * 2, PAGE_ROWS * 4]);
240
+ });
241
+
242
+ test('large rows never grow past PAGE_ROWS, and a refused grown page caps the rest of the table at half of it', async () => {
243
+ const dir = scratch();
244
+ // 20 KB a row: past PAGE_BYTES / PAGE_ROWS (8 KB), so these rows may not grow a page.
245
+ const big = 20_000;
246
+ const n = PAGE_ROWS * 2 + 7;
247
+ const source = live(
248
+ `WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${n}) INSERT INTO items_fts_map (item_id, text) SELECT 'i' || i, printf('%.${big}c', 'x') FROM s; INSERT INTO items VALUES ('i1', 'x');`,
249
+ );
250
+ const { run, seen } = d1(source);
251
+ await pull(dir, run);
252
+ expect(limitsOf(seen, 'items_fts_map')).toEqual([PAGE_ROWS, PAGE_ROWS, PAGE_ROWS]);
253
+
254
+ const n2 = PAGE_ROWS * 8;
255
+ const grown = live(
256
+ `WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${n2}) INSERT INTO items_fts_map (item_id, text) SELECT 'i' || i, 't' FROM s; INSERT INTO items VALUES ('i1', 'x');`,
257
+ );
258
+ const refused = d1(grown, { failWhen: (sql) => sql.includes('FROM "items_fts_map"') && sql.includes(`LIMIT ${PAGE_ROWS * 4}`) });
259
+ await pull(scratch(), refused.run);
260
+ // 500, 1,000, 2,000 refused, then never more than 1,000 again.
261
+ expect(limitsOf(refused.seen, 'items_fts_map')).toEqual([PAGE_ROWS, PAGE_ROWS * 2, PAGE_ROWS * 4, PAGE_ROWS * 2, PAGE_ROWS * 2, PAGE_ROWS * 2]);
262
+ });
263
+
206
264
  test('a WITHOUT ROWID table pages by its primary key and OFFSET', () => {
207
265
  const plan = tablePlan('kv', 'CREATE TABLE kv (k TEXT PRIMARY KEY, v) WITHOUT ROWID', [
208
266
  { name: 'k', pk: 1 },
@@ -251,10 +309,7 @@ describe('pulling D1 down — paged SELECTs, table by table, never an export', (
251
309
  const db = opened(dir);
252
310
  expect((db.query('select count(*) n from items_fts_map').get() as { n: number }).n).toBe(n);
253
311
  db.close();
254
- const limits = seen
255
- .map((a) => a[a.indexOf('--command') + 1] as string)
256
- .filter((sql) => sql.includes('FROM "items_fts_map"'))
257
- .map((sql) => Number(/LIMIT (\d+)/.exec(sql)?.[1]));
312
+ const limits = limitsOf(seen, 'items_fts_map');
258
313
  // refused at 500, read at 250, then back to 500 for the rest.
259
314
  expect(limits.slice(0, 3)).toEqual([PAGE_ROWS, PAGE_ROWS / 2, PAGE_ROWS]);
260
315
  expect(limits.slice(2).every((limit) => limit === PAGE_ROWS)).toBe(true);
@@ -461,17 +516,22 @@ END;`;
461
516
  const dir = scratch();
462
517
  const child = join(dir, 'big.js');
463
518
  writeFileSync(child, "process.stdout.write('[' + JSON.stringify('x'.repeat(2_000_000)) + ']'); process.exit(0);");
464
- const proc = Bun.spawn([process.execPath, child], { stdout: 'pipe' });
465
- const piped = (await new Response(proc.stdout).text()).length;
466
- await proc.exited;
467
- // The failure this exists for: if Bun ever stops cutting the pipe, this line says so.
468
- expect(piped).toBeLessThan(2_000_004);
519
+ // Bun ≤1.3 cut this pipe at a 64 KiB boundary; 1.4.3 delivers it whole (measured 2026-10-29),
520
+ // so the pipe's loss is no longer asserted — only that spawnToFile keeps every byte on any Bun.
469
521
  const r = spawnToFile([process.execPath, child]);
470
522
  expect(r.code).toBe(0);
471
523
  expect(r.stdout.length).toBe(2_000_004);
472
524
  expect(JSON.parse(r.stdout)).toHaveLength(1);
473
525
  });
474
526
 
527
+ test('🔴 a call that never answers is killed, and the kill reads as the wire failing — asked again, never hung on (photos, 2026-10-29: 20 minutes on one call)', () => {
528
+ const started = Date.now();
529
+ const r = spawnToFile(['sleep', '3'], { timeoutMs: 200 });
530
+ expect(Date.now() - started).toBeLessThan(2_500);
531
+ expect(r.code).not.toBe(0);
532
+ expect(isTransient(r.stderr)).toBe(true);
533
+ });
534
+
475
535
  test("🔴 a wrangler call's debug log is the call's own — gone with a green call, kept for a red one", () => {
476
536
  // `bun x wrangler` runs the cwd's own `node_modules/.bin/wrangler` first, so this one stands
477
537
  // in for the real thing. It logs as wrangler does: every message, a `--json` result included,
@@ -120,10 +120,37 @@ export async function servedRuntime(
120
120
  * Rows per paged `SELECT`. The fleet's largest table held 290 rows when this was set (collections'
121
121
  * `items`, 2026-09-25) and one `wrangler` call costs ~1 s, so a page this size is one call per
122
122
  * table for every app today. A page D1 refuses — too large a response — is halved and asked
123
- * again, down to one row, before it is a refusal.
123
+ * again, down to one row, before it is a refusal. It is where every table STARTS: small rows grow
124
+ * past it ({@link nextPageRows}).
124
125
  */
125
126
  export const PAGE_ROWS = 500;
126
127
 
128
+ /**
129
+ * 🔴 How far a table of small rows grows its pages, and the bytes a grown page may carry.
130
+ *
131
+ * At a fixed {@link PAGE_ROWS} the cost of a pull is its ROW count, ~1.5 s of `bun x wrangler` per
132
+ * 500 rows whatever they hold. Measured 2026-10-29: photos' 171,590-row gazetteer and 40,841
133
+ * `asset_tags` made its backup ~600 calls, 730 s on 2026-10-28, 873 s that night, and then
134
+ * past the recovery backup's 900 s ceiling on both WDElementsBlack runs of 2026-10-29 (exit
135
+ * 143, twice each), so the drive carried a stale photos snapshot. A page of tiny rows is a
136
+ * few KB, so it doubles while the rows it read stay small: to {@link MAX_PAGE_ROWS}, while
137
+ * that many rows of the size just read stay under {@link PAGE_BYTES}. Large rows never grow
138
+ * past {@link PAGE_ROWS}, which is where they were already proven.
139
+ */
140
+ export const MAX_PAGE_ROWS = 10_000;
141
+ export const PAGE_BYTES = 4_000_000;
142
+
143
+ /**
144
+ * The next page's size after one of `limit` rows came back with `rows` rows and `bytes` of SQL
145
+ * literals. It doubles, but never past `cap` (lowered by a refusal: see {@link dumpTable}), and
146
+ * never past {@link PAGE_ROWS} unless rows of this size fit {@link PAGE_BYTES}.
147
+ */
148
+ export function nextPageRows(limit: number, rows: number, bytes: number, cap: number = MAX_PAGE_ROWS): number {
149
+ const perRow = rows > 0 ? bytes / rows : 0;
150
+ const fits = perRow > 0 ? Math.floor(PAGE_BYTES / perRow) : MAX_PAGE_ROWS;
151
+ return Math.max(1, Math.min(cap, limit * 2, Math.max(PAGE_ROWS, fits)));
152
+ }
153
+
127
154
  /** One `wrangler` invocation, as {@link pullD1ToSqlite} needs it. Injected so a spec runs none. */
128
155
  export type Wrangler = (args: string[]) => { code: number; stdout: string; stderr: string };
129
156
 
@@ -134,9 +161,18 @@ export type Wrangler = (args: string[]) => { code: number; stdout: string; stder
134
161
  */
135
162
  export const wranglerArgv = (bun: string = process.execPath): string[] => [bun, 'x', 'wrangler'];
136
163
 
164
+ /**
165
+ * 🔴 How long one `wrangler` call may run before it is killed. Without it a call whose connection
166
+ * stalled never returned: measured 2026-10-29, a photos pull logged two `fetch failed` retries and
167
+ * then sat 20 minutes on one call, which inside the recovery backup is the 900 s ceiling's kill and
168
+ * a stale snapshot. A kill reads as `ETIMEDOUT`, which {@link isTransient} waits out and asks again.
169
+ * A healthy page of {@link PAGE_BYTES} answers in seconds.
170
+ */
171
+ export const CALL_TIMEOUT_MS = 120_000;
172
+
137
173
  /**
138
174
  * Run `argv` to completion with its stdout written to a FILE, never a pipe, and return what it
139
- * wrote.
175
+ * wrote — or kill it at `timeoutMs` and say so in a message {@link isTransient} recognizes.
140
176
  *
141
177
  * 🔴 A Bun child that ends with `process.exit()` drops whatever of its stdout the pipe had not
142
178
  * taken yet, at a 64 KiB boundary — and wrangler is a Bun child whenever `node` is not on PATH
@@ -153,6 +189,8 @@ export function spawnToFile(
153
189
  cwd?: string;
154
190
  /** The child's whole environment, or a function of this call's own scratch directory that returns it. */
155
191
  env?: Record<string, string | undefined> | ((scratch: string) => Record<string, string | undefined>);
192
+ /** Kill the child after this long ({@link CALL_TIMEOUT_MS} by default). */
193
+ timeoutMs?: number;
156
194
  } = {},
157
195
  ): { code: number; stdout: string; stderr: string } {
158
196
  const dir = mkdtempSync(join(tmpdir(), 'cursedbelt-spawn-'));
@@ -160,9 +198,14 @@ export function spawnToFile(
160
198
  let code = 1;
161
199
  try {
162
200
  const env = typeof options.env === 'function' ? options.env(dir) : options.env;
163
- const r = Bun.spawnSync(argv, { cwd: options.cwd, env, stdout: Bun.file(out), stderr: 'pipe' });
164
- code = r.exitCode ?? 1;
201
+ const timeoutMs = options.timeoutMs ?? CALL_TIMEOUT_MS;
202
+ const r = Bun.spawnSync(argv, { cwd: options.cwd, env, stdout: Bun.file(out), stderr: 'pipe', timeout: timeoutMs });
165
203
  const stdout = existsSync(out) ? readFileSync(out, 'utf8') : '';
204
+ if (r.exitedDueToTimeout || r.exitCode === null) {
205
+ code = 124;
206
+ return { code, stdout, stderr: `${argv.slice(0, 4).join(' ')} … did not finish in ${timeoutMs / 1000}s and was killed (ETIMEDOUT)` };
207
+ }
208
+ code = r.exitCode;
166
209
  return { code, stdout, stderr: r.stderr.toString() };
167
210
  } finally {
168
211
  // A failed call keeps whatever the child wrote beside its stdout — wrangler's debug log, whose
@@ -374,11 +417,16 @@ export function pageSql(plan: TablePlan, limit: number, after: { key?: number; o
374
417
  * size back toward {@link PAGE_ROWS}. Before 4.33.1 nothing grew it back: desk's first launchd
375
418
  * backup (2026-09-25) hit a few slow calls early and read its 3,381-row table 15 rows per call —
376
419
  * 225 two-minute calls, on course for hours. Only a refusal at ONE row is fatal.
420
+ *
421
+ * Small rows grow on past {@link PAGE_ROWS} ({@link nextPageRows}). A refusal of a page that
422
+ * large caps the rest of the table at half of it, so a size D1 refused is never asked again;
423
+ * a refusal at or under {@link PAGE_ROWS} caps it there, which is the old behavior exactly.
377
424
  */
378
425
  function dumpTable(caller: Caller, database: string, plan: TablePlan): { text: string; rows: number } {
379
426
  const into = `INSERT INTO ${sqlIdent(plan.table)} (${plan.columns.map(sqlIdent).join(', ')}) VALUES (`;
380
427
  const lines: string[] = [];
381
428
  let limit = PAGE_ROWS;
429
+ let cap = MAX_PAGE_ROWS;
382
430
  let after: { key?: number; offset?: number } = {};
383
431
  for (;;) {
384
432
  let page: Array<Record<string, unknown>>;
@@ -389,21 +437,25 @@ function dumpTable(caller: Caller, database: string, plan: TablePlan): { text: s
389
437
  if (limit > 1) {
390
438
  const next = Math.max(1, Math.floor(limit / 2));
391
439
  caller.log(`pull D1: \`${plan.table}\` refused a page of ${limit} — asking for ${next}: ${message}`);
440
+ cap = Math.min(cap, Math.max(PAGE_ROWS, next));
392
441
  limit = next;
393
442
  continue;
394
443
  }
395
444
  throw new Error(`could not read \`${plan.table}\` from D1: ${message}`);
396
445
  }
446
+ let bytes = 0;
397
447
  for (const row of page) {
398
448
  const literals = plan.columns.map((_, i) => row[`c${i}`]);
399
449
  if (literals.some((v) => typeof v !== 'string')) {
400
450
  throw new Error(`D1 returned a non-literal value paging \`${plan.table}\` — refusing a snapshot that may not restore`);
401
451
  }
402
- lines.push(`${into}${literals.join(', ')});`);
452
+ const values = literals.join(', ');
453
+ bytes += values.length;
454
+ lines.push(`${into}${values});`);
403
455
  }
404
456
  if (page.length < limit) break;
405
457
  after = plan.key ? { key: Number(page[page.length - 1]?.k) } : { offset: (after.offset ?? 0) + page.length };
406
- limit = Math.min(PAGE_ROWS, limit * 2);
458
+ limit = nextPageRows(limit, page.length, bytes, cap);
407
459
  }
408
460
  return { text: lines.join('\n'), rows: lines.length };
409
461
  }
@@ -495,7 +547,11 @@ export async function pullD1ToSqlite(options: PullD1Options): Promise<void> {
495
547
  }
496
548
  }
497
549
  // One table at a time, so a fault is located rather than smeared over the whole load.
498
- for (const { text } of dumps) if (text) db.exec(text);
550
+ // 🔴 And each table in ONE transaction: bare, every row's INSERT is its own commit and its
551
+ // own journal and sync. Measured 2026-10-29 (forge task 3957), photos' ~400 s load; 3,000
552
+ // rows took 2,881 ms bare and 13 ms in a transaction.
553
+ const load = db.transaction((text: string) => db.exec(text));
554
+ for (const { text } of dumps) if (text) load(text);
499
555
  for (const t of triggers) db.exec(t.sql);
500
556
  if (options.afterLoadSql) db.exec(options.afterLoadSql);
501
557
  // 🔴 Every table holds as many rows as were read from D1, or this is not a backup: the check
@@ -201,7 +201,10 @@ describe("linkSource and the link beside the code", () => {
201
201
  test("linkedRoomBytes is what statfs says minus the floor and what is owed; a store that is not there holds nothing back", () => {
202
202
  const room = linkedRoomBytes(base);
203
203
  expect(typeof room).toBe("number");
204
- expect(linkedRoomBytes(base, 1024)).toBe((room as number) - 1024);
204
+ // Two statfs reads on a disk something else is writing (a backup, 2026-10-29) differ by what
205
+ // it wrote between them, so what is owed is a terabyte and the check allows 256 MiB of churn.
206
+ const owed = 2 ** 40;
207
+ expect(Math.abs((linkedRoomBytes(base, owed) as number) - ((room as number) - owed))).toBeLessThan(2 ** 28);
205
208
  expect(linkedRoomBytes(join(base, "no", "such", "store"))).toBeNull();
206
209
  });
207
210
 
@@ -78,6 +78,14 @@ describe("reading what yt-dlp prints", () => {
78
78
  expect(ytDlpArgs("abc", "/out", AUDIO)).not.toContain("--merge-output-format");
79
79
  });
80
80
 
81
+ test("🔴 a pasted page URL is fetched as given, and a cookie jar rides along only when handed one", () => {
82
+ const page = "https://www.eporner.com/video-6t3XeYYVBvy/some-title/";
83
+ const args = ytDlpArgs(page, "/out", VIDEO, { cookiesFile: "/jar.txt" });
84
+ expect(args.at(-1)).toBe(page);
85
+ expect(args[args.indexOf("--cookies") + 1]).toBe("/jar.txt");
86
+ expect(ytDlpArgs("abc", "/out", VIDEO)).not.toContain("--cookies");
87
+ });
88
+
81
89
  test("the binary is one per generation, under its state root", () => {
82
90
  expect(ytDlpPath("/state")).toBe("/state/bin/yt-dlp");
83
91
  });
@@ -99,6 +107,16 @@ describe("sorting a failure by what fixes it", () => {
99
107
  });
100
108
  });
101
109
 
110
+ describe("a pasted link yt-dlp cannot read", () => {
111
+ const line = "ERROR: Unsupported URL: https://example.com/watch/1\n";
112
+ test("🔴 is final for a page URL — no retry or update gives yt-dlp a reader it lacks", () => {
113
+ expect(classifyYtDlpFailure(line, "https://example.com/watch/1")).toBe("unsupported");
114
+ });
115
+ test("but for a YouTube id it still reads as YouTube having moved", () => {
116
+ expect(classifyYtDlpFailure(line, "abc")).toBe("outdated");
117
+ });
118
+ });
119
+
102
120
  describe("the fetcher", () => {
103
121
  let dir: string;
104
122
  let binary: string;
@@ -213,6 +231,21 @@ describe("the fetcher", () => {
213
231
  expect(second.message).toMatch(/Run: cd /);
214
232
  });
215
233
 
234
+ test("🔴 a URL target's cookie jar reaches yt-dlp, and its failure sentence names that site", async () => {
235
+ const page = "https://www.eporner.com/video-abc/t/";
236
+ const failure = await make(scripted("Unsupported URL: x"))(page, undefined, { cookiesFile: "/jar.txt" }).then(
237
+ () => {
238
+ throw new Error("expected a failure");
239
+ },
240
+ (e: unknown) => e as YtDlpError,
241
+ );
242
+ expect(runs[0]?.at(-1)).toBe(page);
243
+ expect(runs[0]).toContain("/jar.txt");
244
+ expect(failure.kind).toBe("unsupported");
245
+ expect(failure.message).toContain("eporner.com");
246
+ expect(runs).toHaveLength(1);
247
+ });
248
+
216
249
  test("a private video is not retried and not a reason to update", async () => {
217
250
  const failure = await make(scripted("[youtube] abc: Private video"))("abc").then(() => { throw new Error("expected a failure"); }, (e: unknown) => e as YtDlpError);
218
251
  expect(failure.kind).toBe("unavailable");
@@ -14,6 +14,10 @@
14
14
  * a track; Collections ingests a video), and any re-encode (only Collections has one, and only
15
15
  * when no H.264 stream exists).
16
16
  *
17
+ * A target is a YouTube video id or, since forge task 4003, any page URL yt-dlp reads — the
18
+ * links the owner pastes into Collections. A site that hides its videos behind a sign-in (eporner's
19
+ * age check) is handed the owner's own cookie jar per call; reading that jar is the app's business.
20
+ *
17
21
  * ── The file stays on disk ──────────────────────────────────────────────────────────────
18
22
  * A download resolves to a PATH inside a fresh temporary directory, and the caller disposes of
19
23
  * it. A 1080p video is gigabytes, and reading it into memory to hand it over would make the
@@ -115,8 +119,34 @@ export interface YtDownload {
115
119
  dispose(): Promise<void>;
116
120
  }
117
121
 
118
- /** Fetch one video. `onProgress` gets the fraction of the file received, 0–1. */
119
- export type YtDlpFetch = (videoId: string, onProgress?: (fraction: number) => void) => Promise<YtDownload>;
122
+ /** What one call may add to the profile: a site that needs the owner's sign-in gets his cookies. */
123
+ interface YtDlpCallOptions {
124
+ /** A Netscape-format cookie jar yt-dlp reads (`--cookies`). The caller owns and removes it. */
125
+ cookiesFile?: string;
126
+ }
127
+
128
+ /**
129
+ * Fetch one video. `target` is a YouTube video id, or a page URL (`https://…`) of any site yt-dlp
130
+ * reads — Collections' pasted links (forge task 4003). `onProgress` gets the fraction received, 0–1.
131
+ */
132
+ export type YtDlpFetch = (
133
+ target: string,
134
+ onProgress?: (fraction: number) => void,
135
+ options?: YtDlpCallOptions,
136
+ ) => Promise<YtDownload>;
137
+
138
+ /** Is `target` a page URL rather than a YouTube video id? */
139
+ const isPageUrl = (target: string): boolean => /^https?:\/\//i.test(target);
140
+
141
+ /** The site a target is on, as a sentence names it: `YouTube`, or the URL's host without `www.`. */
142
+ function siteOf(target: string): string {
143
+ if (!isPageUrl(target)) return "YouTube";
144
+ try {
145
+ return new URL(target).hostname.replace(/^www\./i, "") || "that site";
146
+ } catch {
147
+ return "that site";
148
+ }
149
+ }
120
150
 
121
151
  /**
122
152
  * Why a download failed, sorted by what the owner can do about it.
@@ -126,9 +156,11 @@ export type YtDlpFetch = (videoId: string, onProgress?: (fraction: number) => vo
126
156
  * · `blocked` — YouTube is refusing this Mac as a bot. Time fixes it, usually.
127
157
  * · `unavailable` — the video itself: private, deleted, region-locked, members-only.
128
158
  * · `too-big` — over the one-download ceiling.
159
+ * · `unsupported` — a pasted page URL yt-dlp has no reader for. Only a URL target gets it: for a
160
+ * YouTube id the same words mean YouTube moved, which `outdated` fixes.
129
161
  * · `failed` — anything else, with yt-dlp's own last error line.
130
162
  */
131
- export type YtDlpFailure = "missing" | "outdated" | "blocked" | "unavailable" | "too-big" | "failed";
163
+ export type YtDlpFailure = "missing" | "outdated" | "blocked" | "unavailable" | "too-big" | "unsupported" | "failed";
132
164
 
133
165
  export class YtDlpError extends Error {
134
166
  constructor(
@@ -141,7 +173,8 @@ export class YtDlpError extends Error {
141
173
  }
142
174
 
143
175
  /** A failure no retry and no update can change — the video's own fault, or the ceiling. */
144
- export const isFinalYtDlpFailure = (kind: YtDlpFailure): boolean => kind === "unavailable" || kind === "too-big";
176
+ export const isFinalYtDlpFailure = (kind: YtDlpFailure): boolean =>
177
+ kind === "unavailable" || kind === "too-big" || kind === "unsupported";
145
178
 
146
179
  // ── Pure: reading what yt-dlp prints ───────────────────────────────────────────────────
147
180
 
@@ -188,10 +221,13 @@ const OUTDATED =
188
221
  /unable to extract|nsig|n challenge|signature (extraction|function)|precondition check failed|http error 403|requested format is not available|please report this issue|js challenge|player .*(response|js)|unsupported url|jsc/i;
189
222
  const TOO_BIG = /larger than max-filesize|max-filesize/i;
190
223
 
191
- /** Sort a failure by what can be done about it — see {@link YtDlpFailure}. */
192
- export function classifyYtDlpFailure(stderr: string): YtDlpFailure {
224
+ const UNSUPPORTED = /unsupported url/i;
225
+
226
+ /** Sort a failure by what can be done about it — see {@link YtDlpFailure}. `target` is what was fetched. */
227
+ export function classifyYtDlpFailure(stderr: string, target = ""): YtDlpFailure {
193
228
  const line = lastYtDlpError(stderr);
194
229
  if (TOO_BIG.test(line)) return "too-big";
230
+ if (isPageUrl(target) && UNSUPPORTED.test(line)) return "unsupported";
195
231
  if (UNAVAILABLE.test(line)) return "unavailable";
196
232
  if (BLOCKED.test(line)) return "blocked";
197
233
  if (OUTDATED.test(line)) return "outdated";
@@ -202,40 +238,44 @@ export function classifyYtDlpFailure(stderr: string): YtDlpFailure {
202
238
  function describeYtDlpFailure(
203
239
  kind: YtDlpFailure,
204
240
  detail: string,
205
- context: { updated: boolean; fixCommand: string; profile: Pick<YtDlpProfile, "maxFilesize" | "noun"> },
241
+ context: { updated: boolean; fixCommand: string; profile: Pick<YtDlpProfile, "maxFilesize" | "noun">; site: string },
206
242
  ): string {
207
243
  const fix = context.fixCommand;
244
+ const site = context.site;
208
245
  switch (kind) {
209
246
  case "missing":
210
247
  return `yt-dlp is not installed on the Mac and installing it failed (${detail}). Run: ${fix}`;
211
248
  case "outdated":
212
249
  return (
213
- `yt-dlp could not read YouTube — it is out of date for a change YouTube made (${detail}). ` +
250
+ `yt-dlp could not read ${site} — it is out of date for a change ${site} made (${detail}). ` +
214
251
  (context.updated
215
252
  ? `The agent already updated it and it still fails, so the fix is not released yet; try again in a day, or run: ${fix}`
216
253
  : `Run: ${fix}`)
217
254
  );
218
255
  case "blocked":
219
- return `YouTube is refusing this Mac's requests as a bot (${detail}). It usually lifts within hours — try again later. If it persists, update yt-dlp: ${fix}`;
256
+ return `${site} is refusing this Mac's requests as a bot (${detail}). It usually lifts within hours — try again later. If it persists, update yt-dlp: ${fix}`;
220
257
  case "unavailable":
221
- return `YouTube will not play this video to anyone signed out (${detail}), so there is nothing to download.`;
258
+ return `${site} will not play this video to anyone signed out (${detail}), so there is nothing to download.`;
259
+ case "unsupported":
260
+ return `yt-dlp has no reader for ${site} pages (${detail}), so that link cannot be downloaded.`;
222
261
  case "too-big":
223
262
  return `${context.profile.noun} is over this app's ${context.profile.maxFilesize}B ceiling for one download.`;
224
263
  default:
225
- return `yt-dlp failed: ${detail || "no reason given"}. If YouTube links keep failing, update it: ${fix}`;
264
+ return `yt-dlp failed: ${detail || "no reason given"}. If ${site} links keep failing, update it: ${fix}`;
226
265
  }
227
266
  }
228
267
 
229
268
  /** The arguments for one download. Exported so a test pins the flags that matter. */
230
269
  export function ytDlpArgs(
231
- videoId: string,
270
+ target: string,
232
271
  outDir: string,
233
272
  profile: Pick<YtDlpProfile, "format" | "extraArgs" | "maxFilesize">,
234
- options: { cacheDir?: string; jsRuntime?: string } = {},
273
+ options: { cacheDir?: string; jsRuntime?: string; cookiesFile?: string } = {},
235
274
  ): string[] {
236
275
  return [
237
276
  ...(options.jsRuntime ? ["--js-runtimes", `bun:${options.jsRuntime}`] : []),
238
277
  ...(options.cacheDir ? ["--cache-dir", options.cacheDir] : []),
278
+ ...(options.cookiesFile ? ["--cookies", options.cookiesFile] : []),
239
279
  "--no-playlist",
240
280
  "-f",
241
281
  profile.format,
@@ -255,7 +295,7 @@ export function ytDlpArgs(
255
295
  "-o",
256
296
  join(outDir, "%(id)s.%(ext)s"),
257
297
  "--",
258
- `https://www.youtube.com/watch?v=${videoId}`,
298
+ isPageUrl(target) ? target : `https://www.youtube.com/watch?v=${target}`,
259
299
  ];
260
300
  }
261
301
 
@@ -373,8 +413,8 @@ export function createYtDlp(options: YtDlpOptions): YtDlpFetch {
373
413
  const label = options.label ?? "[yt-dlp]";
374
414
  const jsRuntime = options.jsRuntime ?? (process.versions.bun ? process.execPath : undefined);
375
415
  let lastUpdate = Number.NEGATIVE_INFINITY;
376
- const describe = (kind: YtDlpFailure, detail: string, updated: boolean): string =>
377
- describeYtDlpFailure(kind, detail, { updated, fixCommand: options.fixCommand, profile: options.profile });
416
+ const describe = (kind: YtDlpFailure, detail: string, updated: boolean, target: string): string =>
417
+ describeYtDlpFailure(kind, detail, { updated, fixCommand: options.fixCommand, profile: options.profile, site: siteOf(target) });
378
418
 
379
419
  const ensureInstalled = async (): Promise<void> => {
380
420
  if (await isFile(options.binary)) return;
@@ -383,21 +423,22 @@ export function createYtDlp(options: YtDlpOptions): YtDlpFetch {
383
423
  await install(options.binary);
384
424
  } catch (error) {
385
425
  const detail = error instanceof Error ? error.message : String(error);
386
- throw new YtDlpError(describe("missing", detail, false), "missing");
426
+ throw new YtDlpError(describe("missing", detail, false, ""), "missing");
387
427
  }
388
428
  };
389
429
 
390
430
  /** One yt-dlp run into a fresh directory. Throws a classified error on failure. */
391
- const attempt = async (videoId: string, onProgress?: (fraction: number) => void): Promise<YtDownload> => {
431
+ const attempt = async (target: string, onProgress?: (fraction: number) => void, call: YtDlpCallOptions = {}): Promise<YtDownload> => {
392
432
  const dir = await mkdtemp(join(options.tmpRoot ?? tmpdir(), "ytdlp-"));
393
433
  const dispose = () => rm(dir, { recursive: true, force: true });
394
434
  try {
395
435
  let info: YtInfo | null = null;
396
436
  const { code, stderr } = await run(
397
437
  options.binary,
398
- ytDlpArgs(videoId, dir, options.profile, {
438
+ ytDlpArgs(target, dir, options.profile, {
399
439
  ...(options.cacheDir ? { cacheDir: options.cacheDir } : {}),
400
440
  ...(jsRuntime ? { jsRuntime } : {}),
441
+ ...(call.cookiesFile ? { cookiesFile: call.cookiesFile } : {}),
401
442
  }),
402
443
  (line) => {
403
444
  const fraction = parseYtProgress(line);
@@ -407,7 +448,7 @@ export function createYtDlp(options: YtDlpOptions): YtDlpFetch {
407
448
  );
408
449
  const found = info as YtInfo | null;
409
450
  if (code !== 0 || !found?.filepath) {
410
- const kind = code === 0 ? "failed" : classifyYtDlpFailure(stderr);
451
+ const kind = code === 0 ? "failed" : classifyYtDlpFailure(stderr, target);
411
452
  throw new YtDlpError(code === 0 ? "yt-dlp finished without saying where the file went" : lastYtDlpError(stderr), kind);
412
453
  }
413
454
  if (!(await isFile(found.filepath))) throw new YtDlpError(`yt-dlp named ${found.filepath} and it is not there`, "failed");
@@ -419,13 +460,13 @@ export function createYtDlp(options: YtDlpOptions): YtDlpFetch {
419
460
  }
420
461
  };
421
462
 
422
- return async (videoId, onProgress) => {
463
+ return async (target, onProgress, call) => {
423
464
  await ensureInstalled();
424
465
  let updated = false;
425
466
  let last: YtDlpError | null = null;
426
467
  for (let tries = 1; tries <= ATTEMPTS + 1; tries++) {
427
468
  try {
428
- return await attempt(videoId, onProgress);
469
+ return await attempt(target, onProgress, call);
429
470
  } catch (error) {
430
471
  last =
431
472
  error instanceof YtDlpError ? error : new YtDlpError(error instanceof Error ? error.message : String(error), "failed");
@@ -449,6 +490,6 @@ export function createYtDlp(options: YtDlpOptions): YtDlpFetch {
449
490
  }
450
491
  }
451
492
  const failure = last ?? new YtDlpError("no attempt ran", "failed");
452
- throw new YtDlpError(describe(failure.kind, failure.message, updated), failure.kind);
493
+ throw new YtDlpError(describe(failure.kind, failure.message, updated, target), failure.kind);
453
494
  };
454
495
  }