@apocaliss92/addon-series-scraper 0.0.0-stage → 0.1.21

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.
@@ -0,0 +1,925 @@
1
+ import { createRequire as __scraperCreateRequire } from "node:module";
2
+ __scraperCreateRequire(import.meta.url);
3
+ import { S as require_Reflect, _ as watchGate, a as errorText, f as moveChromeHome, g as eventOfNotification, i as HOST_LOG_TAGS, n as forwardedHeaders, v as require_dist, x as require_cjs } from "./proxy-Btrb1iBN.js";
4
+ import { access, chmod, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
5
+ import { downloadBinary, extractDebPayload, findInPath } from "@dominevo/types/node";
6
+ import { dirname, join } from "node:path";
7
+ import { execFile } from "node:child_process";
8
+ import { promisify } from "node:util";
9
+ import { createHash } from "node:crypto";
10
+ import { createWriteStream } from "node:fs";
11
+ import { Readable } from "node:stream";
12
+ import { pipeline as pipeline$1 } from "node:stream/promises";
13
+ import { sendToExportedTarget } from "@dominevo/types";
14
+ import { n as SettingsSecretStore, t as RecordsStateStore } from "./state-store-DT6l2jtx.js";
15
+ require_Reflect();
16
+ var import_dist = require_dist();
17
+ /**
18
+ * The pinned downloads the exits themselves depend on: the tunnel binary, the media tools, Chrome.
19
+ * While the VPN gate is closed every other request is refused, and without these the gate could
20
+ * never open. Each is verified by its sha256 pin after the download. The core honours the
21
+ * allowance only for these exact host names, only while no exit can serve the request, and logs
22
+ * every use. A redirect to a host outside the list is refused like any other request.
23
+ */
24
+ var GITHUB_RELEASE_HOSTS = [
25
+ "github.com",
26
+ "objects.githubusercontent.com",
27
+ "release-assets.githubusercontent.com"
28
+ ];
29
+ var HOSTS = {
30
+ wireproxy: GITHUB_RELEASE_HOSTS,
31
+ ytdlp: GITHUB_RELEASE_HOSTS,
32
+ ffmpeg: GITHUB_RELEASE_HOSTS,
33
+ chrome: [
34
+ "storage.googleapis.com",
35
+ "snapshot.ubuntu.com",
36
+ "archive.ubuntu.com",
37
+ "security.ubuntu.com"
38
+ ]
39
+ };
40
+ function allowDirectDownload(kind, run) {
41
+ return (0, import_dist.runWithDirectAllowance)({
42
+ reason: `pinned ${kind} download`,
43
+ hosts: HOSTS[kind]
44
+ }, run);
45
+ }
46
+ // src/embedded/artifacts.ts
47
+ /**
48
+ * The programs the embedded host downloads on first need. Every artifact is pinned by version AND
49
+ * sha256: a download that does not match is refused, never run.
50
+ */
51
+ /** Chrome for Testing, headless shell, linux x64: the build the scraper's browser pass was proven on. */
52
+ var CHROME_VERSION = "158.0.8127.88";
53
+ var CHROME_SHELL_URL = `https://storage.googleapis.com/chrome-for-testing-public/${CHROME_VERSION}/linux64/chrome-headless-shell-linux64.zip`;
54
+ var CHROME_SHELL_SHA256 = "63401333cc587645bfaeea7f0c90958b327d249251e23954a47f30112ca23d5b";
55
+ /** The directory inside the zip. */
56
+ var CHROME_SHELL_DIR = "chrome-headless-shell-linux64";
57
+ var UBUNTU_MIRRORS = [
58
+ `https://snapshot.ubuntu.com/ubuntu/20261130T000000Z/`,
59
+ "http://archive.ubuntu.com/ubuntu/",
60
+ "http://security.ubuntu.com/ubuntu/"
61
+ ];
62
+ /**
63
+ * The Ubuntu 24.04 (noble) libraries the headless shell links against and a slim container lacks,
64
+ * with their dependencies. Extracted next to the shell and reached through LD_LIBRARY_PATH, never
65
+ * installed system-wide.
66
+ */
67
+ var NOBLE_DEBS = [
68
+ {
69
+ name: "at-spi2-common",
70
+ version: "2.52.0-1build1",
71
+ pool: "pool/main/a/at-spi2-core/at-spi2-common_2.52.0-1build1_all.deb",
72
+ sha256: "7e05959b067031468f21ae46c6653a6813f1dccd994ef12a0b5f75de0ed346b6"
73
+ },
74
+ {
75
+ name: "libasound2-data",
76
+ version: "1.2.11-1ubuntu0.5",
77
+ pool: "pool/main/a/alsa-lib/libasound2-data_1.2.11-1ubuntu0.5_all.deb",
78
+ sha256: "32956095e69e419dac4ac2c2da81effbdc8e37f8bbc32fafb4459d857324ee20"
79
+ },
80
+ {
81
+ name: "libasound2t64",
82
+ version: "1.2.11-1ubuntu0.5",
83
+ pool: "pool/main/a/alsa-lib/libasound2t64_1.2.11-1ubuntu0.5_amd64.deb",
84
+ sha256: "9aa660d6a24995400f042aad895dfe77781ab58adedec32f4b0ccbba9d58bb8b"
85
+ },
86
+ {
87
+ name: "libatk-bridge2.0-0t64",
88
+ version: "2.52.0-1build1",
89
+ pool: "pool/main/a/at-spi2-core/libatk-bridge2.0-0t64_2.52.0-1build1_amd64.deb",
90
+ sha256: "22b7d47e3c0f7953a78d3cfd309d1b20771085de9220fbe610c0989b9e808c9b"
91
+ },
92
+ {
93
+ name: "libatk1.0-0t64",
94
+ version: "2.52.0-1build1",
95
+ pool: "pool/main/a/at-spi2-core/libatk1.0-0t64_2.52.0-1build1_amd64.deb",
96
+ sha256: "42c5d4b00954f17c2c3c4b866844f691eb8b6d57bf08b59203e65f12dc84a4f9"
97
+ },
98
+ {
99
+ name: "libatspi2.0-0t64",
100
+ version: "2.52.0-1build1",
101
+ pool: "pool/main/a/at-spi2-core/libatspi2.0-0t64_2.52.0-1build1_amd64.deb",
102
+ sha256: "d686ace4080eca9c2d6ce8de69392a5ac56c846701894c0858922d4ce341a1d7"
103
+ },
104
+ {
105
+ name: "libdbus-1-3",
106
+ version: "1.14.10-4ubuntu4.1",
107
+ pool: "pool/main/d/dbus/libdbus-1-3_1.14.10-4ubuntu4.1_amd64.deb",
108
+ sha256: "5d630480f04b4b442300ce847a3fa705ea4d14d80ba6de91f99b51a4e4953b08"
109
+ },
110
+ {
111
+ name: "libgbm1",
112
+ version: "25.2.8-0ubuntu0.24.04.5",
113
+ pool: "pool/main/m/mesa/libgbm1_25.2.8-0ubuntu0.24.04.5_amd64.deb",
114
+ sha256: "e841e7d681bec57ffff70df1a9950e5ff42b0f6def7d1a98d7e8671b180bbbe8"
115
+ },
116
+ {
117
+ name: "libglib2.0-0t64",
118
+ version: "2.80.0-6ubuntu3.10",
119
+ pool: "pool/main/g/glib2.0/libglib2.0-0t64_2.80.0-6ubuntu3.10_amd64.deb",
120
+ sha256: "ff1b650f655b36dfe202fdbae6bb02b363c7257b6dd23e4f95ab61f716190df3"
121
+ },
122
+ {
123
+ name: "libnspr4",
124
+ version: "2:4.35-1.1build1",
125
+ pool: "pool/main/n/nspr/libnspr4_4.35-1.1build1_amd64.deb",
126
+ sha256: "e579e72d091f6c7a13f5a756c31065b15aae5b81840d61b069355aa2283c07b4"
127
+ },
128
+ {
129
+ name: "libnss3",
130
+ version: "2:3.98-1ubuntu0.3",
131
+ pool: "pool/main/n/nss/libnss3_3.98-1ubuntu0.3_amd64.deb",
132
+ sha256: "e11fdf8c09a068d0f0c3fd90ed971253dfed7227cc20d3d487fd615d4771f1bb"
133
+ },
134
+ {
135
+ name: "libxcomposite1",
136
+ version: "1:0.4.5-1build3",
137
+ pool: "pool/main/libx/libxcomposite/libxcomposite1_0.4.5-1build3_amd64.deb",
138
+ sha256: "a12d5d9ae70b798cbbf284080eae32b87367561fc9c24492f641b8860ac0f308"
139
+ },
140
+ {
141
+ name: "libxdamage1",
142
+ version: "1:1.1.6-1build1",
143
+ pool: "pool/main/libx/libxdamage/libxdamage1_1.1.6-1build1_amd64.deb",
144
+ sha256: "6891faf325e996ebd28ef53ebb9c043dc96f67327500490affc3e89d366d35ed"
145
+ },
146
+ {
147
+ name: "libxi6",
148
+ version: "2:1.8.1-1ubuntu0.1",
149
+ pool: "pool/main/libx/libxi/libxi6_1.8.1-1ubuntu0.1_amd64.deb",
150
+ sha256: "6838f80980571efd51abd1a7b0f84c5d466c7a57b32bc98dd4b1801b2c358173"
151
+ },
152
+ {
153
+ name: "libxkbcommon0",
154
+ version: "1.6.0-1build1",
155
+ pool: "pool/main/libx/libxkbcommon/libxkbcommon0_1.6.0-1build1_amd64.deb",
156
+ sha256: "2b9caeb423efb540296a1cb20b872cc630c23908407ecb5c1c787a617622d664"
157
+ },
158
+ {
159
+ name: "libxrandr2",
160
+ version: "2:1.5.2-2build1",
161
+ pool: "pool/main/libx/libxrandr/libxrandr2_1.5.2-2build1_amd64.deb",
162
+ sha256: "f2955a5e594f5724b58ad241d9231ea191cb36574a0d5e5ca6b661cd41d6256d"
163
+ },
164
+ {
165
+ name: "libxrender1",
166
+ version: "1:0.9.10-1.1ubuntu0.1",
167
+ pool: "pool/main/libx/libxrender/libxrender1_0.9.10-1.1ubuntu0.1_amd64.deb",
168
+ sha256: "6dfbda7f30bc5c77515622aed7b24e44e38a3c6a317d981894ab1eaafe55bd39"
169
+ },
170
+ {
171
+ name: "xkb-data",
172
+ version: "2.41-2ubuntu1.1",
173
+ pool: "pool/main/x/xkeyboard-config/xkb-data_2.41-2ubuntu1.1_all.deb",
174
+ sha256: "e99f2a0b4c56cdf35dec489e56b6a8418826cab8ce6306ec6d0bd98e2cd0014a"
175
+ }
176
+ ];
177
+ var WIREPROXY_VERSION = "1.1.3";
178
+ /** Release asset digests: https://github.com/pufferffish/wireproxy/releases/tag/v1.1.3 */
179
+ var WIREPROXY_SHA256 = {
180
+ amd64: "e88c1d090740373fc606c1bafd81d9a5eadc642cce5667616e20e9d7a444f51c",
181
+ arm64: "370e00bd2167960d1ecd1c3c1439715bbaa94a0a110a2040468670c9af6021b6"
182
+ };
183
+ function wireproxyUrl(goArch) {
184
+ return `https://github.com/pufferffish/wireproxy/releases/download/v${WIREPROXY_VERSION}/wireproxy_linux_${goArch}.tar.gz`;
185
+ }
186
+ var YTDLP_VERSION = "2026.11.23";
187
+ var YTDLP_ARTIFACTS = {
188
+ "linux-x64": {
189
+ asset: "yt-dlp_linux",
190
+ sha256: "249ddb058234276bc449b9cd9492aad9f133bda5923c61a9e39983ae114ef17d"
191
+ },
192
+ "linux-arm64": {
193
+ asset: "yt-dlp_linux_aarch64",
194
+ sha256: "fb847a2e4a9ddc8cf5fcfb4bb7f42ba8969ecf72068def0278074f9d300bd13c"
195
+ },
196
+ "darwin-x64": {
197
+ asset: "yt-dlp_macos",
198
+ sha256: "57654854886d0398a798895aadf5173e2749fbb5e249b9f3728022ab376e11fb"
199
+ },
200
+ "darwin-arm64": {
201
+ asset: "yt-dlp_macos",
202
+ sha256: "57654854886d0398a798895aadf5173e2749fbb5e249b9f3728022ab376e11fb"
203
+ }
204
+ };
205
+ function ytdlpUrl(artifact) {
206
+ return `https://github.com/yt-dlp/yt-dlp/releases/download/${YTDLP_VERSION}/${artifact.asset}`;
207
+ }
208
+ // src/embedded/binaries.ts
209
+ var GO_ARCH = {
210
+ x64: "amd64",
211
+ arm64: "arm64"
212
+ };
213
+ /**
214
+ * The programs the core starts, each resolved lazily, on its first need, and logged when it is
215
+ * fetched. Nothing is downloaded at boot.
216
+ */
217
+ /** A tunnel child must not outlive this process: killed on `exit`, released once it is gone. */
218
+ function killOnProcessExit(kill) {
219
+ process.once("exit", kill);
220
+ return () => {
221
+ process.off("exit", kill);
222
+ };
223
+ }
224
+ function createEmbeddedBinaries(options) {
225
+ const { chrome, ops, logger } = options;
226
+ let wireproxy;
227
+ let ytdlp;
228
+ const resolveYtdlp = async () => {
229
+ const artifact = YTDLP_ARTIFACTS[`${options.platform}-${options.arch}`];
230
+ if (artifact === void 0) throw new Error(`series-scraper: no pinned yt-dlp for ${options.platform}/${options.arch}`);
231
+ logger.info("series-scraper: resolving yt-dlp", {
232
+ tags: HOST_LOG_TAGS,
233
+ meta: { version: YTDLP_VERSION }
234
+ });
235
+ return {
236
+ path: await allowDirectDownload("ytdlp", () => ops.downloadYtdlp({
237
+ url: ytdlpUrl(artifact),
238
+ sha256: artifact.sha256,
239
+ targetDir: join(options.depsDir, "series-scraper", `ytdlp-${YTDLP_VERSION}`)
240
+ })),
241
+ env: options.electron ?? process.versions.electron !== void 0 ? { ELECTRON_RUN_AS_NODE: "1" } : {},
242
+ nodePath: process.execPath
243
+ };
244
+ };
245
+ const resolveWireproxy = async () => {
246
+ const goArch = GO_ARCH[options.arch];
247
+ const sha256 = goArch === void 0 ? void 0 : WIREPROXY_SHA256[goArch];
248
+ if (options.platform !== "linux" || goArch === void 0 || sha256 === void 0) throw new Error(`series-scraper: no pinned wireproxy for ${options.platform}/${options.arch}`);
249
+ logger.info("series-scraper: resolving wireproxy", {
250
+ tags: HOST_LOG_TAGS,
251
+ meta: { version: WIREPROXY_VERSION }
252
+ });
253
+ return {
254
+ path: await allowDirectDownload("wireproxy", () => ops.downloadWireproxy({
255
+ url: wireproxyUrl(goArch),
256
+ sha256,
257
+ targetDir: join(options.depsDir, "series-scraper", `wireproxy-${WIREPROXY_VERSION}`)
258
+ })),
259
+ env: {},
260
+ onHostExit: killOnProcessExit
261
+ };
262
+ };
263
+ return {
264
+ async chrome() {
265
+ return chrome.expectedPath() ?? ops.findSystemChrome() ?? void 0;
266
+ },
267
+ async prepareChrome() {
268
+ if (chrome.expectedPath() !== void 0) await chrome.prepare();
269
+ },
270
+ ffmpeg: () => allowDirectDownload("ffmpeg", () => ops.ensureFfmpeg()),
271
+ ytdlp() {
272
+ ytdlp ??= resolveYtdlp().catch((error) => {
273
+ ytdlp = void 0;
274
+ throw error;
275
+ });
276
+ return ytdlp;
277
+ },
278
+ wireproxy() {
279
+ wireproxy ??= resolveWireproxy().catch((error) => {
280
+ wireproxy = void 0;
281
+ throw error;
282
+ });
283
+ return wireproxy;
284
+ }
285
+ };
286
+ }
287
+ // src/embedded/fetch-pinned.ts
288
+ var DEFAULT_TIMEOUT_MS = 12e4;
289
+ async function httpBody(url, signal) {
290
+ const response = await fetch(url, {
291
+ redirect: "follow",
292
+ signal
293
+ });
294
+ if (!response.ok || response.body === null) throw new Error(`${response.status} ${response.statusText}`);
295
+ return Readable.from(chunksOf(response.body.getReader()));
296
+ }
297
+ async function* chunksOf(reader) {
298
+ for (;;) {
299
+ const { done, value } = await reader.read();
300
+ if (done) return;
301
+ yield value;
302
+ }
303
+ }
304
+ /**
305
+ * Download one pinned file. The bytes land in `<dest>.part`, are hashed on the way, and only a
306
+ * match is renamed to `dest`: a file at `dest` is always the pinned one. Every failed mirror is
307
+ * logged with its url; the error that ends the call names all of them.
308
+ */
309
+ async function fetchPinned(download, logger, body = httpBody) {
310
+ await mkdir(dirname(download.dest), { recursive: true });
311
+ const part = `${download.dest}.part`;
312
+ const failures = [];
313
+ for (const url of download.urls) try {
314
+ const hash = createHash("sha256");
315
+ const timeoutMs = download.timeoutMs ?? DEFAULT_TIMEOUT_MS;
316
+ const signal = AbortSignal.timeout(timeoutMs);
317
+ const stream = await body(url, signal);
318
+ signal.addEventListener("abort", () => stream.destroy(/* @__PURE__ */ new Error(`timed out after ${Math.round(timeoutMs / 1e3)} s`)), { once: true });
319
+ stream.on("data", (chunk) => hash.update(chunk));
320
+ await pipeline$1(stream, createWriteStream(part));
321
+ const digest = hash.digest("hex");
322
+ if (digest !== download.sha256) throw new Error(`sha256 mismatch (got ${digest})`);
323
+ await rename(part, download.dest);
324
+ return download.dest;
325
+ } catch (error) {
326
+ await rm(part, { force: true });
327
+ failures.push(`${url}: ${errorText(error)}`);
328
+ logger.warn("series-scraper: a pinned download failed, trying the next source", {
329
+ tags: HOST_LOG_TAGS,
330
+ meta: {
331
+ artifact: download.name,
332
+ url,
333
+ reason: errorText(error)
334
+ }
335
+ });
336
+ }
337
+ throw new Error(`could not download ${download.name}: ${failures.join("; ")}`);
338
+ }
339
+ // src/embedded/chrome.ts
340
+ var execFileAsync = promisify(execFile);
341
+ /** Per source: the Chrome zip is ~100 MB, a deb a few MB. `unzip` of the zip is local work. */
342
+ var CHROME_ZIP_TIMEOUT_MS = 6e5;
343
+ var DEB_TIMEOUT_MS = 12e4;
344
+ var UNZIP_TIMEOUT_MS = 12e4;
345
+ var SUPPORTED_NOTE = "the pinned headless Chrome is built for linux x64 only";
346
+ async function exists(path) {
347
+ try {
348
+ await access(path);
349
+ return true;
350
+ } catch {
351
+ return false;
352
+ }
353
+ }
354
+ /** A launcher that sets what the browser needs, so the core can start it as if it were Chrome. */
355
+ function launcherScript(options) {
356
+ return [
357
+ "#!/bin/sh",
358
+ `export LD_LIBRARY_PATH="${options.libDirs.join(":")}\${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"`,
359
+ `export HOME="${options.home}"`,
360
+ `exec "${options.shell}" --no-sandbox --disable-dev-shm-usage "$@"`,
361
+ ""
362
+ ].join("\n");
363
+ }
364
+ function debUrls(deb) {
365
+ return UBUNTU_MIRRORS.map((mirror) => `${mirror}${deb.pool}`);
366
+ }
367
+ /**
368
+ * Chrome on first need. The headless shell and the noble libraries it links against are
369
+ * downloaded (pinned, sha256-checked) into `<depsDir>/series-scraper/chrome-<version>/`, the
370
+ * libraries are reached through LD_LIBRARY_PATH in a launcher script, nothing is installed
371
+ * system-wide. `prepare()` is memoised; a failure is not (the next launch tries again).
372
+ */
373
+ var ChromeInstaller = class {
374
+ options;
375
+ root;
376
+ ready;
377
+ constructor(options) {
378
+ this.options = options;
379
+ this.root = join(options.depsDir, "series-scraper", `chrome-${CHROME_VERSION}`);
380
+ }
381
+ get supported() {
382
+ return this.options.platform === "linux" && this.options.arch === "x64";
383
+ }
384
+ get launcher() {
385
+ return join(this.root, "chrome-launcher.sh");
386
+ }
387
+ /** The launcher's path when this host can run the pinned Chrome (it may not be installed yet). */
388
+ expectedPath() {
389
+ return this.supported ? this.launcher : void 0;
390
+ }
391
+ prepare() {
392
+ if (!this.supported) return Promise.reject(/* @__PURE__ */ new Error(`series-scraper: no Chrome to install: ${SUPPORTED_NOTE}; set the Chrome path`));
393
+ this.ready ??= this.install().catch((error) => {
394
+ this.ready = void 0;
395
+ this.options.logger.error("series-scraper: installing headless Chrome failed", {
396
+ tags: HOST_LOG_TAGS,
397
+ meta: {
398
+ version: CHROME_VERSION,
399
+ reason: errorText(error)
400
+ }
401
+ });
402
+ throw error;
403
+ });
404
+ return this.ready;
405
+ }
406
+ async install() {
407
+ const { logger, ops } = this.options;
408
+ const done = join(this.root, ".installed");
409
+ if (await exists(done)) return;
410
+ logger.info("series-scraper: installing headless Chrome on first use", {
411
+ tags: HOST_LOG_TAGS,
412
+ meta: {
413
+ version: CHROME_VERSION,
414
+ dir: this.root
415
+ }
416
+ });
417
+ const work = join(this.root, "work");
418
+ await rm(work, {
419
+ recursive: true,
420
+ force: true
421
+ });
422
+ await mkdir(work, { recursive: true });
423
+ const zip = await ops.download({
424
+ name: `chrome-headless-shell ${CHROME_VERSION}`,
425
+ urls: [CHROME_SHELL_URL],
426
+ sha256: CHROME_SHELL_SHA256,
427
+ dest: join(work, "chrome-headless-shell.zip"),
428
+ timeoutMs: CHROME_ZIP_TIMEOUT_MS
429
+ });
430
+ const shellRoot = join(this.root, "shell");
431
+ await rm(shellRoot, {
432
+ recursive: true,
433
+ force: true
434
+ });
435
+ await ops.unzip(zip, shellRoot);
436
+ const libsRoot = join(this.root, "libs");
437
+ await rm(libsRoot, {
438
+ recursive: true,
439
+ force: true
440
+ });
441
+ await mkdir(libsRoot, { recursive: true });
442
+ for (const deb of NOBLE_DEBS) {
443
+ const file = await ops.download({
444
+ name: `${deb.name} ${deb.version}`,
445
+ urls: debUrls(deb),
446
+ sha256: deb.sha256,
447
+ dest: join(work, `${deb.name}.deb`),
448
+ timeoutMs: DEB_TIMEOUT_MS
449
+ });
450
+ await ops.extractDeb(file, libsRoot, join(work, `${deb.name}-x`));
451
+ }
452
+ const shell = join(shellRoot, CHROME_SHELL_DIR, "chrome-headless-shell");
453
+ await chmod(shell, 493);
454
+ const libDirs = [
455
+ "usr/lib/x86_64-linux-gnu",
456
+ "lib/x86_64-linux-gnu",
457
+ "usr/lib/x86_64-linux-gnu/nss"
458
+ ].map((dir) => join(libsRoot, dir));
459
+ await mkdir(this.options.homeDir, { recursive: true });
460
+ await writeFile(this.launcher, launcherScript({
461
+ libDirs,
462
+ home: this.options.homeDir,
463
+ shell
464
+ }), { mode: 493 });
465
+ await chmod(this.launcher, 493);
466
+ const version = (await ops.smoke(this.launcher)).trim();
467
+ await rm(work, {
468
+ recursive: true,
469
+ force: true
470
+ });
471
+ await writeFile(done, `${version}\n`);
472
+ logger.info("series-scraper: headless Chrome is ready", {
473
+ tags: HOST_LOG_TAGS,
474
+ meta: {
475
+ launcher: this.launcher,
476
+ reported: version,
477
+ libs: (await readdir(libsRoot)).join(",")
478
+ }
479
+ });
480
+ }
481
+ };
482
+ /** The real operations: a pinned download, `unzip`, the framework's deb unpacker, a `--version` run. */
483
+ async function realChromeOps(logger, extractDebPayload, readFileBuffer) {
484
+ return {
485
+ download: (download) => allowDirectDownload("chrome", () => fetchPinned(download, logger)),
486
+ unzip: async (zip, destDir) => {
487
+ await mkdir(destDir, { recursive: true });
488
+ try {
489
+ await execFileAsync("unzip", [
490
+ "-q",
491
+ "-o",
492
+ zip,
493
+ "-d",
494
+ destDir
495
+ ], { timeout: UNZIP_TIMEOUT_MS });
496
+ } catch (error) {
497
+ throw new Error(`series-scraper: could not unzip Chrome (is "unzip" installed, or did it time out?): ${errorText(error)}`);
498
+ }
499
+ },
500
+ extractDeb: async (deb, destDir, workDir) => {
501
+ await mkdir(workDir, { recursive: true });
502
+ extractDebPayload(await readFileBuffer(deb), destDir, workDir);
503
+ await rm(workDir, {
504
+ recursive: true,
505
+ force: true
506
+ });
507
+ },
508
+ smoke: async (launcher) => (await execFileAsync(launcher, ["--version"], { timeout: 3e4 })).stdout
509
+ };
510
+ }
511
+ // src/embedded/close-within.ts
512
+ /** Wait for the application to close; a hang or a failure is a log line, and shutdown goes on. */
513
+ async function closeWithin(closing, timeoutMs, logger) {
514
+ let timer;
515
+ const timedOut = new Promise((resolve) => {
516
+ timer = setTimeout(() => resolve("timeout"), timeoutMs);
517
+ timer.unref();
518
+ });
519
+ try {
520
+ if (await Promise.race([closing.then(() => "closed"), timedOut]) === "timeout") logger.error("series-scraper: closing the embedded scraper timed out, shutdown goes on", {
521
+ tags: HOST_LOG_TAGS,
522
+ meta: { timeoutMs }
523
+ });
524
+ } catch (error) {
525
+ logger.warn("series-scraper: closing the embedded scraper failed", {
526
+ tags: HOST_LOG_TAGS,
527
+ meta: { reason: errorText(error) }
528
+ });
529
+ } finally {
530
+ if (timer !== void 0) clearTimeout(timer);
531
+ }
532
+ }
533
+ // src/embedded/core-logger.ts
534
+ /**
535
+ * The core's logger over the addon's `ctx.logger`. The core's `context` (the class that logs)
536
+ * becomes a `scraper` tag; the core logs nothing per device, so there is no `deviceId` to carry.
537
+ */
538
+ function coreLoggerOver(logger) {
539
+ const tags = (context) => context === void 0 ? { ...HOST_LOG_TAGS } : {
540
+ ...HOST_LOG_TAGS,
541
+ scraper: context
542
+ };
543
+ return {
544
+ log: (message, context) => logger.info(message, { tags: tags(context) }),
545
+ warn: (message, context) => logger.warn(message, { tags: tags(context) }),
546
+ debug: (message, context) => logger.debug(message, { tags: tags(context) }),
547
+ verbose: (message, context) => logger.debug(message, { tags: tags(context) }),
548
+ error: (message, trace, context) => logger.error(message, {
549
+ tags: tags(context),
550
+ ...trace === void 0 ? {} : { meta: { trace } }
551
+ })
552
+ };
553
+ }
554
+ // src/embedded/log-files.ts
555
+ /** The addon's lines in Dominevo's log store: the manifest id every line is stored under. */
556
+ var ADDON_ID = HOST_LOG_TAGS.addonId;
557
+ /** Lines the logs page can reach: the newest ones, like a rotated file's tail. */
558
+ var LOG_WINDOW = 2e3;
559
+ /** One store read; the store caps a read at 1000. */
560
+ var READ_LIMIT = 500;
561
+ /** A read is bounded in time by the store, so a short page is not the end: ask again, a few times. */
562
+ var MAX_READS = 12;
563
+ var PAGE_SIZE = 100;
564
+ var LOG_NAME = "series-scraper.log";
565
+ var FLOORS = [
566
+ "debug",
567
+ "info",
568
+ "warn",
569
+ "error"
570
+ ];
571
+ function floorOf(level) {
572
+ const lower = level?.toLowerCase();
573
+ return FLOORS.find((floor) => floor === lower);
574
+ }
575
+ function entryOf(line) {
576
+ return {
577
+ timestamp: line.timestamp,
578
+ level: line.level.toUpperCase(),
579
+ ...line.scope !== void 0 ? { context: line.scope } : {},
580
+ message: line.message
581
+ };
582
+ }
583
+ /**
584
+ * The scraper's log page over Dominevo's own log store — never a file on disk. The store keeps
585
+ * the addon's lines, so this lists one virtual log, pages the newest `LOG_WINDOW` of them and
586
+ * hands the same window out as a download. One addon's lines cannot be wiped from a store every
587
+ * addon shares, and the clear says so.
588
+ */
589
+ var StoreLogFiles = class {
590
+ api;
591
+ logger;
592
+ now;
593
+ constructor(api, logger, now = () => /* @__PURE__ */ new Date()) {
594
+ this.api = api;
595
+ this.logger = logger;
596
+ this.now = now;
597
+ }
598
+ listFiles() {
599
+ return [{
600
+ name: LOG_NAME,
601
+ size: 0,
602
+ date: this.now().toISOString()
603
+ }];
604
+ }
605
+ async getPage(page, level) {
606
+ const entries = await this.window(level);
607
+ const start = page * PAGE_SIZE;
608
+ return {
609
+ entries: entries.slice(start, start + PAGE_SIZE),
610
+ total: entries.length,
611
+ page
612
+ };
613
+ }
614
+ async getRaw() {
615
+ return {
616
+ fileName: LOG_NAME,
617
+ content: [...await this.window(void 0)].reverse().map((e) => `${e.timestamp} ${e.level}${e.context ? ` [${e.context}]` : ""} ${e.message}`).join("\n")
618
+ };
619
+ }
620
+ clear() {
621
+ throw new import_dist.LogFilesRefused("Dominevo keeps this log in its shared log store, which one addon cannot clear. Clear it from Dominevo's Logs page.");
622
+ }
623
+ /** Newest first, at most `LOG_WINDOW`, only this addon's lines, the asked level exactly. */
624
+ async window(level) {
625
+ const floor = floorOf(level);
626
+ const out = [];
627
+ let before;
628
+ try {
629
+ for (let read = 0; read < MAX_READS && out.length < 2e3; read += 1) {
630
+ const page = await this.api.logs.query.query({
631
+ tags: { addonId: ADDON_ID },
632
+ ...floor !== void 0 ? { level: floor } : {},
633
+ limit: READ_LIMIT,
634
+ ...before !== void 0 ? { before } : {}
635
+ });
636
+ for (const line of page.entries) if (floor === void 0 || line.level.toLowerCase() === floor) out.push(entryOf(line));
637
+ if (page.done || page.nextBefore === null) break;
638
+ before = page.nextBefore;
639
+ }
640
+ } catch (error) {
641
+ this.logger.error("series-scraper: the Dominevo log store could not be read for the logs page", {
642
+ tags: HOST_LOG_TAGS,
643
+ meta: { reason: errorText(error) }
644
+ });
645
+ throw new Error("The Dominevo log store could not be read.");
646
+ }
647
+ return out.slice(0, LOG_WINDOW);
648
+ }
649
+ };
650
+ // src/embedded/scrubbed-logger.ts
651
+ /** Scrub every string of a meta value, however deep: a URL in `meta.url` or an error text is a log line too. */
652
+ function scrubValue(value, depth = 0) {
653
+ if (typeof value === "string") return (0, import_dist.scrubSecrets)(value);
654
+ if (depth > 4 || value === null || typeof value !== "object") return value;
655
+ if (Array.isArray(value)) return value.map((item) => scrubValue(item, depth + 1));
656
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, scrubValue(item, depth + 1)]));
657
+ }
658
+ function isRecord(value) {
659
+ return typeof value === "object" && value !== null && !Array.isArray(value);
660
+ }
661
+ /**
662
+ * The embedded host's logger with credentials removed from the message and the meta, through the
663
+ * same function the core's logger uses. Wrap the addon's logger once, where the host is built.
664
+ */
665
+ function scrubbedLogger(inner) {
666
+ const clean = (message, options) => {
667
+ if (options?.meta === void 0) return [(0, import_dist.scrubSecrets)(message), options];
668
+ const meta = scrubValue(options.meta);
669
+ return [(0, import_dist.scrubSecrets)(message), {
670
+ ...options,
671
+ meta: isRecord(meta) ? meta : {}
672
+ }];
673
+ };
674
+ return {
675
+ debug: (message, options) => inner.debug(...clean(message, options)),
676
+ info: (message, options) => inner.info(...clean(message, options)),
677
+ warn: (message, options) => inner.warn(...clean(message, options)),
678
+ error: (message, options) => inner.error(...clean(message, options)),
679
+ child: (scope) => scrubbedLogger(inner.child(scope)),
680
+ withTags: (tags) => scrubbedLogger(inner.withTags(tags))
681
+ };
682
+ }
683
+ // src/embedded/notifier.ts
684
+ var import_cjs = require_cjs();
685
+ /** The title and body of a core event; the core has already worded both. */
686
+ function messageOf(notification) {
687
+ return {
688
+ title: notification.title,
689
+ body: notification.message,
690
+ level: notification.level
691
+ };
692
+ }
693
+ /** Events worth a push; a scan start or a download start is noise on a phone (an episode start is not: the old webhook pushed it). The live stream still carries all of them. */
694
+ var PUSHED_TYPES = /* @__PURE__ */ new Set([
695
+ "download_complete",
696
+ "download_fail",
697
+ "episode_start",
698
+ "episode_complete",
699
+ "episode_fail",
700
+ "captcha_needed"
701
+ ]);
702
+ /**
703
+ * The embedded host's notifications: every event goes to the page's live stream (SSE), and the
704
+ * ones worth a push go to the Dominevo notification target picked in the settings. A failed push
705
+ * is logged with the target and never throws into the core.
706
+ */
707
+ var TargetNotifier = class {
708
+ options;
709
+ events$ = new import_cjs.Subject();
710
+ constructor(options) {
711
+ this.options = options;
712
+ }
713
+ stream() {
714
+ return this.events$.asObservable();
715
+ }
716
+ notify(notification) {
717
+ this.events$.next(notification);
718
+ this.emitEvent(notification);
719
+ if (!PUSHED_TYPES.has(notification.type)) return;
720
+ this.push(notification).catch((error) => {
721
+ this.options.logger.warn("series-scraper: the notification was not delivered to the target", {
722
+ tags: HOST_LOG_TAGS,
723
+ meta: {
724
+ type: notification.type,
725
+ reason: errorText(error)
726
+ }
727
+ });
728
+ });
729
+ }
730
+ /** Independent of the target: the hub's rules decide who hears about it. A failing sink never reaches the core. */
731
+ emitEvent(notification) {
732
+ const event = eventOfNotification(notification);
733
+ if (event === null || this.options.events === void 0) return;
734
+ try {
735
+ this.options.events(event);
736
+ } catch (error) {
737
+ this.options.logger.warn("series-scraper: the addon event was not emitted", {
738
+ tags: HOST_LOG_TAGS,
739
+ meta: {
740
+ kind: event.kind,
741
+ reason: errorText(error)
742
+ }
743
+ });
744
+ }
745
+ }
746
+ async push(notification) {
747
+ const targetId = await this.options.targetId();
748
+ if (targetId === "") return;
749
+ try {
750
+ await this.options.send(targetId, messageOf(notification));
751
+ } catch (error) {
752
+ throw new Error(`target ${targetId}: ${errorText(error)}`);
753
+ }
754
+ }
755
+ close() {
756
+ this.events$.complete();
757
+ }
758
+ };
759
+ /**
760
+ * Deliver through a Dominevo notification target over `ctx.api`. `sendToExportedTarget` already
761
+ * logs a refusal or a failed send with the target id; this turns anything but `sent` into a
762
+ * rejection so the notifier's own line names the event that was lost.
763
+ */
764
+ function targetSendOver(api, logger) {
765
+ return async (targetId, message) => {
766
+ const result = await sendToExportedTarget(api, logger, {
767
+ exporter: "series-scraper",
768
+ targetId,
769
+ notification: {
770
+ title: message.title,
771
+ body: message.body,
772
+ level: message.level
773
+ }
774
+ });
775
+ if (result.status === "refused") throw new Error(result.reason);
776
+ if (result.status === "failed") throw new Error(result.message);
777
+ };
778
+ }
779
+ // src/embedded/host.ts
780
+ var API_PREFIX = "/api";
781
+ /** How long `app.close()` (tunnels, Chrome, downloads) may take before shutdown moves on. */
782
+ var APP_CLOSE_TIMEOUT_MS = 1e4;
783
+ /**
784
+ * Boot the scraper core inside this process. Order matters: records declared and read, secrets
785
+ * read, and only then the Nest application is created, because the core reads state and
786
+ * credentials synchronously. The application is initialised and never listens.
787
+ */
788
+ async function startEmbeddedHost(options) {
789
+ const logger = scrubbedLogger(options.logger);
790
+ const platform = options.platform ?? process.platform;
791
+ const arch = options.arch ?? process.arch;
792
+ const state = new RecordsStateStore({
793
+ records: options.records,
794
+ logger,
795
+ writeBehind: options.writeBehind
796
+ });
797
+ try {
798
+ await state.hydrate();
799
+ } catch (error) {
800
+ throw new Error(`state could not be loaded: ${errorText(error)}`, { cause: error });
801
+ }
802
+ const secrets = new SettingsSecretStore({
803
+ settings: options.settings,
804
+ records: options.records,
805
+ logger,
806
+ writeBehind: options.writeBehind
807
+ });
808
+ try {
809
+ await secrets.hydrate();
810
+ } catch (error) {
811
+ throw new Error(`state could not be loaded: ${errorText(error)}`, { cause: error });
812
+ }
813
+ const notifier = new TargetNotifier({
814
+ targetId: async () => (await options.settings.get()).notifierTarget ?? "",
815
+ send: targetSendOver(options.api, logger),
816
+ logger,
817
+ events: options.events
818
+ });
819
+ const chromeOps = options.chromeOps ?? await realChromeOps(logger, extractDebPayload, (path) => readFile(path));
820
+ const cacheDir = options.cacheDir ?? options.dataDir;
821
+ (0, import_dist.moveChromeProfiles)(options.dataDir, {
822
+ cacheDir,
823
+ log: (message) => logger.warn(message)
824
+ });
825
+ const chrome = new ChromeInstaller({
826
+ depsDir: options.depsDir,
827
+ homeDir: moveChromeHome(options.dataDir, cacheDir, { log: (message) => logger.warn(message) }),
828
+ logger,
829
+ platform,
830
+ arch,
831
+ ops: chromeOps
832
+ });
833
+ const binaries = createEmbeddedBinaries({
834
+ depsDir: options.depsDir,
835
+ platform,
836
+ arch,
837
+ chrome,
838
+ logger,
839
+ ops: {
840
+ ensureFfmpeg: options.ensureFfmpeg,
841
+ downloadWireproxy: async ({ url, sha256, targetDir }) => downloadBinary({
842
+ name: "wireproxy",
843
+ url,
844
+ targetDir,
845
+ targetName: "wireproxy",
846
+ logger,
847
+ isArchive: true,
848
+ archiveFormat: "tar.gz",
849
+ archiveInnerPath: "wireproxy",
850
+ sha256
851
+ }),
852
+ downloadYtdlp: async ({ url, sha256, targetDir }) => downloadBinary({
853
+ name: "yt-dlp",
854
+ url,
855
+ targetDir,
856
+ targetName: "yt-dlp",
857
+ logger,
858
+ sha256
859
+ }),
860
+ findSystemChrome: () => findInPath("google-chrome-stable") ?? findInPath("chromium"),
861
+ ...options.binaryOps
862
+ }
863
+ });
864
+ const paths = {
865
+ dataDir: options.dataDir,
866
+ cacheDir
867
+ };
868
+ const ports = {
869
+ stateStore: state,
870
+ secretStore: secrets,
871
+ logger: coreLoggerOver(logger),
872
+ notifier,
873
+ logFiles: new StoreLogFiles(options.logs, logger),
874
+ paths,
875
+ binaries,
876
+ hostInfo: {
877
+ version: options.version,
878
+ egressFirewall: false,
879
+ requireExit: true
880
+ }
881
+ };
882
+ const app = await (0, import_dist.createScraperApp)(ports);
883
+ const stopWatchingGate = options.events === void 0 ? void 0 : watchGate(app.get(import_dist.EgressGate), options.events);
884
+ const express = app.getHttpAdapter().getInstance();
885
+ logger.info("series-scraper: the embedded scraper is up", {
886
+ tags: HOST_LOG_TAGS,
887
+ meta: {
888
+ dataDir: options.dataDir,
889
+ version: options.version
890
+ }
891
+ });
892
+ const handler = (req, res) => {
893
+ req.headers = forwardedHeaders(req);
894
+ const rest = req.url ?? "/";
895
+ req.url = `${API_PREFIX}${rest.startsWith("/") ? rest : `/${rest}`}`;
896
+ try {
897
+ express(req, res);
898
+ } catch (error) {
899
+ logger.error("series-scraper: the embedded scraper threw on a request", {
900
+ tags: HOST_LOG_TAGS,
901
+ meta: {
902
+ reason: errorText(error),
903
+ url: req.url
904
+ }
905
+ });
906
+ if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" });
907
+ res.end(JSON.stringify({ error: "embedded-scraper-failed" }));
908
+ }
909
+ };
910
+ return {
911
+ handler,
912
+ refreshSecrets: () => secrets.refreshFixed(),
913
+ async stop() {
914
+ await closeWithin(app.close(), options.closeTimeoutMs ?? APP_CLOSE_TIMEOUT_MS, logger);
915
+ stopWatchingGate?.();
916
+ notifier.close();
917
+ const unwritten = [...await secrets.flush(), ...await state.flush()];
918
+ if (unwritten.length > 0) logger.error("series-scraper: state that could not be written at shutdown is lost", {
919
+ tags: HOST_LOG_TAGS,
920
+ meta: { unwritten }
921
+ });
922
+ }
923
+ };
924
+ }
925
+ export { startEmbeddedHost };