gutterpress 0.11.10-alpha.2 → 0.11.10-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +24 -46
  2. package/dist/api/index.d.ts +1 -1
  3. package/dist/api/index.js +10 -6
  4. package/dist/{build-dfpvvhys.js → build-npxq1tvm.js} +7 -6
  5. package/dist/cdp-jg95s674.js +15 -0
  6. package/dist/cdp-smdx6mr3.js +16 -0
  7. package/dist/{cli-d8rdk1y7.js → cli-30j93gzt.js} +11 -335
  8. package/dist/{cli-pfczdbyd.js → cli-5qr3z0qa.js} +10 -404
  9. package/dist/{cli-c41yr7he.js → cli-7fkhgtfn.js} +3 -1
  10. package/dist/{cli-k2hwrp7s.js → cli-97bdz5k0.js} +1 -4
  11. package/dist/cli-kkzka31p.js +261 -0
  12. package/dist/{cli-p679pvce.js → cli-vbzkkcbv.js} +2 -2
  13. package/dist/{cli-4xksazfr.js → cli-z8ye91f0.js} +283 -1142
  14. package/dist/cli.js +12 -14
  15. package/dist/{doctor-hheax5yc.js → doctor-ykr6gtpv.js} +3 -3
  16. package/dist/engine/shared/cdp.d.ts +23 -19
  17. package/dist/engine-3gwctsty.js +24 -0
  18. package/dist/engine-mwshptgf.js +25 -0
  19. package/dist/{ext-q5024j6v.js → ext-bna9nr3v.js} +7 -6
  20. package/dist/{index-1a4rx87v.js → index-322fxk25.js} +344 -1130
  21. package/dist/{index-kqftehgy.js → index-dzp0hc2c.js} +4 -2
  22. package/dist/{index-fnhak0nh.js → index-qf7y4d85.js} +10 -404
  23. package/dist/index-r4wvy5v3.js +267 -0
  24. package/dist/{index-t43k5rq1.js → index-rzm1phg0.js} +23 -356
  25. package/dist/index.d.ts +0 -1
  26. package/dist/index.js +12 -87
  27. package/dist/lib/build-error.d.ts +4 -5
  28. package/dist/lib/build-preflight.d.ts +1 -35
  29. package/dist/lib/build-runner.d.ts +27 -44
  30. package/dist/lib/chromium.d.ts +5 -1
  31. package/dist/lib/engine.d.ts +3 -18
  32. package/dist/lib/extension-manager.d.ts +2 -2
  33. package/dist/lib/extension-manifest.d.ts +1 -1
  34. package/dist/lib/markdown/assemble.d.ts +2 -9
  35. package/dist/lib/markdown/index.d.ts +2 -4
  36. package/dist/lib/markdown/plugins.d.ts +0 -3
  37. package/dist/lib/npm-plugin-installer.d.ts +6 -1
  38. package/dist/lib/plugin-vendor.d.ts +10 -78
  39. package/dist/lib/source-provider.d.ts +1 -1
  40. package/dist/lib/validation-exec.d.ts +5 -6
  41. package/dist/{new-6xm4tdxb.js → new-0hv3nwqj.js} +9 -8
  42. package/dist/{preflight-ezt8rvg3.js → preflight-pk0k25fm.js} +7 -6
  43. package/dist/preview/file-watcher.d.ts +4 -43
  44. package/dist/preview/http-server.d.ts +1 -3
  45. package/dist/{preview-hehs46dd.js → preview-8b1fn59h.js} +7 -6
  46. package/dist/{preview-shell-gqnc5xxe.js → preview-shell-tqndvhbx.js} +5 -7
  47. package/dist/{publish-ha505ejq.js → publish-ba5h76tz.js} +7 -6
  48. package/dist/render.d.ts +1 -1
  49. package/dist/render.js +1 -9
  50. package/dist/{source-provider-ta09wegv.js → source-provider-pzmz0br9.js} +1 -1
  51. package/dist/{source-provider-7c2ww3bz.js → source-provider-qbthnmqw.js} +1 -1
  52. package/dist/{validate-je56vdbj.js → validate-4rq2r5b3.js} +7 -6
  53. package/package.json +1 -4
  54. package/dist/audit-v9594a72.js +0 -69
  55. package/dist/engine-qtfrfbpk.js +0 -41
  56. package/dist/engine-trte2tg2.js +0 -40
  57. package/dist/lib/browser-pool.d.ts +0 -35
  58. package/dist/lib/lint-runner.d.ts +0 -29
  59. package/dist/lint-tbywt66a.js +0 -68
@@ -1,31 +1,25 @@
1
1
  import {
2
2
  BuildError,
3
3
  EXIT_CODES,
4
- INSTALL_HINTS,
5
4
  MARGIN_BOX_IGNORED_PROPERTIES,
6
- RENDER_TIMEOUT_MS,
7
- REQUIRED_MILESTONE,
8
- closeBrowser,
5
+ getAssetPath,
6
+ getAssetsDir
7
+ } from "./index-r4wvy5v3.js";
8
+ import {
9
+ INSTALL_HINTS,
9
10
  execCapture,
10
11
  findTool,
11
12
  fullInstallHint,
12
- getAssetPath,
13
- getAssetsDir,
14
- getBrowser,
15
13
  isToolAvailable,
16
- prewarmBrowser,
17
14
  requireChromiumExecutable,
18
15
  resolveChromiumExecutable,
19
16
  run,
20
17
  spawnCapture
21
- } from "./index-t43k5rq1.js";
18
+ } from "./index-rzm1phg0.js";
22
19
  import {
23
20
  PLUGINS_DIR,
24
21
  VENDORED_NPM_DIR,
25
- VENDOR_RECEIPT_FILE,
26
- VENDOR_RECEIPT_VERSION,
27
22
  assertWindowsSafeRelativePath,
28
- computeVendorTreeDigest,
29
23
  errorLogData,
30
24
  gitFs,
31
25
  gitScopeFor,
@@ -34,23 +28,21 @@ import {
34
28
  isExactNpmVersion,
35
29
  isValidNpmPackageName,
36
30
  listWorkdirChanges,
37
- npmRegistryUrl,
38
- packageEntryFormat,
39
31
  packageResolutionTargets,
40
32
  parseNpmPluginSpec,
41
33
  resolveGitAuthor,
42
34
  resolveLogger,
43
35
  resolvePackageEntry,
44
36
  resolveVendoredPluginInstallRoot,
37
+ safePackageTarget,
45
38
  snapshotStagingMarkerPath,
46
39
  snapshotWorkingTreeUnlocked,
47
40
  toPosixPath,
48
41
  vendoredNpmPluginPackageDir,
49
42
  vendoredNpmPluginRoot,
50
- verifyVendoredPlugin,
51
43
  windowsPathKey,
52
44
  withRepoLock
53
- } from "./index-fnhak0nh.js";
45
+ } from "./index-qf7y4d85.js";
54
46
  import {
55
47
  detectProjectSource,
56
48
  repoSubPath,
@@ -2597,16 +2589,8 @@ async function assembleBookHtml(opts) {
2597
2589
  }
2598
2590
  for (const ref of env.imageRefs ?? [])
2599
2591
  imageRefs.add(ref);
2600
- if (opts.wrapChapters) {
2601
- const safe = chapterId.replace(/&/g, "&").replace(/"/g, """);
2602
- bodyContent += `<div class="gutterpress-chapter" data-chapter-src="${safe}">
2603
- ${rendered}
2604
- </div>
2592
+ bodyContent += rendered + `
2605
2593
  `;
2606
- } else {
2607
- bodyContent += rendered + `
2608
- `;
2609
- }
2610
2594
  }
2611
2595
  if (opts.onImageRefs) {
2612
2596
  for (const ref of collectHtmlImageRefs(bodyContent))
@@ -3094,7 +3078,6 @@ ${css.trim()}
3094
3078
  title: opts.title,
3095
3079
  plugins: opts.plugins,
3096
3080
  pluginCss,
3097
- wrapChapters: opts.wrapChapters,
3098
3081
  annotateSourceChapters: opts.annotateSourceChapters,
3099
3082
  onChapterWarnings: opts.onChapterWarnings,
3100
3083
  onImageRefs: opts.onImageRefs
@@ -3119,16 +3102,11 @@ async function renderChaptersToFile(inputDir, outDir, opts = {}) {
3119
3102
  }
3120
3103
 
3121
3104
  // src/lib/markdown/plugins.ts
3122
- import { createHash as createHash2 } from "node:crypto";
3123
- import { existsSync as existsSync4, lstatSync, realpathSync, rmSync, statSync as statSync2, unlinkSync } from "node:fs";
3124
- import { cp, link, mkdir as mkdir2, mkdtemp, readFile as readFile5, rm, unlink, writeFile as writeFile2 } from "node:fs/promises";
3125
- import { tmpdir } from "node:os";
3126
- import { resolve as resolve3, join as join2, dirname as dirname2, basename, extname, relative, isAbsolute } from "node:path";
3127
- import { fileURLToPath, pathToFileURL } from "node:url";
3128
- import Module, { builtinModules, createRequire } from "node:module";
3129
- import { parse as parseJavaScript } from "acorn";
3130
- import { parse as parseModuleImports } from "es-module-lexer/js";
3131
- import { imports as resolvePackageImports } from "resolve.exports";
3105
+ import { existsSync as existsSync4, readFileSync, statSync as statSync2, unlinkSync } from "node:fs";
3106
+ import { link, unlink } from "node:fs/promises";
3107
+ import { isBuiltin } from "node:module";
3108
+ import { resolve as resolve3, join as join2, dirname as dirname2, basename, extname, isAbsolute, relative, sep } from "node:path";
3109
+ import { pathToFileURL } from "node:url";
3132
3110
 
3133
3111
  // src/lib/style-declarations.ts
3134
3112
  import { existsSync as existsSync3 } from "node:fs";
@@ -3240,513 +3218,97 @@ function resolveExtension(dir, meta, subject) {
3240
3218
  };
3241
3219
  }
3242
3220
  // src/lib/markdown/plugins.ts
3243
- var moduleInternals = Module;
3244
- var vendorCjsTrees = new Map;
3245
- var latestVendorCjsTree = new Map;
3246
- var isolatedVendorTrees = new Map;
3247
- var nodeBuiltins = new Set(builtinModules.flatMap((name) => [name, `node:${name}`]));
3248
- var needsNativeCjsResolver = !process.versions.bun;
3249
- var cjsResolverInstalled = false;
3250
- var isolatedVendorBase;
3251
- var isolatedVendorBasePath = null;
3252
- var vendorSnapshotHook;
3253
- function pathContains(root, candidate) {
3254
- const value = relative(root, candidate);
3255
- return value === "" || !value.startsWith("..") && !isAbsolute(value);
3256
- }
3257
- function barePackageRequest(request) {
3258
- if (!request || request.startsWith(".") || request.startsWith("/") || request.startsWith("#") || isAbsolute(request) || /^[a-zA-Z][a-zA-Z+.-]*:/.test(request)) {
3259
- return null;
3260
- }
3261
- const parts = request.split("/");
3262
- if (request.startsWith("@")) {
3263
- if (parts.length < 2)
3264
- return null;
3265
- return { name: `${parts[0]}/${parts[1]}`, subpath: parts.slice(2).join("/") };
3266
- }
3267
- return { name: parts[0], subpath: parts.slice(1).join("/") };
3268
- }
3269
- function resolveVerifiedTarget(pkg, resolution) {
3270
- const target = resolution.target.startsWith("./") ? resolution.target.slice(2) : resolution.target;
3271
- if (!target || target.includes("\\") || target.includes("*") || target.includes("?") || target.includes("#")) {
3272
- return null;
3273
- }
3274
- try {
3275
- assertWindowsSafeRelativePath(target);
3276
- } catch {
3277
- return null;
3278
- }
3279
- if (target.normalize("NFKC").split("/").some((part) => part.toLowerCase() === "node_modules")) {
3280
- return null;
3281
- }
3282
- const base = resolve3(pkg.packageDir, ...target.split("/"));
3283
- if (!pathContains(pkg.packageDir, base))
3284
- return null;
3285
- const candidates = resolution.exact ? [base] : [
3286
- base,
3287
- `${base}.js`,
3288
- `${base}.cjs`,
3289
- `${base}.mjs`,
3290
- `${base}.json`,
3291
- join2(base, "index.js"),
3292
- join2(base, "index.cjs"),
3293
- join2(base, "index.mjs"),
3294
- join2(base, "index.json")
3295
- ];
3296
- for (const candidate of candidates) {
3297
- try {
3298
- const info2 = lstatSync(candidate);
3299
- const extension = extname(candidate);
3300
- if (info2.isFile() && !info2.isSymbolicLink() && (!extension || [".js", ".cjs", ".mjs", ".json"].includes(extension))) {
3301
- return candidate;
3302
- }
3303
- } catch {}
3304
- }
3305
- return null;
3306
- }
3307
- function resolveVerifiedRequest(pkg, subpath, condition) {
3308
- for (const resolution of packageResolutionTargets(pkg.manifest, subpath, condition)) {
3309
- const resolved = resolveVerifiedTarget(pkg, resolution);
3310
- if (resolved)
3311
- return resolved;
3312
- }
3313
- return null;
3314
- }
3315
- function resolveApprovedPackageRequest(owner, request, condition, tree, depth = 0) {
3316
- if (depth > 8)
3317
- return null;
3318
- if (nodeBuiltins.has(request)) {
3319
- return request.startsWith("node:") ? request : `node:${request}`;
3320
- }
3321
- if (request.startsWith("#")) {
3322
- let targets;
3221
+ var vendoredRootsOpened = new Set;
3222
+ var bunVendoredResolverInstalled = false;
3223
+ function isInsideDir(candidate, root) {
3224
+ return candidate === root || candidate.startsWith(root.endsWith(sep) ? root : root + sep);
3225
+ }
3226
+ function resolveBareSpecifierSync(specifier, fromDir, stopRoot, condition) {
3227
+ const parts = specifier.split("/");
3228
+ const name = specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
3229
+ const subpath = specifier.slice(name.length).replace(/^\//, "");
3230
+ for (let dir = fromDir;isInsideDir(dir, stopRoot); dir = dirname2(dir)) {
3231
+ const packageDir = join2(dir, "node_modules", ...name.split("/"));
3232
+ const packageJson = join2(packageDir, "package.json");
3233
+ if (!existsSync4(packageJson)) {
3234
+ if (dir === stopRoot)
3235
+ break;
3236
+ continue;
3237
+ }
3238
+ let manifest;
3323
3239
  try {
3324
- targets = resolvePackageImports(owner.manifest, request, {
3325
- require: condition === "require"
3326
- }) ?? [];
3240
+ manifest = JSON.parse(readFileSync(packageJson, "utf8"));
3327
3241
  } catch {
3328
3242
  return null;
3329
3243
  }
3330
- for (const target2 of targets) {
3331
- if (target2.startsWith("./")) {
3332
- const resolved = resolveVerifiedTarget(owner, { target: target2, exact: true });
3333
- if (resolved)
3334
- return resolved;
3335
- } else {
3336
- const resolved = resolveApprovedPackageRequest(owner, target2, condition, tree, depth + 1);
3337
- if (resolved)
3338
- return resolved;
3244
+ for (const target of packageResolutionTargets(manifest, subpath, condition)) {
3245
+ const rel = safePackageTarget(target.target);
3246
+ if (!rel)
3247
+ continue;
3248
+ const base = resolve3(packageDir, ...rel.split("/"));
3249
+ if (!isInsideDir(base, packageDir))
3250
+ continue;
3251
+ const candidates = target.exact ? [base] : [base, `${base}.mjs`, `${base}.js`, `${base}.cjs`, `${base}.json`, join2(base, "index.mjs"), join2(base, "index.js"), join2(base, "index.cjs")];
3252
+ for (const candidate of candidates) {
3253
+ try {
3254
+ if (statSync2(candidate).isFile())
3255
+ return candidate;
3256
+ } catch {}
3339
3257
  }
3340
3258
  }
3341
3259
  return null;
3342
3260
  }
3343
- const parsed = barePackageRequest(request);
3344
- if (!parsed)
3345
- return null;
3346
- const targetPath = parsed.name === owner.name ? owner.path : owner.dependencies[parsed.name];
3347
- const target = targetPath ? tree.byPath.get(targetPath) : undefined;
3348
- if (!target)
3349
- return null;
3350
- if (parsed.subpath)
3351
- return resolveVerifiedRequest(target, parsed.subpath, condition);
3352
- return condition === "require" ? target.requireEntryPath ?? null : target.entryPath ?? null;
3353
- }
3354
- function unresolvedVendorRequest(request, parent) {
3355
- const error2 = new Error(`Cannot resolve undeclared or unexported package request "${request}" from ${parent}.`);
3356
- error2.code = "MODULE_NOT_FOUND";
3357
- return error2;
3261
+ return null;
3358
3262
  }
3359
- function ensureVendorCjsResolver() {
3360
- if (!needsNativeCjsResolver || cjsResolverInstalled)
3263
+ function installBunVendoredResolver() {
3264
+ if (bunVendoredResolverInstalled)
3361
3265
  return;
3362
- cjsResolverInstalled = true;
3363
- const original = moduleInternals._resolveFilename;
3364
- moduleInternals._resolveFilename = function resolveVendorRequest(request, parent, isMain, options) {
3365
- if (parent?.filename && (request.startsWith("#") || barePackageRequest(request))) {
3366
- for (const tree of vendorCjsTrees.values()) {
3367
- const owner = tree.packages.find((pkg) => pathContains(pkg.packageDir, parent.filename));
3368
- if (!owner)
3369
- continue;
3370
- const resolved = resolveApprovedPackageRequest(owner, request, "require", tree);
3371
- if (resolved)
3372
- return resolved;
3373
- if (!nodeBuiltins.has(request)) {
3374
- throw unresolvedVendorRequest(request, parent.filename);
3375
- }
3376
- }
3377
- }
3378
- return Reflect.apply(original, this, [request, parent, isMain, options]);
3379
- };
3380
- }
3381
- async function getIsolatedVendorBase() {
3382
- isolatedVendorBase ??= mkdtemp(join2(tmpdir(), "gutterpress-plugin-loads-"));
3383
- const base = await isolatedVendorBase;
3384
- isolatedVendorBasePath = base;
3385
- ensureExitCleanupRegistered();
3386
- return base;
3387
- }
3388
- function isolatedPackageCopyFilter(packageDir, candidate) {
3389
- const candidateRelative = relative(packageDir, candidate);
3390
- if (!candidateRelative)
3391
- return true;
3392
- const parts = candidateRelative.split(/[\\/]/);
3393
- const nodeModulesAt = parts.findIndex((part) => part.normalize("NFKC").toLowerCase() === "node_modules");
3394
- if (nodeModulesAt < 0)
3395
- return true;
3396
- if (nodeModulesAt === 0 && parts[0] === "node_modules")
3397
- return false;
3398
- throw new Error(`Package contains bundled node_modules content: ${candidateRelative}`);
3399
- }
3400
- function rewrittenSpecifier(owner, specifier, condition, tree) {
3401
- if (!specifier.startsWith("#") && !barePackageRequest(specifier) && !nodeBuiltins.has(specifier)) {
3402
- return null;
3403
- }
3404
- const resolved = resolveApprovedPackageRequest(owner, specifier, condition, tree);
3405
- if (!resolved) {
3406
- throw new Error(`Package request "${specifier}" from ${owner.name} is not a receipt-approved dependency.`);
3407
- }
3408
- if (resolved.startsWith("node:"))
3409
- return { replacement: resolved };
3410
- return {
3411
- replacement: condition === "require" ? resolved : pathToFileURL(resolved).href,
3412
- targetPath: resolved
3413
- };
3414
- }
3415
- function localModuleTarget(absolute, specifier, condition) {
3416
- if (!specifier.startsWith(".") && !specifier.startsWith("file:") && !isAbsolute(specifier)) {
3417
- return null;
3418
- }
3419
- try {
3420
- if (condition === "require" && !specifier.startsWith("file:")) {
3421
- return createRequire(absolute).resolve(specifier);
3422
- }
3423
- const url = specifier.startsWith("file:") ? new URL(specifier) : isAbsolute(specifier) ? pathToFileURL(specifier) : new URL(specifier, pathToFileURL(absolute));
3424
- const target = fileURLToPath(url);
3425
- return lstatSync(target).isFile() ? target : null;
3426
- } catch {
3427
- return null;
3428
- }
3429
- }
3430
- function packageOwningFile(tree, file) {
3431
- return tree.packages.find((pkg) => pathContains(pkg.packageDir, file));
3432
- }
3433
- function addReachableTarget(targets, target, specifier, absolute, tree) {
3434
- if (!target)
3266
+ bunVendoredResolverInstalled = true;
3267
+ const bun = globalThis.Bun;
3268
+ if (typeof bun?.plugin !== "function")
3435
3269
  return;
3436
- if (!packageOwningFile(tree, target)) {
3437
- throw new Error(`Module "${specifier}" from ${absolute} resolves outside the verified package tree.`);
3438
- }
3439
- targets.add(target);
3440
- }
3441
- function visitSyntax(node, visitor) {
3442
- visitor(node);
3443
- for (const [key, value] of Object.entries(node)) {
3444
- if (["type", "start", "end", "loc", "range"].includes(key) || !value)
3445
- continue;
3446
- if (Array.isArray(value)) {
3447
- for (const item of value) {
3448
- if (item && typeof item === "object" && typeof item.type === "string") {
3449
- visitSyntax(item, visitor);
3270
+ bun.plugin({
3271
+ name: "gutterpress-vendored-plugins",
3272
+ setup(build) {
3273
+ build.onResolve({ filter: /^[^./]/ }, (args) => {
3274
+ if (!args.importer || isAbsolute(args.path) || /^[a-z]+:/i.test(args.path) || isBuiltin(args.path)) {
3275
+ return;
3450
3276
  }
3451
- }
3452
- } else if (typeof value === "object" && typeof value.type === "string") {
3453
- visitSyntax(value, visitor);
3454
- }
3455
- }
3456
- }
3457
- function memberName(node) {
3458
- if (node.type !== "MemberExpression")
3459
- return null;
3460
- const property = node.property;
3461
- if (!property)
3462
- return null;
3463
- if (property.type === "Identifier")
3464
- return property.name;
3465
- if (property.type === "Literal" && typeof property.value === "string")
3466
- return property.value;
3467
- return null;
3468
- }
3469
- function isReceiptBoundRequireCall(node) {
3470
- if (node.type !== "CallExpression")
3471
- return false;
3472
- const callee = node.callee;
3473
- if (!callee)
3474
- return false;
3475
- if (callee.type === "Identifier" && callee.name === "require")
3476
- return true;
3477
- if (callee.type !== "MemberExpression")
3478
- return false;
3479
- const object2 = callee.object;
3480
- const property = memberName(callee);
3481
- return Boolean(object2 && (object2.type === "Identifier" && object2.name === "module" && property === "require" || object2.type === "Identifier" && object2.name === "require" && property === "resolve"));
3482
- }
3483
- function rewriteCommonJsRequires(source, absolute, pkg, tree) {
3484
- const ast = parseJavaScript(source, {
3485
- ecmaVersion: "latest",
3486
- sourceType: "script",
3487
- allowHashBang: true,
3488
- allowReturnOutsideFunction: true
3489
- });
3490
- const replacements = [];
3491
- const targets = new Set;
3492
- visitSyntax(ast, (node) => {
3493
- if (!isReceiptBoundRequireCall(node))
3494
- return;
3495
- const args = node.arguments;
3496
- const argument = args?.[0];
3497
- if (!argument || argument.type !== "Literal" || typeof argument.value !== "string") {
3498
- throw new Error(`Dynamic require in ${pkg.name}/${relative(pkg.packageDir, absolute)} must use a string literal.`);
3499
- }
3500
- const rewritten = rewrittenSpecifier(pkg, argument.value, "require", tree);
3501
- if (rewritten) {
3502
- replacements.push({
3503
- start: argument.start,
3504
- end: argument.end,
3505
- value: JSON.stringify(rewritten.replacement)
3506
- });
3507
- addReachableTarget(targets, rewritten.targetPath, argument.value, absolute, tree);
3508
- } else {
3509
- const target = localModuleTarget(absolute, argument.value, "require");
3510
- if (!target) {
3511
- throw new Error(`CommonJS module "${argument.value}" from ${pkg.name}/${relative(pkg.packageDir, absolute)} could not be resolved.`);
3512
- }
3513
- addReachableTarget(targets, target, argument.value, absolute, tree);
3514
- }
3515
- });
3516
- return { replacements, targets };
3517
- }
3518
- async function rewriteReachableModuleImports(entryPath, tree) {
3519
- const pending = [entryPath];
3520
- const visited = new Set;
3521
- while (pending.length > 0) {
3522
- const absolute = pending.pop();
3523
- if (visited.has(absolute))
3524
- continue;
3525
- visited.add(absolute);
3526
- const extension = extname(absolute);
3527
- if (![".js", ".mjs", ".cjs"].includes(extension))
3528
- continue;
3529
- const pkg = packageOwningFile(tree, absolute);
3530
- if (!pkg)
3531
- throw new Error(`Reachable plugin module is outside the verified package tree: ${absolute}`);
3532
- const source = await readFile5(absolute, "utf8");
3533
- const [imports] = parseModuleImports(source, absolute);
3534
- const replacements = [];
3535
- const targets = new Set;
3536
- for (const imported of imports) {
3537
- if (imported.d === -2)
3538
- continue;
3539
- if (imported.n === undefined) {
3540
- throw new Error(`Dynamic import in ${pkg.name}/${relative(pkg.packageDir, absolute)} must use a string literal.`);
3541
- }
3542
- const rewritten2 = rewrittenSpecifier(pkg, imported.n, "import", tree);
3543
- if (rewritten2) {
3544
- addReachableTarget(targets, rewritten2.targetPath, imported.n, absolute, tree);
3545
- if (imported.d === -1) {
3546
- const quote = source[imported.s - 1];
3547
- if (quote !== '"' && quote !== "'" || source[imported.e] !== quote) {
3548
- throw new Error(`Could not safely rewrite an import in ${absolute}.`);
3277
+ let root;
3278
+ for (const opened of vendoredRootsOpened) {
3279
+ if (isInsideDir(args.importer, opened)) {
3280
+ root = opened;
3281
+ break;
3549
3282
  }
3550
- replacements.push({
3551
- start: imported.s - 1,
3552
- end: imported.e + 1,
3553
- value: JSON.stringify(rewritten2.replacement)
3554
- });
3555
- } else {
3556
- replacements.push({
3557
- start: imported.s,
3558
- end: imported.e,
3559
- value: JSON.stringify(rewritten2.replacement)
3560
- });
3561
3283
  }
3562
- } else {
3563
- const target = localModuleTarget(absolute, imported.n, "import");
3564
- if (target) {
3565
- addReachableTarget(targets, target, imported.n, absolute, tree);
3566
- } else if (imported.n.startsWith(".") || imported.n.startsWith("file:") || isAbsolute(imported.n)) {
3567
- throw new Error(`ESM module "${imported.n}" from ${pkg.name}/${relative(pkg.packageDir, absolute)} could not be resolved.`);
3568
- }
3569
- }
3570
- }
3571
- if (extension === ".cjs" || extension === ".js" && pkg.manifest.type !== "module") {
3572
- const commonJs = rewriteCommonJsRequires(source, absolute, pkg, tree);
3573
- replacements.push(...commonJs.replacements);
3574
- for (const target of commonJs.targets)
3575
- targets.add(target);
3576
- }
3577
- replacements.sort((a, b) => b.start - a.start);
3578
- let rewritten = source;
3579
- for (const replacement of replacements) {
3580
- rewritten = rewritten.slice(0, replacement.start) + replacement.value + rewritten.slice(replacement.end);
3581
- }
3582
- if (replacements.length > 0)
3583
- await writeFile2(absolute, rewritten, "utf8");
3584
- pending.push(...targets);
3585
- }
3586
- }
3587
- function remapPackageEntry(source, destination, entry) {
3588
- if (!entry)
3589
- return;
3590
- const entryRelative = relative(source.packageDir, entry);
3591
- if (!pathContains(source.packageDir, entry) || !entryRelative) {
3592
- throw new Error(`Verified entry for ${source.name} is outside its package.`);
3593
- }
3594
- return resolve3(destination, entryRelative);
3595
- }
3596
- async function createIsolatedVendorTree(verified, address) {
3597
- const base = await getIsolatedVendorBase();
3598
- const loadRoot = join2(base, address);
3599
- await mkdir2(loadRoot);
3600
- try {
3601
- const packageMap = new Map;
3602
- const sorted = [...verified.packages].sort((a, b) => a.path.localeCompare(b.path));
3603
- for (let index = 0;index < sorted.length; index++) {
3604
- const source = sorted[index];
3605
- const destination = join2(loadRoot, "packages", String(index), "package");
3606
- await mkdir2(dirname2(destination), { recursive: true });
3607
- await cp(source.packageDir, destination, {
3608
- recursive: true,
3609
- filter: (candidate) => isolatedPackageCopyFilter(source.packageDir, candidate)
3610
- });
3611
- packageMap.set(source.path, {
3612
- ...source,
3613
- packageDir: destination,
3614
- entryPath: remapPackageEntry(source, destination, source.entryPath),
3615
- requireEntryPath: remapPackageEntry(source, destination, source.requireEntryPath)
3284
+ if (!root)
3285
+ return;
3286
+ const resolved = resolveBareSpecifierSync(args.path, dirname2(args.importer), root, args.kind === "require-call" || args.kind === "require-resolve" ? "require" : "import");
3287
+ return resolved ? { path: resolved } : undefined;
3616
3288
  });
3617
3289
  }
3618
- const packages = [...packageMap.values()];
3619
- const tree = {
3620
- sourceRoot: verified.installRoot,
3621
- packages,
3622
- byPath: new Map(packages.map((pkg) => [pkg.path, pkg]))
3623
- };
3624
- const rootPackage = packageMap.get(verified.receipt.root.packagePath);
3625
- if (!rootPackage)
3626
- throw new Error("Verified root package is missing from the isolated tree.");
3627
- const sourceRoot = verified.packages.find((pkg) => pkg.path === verified.receipt.root.packagePath);
3628
- const entryPath = remapPackageEntry(sourceRoot, rootPackage.packageDir, verified.entryPath);
3629
- if (!entryPath)
3630
- throw new Error("Verified plugin entry is missing from the isolated tree.");
3631
- await rewriteReachableModuleImports(entryPath, tree);
3632
- return { loadRoot, entryPath, packages };
3633
- } catch (error2) {
3634
- await rm(loadRoot, { recursive: true, force: true }).catch(() => {});
3635
- throw error2;
3636
- }
3637
- }
3638
- async function isolateVendoredPlugin(verified) {
3639
- const address = createHash2("sha256").update(verified.receipt.tree.digest).update("\x00").update(JSON.stringify(verified.receipt)).digest("hex");
3640
- let pending = isolatedVendorTrees.get(address);
3641
- if (!pending) {
3642
- pending = createIsolatedVendorTree(verified, address).catch((error2) => {
3643
- isolatedVendorTrees.delete(address);
3644
- throw error2;
3645
- });
3646
- isolatedVendorTrees.set(address, pending);
3647
- }
3648
- const isolated = await pending;
3649
- return {
3650
- ...verified,
3651
- loadRoot: isolated.loadRoot,
3652
- entryPath: isolated.entryPath,
3653
- packages: isolated.packages
3654
- };
3655
- }
3656
- async function snapshotAndIsolateVendoredPlugin(baseDir, packageName, version) {
3657
- const sourceRoot = await resolveVendoredPluginInstallRoot(baseDir, packageName, version);
3658
- if (!sourceRoot)
3659
- return null;
3660
- const base = await getIsolatedVendorBase();
3661
- const container = await mkdtemp(join2(base, "snapshot-"));
3662
- const snapshotProject = join2(container, "project");
3663
- const snapshotRoot = vendoredNpmPluginRoot(snapshotProject, packageName, version);
3664
- try {
3665
- await mkdir2(dirname2(snapshotRoot), { recursive: true });
3666
- await cp(sourceRoot, snapshotRoot, {
3667
- recursive: true,
3668
- dereference: false,
3669
- verbatimSymlinks: true
3670
- });
3671
- await vendorSnapshotHook?.(sourceRoot, snapshotRoot);
3672
- const verifiedSnapshot = await verifyVendoredPlugin(snapshotProject, packageName, version);
3673
- if (!verifiedSnapshot)
3674
- return null;
3675
- const isolated = await isolateVendoredPlugin(verifiedSnapshot);
3676
- return { ...isolated, installRoot: sourceRoot };
3677
- } finally {
3678
- await rm(container, { recursive: true, force: true }).catch(() => {});
3679
- }
3680
- }
3681
- function registerVendorCjsTree(verified) {
3682
- ensureVendorCjsResolver();
3683
- const key = `${verified.installRoot}\x00${verified.loadRoot}`;
3684
- const previousKey = latestVendorCjsTree.get(verified.installRoot);
3685
- if (vendorCjsTrees.has(key)) {
3686
- latestVendorCjsTree.set(verified.installRoot, key);
3687
- return () => {};
3688
- }
3689
- const packages = [...verified.packages].sort((a, b) => b.packageDir.length - a.packageDir.length);
3690
- vendorCjsTrees.set(key, {
3691
- sourceRoot: verified.installRoot,
3692
- ...previousKey ? { previousKey } : {},
3693
- packages,
3694
- byPath: new Map(packages.map((pkg) => [pkg.path, pkg]))
3695
3290
  });
3696
- latestVendorCjsTree.set(verified.installRoot, key);
3697
- return () => {
3698
- vendorCjsTrees.delete(key);
3699
- if (latestVendorCjsTree.get(verified.installRoot) === key) {
3700
- if (previousKey)
3701
- latestVendorCjsTree.set(verified.installRoot, previousKey);
3702
- else
3703
- latestVendorCjsTree.delete(verified.installRoot);
3704
- }
3705
- };
3706
- }
3707
- function clearVendoredPluginResolver(baseDir, packageName, version) {
3708
- let projectDir = baseDir;
3709
- try {
3710
- projectDir = realpathSync(baseDir);
3711
- } catch {}
3712
- const sourceRoot = vendoredNpmPluginRoot(projectDir, packageName, version);
3713
- const key = latestVendorCjsTree.get(sourceRoot);
3714
- if (!key)
3715
- return;
3716
- const tree = vendorCjsTrees.get(key);
3717
- vendorCjsTrees.delete(key);
3718
- if (tree?.previousKey)
3719
- latestVendorCjsTree.set(sourceRoot, tree.previousKey);
3720
- else
3721
- latestVendorCjsTree.delete(sourceRoot);
3722
3291
  }
3723
3292
  async function loadNpmPackage(packageName, baseDir, version) {
3724
3293
  if (version && isValidNpmPackageName(packageName) && isExactNpmVersion(version)) {
3725
- const verified = await snapshotAndIsolateVendoredPlugin(baseDir, packageName, version);
3726
- if (verified) {
3727
- const restoreRegistration = registerVendorCjsTree(verified);
3294
+ const installRoot = await resolveVendoredPluginInstallRoot(baseDir, packageName, version);
3295
+ if (installRoot) {
3296
+ const packageDir = vendoredNpmPluginPackageDir(installRoot, packageName);
3297
+ let entry;
3728
3298
  try {
3729
- const moduleDir = dirname2(verified.entryPath);
3730
- const packageDir = verified.packages.find((pkg) => pkg.path === verified.receipt.root.packagePath)?.packageDir ?? null;
3731
- const entryPath = verified.entryPath;
3732
- if (verified.format === "commonjs") {
3733
- return {
3734
- module: createRequire(verified.entryPath)(verified.entryPath),
3735
- moduleDir,
3736
- packageDir,
3737
- entryPath
3738
- };
3739
- }
3740
- return {
3741
- module: await import(pathToFileURL(verified.entryPath).href),
3742
- moduleDir,
3743
- packageDir,
3744
- entryPath
3745
- };
3746
- } catch (error2) {
3747
- restoreRegistration();
3748
- throw error2;
3299
+ entry = await resolvePackageEntry(packageDir);
3300
+ } catch (cause) {
3301
+ throw new Error(`the downloaded copy of ${packageName}@${version} under plugins/npm/ is incomplete ` + `(${cause instanceof Error ? cause.message : String(cause)}). ` + `Reinstall it with \`gutterpress ext add ${packageName}@${version}\`.`, { cause });
3749
3302
  }
3303
+ const entryPath = join2(packageDir, ...entry.split("/"));
3304
+ vendoredRootsOpened.add(installRoot);
3305
+ installBunVendoredResolver();
3306
+ return {
3307
+ module: await import(pathToFileURL(entryPath).href),
3308
+ moduleDir: dirname2(entryPath),
3309
+ packageDir,
3310
+ entryPath
3311
+ };
3750
3312
  }
3751
3313
  }
3752
3314
  try {
@@ -3828,11 +3390,6 @@ function ensureExitCleanupRegistered() {
3828
3390
  unlinkSync(shadowPath);
3829
3391
  } catch {}
3830
3392
  }
3831
- if (isolatedVendorBasePath) {
3832
- try {
3833
- rmSync(isolatedVendorBasePath, { recursive: true, force: true });
3834
- } catch {}
3835
- }
3836
3393
  });
3837
3394
  }
3838
3395
  function shadowPathFor(pluginPath, mtimeMs) {
@@ -4066,7 +3623,7 @@ function artifactName(title, format) {
4066
3623
 
4067
3624
  // src/lib/ghostscript.ts
4068
3625
  import { existsSync as existsSync5 } from "node:fs";
4069
- import { readFile as readFile6, writeFile as writeFile3, unlink as unlink2, rename, readdir as readdir3 } from "node:fs/promises";
3626
+ import { readFile as readFile5, writeFile as writeFile2, unlink as unlink2, rename, readdir as readdir3 } from "node:fs/promises";
4070
3627
  import { join as join3, basename as basename2, resolve as resolve4 } from "node:path";
4071
3628
  var WINDOWS_GHOSTSCRIPT_NAMES = ["gswin64c", "gswin32c", "gs"];
4072
3629
  var POSIX_GHOSTSCRIPT_NAMES = ["gs"];
@@ -4168,13 +3725,13 @@ async function stripAnnotations(pdfPath, stagingDir) {
4168
3725
  await unlink2(tmp).catch(() => {});
4169
3726
  }
4170
3727
  const { PDFDocument, PDFName } = await import("pdf-lib");
4171
- const bytes = await readFile6(pdfPath);
3728
+ const bytes = await readFile5(pdfPath);
4172
3729
  const doc = await PDFDocument.load(bytes, { updateMetadata: false });
4173
3730
  const annots = PDFName.of("Annots");
4174
3731
  for (const page of doc.getPages())
4175
3732
  page.node.delete(annots);
4176
3733
  const out = await doc.save();
4177
- await writeFile3(pdfPath, out);
3734
+ await writeFile2(pdfPath, out);
4178
3735
  }
4179
3736
  function makePdfxDefPs(params) {
4180
3737
  const pdfxVersion = params.pdfx === "x3" ? "PDF/X-3:2002" : "PDF/X-1:2001";
@@ -4243,11 +3800,11 @@ ${docInfoConformance}/DOCINFO pdfmark
4243
3800
  }
4244
3801
  async function stampCreator(pdfPath) {
4245
3802
  const { PDFDocument } = await import("pdf-lib");
4246
- const bytes = await readFile6(pdfPath);
3803
+ const bytes = await readFile5(pdfPath);
4247
3804
  const doc = await PDFDocument.load(bytes, { updateMetadata: false });
4248
3805
  doc.setCreator("gutterpress");
4249
3806
  const out = await doc.save();
4250
- await writeFile3(pdfPath, out);
3807
+ await writeFile2(pdfPath, out);
4251
3808
  }
4252
3809
  async function convertToPdfxCmyk(inputPdf, outPdf, config) {
4253
3810
  const iccPath = resolve4(config.iccPath);
@@ -4276,7 +3833,7 @@ async function convertToPdfxCmyk(inputPdf, outPdf, config) {
4276
3833
  inputPdf
4277
3834
  ];
4278
3835
  try {
4279
- await writeFile3(tmpDef, makePdfxDefPs({
3836
+ await writeFile2(tmpDef, makePdfxDefPs({
4280
3837
  iccPath,
4281
3838
  pdfx: config.pdfx,
4282
3839
  title: config.title ?? basename2(outPdf),
@@ -4294,14 +3851,14 @@ async function convertToPdfxCmyk(inputPdf, outPdf, config) {
4294
3851
 
4295
3852
  // src/lib/build-fingerprint.ts
4296
3853
  import * as fs from "node:fs";
4297
- import { mkdir as mkdir3, readFile as readFile7, writeFile as writeFile4 } from "node:fs/promises";
4298
- import { createHash as createHash3 } from "node:crypto";
3854
+ import { mkdir as mkdir2, readFile as readFile6, writeFile as writeFile3 } from "node:fs/promises";
3855
+ import { createHash as createHash2 } from "node:crypto";
4299
3856
  import path5 from "node:path";
4300
3857
  import git from "isomorphic-git";
4301
3858
  // package.json
4302
3859
  var package_default = {
4303
3860
  name: "gutterpress",
4304
- version: "0.11.10-alpha.2",
3861
+ version: "0.11.10-alpha.6",
4305
3862
  description: "Markdown-to-PDF converter for professional print layout using a native Chromium print engine and Ghostscript.",
4306
3863
  author: "itlackey",
4307
3864
  license: "MPL-2.0",
@@ -4361,11 +3918,9 @@ var package_default = {
4361
3918
  node: ">=22.0.0"
4362
3919
  },
4363
3920
  dependencies: {
4364
- acorn: "8.16.0",
4365
3921
  chokidar: "^5.0.0",
4366
3922
  citty: "^0.2.0",
4367
3923
  diff3: "0.0.3",
4368
- "es-module-lexer": "2.0.0",
4369
3924
  fflate: "0.8.3",
4370
3925
  glob: "^13.0.0",
4371
3926
  htmlhint: "^1.9.2",
@@ -4382,7 +3937,6 @@ var package_default = {
4382
3937
  markdownlint: "^0.40.0",
4383
3938
  "pdf-lib": "^1.17.1",
4384
3939
  postcss: "^8.5.18",
4385
- "puppeteer-core": "^25.0.4",
4386
3940
  "resolve.exports": "2.0.3",
4387
3941
  semver: "7.8.0",
4388
3942
  tar: "7.5.20",
@@ -4494,10 +4048,10 @@ async function getEngineBundleHash() {
4494
4048
  getAssetPath("engine/gutterpress-agent.js")
4495
4049
  ]);
4496
4050
  const [viewerBytes, agentBytes] = await Promise.all([
4497
- readFile7(viewerPath),
4498
- readFile7(agentPath)
4051
+ readFile6(viewerPath),
4052
+ readFile6(agentPath)
4499
4053
  ]);
4500
- const hash = createHash3("sha256");
4054
+ const hash = createHash2("sha256");
4501
4055
  hash.update(viewerBytes);
4502
4056
  hash.update(agentBytes);
4503
4057
  return hash.digest("hex").slice(0, 12);
@@ -4517,7 +4071,6 @@ async function getToolVersions() {
4517
4071
  gutterpress: PACKAGE_META.version,
4518
4072
  bun: process.versions.bun ?? null,
4519
4073
  node: process.versions.node,
4520
- "puppeteer-core": PACKAGE_META.dependencies["puppeteer-core"] ?? null,
4521
4074
  engineBundle: engineBundleHash,
4522
4075
  ghostscript: gsVersion,
4523
4076
  qpdf: qpdfVersion,
@@ -4565,8 +4118,8 @@ async function writeBuildFingerprint(input) {
4565
4118
  sourceRevision,
4566
4119
  tools
4567
4120
  };
4568
- await mkdir3(outputDir, { recursive: true });
4569
- await writeFile4(outPath, stableJsonStringify(payload), "utf8");
4121
+ await mkdir2(outputDir, { recursive: true });
4122
+ await writeFile3(outPath, stableJsonStringify(payload), "utf8");
4570
4123
  return outPath;
4571
4124
  }
4572
4125
 
@@ -4575,7 +4128,7 @@ import { existsSync as existsSync10 } from "node:fs";
4575
4128
  import { dirname as dirname4, join as join4, resolve as resolve8 } from "node:path";
4576
4129
 
4577
4130
  // src/lib/markdownlint-fix.ts
4578
- import { readFile as readFile9, writeFile as writeFile5 } from "node:fs/promises";
4131
+ import { readFile as readFile8, writeFile as writeFile4 } from "node:fs/promises";
4579
4132
  import { applyFixes } from "markdownlint";
4580
4133
  import { lint as lint2 } from "markdownlint/sync";
4581
4134
 
@@ -4596,7 +4149,7 @@ function findConfigFile(inputDir, names, explicit) {
4596
4149
  }
4597
4150
 
4598
4151
  // src/checks/source/markdownlint.ts
4599
- import { readFile as readFile8 } from "node:fs/promises";
4152
+ import { readFile as readFile7 } from "node:fs/promises";
4600
4153
  import { lint } from "markdownlint/sync";
4601
4154
  import { parse as parseYaml2 } from "yaml";
4602
4155
 
@@ -4678,7 +4231,7 @@ function stripJsonComments(s) {
4678
4231
  return s.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");
4679
4232
  }
4680
4233
  async function loadConfig(configPath) {
4681
- const raw = await readFile8(configPath, "utf8");
4234
+ const raw = await readFile7(configPath, "utf8");
4682
4235
  let parsed;
4683
4236
  if (configPath.endsWith(".json")) {
4684
4237
  parsed = JSON.parse(raw);
@@ -4775,7 +4328,7 @@ async function applyMarkdownlintFixes(ctx) {
4775
4328
  for (const [file, violations] of Object.entries(results)) {
4776
4329
  if (!Array.isArray(violations) || violations.length === 0)
4777
4330
  continue;
4778
- const before = await readFile9(file, "utf8");
4331
+ const before = await readFile8(file, "utf8");
4779
4332
  const after = applyFixes(before, violations);
4780
4333
  if (after !== before)
4781
4334
  pending.push({ file, content: after });
@@ -4786,7 +4339,7 @@ async function applyMarkdownlintFixes(ctx) {
4786
4339
  }
4787
4340
  const dirty = await uncommittedAmong(ctx.inputDir, pending.map((p) => p.file));
4788
4341
  for (const { file, content } of pending) {
4789
- await writeFile5(file, content, "utf8");
4342
+ await writeFile4(file, content, "utf8");
4790
4343
  }
4791
4344
  log.warn(`--fix: rewrote ${pending.length} file(s):`);
4792
4345
  for (const { file } of pending)
@@ -4900,7 +4453,7 @@ function inspectionFailed(checkId, message, extra = {}) {
4900
4453
  }
4901
4454
 
4902
4455
  // src/lib/pdf-inspect.ts
4903
- import { stat, readFile as readFile10 } from "node:fs/promises";
4456
+ import { stat, readFile as readFile9 } from "node:fs/promises";
4904
4457
  import { getDocumentProxy } from "unpdf";
4905
4458
  import * as pdfjs from "unpdf/pdfjs";
4906
4459
  function getOps(mod) {
@@ -4955,7 +4508,7 @@ async function loadPdf(path6) {
4955
4508
  }
4956
4509
  if (hit)
4957
4510
  destroyEntry(hit);
4958
- const docPromise = readFile10(path6).then((buf) => getDocumentProxy(new Uint8Array(buf)));
4511
+ const docPromise = readFile9(path6).then((buf) => getDocumentProxy(new Uint8Array(buf)));
4959
4512
  docCache.delete(path6);
4960
4513
  docCache.set(path6, { mtimeMs: st.mtimeMs, size: st.size, doc: docPromise });
4961
4514
  evictLru();
@@ -5414,9 +4967,9 @@ var check4 = {
5414
4967
  registerCheck(check4);
5415
4968
 
5416
4969
  // src/lib/pdf-parse.ts
5417
- import { readFile as readFile11 } from "node:fs/promises";
4970
+ import { readFile as readFile10 } from "node:fs/promises";
5418
4971
  async function readPdfBytes(pdfPath) {
5419
- return readFile11(pdfPath, "latin1");
4972
+ return readFile10(pdfPath, "latin1");
5420
4973
  }
5421
4974
  function parseInkCov(out) {
5422
4975
  const lines = out.split(/\r?\n/).filter((l) => l.includes("CMYK"));
@@ -5988,7 +5541,7 @@ registerCheck(check16);
5988
5541
 
5989
5542
  // src/checks/source/htmlhint.ts
5990
5543
  import { existsSync as existsSync7 } from "node:fs";
5991
- import { readFile as readFile12 } from "node:fs/promises";
5544
+ import { readFile as readFile11 } from "node:fs/promises";
5992
5545
  import htmlhint from "htmlhint";
5993
5546
  var { HTMLHint } = htmlhint;
5994
5547
  var CONFIG_NAMES2 = [".htmlhintrc"];
@@ -6008,8 +5561,8 @@ var check17 = {
6008
5561
  const resolvedConfig = findConfigFile(ctx.inputDir, CONFIG_NAMES2, configPath);
6009
5562
  if (!resolvedConfig && !configPath)
6010
5563
  return [];
6011
- const ruleset = resolvedConfig ? JSON.parse(await readFile12(resolvedConfig, "utf8")) : HTMLHint.defaultRuleset;
6012
- const html = await readFile12(ctx.htmlPath, "utf8");
5564
+ const ruleset = resolvedConfig ? JSON.parse(await readFile11(resolvedConfig, "utf8")) : HTMLHint.defaultRuleset;
5565
+ const html = await readFile11(ctx.htmlPath, "utf8");
6013
5566
  const messages = HTMLHint.verify(html, ruleset);
6014
5567
  return messages.map((m) => ({
6015
5568
  checkId: check17.id,
@@ -6024,7 +5577,7 @@ var check17 = {
6024
5577
  registerCheck(check17);
6025
5578
 
6026
5579
  // src/checks/source/stylelint.ts
6027
- import { readFile as readFile13 } from "node:fs/promises";
5580
+ import { readFile as readFile12 } from "node:fs/promises";
6028
5581
 
6029
5582
  // src/lib/printsafe.ts
6030
5583
  import postcss2 from "postcss";
@@ -6300,7 +5853,7 @@ var check18 = {
6300
5853
  for (const file of files) {
6301
5854
  let css;
6302
5855
  try {
6303
- css = await readFile13(file, "utf8");
5856
+ css = await readFile12(file, "utf8");
6304
5857
  } catch (err) {
6305
5858
  results.push({
6306
5859
  checkId: check18.id,
@@ -6327,12 +5880,12 @@ var check18 = {
6327
5880
  registerCheck(check18);
6328
5881
 
6329
5882
  // src/checks/source/css-ownership.ts
6330
- import { readFile as readFile14 } from "node:fs/promises";
5883
+ import { readFile as readFile13 } from "node:fs/promises";
6331
5884
  import postcss3 from "postcss";
6332
5885
  import { parse as parseYaml3 } from "yaml";
6333
5886
  var CONFIG_NAMES3 = [".gutterpress/css-contract.yaml", ".gutterpress/css-contract.yml"];
6334
5887
  async function loadContract(configPath) {
6335
- const raw = await readFile14(configPath, "utf8");
5888
+ const raw = await readFile13(configPath, "utf8");
6336
5889
  const parsed = parseYaml3(raw);
6337
5890
  if (parsed && typeof parsed === "object")
6338
5891
  return parsed;
@@ -6483,7 +6036,7 @@ var check19 = {
6483
6036
  continue;
6484
6037
  let css;
6485
6038
  try {
6486
- css = await readFile14(absFile, "utf8");
6039
+ css = await readFile13(absFile, "utf8");
6487
6040
  } catch {
6488
6041
  continue;
6489
6042
  }
@@ -6529,7 +6082,7 @@ import { existsSync as existsSync8 } from "node:fs";
6529
6082
  import { dirname as dirname3, resolve as resolve6 } from "node:path";
6530
6083
 
6531
6084
  // src/checks/source/local-ref-parser.ts
6532
- import { readFile as readFile15 } from "node:fs/promises";
6085
+ import { readFile as readFile14 } from "node:fs/promises";
6533
6086
  function newlineOffsets(content) {
6534
6087
  const offsets = [];
6535
6088
  for (let i = 0;i < content.length; i++)
@@ -6598,7 +6151,7 @@ async function* renderedLocalRefs(ctx, checkId, results) {
6598
6151
  for (const file of files) {
6599
6152
  let refs;
6600
6153
  try {
6601
- refs = collectRenderedLocalRefs(await readFile15(file, "utf8"));
6154
+ refs = collectRenderedLocalRefs(await readFile14(file, "utf8"));
6602
6155
  } catch {
6603
6156
  results.push(inspectionFailed(checkId, `Could not read source file: ${file}`, { file }));
6604
6157
  continue;
@@ -6665,10 +6218,10 @@ import os from "node:os";
6665
6218
  import fsp from "node:fs/promises";
6666
6219
 
6667
6220
  // src/lib/missing-asset-placeholder.ts
6668
- import { createHash as createHash4 } from "node:crypto";
6221
+ import { createHash as createHash3 } from "node:crypto";
6669
6222
  import { deflateSync } from "node:zlib";
6670
6223
  function placeholderOutputPath(missingOutputPath) {
6671
- const hash = createHash4("sha256").update(missingOutputPath).digest("hex").slice(0, 16);
6224
+ const hash = createHash3("sha256").update(missingOutputPath).digest("hex").slice(0, 16);
6672
6225
  return `assets/gutterpress-missing/${hash}.png`;
6673
6226
  }
6674
6227
  function decodeHtmlAttribute(value) {
@@ -6949,7 +6502,7 @@ var check21 = {
6949
6502
  registerCheck(check21);
6950
6503
 
6951
6504
  // src/checks/source/accessibility-alt-text.ts
6952
- import { readFile as readFile16 } from "node:fs/promises";
6505
+ import { readFile as readFile15 } from "node:fs/promises";
6953
6506
  var check22 = {
6954
6507
  id: "source.accessibility.alt-text",
6955
6508
  name: "Image Alt Text",
@@ -6963,7 +6516,7 @@ var check22 = {
6963
6516
  const results = [];
6964
6517
  for (const file of files) {
6965
6518
  try {
6966
- const content = await readFile16(file, "utf8");
6519
+ const content = await readFile15(file, "utf8");
6967
6520
  const lines = content.split(`
6968
6521
  `);
6969
6522
  let inFence = false;
@@ -7007,7 +6560,7 @@ function extractImageAlts(line) {
7007
6560
  registerCheck(check22);
7008
6561
 
7009
6562
  // src/checks/source/accessibility-heading-order.ts
7010
- import { readFile as readFile17 } from "node:fs/promises";
6563
+ import { readFile as readFile16 } from "node:fs/promises";
7011
6564
  var check23 = {
7012
6565
  id: "source.accessibility.heading-order",
7013
6566
  name: "Heading Order",
@@ -7021,7 +6574,7 @@ var check23 = {
7021
6574
  const results = [];
7022
6575
  for (const file of files) {
7023
6576
  try {
7024
- const content = await readFile17(file, "utf8");
6577
+ const content = await readFile16(file, "utf8");
7025
6578
  const lines = content.split(`
7026
6579
  `);
7027
6580
  let inFence = false;
@@ -7057,7 +6610,7 @@ var check23 = {
7057
6610
  registerCheck(check23);
7058
6611
 
7059
6612
  // src/checks/source/layout-markers.ts
7060
- import { readFile as readFile18 } from "node:fs/promises";
6613
+ import { readFile as readFile17 } from "node:fs/promises";
7061
6614
  var check24 = {
7062
6615
  id: "source.markdown.layout-markers",
7063
6616
  name: "Layout Markers",
@@ -7075,7 +6628,7 @@ var check24 = {
7075
6628
  const md = createMarkdownRenderer(plugins);
7076
6629
  for (const file of files) {
7077
6630
  try {
7078
- const content = await readFile18(file, "utf8");
6631
+ const content = await readFile17(file, "utf8");
7079
6632
  const env = {};
7080
6633
  md.render(content, env);
7081
6634
  for (const w of env.layoutWarnings ?? []) {
@@ -7097,7 +6650,7 @@ var check24 = {
7097
6650
  registerCheck(check24);
7098
6651
 
7099
6652
  // src/checks/source/merge-markers.ts
7100
- import { readFile as readFile19 } from "node:fs/promises";
6653
+ import { readFile as readFile18 } from "node:fs/promises";
7101
6654
  import path7 from "node:path";
7102
6655
 
7103
6656
  // src/checks/asset/extensions.ts
@@ -7139,7 +6692,7 @@ var check25 = {
7139
6692
  for (const file of textFiles) {
7140
6693
  let content;
7141
6694
  try {
7142
- content = await readFile19(file, "utf8");
6695
+ content = await readFile18(file, "utf8");
7143
6696
  } catch {
7144
6697
  results.push(inspectionFailed(check25.id, `Could not read source file: ${file}`, { file }));
7145
6698
  continue;
@@ -7202,7 +6755,7 @@ registerCheck(check25);
7202
6755
  import { stat as stat3 } from "node:fs/promises";
7203
6756
 
7204
6757
  // src/lib/image-inspect.ts
7205
- import { stat as stat2, readFile as readFile20 } from "node:fs/promises";
6758
+ import { stat as stat2, readFile as readFile19 } from "node:fs/promises";
7206
6759
  var DEFAULT_DPI = 72;
7207
6760
  var cache = new Map;
7208
6761
  async function inspectImage(path8) {
@@ -7217,7 +6770,7 @@ async function inspectImage(path8) {
7217
6770
  return hit.info;
7218
6771
  let info2 = null;
7219
6772
  try {
7220
- const buf = await readFile20(path8);
6773
+ const buf = await readFile19(path8);
7221
6774
  info2 = parseImage(buf);
7222
6775
  } catch {
7223
6776
  info2 = null;
@@ -7777,7 +7330,7 @@ var check33 = {
7777
7330
  registerCheck(check33);
7778
7331
 
7779
7332
  // src/checks/heuristic/section-density.ts
7780
- import { readFile as readFile21 } from "node:fs/promises";
7333
+ import { readFile as readFile20 } from "node:fs/promises";
7781
7334
  var check34 = {
7782
7335
  id: "heuristic.chunking.section-density",
7783
7336
  name: "Section Density",
@@ -7794,7 +7347,7 @@ var check34 = {
7794
7347
  const results = [];
7795
7348
  for (const file of files) {
7796
7349
  try {
7797
- const content = await readFile21(file, "utf8");
7350
+ const content = await readFile20(file, "utf8");
7798
7351
  const lines = content.split(`
7799
7352
  `);
7800
7353
  let currentSectionStart = 0;
@@ -8378,12 +7931,9 @@ var INSTALL_HINTS2 = {
8378
7931
  gs: INSTALL_HINTS.gs.body,
8379
7932
  qpdf: INSTALL_HINTS.qpdf.body
8380
7933
  };
8381
- function rendersInPooledChromium(format, opts) {
8382
- return format !== "html" && !opts.engineBrowser;
8383
- }
8384
7934
  async function preflightBuildTools(format, opts, config) {
8385
7935
  const missing = [];
8386
- if (rendersInPooledChromium(format, opts) && !await resolveChromiumExecutable()) {
7936
+ if (format !== "html" && !opts.engineBrowser && !await resolveChromiumExecutable()) {
8387
7937
  await requireChromiumExecutable();
8388
7938
  }
8389
7939
  if (format === "pdfx" && !await resolveGhostscript()) {
@@ -8407,24 +7957,6 @@ ${list}
8407
7957
 
8408
7958
  Install the missing tools and re-run, or set GHOSTSCRIPT_PATH, CHROMIUM_PATH, or system PATH so gutterpress can find them. See the User Guide Chapter 7 (System Setup) at examples/gutterpress-user-guide/07-system-setup.md for the full per-feature matrix.`, 2);
8409
7959
  }
8410
- async function verifyNativeChromiumMilestone() {
8411
- let version;
8412
- try {
8413
- const browser = await getBrowser(RENDER_TIMEOUT_MS);
8414
- version = await browser.version();
8415
- } catch (err) {
8416
- throw new BuildError(`Could not launch a Chromium browser for the PDF build: ` + `${err instanceof Error ? err.message : String(err)}`, 2);
8417
- }
8418
- const milestone = Number(/Chrome\/(\d+)/.exec(version)?.[1] ?? 0);
8419
- if (milestone < REQUIRED_MILESTONE) {
8420
- await closeBrowser();
8421
- throw new BuildError(`The Gutterpress native engine requires Chromium ${REQUIRED_MILESTONE}+; found ${version}.
8422
-
8423
- ` + `Install a newer Chrome, Chromium, or Edge, or point CHROMIUM_PATH ` + `(or PUPPETEER_EXECUTABLE_PATH) at a ${REQUIRED_MILESTONE}+ binary.
8424
-
8425
- ` + `Note: this applies to the CLI's own Chromium only — the desktop app ` + `renders PDFs with its own bundled browser and needs no ` + `separate install.`, 2);
8426
- }
8427
- }
8428
7960
  function computeGates(format, opts, config) {
8429
7961
  if (format === "html") {
8430
7962
  if (opts.skipLint || opts.skipPreValidate || opts.skipPostValidate) {
@@ -8673,7 +8205,9 @@ class HtmlOutput {
8673
8205
  }
8674
8206
 
8675
8207
  class PdfOutput {
8676
- async finish(ctx, htmlFile) {
8208
+ async finish(ctx, htmlFile, browser) {
8209
+ if (!browser)
8210
+ throw new BuildError("PDF build reached the render stage without a browser");
8677
8211
  const { workDir, outDir, inputDir, config, opts, format, manifestDir, gates } = ctx;
8678
8212
  const pdfxMode = format === "pdfx" ? opts.pdfxFlavor ?? config.pdfx.flavor : undefined;
8679
8213
  const pdfName = artifactName(config.title, pdfxMode ? "pdfx" : "pdf");
@@ -8684,13 +8218,13 @@ class PdfOutput {
8684
8218
  const rawPdf = pdfxMode ? path8.join(stage, "raw.pdf") : path8.resolve(pdfFile);
8685
8219
  await fsp2.mkdir(path8.dirname(path8.resolve(pdfFile)), { recursive: true });
8686
8220
  log.info("Rendering HTML to PDF via the Gutterpress engine (native Chromium pagination)");
8687
- const { buildNativePdf } = await import("./engine-trte2tg2.js");
8221
+ const { buildNativePdf } = await import("./engine-3gwctsty.js");
8688
8222
  const engineDiagnostics = await buildNativePdf(htmlFile, rawPdf, {
8689
8223
  title: config.title,
8690
8224
  author: config.authors.length > 0 ? config.authors.join(", ") : undefined,
8691
8225
  signature: config.print.signature,
8692
8226
  allowShrink: opts.allowShrink
8693
- }, opts.engineBrowser);
8227
+ }, browser);
8694
8228
  for (const d of engineDiagnostics)
8695
8229
  log.warn(d.message);
8696
8230
  if (!pdfxMode) {
@@ -8757,28 +8291,34 @@ async function runBuild(opts) {
8757
8291
  if (ctx.format !== "html") {
8758
8292
  await preflightBuildTools(ctx.format, opts, ctx.config);
8759
8293
  }
8760
- if (rendersInPooledChromium(ctx.format, opts))
8761
- prewarmBrowser(RENDER_TIMEOUT_MS);
8294
+ const launch = opts.engineBrowser ?? (async () => (await import("./cdp-jg95s674.js")).launchChromium());
8295
+ const browserPromise = ctx.format === "html" ? null : launch();
8296
+ browserPromise?.catch(() => {});
8762
8297
  try {
8763
8298
  await fsp2.mkdir(ctx.workDir, { recursive: true });
8764
8299
  await runQualityGates(ctx);
8765
- if (rendersInPooledChromium(ctx.format, opts)) {
8766
- await verifyNativeChromiumMilestone();
8300
+ let browser;
8301
+ if (browserPromise) {
8302
+ try {
8303
+ browser = await browserPromise;
8304
+ } catch (err) {
8305
+ throw new BuildError(`Could not launch a Chromium browser for the PDF build: ${err instanceof Error ? err.message : String(err)}`, 2);
8306
+ }
8767
8307
  }
8768
8308
  const htmlFile = await renderBook(ctx);
8769
8309
  const strategy = ctx.format === "html" ? new HtmlOutput : new PdfOutput;
8770
- return await strategy.finish(ctx, htmlFile);
8310
+ return await strategy.finish(ctx, htmlFile, browser);
8771
8311
  } finally {
8772
- if (!opts.keepBrowserAlive)
8773
- await closeBrowser();
8312
+ if (browserPromise)
8313
+ await browserPromise.then((b) => b.close(), () => {});
8774
8314
  await fsp2.rm(ctx.workDir, { recursive: true, force: true });
8775
8315
  }
8776
8316
  }
8777
8317
  // src/preview/lifecycle.ts
8778
8318
  import path10 from "path";
8779
- import { tmpdir as tmpdir2 } from "os";
8319
+ import { tmpdir } from "os";
8780
8320
  import { randomBytes as randomBytes2 } from "crypto";
8781
- import { readdir as readdir4, readFile as readFile22, writeFile as writeFile6 } from "node:fs/promises";
8321
+ import { readdir as readdir4, readFile as readFile21, writeFile as writeFile5 } from "node:fs/promises";
8782
8322
 
8783
8323
  // src/utils/file-utils.ts
8784
8324
  import { promises as fs3 } from "fs";
@@ -8793,7 +8333,7 @@ async function fileExists(filePath) {
8793
8333
  async function remove(targetPath) {
8794
8334
  await fs3.rm(targetPath, { recursive: true, force: true });
8795
8335
  }
8796
- async function mkdir4(dirPath) {
8336
+ async function mkdir3(dirPath) {
8797
8337
  await fs3.mkdir(dirPath, { recursive: true });
8798
8338
  }
8799
8339
 
@@ -8817,9 +8357,6 @@ var EMPTY_BOOK_HTML = `<!doctype html>
8817
8357
  </body>
8818
8358
  </html>
8819
8359
  `;
8820
- function incrementalPreviewEnabled() {
8821
- return process.env.GUTTERPRESS_PREVIEW_INCREMENTAL !== "0";
8822
- }
8823
8360
  async function renderPreviewBook(inputPath, config, opts) {
8824
8361
  const { plugins, pluginStyles } = await loadPluginsWithCss(config.extensions, inputPath, (ref, err) => warn2(`Skipping plugin "${ref}" in preview — ${err.message}`));
8825
8362
  return renderChapters(inputPath, {
@@ -8828,7 +8365,6 @@ async function renderPreviewBook(inputPath, config, opts) {
8828
8365
  files: opts.files,
8829
8366
  plugins,
8830
8367
  pluginStyles,
8831
- wrapChapters: opts.wrapChapters,
8832
8368
  annotateSourceChapters: true,
8833
8369
  ...opts.onCssAssets ? { onCssAssets: opts.onCssAssets } : {},
8834
8370
  onChapterWarnings: (file, warnings) => {
@@ -8838,17 +8374,12 @@ async function renderPreviewBook(inputPath, config, opts) {
8838
8374
  }
8839
8375
  });
8840
8376
  }
8841
- function injectPreviewScripts(html, pageIsolateChapters) {
8377
+ function injectPreviewScripts(html) {
8842
8378
  const scripts = ` <script src="/engine/gutterpress-viewer.js"></script>
8843
8379
  ` + `<script src="/preview/scripts/preview-interface.js"></script>
8844
8380
  ` + `<script src="/preview/scripts/preview-bridge.js"></script>
8845
8381
  `;
8846
- let output = /<\/head>/i.test(html) ? html.replace(/<\/head>/i, scripts + "</head>") : html + scripts;
8847
- if (pageIsolateChapters && /<\/head>/i.test(output)) {
8848
- output = output.replace(/<\/head>/i, `<style>.gutterpress-chapter{break-before:page}</style>
8849
- </head>`);
8850
- }
8851
- return output;
8382
+ return /<\/head>/i.test(html) ? html.replace(/<\/head>/i, scripts + "</head>") : html + scripts;
8852
8383
  }
8853
8384
  async function generateAndWriteHtml(inputPath, tempDir, config, cssAssets) {
8854
8385
  if (!inputPath) {
@@ -8859,7 +8390,6 @@ async function generateAndWriteHtml(inputPath, tempDir, config, cssAssets) {
8859
8390
  const nextAssets = new Map;
8860
8391
  const html = await renderPreviewBook(inputPath, config, {
8861
8392
  files: config.source?.files ?? null,
8862
- wrapChapters: false,
8863
8393
  onCssAssets: (copies) => {
8864
8394
  for (const copy of copies)
8865
8395
  nextAssets.set(copy.to, copy.from);
@@ -8868,39 +8398,7 @@ async function generateAndWriteHtml(inputPath, tempDir, config, cssAssets) {
8868
8398
  cssAssets.clear();
8869
8399
  for (const [to, from] of nextAssets)
8870
8400
  cssAssets.set(to, from);
8871
- await fsp3.writeFile(path9.join(tempDir, BOOK_HTML_FILENAME), injectPreviewScripts(html, false), "utf-8");
8872
- }
8873
- async function renderChapterPreviewHtml(inputPath, file, config) {
8874
- const html = await renderPreviewBook(inputPath, config, {
8875
- files: [canonicalChapterId(file)],
8876
- wrapChapters: true
8877
- });
8878
- return injectPreviewScripts(html, true);
8879
- }
8880
- function describeChanges(changes, inputResolved) {
8881
- const files = [];
8882
- for (const [changedPath, event] of changes) {
8883
- const relative2 = path9.relative(inputResolved, path9.resolve(changedPath));
8884
- if (relative2 === "" || relative2 === ".." || relative2.startsWith(`..${path9.sep}`) || path9.isAbsolute(relative2))
8885
- continue;
8886
- files.push({
8887
- relativePath: canonicalChapterId(relative2),
8888
- ext: path9.extname(changedPath).toLowerCase(),
8889
- event
8890
- });
8891
- }
8892
- return files;
8893
- }
8894
- function decideBroadcast(files, changeCount, incremental) {
8895
- const only = files.length === 1 ? files[0] : null;
8896
- if (incremental && changeCount === 1 && only?.ext === ".md" && only.event !== "unlink" && only.event !== "unlinkDir") {
8897
- return {
8898
- kind: "chapter-splice",
8899
- chapterId: canonicalChapterId(only.relativePath),
8900
- relativePath: only.relativePath
8901
- };
8902
- }
8903
- return { kind: "full-reload" };
8401
+ await fsp3.writeFile(path9.join(tempDir, BOOK_HTML_FILENAME), injectPreviewScripts(html), "utf-8");
8904
8402
  }
8905
8403
  function isDotPathUnderRoot(candidatePath, root) {
8906
8404
  const normalizedRoot = root.replace(/\\/g, "/").replace(/\/+$/, "");
@@ -9216,14 +8714,8 @@ function createFileWatcher(state) {
9216
8714
  await generateAndWriteHtml(inputResolved, state.tempDir, updatedConfig, state.cssAssets);
9217
8715
  if (closed)
9218
8716
  return;
9219
- const decision = decideBroadcast(describeChanges(changes, inputResolved), changes.length, incrementalPreviewEnabled());
9220
- if (decision.kind === "chapter-splice") {
9221
- state.previewServer?.broadcastContentUpdate(decision.chapterId);
9222
- info(`Chapter updated: ${decision.relativePath}`);
9223
- } else {
9224
- state.previewServer?.broadcastReload();
9225
- info(changes.length > 1 ? `Preview updated (${changes.length} files changed — full reload)` : "Preview updated");
9226
- }
8717
+ state.previewServer?.broadcastReload();
8718
+ info(changes.length > 1 ? `Preview updated (${changes.length} files changed)` : "Preview updated");
9227
8719
  } catch (err) {
9228
8720
  error("Failed to regenerate preview:", err);
9229
8721
  } finally {
@@ -9281,7 +8773,7 @@ async function stopFileWatcher(state) {
9281
8773
  }
9282
8774
 
9283
8775
  // src/preview/lifecycle.ts
9284
- var TEMP_DIR_BASE = path10.join(tmpdir2(), "gutterpress-preview");
8776
+ var TEMP_DIR_BASE = path10.join(tmpdir(), "gutterpress-preview");
9285
8777
  var PID_FILE_NAME = ".gutterpress.pid";
9286
8778
  function isProcessAlive(pid) {
9287
8779
  if (!Number.isFinite(pid) || pid <= 0)
@@ -9304,7 +8796,7 @@ async function cleanupOrphanTempDirs() {
9304
8796
  const dir = path10.join(TEMP_DIR_BASE, entry);
9305
8797
  const pidFile = path10.join(dir, PID_FILE_NAME);
9306
8798
  try {
9307
- const raw = await readFile22(pidFile, "utf8");
8799
+ const raw = await readFile21(pidFile, "utf8");
9308
8800
  const pid = parseInt(raw.trim(), 10);
9309
8801
  if (!isProcessAlive(pid)) {
9310
8802
  debug(`Removing orphan temp dir ${dir} (pid ${pid} not alive)`);
@@ -9317,9 +8809,9 @@ async function initializePreviewDirectories() {
9317
8809
  await cleanupOrphanTempDirs();
9318
8810
  const tempDirSuffix = randomBytes2(8).toString("hex");
9319
8811
  const tempDir = path10.join(TEMP_DIR_BASE, tempDirSuffix);
9320
- await mkdir4(tempDir);
8812
+ await mkdir3(tempDir);
9321
8813
  debug(`Created temporary directory: ${tempDir}`);
9322
- await writeFile6(path10.join(tempDir, PID_FILE_NAME), `${process.pid}
8814
+ await writeFile5(path10.join(tempDir, PID_FILE_NAME), `${process.pid}
9323
8815
  `, "utf8");
9324
8816
  return tempDir;
9325
8817
  }
@@ -9409,8 +8901,8 @@ function createServerState(inputPath, tempDir, config, options) {
9409
8901
  // src/preview/http-server.ts
9410
8902
  import http from "node:http";
9411
8903
  import net from "node:net";
9412
- import { createHash as createHash5, randomUUID } from "node:crypto";
9413
- import { readFile as readFile23, stat as stat4 } from "node:fs/promises";
8904
+ import { createHash as createHash4, randomUUID } from "node:crypto";
8905
+ import { readFile as readFile22, stat as stat4 } from "node:fs/promises";
9414
8906
  import path12 from "path";
9415
8907
  import { WebSocket, WebSocketServer } from "ws";
9416
8908
 
@@ -9493,169 +8985,6 @@ function resolveStaticPath(urlPathname, root) {
9493
8985
 
9494
8986
  // src/preview/http-server.ts
9495
8987
  var HMR_PATH = "/__gutterpress-hmr";
9496
- function hmrClientSnippet(initialRevision, instanceId) {
9497
- return `
9498
- <script>
9499
- (function () {
9500
- // When loaded by the preview SHELL (iframe double-buffer), the shell loads us
9501
- // with ?gutterpressshell=1 and owns HMR (it swaps frames + syncs scroll), so we stay
9502
- // inert. We must NOT bail merely because we're framed — other hosts (the
9503
- // Electron desktop's SPA) embed book.html directly and rely on this HMR client
9504
- // for scroll-anchor and reload.
9505
- if (/[?&]gutterpressshell=1/.test(location.search)) return;
9506
- var ANCHOR_KEY = 'gutterpress-scroll-anchor';
9507
- var appliedRevision = ${initialRevision};
9508
- var appliedInstance = ${JSON.stringify(instanceId)};
9509
- var readyToAcknowledge = false;
9510
- var reloadRequested = false;
9511
-
9512
- // Find the element nearest the top of the viewport that carries a source
9513
- // line (markdown-it-source-map emits data-source-line on block elements).
9514
- // We anchor on SOURCE position, not pixels, because page breaks move when
9515
- // content re-paginates.
9516
- function captureAnchor() {
9517
- var els = document.querySelectorAll('[data-source-line]');
9518
- var best = null, bestTop = -Infinity;
9519
- for (var i = 0; i < els.length; i++) {
9520
- var r = els[i].getBoundingClientRect();
9521
- if (r.bottom < 0 || r.height === 0) continue;
9522
- if (r.top <= 80 && r.top > bestTop) { bestTop = r.top; best = els[i]; }
9523
- }
9524
- if (!best) {
9525
- for (var j = 0; j < els.length; j++) {
9526
- var rr = els[j].getBoundingClientRect();
9527
- if (rr.bottom > 0 && rr.height > 0) { best = els[j]; break; }
9528
- }
9529
- }
9530
- if (!best) return null;
9531
- var chapter = best.closest && best.closest('[data-chapter-src]');
9532
- return {
9533
- chapter: chapter ? chapter.getAttribute('data-chapter-src') : null,
9534
- line: best.getAttribute('data-source-line'),
9535
- offset: best.getBoundingClientRect().top
9536
- };
9537
- }
9538
-
9539
- // After a content reload, put the same source line back at the same viewport
9540
- // offset so the author keeps their place (no jump to the top).
9541
- function restoreAnchor() {
9542
- var raw;
9543
- try { raw = sessionStorage.getItem(ANCHOR_KEY); } catch (_) { return; }
9544
- if (!raw) return;
9545
- try { sessionStorage.removeItem(ANCHOR_KEY); } catch (_) {}
9546
- var a; try { a = JSON.parse(raw); } catch (_) { return; }
9547
- var tries = 0;
9548
- (function attempt() {
9549
- var blocks = document.querySelectorAll('[data-source-line]');
9550
- var el = null;
9551
- for (var i = 0; i < blocks.length; i++) {
9552
- var chapter = blocks[i].closest && blocks[i].closest('[data-chapter-src]');
9553
- var chapterId = chapter ? chapter.getAttribute('data-chapter-src') : null;
9554
- if ((!a.chapter || chapterId === a.chapter) &&
9555
- blocks[i].getAttribute('data-source-line') === String(a.line)) {
9556
- el = blocks[i];
9557
- break;
9558
- }
9559
- }
9560
- if (el) {
9561
- window.scrollBy({
9562
- top: el.getBoundingClientRect().top - a.offset,
9563
- behavior: 'instant'
9564
- });
9565
- if (window.previewAPI && typeof window.previewAPI.refresh === 'function') {
9566
- window.previewAPI.refresh();
9567
- }
9568
- return;
9569
- }
9570
- if (tries++ < 240) setTimeout(attempt, 25); // wait for pagination
9571
- })();
9572
- }
9573
- var restored = false;
9574
- function restoreOnce() { if (restored) return; restored = true; restoreAnchor(); }
9575
- function finishInitialRender() {
9576
- restoreOnce();
9577
- readyToAcknowledge = true;
9578
- acknowledge();
9579
- }
9580
- // CRITICAL ordering: when the pagination engine is present it restructures
9581
- // the DOM after load, so restoring the scroll anchor early would target
9582
- // pre-pagination geometry. The Gutterpress engine viewer fires
9583
- // 'gp:layout' when its pagination completes — wait for it. In static
9584
- // mode (no engine) the content is final immediately, so restore right
9585
- // after load.
9586
- var hasEngine = !!document.querySelector('script[src*="/engine/gutterpress-viewer.js"]');
9587
- window.addEventListener('gp:layout', finishInitialRender, { once: true });
9588
- if (!hasEngine) {
9589
- if (document.readyState === 'loading') {
9590
- document.addEventListener('DOMContentLoaded', function () { setTimeout(finishInitialRender, 50); });
9591
- } else {
9592
- setTimeout(finishInitialRender, 50);
9593
- }
9594
- }
9595
- var ws = null;
9596
- var reconnectTimer = null;
9597
- var reconnectDelay = 250;
9598
- var stopped = false;
9599
-
9600
- function acknowledge() {
9601
- if (!readyToAcknowledge || !ws || ws.readyState !== 1) return;
9602
- try {
9603
- ws.send(JSON.stringify({
9604
- type: 'reload-applied',
9605
- instance: appliedInstance,
9606
- revision: appliedRevision
9607
- }));
9608
- } catch (_) {}
9609
- }
9610
-
9611
- function connect() {
9612
- if (stopped) return;
9613
- ws = new WebSocket(location.origin.replace(/^http/, 'ws') + '${HMR_PATH}');
9614
- ws.onopen = function () {
9615
- reconnectDelay = 250;
9616
- acknowledge();
9617
- };
9618
- ws.onmessage = function (e) {
9619
- var msg;
9620
- try { msg = JSON.parse(e.data); } catch (_) { return; }
9621
- if (
9622
- msg.type !== 'reload-state' &&
9623
- msg.type !== 'full-reload' &&
9624
- msg.type !== 'content-update'
9625
- ) return;
9626
- var instance = typeof msg.instance === 'string' ? msg.instance : null;
9627
- var revision = Number(msg.revision);
9628
- if (!instance || !Number.isSafeInteger(revision) || revision < 0) return;
9629
- if (instance === appliedInstance && revision <= appliedRevision) {
9630
- acknowledge();
9631
- return;
9632
- }
9633
- if (reloadRequested) return;
9634
- reloadRequested = true;
9635
- try { var a = captureAnchor(); if (a) sessionStorage.setItem(ANCHOR_KEY, JSON.stringify(a)); } catch (_) {}
9636
- location.reload();
9637
- };
9638
- ws.onclose = function () {
9639
- ws = null;
9640
- if (stopped || reconnectTimer !== null) return;
9641
- reconnectTimer = setTimeout(function () {
9642
- reconnectTimer = null;
9643
- connect();
9644
- }, reconnectDelay);
9645
- reconnectDelay = Math.min(reconnectDelay * 2, 5000);
9646
- };
9647
- ws.onerror = function () { try { ws.close(); } catch (_) {} };
9648
- }
9649
-
9650
- window.addEventListener('beforeunload', function () {
9651
- stopped = true;
9652
- if (reconnectTimer !== null) clearTimeout(reconnectTimer);
9653
- });
9654
- connect();
9655
- })();
9656
- </script>
9657
- `;
9658
- }
9659
8988
  function shellHtml(initialRevision, instanceId) {
9660
8989
  return `<!doctype html>
9661
8990
  <html lang="en"><head><meta charset="utf-8"><title>gutterpress preview</title>
@@ -9708,14 +9037,7 @@ async function findAvailablePort(startPort, host = "127.0.0.1") {
9708
9037
  }
9709
9038
  throw new BuildError(`Could not find an available port on ${host} from ${firstPort} to ${port - 1}; all are already in use. ` + "Stop another preview server or pass --port with an available port.", undefined, { cause: lastBusyError });
9710
9039
  }
9711
- function injectHmrClient(html, revision, instanceId) {
9712
- const snippet = hmrClientSnippet(revision, instanceId);
9713
- const closingBody = html.lastIndexOf("</body>");
9714
- if (closingBody === -1)
9715
- return html + snippet;
9716
- return html.slice(0, closingBody) + snippet + html.slice(closingBody);
9717
- }
9718
- async function serveStatic(absPath, res, cacheControl = "no-store", extraHeaders = {}, hmrRevision = 0, hmrInstance = "") {
9040
+ async function serveStatic(absPath, res, cacheControl = "no-store", extraHeaders = {}) {
9719
9041
  let filePath = absPath;
9720
9042
  try {
9721
9043
  const s = await stat4(filePath);
@@ -9728,7 +9050,7 @@ async function serveStatic(absPath, res, cacheControl = "no-store", extraHeaders
9728
9050
  }
9729
9051
  let data;
9730
9052
  try {
9731
- data = await readFile23(filePath);
9053
+ data = await readFile22(filePath);
9732
9054
  } catch {
9733
9055
  res.writeHead(404);
9734
9056
  res.end("Not Found");
@@ -9736,9 +9058,8 @@ async function serveStatic(absPath, res, cacheControl = "no-store", extraHeaders
9736
9058
  }
9737
9059
  const isHtml = filePath.endsWith(".html") || filePath.endsWith(".htm");
9738
9060
  if (isHtml) {
9739
- const withHmr = injectHmrClient(data.toString("utf-8"), hmrRevision, hmrInstance);
9740
9061
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
9741
- res.end(withHmr);
9062
+ res.end(data);
9742
9063
  return;
9743
9064
  }
9744
9065
  const ct = STATIC_MIME[path12.extname(filePath).toLowerCase()] ?? "application/octet-stream";
@@ -9778,12 +9099,12 @@ async function serveRevalidatedStatic(req, absPath, res, validators) {
9778
9099
  let data;
9779
9100
  if (!validator || validator.stamp !== stamp) {
9780
9101
  try {
9781
- data = await readFile23(absPath);
9102
+ data = await readFile22(absPath);
9782
9103
  } catch {
9783
9104
  await serveStatic(absPath, res);
9784
9105
  return;
9785
9106
  }
9786
- const digest = createHash5("sha256").update(data).digest("base64url");
9107
+ const digest = createHash4("sha256").update(data).digest("base64url");
9787
9108
  validator = { stamp, etag: `"gutterpress-file-${digest}"` };
9788
9109
  validators.set(absPath, validator);
9789
9110
  }
@@ -9813,16 +9134,11 @@ async function createPreviewServer(state, port) {
9813
9134
  const projectAssetValidators = new Map;
9814
9135
  let reloadRevision = 0;
9815
9136
  const clients = new Map;
9816
- function sendRevision(ws, type, file) {
9137
+ function sendRevision(ws, type) {
9817
9138
  if (ws.readyState !== WebSocket.OPEN)
9818
9139
  return;
9819
9140
  try {
9820
- ws.send(JSON.stringify({
9821
- type,
9822
- instance: instanceId,
9823
- revision: reloadRevision,
9824
- ...file ? { file } : {}
9825
- }));
9141
+ ws.send(JSON.stringify({ type, instance: instanceId, revision: reloadRevision }));
9826
9142
  } catch {}
9827
9143
  }
9828
9144
  function waitForAcknowledgement(ws) {
@@ -9912,34 +9228,6 @@ async function createPreviewServer(state, port) {
9912
9228
  res.end("Not Found");
9913
9229
  return;
9914
9230
  }
9915
- if (url.pathname === "/__chapter" && req.method === "GET") {
9916
- const rawFile = url.searchParams.get("file");
9917
- const file = rawFile ? canonicalChapterId(rawFile) : "";
9918
- const revision = Number(url.searchParams.get("revision"));
9919
- const configuredFiles = state.config.source?.files;
9920
- if (!file || !state.currentInputPath || !incrementalPreviewEnabled() || !Number.isSafeInteger(revision) || revision !== reloadRevision || path12.extname(file).toLowerCase() !== ".md" || hasDotSegment(file) || !resolveWithinRoot(file, state.currentInputPath) || Array.isArray(configuredFiles) && configuredFiles.length > 0 && !configuredFiles.some((configured) => canonicalChapterId(configured) === file)) {
9921
- res.writeHead(400);
9922
- res.end("Bad Request");
9923
- return;
9924
- }
9925
- try {
9926
- const html = await renderChapterPreviewHtml(state.currentInputPath, file, state.config);
9927
- if (revision !== reloadRevision) {
9928
- res.writeHead(409);
9929
- res.end("Superseded");
9930
- return;
9931
- }
9932
- res.writeHead(200, {
9933
- "Content-Type": "text/html; charset=utf-8",
9934
- "Cache-Control": "no-store"
9935
- });
9936
- res.end(html);
9937
- } catch (error2) {
9938
- res.writeHead(500);
9939
- res.end(error2 instanceof Error ? error2.message : String(error2));
9940
- }
9941
- return;
9942
- }
9943
9231
  if (matchesEmbedded(url.pathname)) {
9944
9232
  if (req.headers["if-none-match"] === EMBEDDED_ETAG) {
9945
9233
  res.writeHead(304, { ETag: EMBEDDED_ETAG, "Cache-Control": EMBEDDED_CACHE_CONTROL });
@@ -9956,12 +9244,12 @@ async function createPreviewServer(state, port) {
9956
9244
  }
9957
9245
  return;
9958
9246
  }
9959
- if (url.pathname === "/" && incrementalPreviewEnabled()) {
9247
+ if (url.pathname === "/") {
9960
9248
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
9961
9249
  res.end(shellHtml(reloadRevision, instanceId));
9962
9250
  return;
9963
9251
  }
9964
- const pathname = url.pathname === "/" ? "/book.html" : url.pathname;
9252
+ const pathname = url.pathname;
9965
9253
  const cssAssetSource = state.cssAssets.get(pathname.replace(/^\/+/, ""));
9966
9254
  if (cssAssetSource) {
9967
9255
  await serveRevalidatedStatic(req, cssAssetSource, res, projectAssetValidators).catch((err) => {
@@ -9985,7 +9273,7 @@ async function createPreviewServer(state, port) {
9985
9273
  res.end("Not Found");
9986
9274
  return;
9987
9275
  }
9988
- const serve = servingProjectRoot ? serveRevalidatedStatic(req, absPath, res, projectAssetValidators) : serveStatic(absPath, res, "no-store", {}, reloadRevision, instanceId);
9276
+ const serve = servingProjectRoot ? serveRevalidatedStatic(req, absPath, res, projectAssetValidators) : serveStatic(absPath, res);
9989
9277
  await serve.catch((err) => {
9990
9278
  if (!res.headersSent) {
9991
9279
  res.writeHead(500);
@@ -10013,22 +9301,6 @@ async function createPreviewServer(state, port) {
10013
9301
  openPath(serverUrl).catch(() => {});
10014
9302
  }
10015
9303
  let stopped = false;
10016
- const broadcastUpdate = (type, file) => {
10017
- if (stopped)
10018
- return;
10019
- reloadRevision++;
10020
- for (const [ws] of clients) {
10021
- sendRevision(ws, type, file);
10022
- waitForAcknowledgement(ws);
10023
- }
10024
- };
10025
- const updateInFlight = () => {
10026
- for (const client of clients.values()) {
10027
- if (client.acknowledgedRevision < reloadRevision)
10028
- return true;
10029
- }
10030
- return false;
10031
- };
10032
9304
  return {
10033
9305
  port: boundPort,
10034
9306
  async close() {
@@ -10050,13 +9322,13 @@ async function createPreviewServer(state, port) {
10050
9322
  });
10051
9323
  },
10052
9324
  broadcastReload() {
10053
- broadcastUpdate("full-reload");
10054
- },
10055
- broadcastContentUpdate(file) {
10056
- if (updateInFlight())
10057
- broadcastUpdate("full-reload");
10058
- else
10059
- broadcastUpdate("content-update", canonicalChapterId(file));
9325
+ if (stopped)
9326
+ return;
9327
+ reloadRevision++;
9328
+ for (const [ws] of clients) {
9329
+ sendRevision(ws, "full-reload");
9330
+ waitForAcknowledgement(ws);
9331
+ }
10060
9332
  }
10061
9333
  };
10062
9334
  }
@@ -10119,7 +9391,7 @@ async function startPreviewServer(options) {
10119
9391
  import { platform, arch, release } from "node:os";
10120
9392
 
10121
9393
  // src/lib/remote-auth/token-store.ts
10122
- import { chmod, mkdir as mkdir5, readFile as readFile24, rename as rename2, writeFile as writeFile7 } from "node:fs/promises";
9394
+ import { chmod, mkdir as mkdir4, readFile as readFile23, rename as rename2, writeFile as writeFile6 } from "node:fs/promises";
10123
9395
  import os3 from "node:os";
10124
9396
  import path13 from "node:path";
10125
9397
  function credentialHostKey(hostOrUrl) {
@@ -10163,7 +9435,7 @@ class FileTokenStore {
10163
9435
  async read() {
10164
9436
  let raw;
10165
9437
  try {
10166
- raw = await readFile24(this.filePath, "utf8");
9438
+ raw = await readFile23(this.filePath, "utf8");
10167
9439
  } catch (e) {
10168
9440
  if (e?.code === "ENOENT") {
10169
9441
  return { version: 1, credentials: {} };
@@ -10175,7 +9447,7 @@ class FileTokenStore {
10175
9447
  if (parsed && typeof parsed === "object" && parsed.credentials)
10176
9448
  return parsed;
10177
9449
  } catch {
10178
- await writeFile7(`${this.filePath}.corrupt`, raw, {
9450
+ await writeFile6(`${this.filePath}.corrupt`, raw, {
10179
9451
  encoding: "utf8",
10180
9452
  mode: 384
10181
9453
  }).catch(() => {});
@@ -10183,9 +9455,9 @@ class FileTokenStore {
10183
9455
  return { version: 1, credentials: {} };
10184
9456
  }
10185
9457
  async write(data) {
10186
- await mkdir5(path13.dirname(this.filePath), { recursive: true });
9458
+ await mkdir4(path13.dirname(this.filePath), { recursive: true });
10187
9459
  const tmpPath = `${this.filePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
10188
- await writeFile7(tmpPath, JSON.stringify(data, null, 2), {
9460
+ await writeFile6(tmpPath, JSON.stringify(data, null, 2), {
10189
9461
  encoding: "utf8",
10190
9462
  mode: 384
10191
9463
  });
@@ -10363,14 +9635,14 @@ async function getSystemDiagnostics() {
10363
9635
  };
10364
9636
  }
10365
9637
  // src/lib/project-scaffold.ts
10366
- import { access, copyFile, cp as cp2, mkdir as mkdir7, readdir as readdir5, readFile as readFile26, stat as stat5, writeFile as writeFile8 } from "node:fs/promises";
9638
+ import { access, copyFile, cp, mkdir as mkdir6, readdir as readdir5, readFile as readFile25, stat as stat5, writeFile as writeFile7 } from "node:fs/promises";
10367
9639
  import { constants as FS, existsSync as existsSync12 } from "node:fs";
10368
9640
  import path15 from "node:path";
10369
9641
 
10370
9642
  // src/lib/manifest-doc.ts
10371
9643
  import { existsSync as existsSync11 } from "node:fs";
10372
9644
  import { randomUUID as randomUUID2 } from "node:crypto";
10373
- import { mkdir as mkdir6, open, readFile as readFile25, rename as rename3, rm as rm2 } from "node:fs/promises";
9645
+ import { mkdir as mkdir5, open, readFile as readFile24, rename as rename3, rm } from "node:fs/promises";
10374
9646
  import path14 from "node:path";
10375
9647
  import { parseDocument, isSeq, YAMLSeq } from "yaml";
10376
9648
  function resolveManifestPath(projectDir) {
@@ -10381,7 +9653,7 @@ async function loadManifestDoc(projectDir) {
10381
9653
  const file = resolveManifestPath(projectDir);
10382
9654
  let text = "";
10383
9655
  try {
10384
- text = await readFile25(file, "utf8");
9656
+ text = await readFile24(file, "utf8");
10385
9657
  } catch (error2) {
10386
9658
  if (error2.code !== "ENOENT")
10387
9659
  throw error2;
@@ -10390,7 +9662,7 @@ async function loadManifestDoc(projectDir) {
10390
9662
  }
10391
9663
  async function writeManifestDoc(file, doc) {
10392
9664
  const dir = path14.dirname(file);
10393
- await mkdir6(dir, { recursive: true });
9665
+ await mkdir5(dir, { recursive: true });
10394
9666
  const temporary = path14.join(dir, `.${path14.basename(file)}.tmp-${process.pid}-${randomUUID2()}`);
10395
9667
  try {
10396
9668
  const handle = await open(temporary, "wx", 438);
@@ -10407,7 +9679,7 @@ async function writeManifestDoc(file, doc) {
10407
9679
  await directory.close();
10408
9680
  }
10409
9681
  } finally {
10410
- await rm2(temporary, { force: true });
9682
+ await rm(temporary, { force: true });
10411
9683
  }
10412
9684
  }
10413
9685
  function ensureSeq(doc, key) {
@@ -10523,23 +9795,23 @@ async function scaffoldProject(options) {
10523
9795
  const preset = customTemplateDir && options.preset === undefined ? undefined : requirePreset(options.preset, options.customPage);
10524
9796
  const targets = preset ? resolveScaffoldTargets(options.targets, preset) : undefined;
10525
9797
  try {
10526
- await mkdir7(projectDir, { recursive: true });
9798
+ await mkdir6(projectDir, { recursive: true });
10527
9799
  if (customTemplateDir) {
10528
9800
  const entries = await readdir5(customTemplateDir, { withFileTypes: true });
10529
9801
  for (const entry of entries) {
10530
9802
  if (entry.name === ".gutterpress-template.json")
10531
9803
  continue;
10532
- await cp2(path15.join(customTemplateDir, entry.name), path15.join(projectDir, entry.name), { recursive: true });
9804
+ await cp(path15.join(customTemplateDir, entry.name), path15.join(projectDir, entry.name), { recursive: true });
10533
9805
  }
10534
- await mkdir7(path15.join(projectDir, "assets"), { recursive: true });
9806
+ await mkdir6(path15.join(projectDir, "assets"), { recursive: true });
10535
9807
  } else {
10536
9808
  const tplManifest = await getAssetPath(`templates/${template}/manifest.yaml`);
10537
9809
  const tplChapter = await getAssetPath(`templates/${template}/chapter-01.md`);
10538
- await mkdir7(path15.join(projectDir, "assets"), { recursive: true });
9810
+ await mkdir6(path15.join(projectDir, "assets"), { recursive: true });
10539
9811
  await copyFile(tplManifest, path15.join(projectDir, MANIFEST_FILENAMES[0]));
10540
9812
  await copyFile(tplChapter, path15.join(projectDir, "chapter-01.md"));
10541
- await mkdir7(path15.join(projectDir, "styles"), { recursive: true });
10542
- await writeFile8(path15.join(projectDir, "styles", "book.css"), starterOverridesCss(), "utf8");
9813
+ await mkdir6(path15.join(projectDir, "styles"), { recursive: true });
9814
+ await writeFile7(path15.join(projectDir, "styles", "book.css"), starterOverridesCss(), "utf8");
10543
9815
  }
10544
9816
  } catch (e) {
10545
9817
  throw new CreateProjectErrorImpl("scaffold-io", `Could not create the book files: ${e instanceof Error ? e.message : String(e)}`);
@@ -10586,7 +9858,7 @@ async function scaffoldProject(options) {
10586
9858
  let versionHistoryError;
10587
9859
  if (requested === "local-git") {
10588
9860
  try {
10589
- const { providerFor } = await import("./source-provider-7c2ww3bz.js");
9861
+ const { providerFor } = await import("./source-provider-qbthnmqw.js");
10590
9862
  const provider = providerFor({ type: "local-folder", path: projectDir });
10591
9863
  await provider.initVersionHistory({
10592
9864
  projectDir,
@@ -10646,10 +9918,10 @@ async function adoptFolder(options) {
10646
9918
  await fillTemplateFile(path15.join(dir, "chapter-01.md"), { "{{TITLE}}": title }).catch(() => {});
10647
9919
  mdFiles = ["chapter-01.md"];
10648
9920
  }
10649
- await mkdir7(path15.join(dir, "styles"), { recursive: true });
9921
+ await mkdir6(path15.join(dir, "styles"), { recursive: true });
10650
9922
  const bookCssPath = path15.join(dir, "styles", "book.css");
10651
9923
  if (!existsSync12(bookCssPath)) {
10652
- await writeFile8(bookCssPath, starterOverridesCss(), "utf8");
9924
+ await writeFile7(bookCssPath, starterOverridesCss(), "utf8");
10653
9925
  }
10654
9926
  const filesYaml = mdFiles.map((f) => ` - "${escapeYamlScalar(f)}"`).join(`
10655
9927
  `);
@@ -10665,8 +9937,8 @@ ${filesYaml}
10665
9937
  styles:
10666
9938
  - styles/book.css
10667
9939
  `;
10668
- await writeFile8(path15.join(dir, MANIFEST_FILENAMES[0]), manifest, "utf8");
10669
- await mkdir7(path15.join(dir, "assets"), { recursive: true });
9940
+ await writeFile7(path15.join(dir, MANIFEST_FILENAMES[0]), manifest, "utf8");
9941
+ await mkdir6(path15.join(dir, "assets"), { recursive: true });
10670
9942
  await ensureGitignoreHasDist(dir);
10671
9943
  } catch (e) {
10672
9944
  if (e instanceof CreateProjectErrorImpl)
@@ -10678,7 +9950,7 @@ styles:
10678
9950
  let versionHistoryError;
10679
9951
  if (requested === "local-git") {
10680
9952
  try {
10681
- const { providerFor } = await import("./source-provider-7c2ww3bz.js");
9953
+ const { providerFor } = await import("./source-provider-qbthnmqw.js");
10682
9954
  const provider = providerFor({ type: "local-folder", path: dir });
10683
9955
  await provider.initVersionHistory({
10684
9956
  projectDir: dir,
@@ -10705,10 +9977,10 @@ async function ensureGitignoreHasDist(projectDir) {
10705
9977
  const gitignorePath = path15.join(projectDir, ".gitignore");
10706
9978
  let existing = null;
10707
9979
  try {
10708
- existing = await readFile26(gitignorePath, "utf8");
9980
+ existing = await readFile25(gitignorePath, "utf8");
10709
9981
  } catch {}
10710
9982
  if (existing === null) {
10711
- await writeFile8(gitignorePath, `dist/
9983
+ await writeFile7(gitignorePath, `dist/
10712
9984
  `, "utf8");
10713
9985
  return;
10714
9986
  }
@@ -10718,14 +9990,14 @@ async function ensureGitignoreHasDist(projectDir) {
10718
9990
  return;
10719
9991
  const needsLeadingNewline = existing.length > 0 && !existing.endsWith(`
10720
9992
  `);
10721
- await writeFile8(gitignorePath, existing + (needsLeadingNewline ? `
9993
+ await writeFile7(gitignorePath, existing + (needsLeadingNewline ? `
10722
9994
  ` : "") + `dist/
10723
9995
  `, "utf8");
10724
9996
  }
10725
9997
  async function firstSourceFile(manifestPath) {
10726
9998
  let text;
10727
9999
  try {
10728
- text = await readFile26(manifestPath, "utf8");
10000
+ text = await readFile25(manifestPath, "utf8");
10729
10001
  } catch {
10730
10002
  return;
10731
10003
  }
@@ -10737,14 +10009,14 @@ async function firstSourceFile(manifestPath) {
10737
10009
  return m ? m[1].trim() : undefined;
10738
10010
  }
10739
10011
  async function fillTemplateFile(filePath, substitutions) {
10740
- let text = await readFile26(filePath, "utf8");
10012
+ let text = await readFile25(filePath, "utf8");
10741
10013
  for (const [token, value] of Object.entries(substitutions)) {
10742
10014
  text = text.split(token).join(value);
10743
10015
  }
10744
- await writeFile8(filePath, text, "utf8");
10016
+ await writeFile7(filePath, text, "utf8");
10745
10017
  }
10746
10018
  // src/lib/extension-scaffold.ts
10747
- import { access as access2, mkdir as mkdir8, readFile as readFile27, writeFile as writeFile9 } from "node:fs/promises";
10019
+ import { access as access2, mkdir as mkdir7, readFile as readFile26, writeFile as writeFile8 } from "node:fs/promises";
10748
10020
  import { constants as FS2 } from "node:fs";
10749
10021
  import path16 from "node:path";
10750
10022
  var EXTENSION_KINDS = ["plugin", "theme"];
@@ -10856,14 +10128,14 @@ async function scaffoldExtension(options) {
10856
10128
  const entries = TEMPLATE_FILES[kind];
10857
10129
  const written = [];
10858
10130
  try {
10859
- await mkdir8(extensionDir, { recursive: true });
10131
+ await mkdir7(extensionDir, { recursive: true });
10860
10132
  for (const [assetName, relDest] of entries) {
10861
10133
  const src = await getAssetPath(`extension-templates/${kind}/${assetName}`);
10862
10134
  const dest = path16.join(extensionDir, relDest);
10863
- await mkdir8(path16.dirname(dest), { recursive: true });
10864
- const text = await readFile27(src, "utf8");
10135
+ await mkdir7(path16.dirname(dest), { recursive: true });
10136
+ const text = await readFile26(src, "utf8");
10865
10137
  const table = relDest.endsWith(".json") ? jsonSafe : plain;
10866
- await writeFile9(dest, substitute(text, table), "utf8");
10138
+ await writeFile8(dest, substitute(text, table), "utf8");
10867
10139
  written.push(relDest);
10868
10140
  }
10869
10141
  } catch (e) {
@@ -10887,7 +10159,7 @@ function substitute(text, table) {
10887
10159
  return out;
10888
10160
  }
10889
10161
  // src/lib/project-templates.ts
10890
- import { cp as cp3, mkdir as mkdir9, readFile as readFile28, readdir as readdir6, stat as stat6, writeFile as writeFile10 } from "node:fs/promises";
10162
+ import { cp as cp2, mkdir as mkdir8, readFile as readFile27, readdir as readdir6, stat as stat6, writeFile as writeFile9 } from "node:fs/promises";
10891
10163
  import { constants as FS3, existsSync as existsSync13 } from "node:fs";
10892
10164
  import { access as access3 } from "node:fs/promises";
10893
10165
  import path17 from "node:path";
@@ -10899,7 +10171,7 @@ var BUILT_IN_TEMPLATE_IDS = [
10899
10171
  ];
10900
10172
  async function readTemplateChoices(manifestPath) {
10901
10173
  try {
10902
- const text = await readFile28(manifestPath, "utf8");
10174
+ const text = await readFile27(manifestPath, "utf8");
10903
10175
  const doc = parseDocument2(text);
10904
10176
  const out = {};
10905
10177
  const preset = doc.get("preset");
@@ -11022,8 +10294,8 @@ async function reconcileSharedRefs(templateDir, sourceProjectDir, mode) {
11022
10294
  const vendorDir = pickVendorDir(templateDir, base);
11023
10295
  await Promise.all(externalFiles.filter((abs) => existsSync13(abs)).map(async (abs) => {
11024
10296
  const dest = path17.join(templateDir, vendorDir, path17.relative(base, abs));
11025
- await mkdir9(path17.dirname(dest), { recursive: true });
11026
- await cp3(abs, dest, { recursive: true });
10297
+ await mkdir8(path17.dirname(dest), { recursive: true });
10298
+ await cp2(abs, dest, { recursive: true });
11027
10299
  }));
11028
10300
  const bookLocal = (value) => toPosixPath(path17.join(vendorDir, path17.relative(base, path17.resolve(sourceProjectDir, value))));
11029
10301
  const vendoredRefs = [];
@@ -11055,20 +10327,20 @@ async function saveProjectAsTemplate(options) {
11055
10327
  if (exists) {
11056
10328
  throw new Error(`A template named "${name}" already exists. Choose a different name.`);
11057
10329
  }
11058
- await mkdir9(dir, { recursive: true });
10330
+ await mkdir8(dir, { recursive: true });
11059
10331
  const entries = await readdir6(projectDir, { withFileTypes: true });
11060
10332
  for (const entry of entries) {
11061
10333
  if (SKIP_ENTRIES.has(entry.name))
11062
10334
  continue;
11063
10335
  if (entry.name === TEMPLATE_META_FILE)
11064
10336
  continue;
11065
- await cp3(path17.join(projectDir, entry.name), path17.join(dir, entry.name), { recursive: true });
10337
+ await cp2(path17.join(projectDir, entry.name), path17.join(dir, entry.name), { recursive: true });
11066
10338
  }
11067
10339
  const manifestName = MANIFEST_FILENAMES.find((name2) => entries.some((entry) => entry.name === name2));
11068
10340
  const shared = manifestName ? await reconcileSharedRefs(dir, projectDir, options.sharedRefs ?? "vendor") : { vendoredRefs: [], excludedRefs: [] };
11069
10341
  if (manifestName)
11070
10342
  await retokeniseManifest(path17.join(dir, manifestName));
11071
- await writeFile10(path17.join(dir, TEMPLATE_META_FILE), JSON.stringify({ label: name }, null, 2), "utf8");
10343
+ await writeFile9(path17.join(dir, TEMPLATE_META_FILE), JSON.stringify({ label: name }, null, 2), "utf8");
11072
10344
  return {
11073
10345
  id,
11074
10346
  label: name,
@@ -11081,12 +10353,12 @@ async function saveProjectAsTemplate(options) {
11081
10353
  async function retokeniseManifest(manifestPath) {
11082
10354
  let text;
11083
10355
  try {
11084
- text = await readFile28(manifestPath, "utf8");
10356
+ text = await readFile27(manifestPath, "utf8");
11085
10357
  } catch {
11086
10358
  return;
11087
10359
  }
11088
10360
  text = text.replace(/^title:\s*.*$/m, 'title: "{{TITLE}}"').replace(/^(authors:[^\n]*\n[ \t]*-[ \t]*).*$/m, '$1"{{AUTHOR}}"');
11089
- await writeFile10(manifestPath, text, "utf8");
10361
+ await writeFile9(manifestPath, text, "utf8");
11090
10362
  }
11091
10363
  async function listCustomTemplates(templatesRoot) {
11092
10364
  let entries;
@@ -11102,7 +10374,7 @@ async function listCustomTemplates(templatesRoot) {
11102
10374
  const dir = path17.join(templatesRoot, entry.name);
11103
10375
  let label = prettify(entry.name);
11104
10376
  try {
11105
- const meta = JSON.parse(await readFile28(path17.join(dir, TEMPLATE_META_FILE), "utf8"));
10377
+ const meta = JSON.parse(await readFile27(path17.join(dir, TEMPLATE_META_FILE), "utf8"));
11106
10378
  if (typeof meta.label === "string" && meta.label)
11107
10379
  label = meta.label;
11108
10380
  } catch {}
@@ -11128,27 +10400,27 @@ async function importTemplateFromFolder(options) {
11128
10400
  return saveProjectAsTemplate({ projectDir: sourceDir, name, templatesRoot });
11129
10401
  }
11130
10402
  // src/lib/snippets.ts
11131
- import { readdir as readdir7, readFile as readFile31, writeFile as writeFile11, mkdir as mkdir12, rm as rm5 } from "node:fs/promises";
10403
+ import { readdir as readdir7, readFile as readFile30, writeFile as writeFile10, mkdir as mkdir11, rm as rm4 } from "node:fs/promises";
11132
10404
  import path20 from "node:path";
11133
10405
 
11134
10406
  // src/lib/extension-manager.ts
11135
- import { cp as cp4, mkdir as mkdir11, readFile as readFile30, rm as rm4, stat as stat7 } from "node:fs/promises";
10407
+ import { cp as cp3, mkdir as mkdir10, readFile as readFile29, rm as rm3, stat as stat7 } from "node:fs/promises";
11136
10408
  import { existsSync as existsSync14 } from "node:fs";
11137
10409
  import path19 from "node:path";
11138
10410
  import { isSeq as isSeq3, isMap as isMap2, isScalar as isScalar2, YAMLMap, Scalar } from "yaml";
11139
10411
 
11140
10412
  // src/lib/npm-plugin-installer.ts
11141
- import { createHash as createHash6, randomUUID as randomUUID3, timingSafeEqual } from "node:crypto";
10413
+ import { createHash as createHash5, randomUUID as randomUUID3, timingSafeEqual } from "node:crypto";
11142
10414
  import { createReadStream } from "node:fs";
11143
10415
  import {
11144
10416
  lstat,
11145
- mkdir as mkdir10,
11146
- mkdtemp as mkdtemp2,
10417
+ mkdir as mkdir9,
10418
+ mkdtemp,
11147
10419
  open as open2,
11148
- readFile as readFile29,
10420
+ readFile as readFile28,
11149
10421
  realpath,
11150
10422
  rename as rename4,
11151
- rm as rm3
10423
+ rm as rm2
11152
10424
  } from "node:fs/promises";
11153
10425
  import path18 from "node:path";
11154
10426
  import { Transform } from "node:stream";
@@ -11189,6 +10461,25 @@ async function withFetchTimeout(options, run2) {
11189
10461
  }
11190
10462
  }
11191
10463
 
10464
+ // src/lib/npm-registry.ts
10465
+ var DEFAULT_NPM_REGISTRY = "https://registry.npmjs.org";
10466
+ var ENV_OVERRIDE = "GUTTERPRESS_NPM_REGISTRY";
10467
+ function npmRegistryUrl() {
10468
+ const configured = process.env[ENV_OVERRIDE]?.trim();
10469
+ if (!configured)
10470
+ return DEFAULT_NPM_REGISTRY;
10471
+ let scheme;
10472
+ try {
10473
+ scheme = new URL(configured).protocol;
10474
+ } catch {
10475
+ throw new Error(`Invalid ${ENV_OVERRIDE} URL "${configured}".`);
10476
+ }
10477
+ if (scheme !== "http:" && scheme !== "https:") {
10478
+ throw new Error(`${ENV_OVERRIDE} must be an http(s) URL — got "${scheme}".`);
10479
+ }
10480
+ return configured.replace(/\/+$/, "");
10481
+ }
10482
+
11192
10483
  // src/lib/npm-plugin-installer.ts
11193
10484
  var DEFAULT_LIMITS = {
11194
10485
  metadataBytes: 15 * 1024 * 1024,
@@ -11403,7 +10694,7 @@ async function selectPackage(ctx, name, selector) {
11403
10694
  }
11404
10695
  async function downloadTarball(ctx, pkg, archivePath) {
11405
10696
  const file = await open2(archivePath, "wx");
11406
- const hash = createHash6(pkg.integrity.algorithm);
10697
+ const hash = createHash5(pkg.integrity.algorithm);
11407
10698
  try {
11408
10699
  await withFetchTimeout({
11409
10700
  timeoutMs: TARBALL_TIMEOUT_MS,
@@ -11464,7 +10755,7 @@ async function extractTarball(ctx, archivePath, packageDir, packageName) {
11464
10755
  "OldGnuLongPath",
11465
10756
  "OldExtendedHeader"
11466
10757
  ]);
11467
- await mkdir10(packageDir, { recursive: true });
10758
+ await mkdir9(packageDir, { recursive: true });
11468
10759
  const unpack = extract({
11469
10760
  cwd: packageDir,
11470
10761
  strip: 1,
@@ -11543,7 +10834,7 @@ async function readInstalledManifest(packageDir, selected) {
11543
10834
  const info2 = await lstat(packageJsonPath);
11544
10835
  if (!info2.isFile() || info2.isSymbolicLink())
11545
10836
  throw new Error("not a regular file");
11546
- manifest = object2(JSON.parse(await readFile29(packageJsonPath, "utf8")));
10837
+ manifest = object2(JSON.parse(await readFile28(packageJsonPath, "utf8")));
11547
10838
  } catch (error2) {
11548
10839
  throw new SecurityInstallError(`Downloaded ${selected.name}@${selected.version} has no valid package.json (${error2 instanceof Error ? error2.message : String(error2)}).`);
11549
10840
  }
@@ -11552,16 +10843,6 @@ async function readInstalledManifest(packageDir, selected) {
11552
10843
  }
11553
10844
  return manifest;
11554
10845
  }
11555
- async function optionalPackageEntry(packageDir, manifest, condition) {
11556
- try {
11557
- return await resolvePackageEntry(packageDir, manifest, condition);
11558
- } catch (error2) {
11559
- if (error2 instanceof Error && error2.message.includes("no contained JavaScript entry point")) {
11560
- return;
11561
- }
11562
- throw error2;
11563
- }
11564
- }
11565
10846
  function platformAllowed(rule, current) {
11566
10847
  let values;
11567
10848
  if (typeof rule === "string") {
@@ -11586,11 +10867,9 @@ function relativePackagePath(parentPackagePath, name) {
11586
10867
  }
11587
10868
  async function installPackage(ctx, name, selector, parentPackagePath, ancestors, depth, optional) {
11588
10869
  const recordStart = ctx.records.length;
11589
- const skippedStart = ctx.skipped.length;
11590
10870
  const warningsBefore = new Set(ctx.warnings);
11591
10871
  const discardOptionalSubtree = () => {
11592
10872
  ctx.records.splice(recordStart);
11593
- ctx.skipped.splice(skippedStart);
11594
10873
  ctx.warnings = warningsBefore;
11595
10874
  };
11596
10875
  if (depth > ctx.limits.dependencyDepth) {
@@ -11616,39 +10895,35 @@ async function installPackage(ctx, name, selector, parentPackagePath, ancestors,
11616
10895
  const packageDir = path18.join(ctx.stageRoot, ...relativePath.split("/"));
11617
10896
  const archivePath = path18.join(ctx.downloadsDir, `${ctx.archiveCounter++}.tgz`);
11618
10897
  try {
11619
- await mkdir10(path18.dirname(packageDir), { recursive: true });
10898
+ await mkdir9(path18.dirname(packageDir), { recursive: true });
11620
10899
  await downloadTarball(ctx, selected, archivePath);
11621
10900
  await extractTarball(ctx, archivePath, packageDir, selected.name);
11622
10901
  const manifest = await readInstalledManifest(packageDir, selected);
11623
10902
  if (!platformAllowed(manifest.os, process.platform) || !platformAllowed(manifest.cpu, process.arch)) {
11624
10903
  const reason = `${name}@${selected.version} does not support ${process.platform}/${process.arch}`;
11625
10904
  if (optional) {
11626
- await rm3(packageDir, { recursive: true, force: true });
10905
+ await rm2(packageDir, { recursive: true, force: true });
11627
10906
  return { skipped: reason };
11628
10907
  }
11629
10908
  throw new PackageUnavailableError(reason);
11630
10909
  }
11631
- const importEntry = await optionalPackageEntry(packageDir, manifest, "import");
11632
- const requireEntry = await optionalPackageEntry(packageDir, manifest, "require");
11633
- if (parentPackagePath === null && !importEntry && !requireEntry) {
11634
- throw new SecurityInstallError(`${name}@${selected.version} has no JavaScript plugin entry.`);
10910
+ if (parentPackagePath === null) {
10911
+ try {
10912
+ await resolvePackageEntry(packageDir, manifest);
10913
+ } catch (cause) {
10914
+ throw new SecurityInstallError(`${name}@${selected.version} has no JavaScript plugin entry.`, { cause });
10915
+ }
11635
10916
  }
11636
10917
  const record = {
11637
10918
  path: relativePath,
11638
10919
  name,
11639
10920
  version: selected.version,
11640
- tarball: selected.tarball,
11641
- integrity: selected.integrity.label,
11642
- legacySha1: selected.integrity.legacySha1,
11643
- ...importEntry ? { entry: `${relativePath}/${importEntry}` } : {},
11644
- ...requireEntry ? { requireEntry: `${relativePath}/${requireEntry}` } : {},
11645
- dependencies: {},
11646
10921
  packageDir,
11647
10922
  manifest
11648
10923
  };
11649
10924
  ctx.records.push(record);
11650
10925
  if (selected.integrity.legacySha1) {
11651
- ctx.warnings.add(`${name}@${selected.version} is an old npm release with only SHA-1 registry integrity. It was accepted for compatibility and recorded as legacy SHA-1 in the vendor receipt.`);
10926
+ ctx.warnings.add(`${name}@${selected.version} is an old npm release with only SHA-1 registry integrity. It was accepted for compatibility.`);
11652
10927
  }
11653
10928
  const dependencies = stringMap(manifest.dependencies);
11654
10929
  const optionalDependencies = stringMap(manifest.optionalDependencies);
@@ -11668,38 +10943,21 @@ async function installPackage(ctx, name, selector, parentPackagePath, ancestors,
11668
10943
  const child = await installPackage(ctx, dependency, range, relativePath, nextAncestors, depth + 1, false);
11669
10944
  if (!child.path)
11670
10945
  throw new Error(`Required dependency ${dependency} was unexpectedly skipped.`);
11671
- record.dependencies[dependency] = child.path;
11672
10946
  }
11673
10947
  const optionalEntries = Object.entries(optionalDependencies).sort(([a], [b]) => a.localeCompare(b));
11674
10948
  for (const [dependency, range] of optionalEntries) {
11675
- const child = await installPackage(ctx, dependency, range, relativePath, nextAncestors, depth + 1, true);
11676
- if (child.path)
11677
- record.dependencies[dependency] = child.path;
11678
- else if (child.skipped) {
11679
- ctx.skipped.push({ from: relativePath, name: dependency, selector: range, kind: "optional", reason: child.skipped });
11680
- }
11681
- }
11682
- for (const [dependency, range] of Object.entries(peerDependencies)) {
11683
- if (object2(peerMeta[dependency])?.optional === true) {
11684
- ctx.skipped.push({
11685
- from: relativePath,
11686
- name: dependency,
11687
- selector: range,
11688
- kind: "optional-peer",
11689
- reason: "Optional peer dependencies are not auto-installed."
11690
- });
11691
- }
10949
+ await installPackage(ctx, dependency, range, relativePath, nextAncestors, depth + 1, true);
11692
10950
  }
11693
10951
  return { path: relativePath };
11694
10952
  } catch (error2) {
11695
- await rm3(packageDir, { recursive: true, force: true });
10953
+ await rm2(packageDir, { recursive: true, force: true });
11696
10954
  if (optional && isOptionalAvailabilityError(error2)) {
11697
10955
  discardOptionalSubtree();
11698
10956
  return { skipped: error2 instanceof Error ? error2.message : String(error2) };
11699
10957
  }
11700
10958
  throw error2;
11701
10959
  } finally {
11702
- await rm3(archivePath, { force: true });
10960
+ await rm2(archivePath, { force: true });
11703
10961
  }
11704
10962
  }
11705
10963
  async function ensureDirectory(pathname) {
@@ -11711,14 +10969,14 @@ async function ensureDirectory(pathname) {
11711
10969
  } catch (error2) {
11712
10970
  if (error2.code !== "ENOENT")
11713
10971
  throw error2;
11714
- await mkdir10(pathname);
10972
+ await mkdir9(pathname);
11715
10973
  }
11716
10974
  }
11717
10975
  async function prepareVendorParent(projectDir, name) {
11718
10976
  const plugins = path18.join(projectDir, PLUGINS_DIR);
11719
10977
  const npm = path18.join(plugins, VENDORED_NPM_DIR);
11720
10978
  const packageParent = path18.dirname(vendoredNpmPluginRoot(projectDir, name, "0.0.0"));
11721
- await mkdir10(projectDir, { recursive: true });
10979
+ await mkdir9(projectDir, { recursive: true });
11722
10980
  await ensureDirectory(plugins);
11723
10981
  await ensureDirectory(npm);
11724
10982
  await ensureDirectory(packageParent);
@@ -11731,29 +10989,16 @@ async function prepareVendorParent(projectDir, name) {
11731
10989
  }
11732
10990
  return realNpm;
11733
10991
  }
11734
- function publicReceipt(record) {
11735
- return {
11736
- path: record.path,
11737
- name: record.name,
11738
- version: record.version,
11739
- tarball: record.tarball,
11740
- integrity: record.integrity,
11741
- legacySha1: record.legacySha1,
11742
- ...record.entry ? { entry: record.entry } : {},
11743
- ...record.requireEntry ? { requireEntry: record.requireEntry } : {},
11744
- dependencies: record.dependencies
11745
- };
11746
- }
11747
10992
  async function installNpmPlugin(projectDirInput, packageSpec, options = {}) {
11748
10993
  const requestedProjectDir = path18.resolve(projectDirInput);
11749
- await mkdir10(requestedProjectDir, { recursive: true });
10994
+ await mkdir9(requestedProjectDir, { recursive: true });
11750
10995
  const projectDir = await realpath(requestedProjectDir);
11751
10996
  const requested = parseNpmPluginSpec(packageSpec);
11752
10997
  const npmRoot = await prepareVendorParent(projectDir, requested.name);
11753
- const container = await mkdtemp2(path18.join(npmRoot, ".install-"));
10998
+ const container = await mkdtemp(path18.join(npmRoot, ".install-"));
11754
10999
  const stageRoot = path18.join(container, "root");
11755
11000
  const downloadsDir = path18.join(container, "downloads");
11756
- await Promise.all([mkdir10(stageRoot), mkdir10(downloadsDir)]);
11001
+ await Promise.all([mkdir9(stageRoot), mkdir9(downloadsDir)]);
11757
11002
  const ctx = {
11758
11003
  fetch: options.fetch ?? globalThis.fetch,
11759
11004
  signal: options.signal,
@@ -11762,7 +11007,6 @@ async function installNpmPlugin(projectDirInput, packageSpec, options = {}) {
11762
11007
  downloadsDir,
11763
11008
  packuments: new Map,
11764
11009
  records: [],
11765
- skipped: [],
11766
11010
  warnings: new Set,
11767
11011
  totalNetworkBytes: 0,
11768
11012
  totalUnpackedBytes: 0,
@@ -11778,34 +11022,6 @@ async function installNpmPlugin(projectDirInput, packageSpec, options = {}) {
11778
11022
  const rootRecord = ctx.records.find((record) => record.path === rootResult.path);
11779
11023
  if (!rootRecord)
11780
11024
  throw new Error("Root plugin package is missing from the dependency graph.");
11781
- const importEntry = rootRecord.entry ?? rootRecord.requireEntry;
11782
- if (!importEntry)
11783
- throw new Error("Root plugin package has no recorded JavaScript entry.");
11784
- const importFormat = packageEntryFormat(rootRecord.manifest, importEntry);
11785
- const entry = importFormat === "commonjs" ? rootRecord.requireEntry ?? importEntry : importEntry;
11786
- const format = packageEntryFormat(rootRecord.manifest, entry);
11787
- const tree = await computeVendorTreeDigest(stageRoot);
11788
- const receipt = {
11789
- schemaVersion: VENDOR_RECEIPT_VERSION,
11790
- root: {
11791
- name: rootRecord.name,
11792
- version: rootRecord.version,
11793
- packagePath: rootRecord.path,
11794
- entry,
11795
- format
11796
- },
11797
- packages: ctx.records.map(publicReceipt).sort((a, b) => a.path.localeCompare(b.path)),
11798
- skipped: ctx.skipped,
11799
- tree: { algorithm: "sha256", ...tree }
11800
- };
11801
- const receiptFile = await open2(path18.join(stageRoot, VENDOR_RECEIPT_FILE), "wx");
11802
- try {
11803
- await receiptFile.writeFile(`${JSON.stringify(receipt, null, 2)}
11804
- `, "utf8");
11805
- await receiptFile.sync();
11806
- } finally {
11807
- await receiptFile.close();
11808
- }
11809
11025
  finalRoot = vendoredNpmPluginRoot(projectDir, rootRecord.name, rootRecord.version);
11810
11026
  const realFinalParent = await realpath(path18.dirname(finalRoot));
11811
11027
  if (!isContained(projectDir, realFinalParent)) {
@@ -11839,16 +11055,16 @@ async function installNpmPlugin(projectDirInput, packageSpec, options = {}) {
11839
11055
  warnings: [...ctx.warnings]
11840
11056
  };
11841
11057
  } finally {
11842
- await rm3(container, { recursive: true, force: true }).catch(() => {});
11058
+ await rm2(container, { recursive: true, force: true }).catch(() => {});
11843
11059
  }
11844
11060
  }
11845
11061
  async function finalizeNpmPluginInstall(installed) {
11846
11062
  if (installed.backupRoot) {
11847
- await rm3(installed.backupRoot, { recursive: true, force: true });
11063
+ await rm2(installed.backupRoot, { recursive: true, force: true });
11848
11064
  }
11849
11065
  }
11850
11066
  async function rollbackNpmPluginInstall(installed) {
11851
- await rm3(installed.installRoot, { recursive: true, force: true });
11067
+ await rm2(installed.installRoot, { recursive: true, force: true });
11852
11068
  if (installed.backupRoot)
11853
11069
  await rename4(installed.backupRoot, installed.installRoot);
11854
11070
  }
@@ -12147,11 +11363,10 @@ async function removeExtension(projectDir, use) {
12147
11363
  return;
12148
11364
  }
12149
11365
  if (parsed.kind === "npm" && parsed.version) {
12150
- await rm4(vendoredNpmPluginRoot(projectDir, parsed.name, parsed.version), {
11366
+ await rm3(vendoredNpmPluginRoot(projectDir, parsed.name, parsed.version), {
12151
11367
  recursive: true,
12152
11368
  force: true
12153
11369
  });
12154
- clearVendoredPluginResolver(projectDir, parsed.name, parsed.version);
12155
11370
  }
12156
11371
  });
12157
11372
  }
@@ -12233,7 +11448,6 @@ async function addExtensionUnlocked(projectDir, specifier, options) {
12233
11448
  } catch (cause) {
12234
11449
  try {
12235
11450
  await rollbackNpmPluginInstall(installed);
12236
- clearVendoredPluginResolver(projectDir, installed.name, installed.version);
12237
11451
  } catch (rollbackError) {
12238
11452
  throw new Error(`Extension install failed and its previous vendor tree could not be restored: ` + `${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, { cause });
12239
11453
  }
@@ -12275,8 +11489,8 @@ async function addBuiltInStyleSet(projectDir, id) {
12275
11489
  const dest = path19.join(projectDir, EXTENSIONS_DIR, id);
12276
11490
  if (!existsSync14(dest)) {
12277
11491
  const src = path19.join(await getAssetsDir(), "themes", id);
12278
- await mkdir11(path19.dirname(dest), { recursive: true });
12279
- await cp4(src, dest, { recursive: true });
11492
+ await mkdir10(path19.dirname(dest), { recursive: true });
11493
+ await cp3(src, dest, { recursive: true });
12280
11494
  }
12281
11495
  return addExtensionUnlocked(projectDir, `./${EXTENSIONS_DIR}/${id}`, {});
12282
11496
  });
@@ -12315,7 +11529,7 @@ async function readExtensionCss(projectDir, use) {
12315
11529
  throw new Error(`Extension "${use}" declares no stylesheets.`);
12316
11530
  const parts = [];
12317
11531
  for (const sheet of sheets)
12318
- parts.push(await readFile30(sheet, "utf8"));
11532
+ parts.push(await readFile29(sheet, "utf8"));
12319
11533
  return parts.join(`
12320
11534
 
12321
11535
  `);
@@ -12362,7 +11576,7 @@ async function scanSnippetFiles(dir) {
12362
11576
  continue;
12363
11577
  let body = "";
12364
11578
  try {
12365
- body = await readFile31(path20.join(dir, fileName), "utf8");
11579
+ body = await readFile30(path20.join(dir, fileName), "utf8");
12366
11580
  } catch {
12367
11581
  continue;
12368
11582
  }
@@ -12380,7 +11594,7 @@ async function listSnippets(projectDir) {
12380
11594
  return files.map((file) => ({ ...file, source: { kind: "project" } }));
12381
11595
  }
12382
11596
  async function readSnippet(projectDir, fileName) {
12383
- return readFile31(resolveSnippetPath(projectDir, fileName), "utf8");
11597
+ return readFile30(resolveSnippetPath(projectDir, fileName), "utf8");
12384
11598
  }
12385
11599
  async function saveSnippet(projectDir, name, body) {
12386
11600
  const stem = slugify(name);
@@ -12388,12 +11602,12 @@ async function saveSnippet(projectDir, name, body) {
12388
11602
  throw new Error(`Could not derive a filename from "${name}".`);
12389
11603
  const fileName = `${stem}.md`;
12390
11604
  const dir = path20.join(projectDir, SNIPPETS_DIR);
12391
- await mkdir12(dir, { recursive: true });
12392
- await writeFile11(resolveSnippetPath(projectDir, fileName), body, "utf8");
11605
+ await mkdir11(dir, { recursive: true });
11606
+ await writeFile10(resolveSnippetPath(projectDir, fileName), body, "utf8");
12393
11607
  return { name, fileName, variables: extractVariables(body), source: { kind: "project" } };
12394
11608
  }
12395
11609
  async function deleteSnippet(projectDir, fileName) {
12396
- await rm5(resolveSnippetPath(projectDir, fileName), { force: true });
11610
+ await rm4(resolveSnippetPath(projectDir, fileName), { force: true });
12397
11611
  }
12398
11612
  async function listInstalledExtensions(projectDir) {
12399
11613
  const out = [];
@@ -12439,12 +11653,12 @@ async function readExtensionSnippet(projectDir, source, fileName) {
12439
11653
  if (!dir) {
12440
11654
  throw new Error(`Extension "${source.ref}" does not declare a usable snippets folder.`);
12441
11655
  }
12442
- return readFile31(resolveSafeChildFile(dir, fileName), "utf8");
11656
+ return readFile30(resolveSafeChildFile(dir, fileName), "utf8");
12443
11657
  }
12444
11658
  // src/lib/extension-import.ts
12445
11659
  import { existsSync as existsSync15 } from "node:fs";
12446
- import { cp as cp5, mkdir as mkdir13, mkdtemp as mkdtemp3, readFile as readFile32, rm as rm6, writeFile as writeFile12 } from "node:fs/promises";
12447
- import { tmpdir as tmpdir3 } from "node:os";
11660
+ import { cp as cp4, mkdir as mkdir12, mkdtemp as mkdtemp2, readFile as readFile31, rm as rm5, writeFile as writeFile11 } from "node:fs/promises";
11661
+ import { tmpdir as tmpdir2 } from "node:os";
12448
11662
  import path21 from "node:path";
12449
11663
  import { unzipSync } from "fflate";
12450
11664
  var MAX_THEME_ARCHIVE_BYTES = 25 * 1024 * 1024;
@@ -12516,7 +11730,7 @@ async function finalizeExtensionImport(projectDir, sourceDir, relPaths, fallback
12516
11730
  if (!existsSync15(cssPath)) {
12517
11731
  throw new Error("A theme must contain a theme.css file.");
12518
11732
  }
12519
- const css = await readFile32(cssPath, "utf8");
11733
+ const css = await readFile31(cssPath, "utf8");
12520
11734
  const { reject, warnings: printFindings } = classifyThemeCssFindings(checkCss(css, "theme.css"));
12521
11735
  if (reject) {
12522
11736
  throw new Error(`theme.css could not be parsed — ${reject.message}`);
@@ -12544,7 +11758,7 @@ async function finalizeExtensionImport(projectDir, sourceDir, relPaths, fallback
12544
11758
  for (let i = 0;i < extraSheets.length; i++) {
12545
11759
  const rel = extraSheets[i];
12546
11760
  const sheetPath = extraSheetPaths[i];
12547
- const sheetCss = await readFile32(sheetPath, "utf8");
11761
+ const sheetCss = await readFile31(sheetPath, "utf8");
12548
11762
  const { reject: sheetReject, warnings: sheetFindings } = classifyThemeCssFindings(checkCss(sheetCss, rel));
12549
11763
  if (sheetReject) {
12550
11764
  throw new Error(`${rel} could not be parsed — ${sheetReject.message}`);
@@ -12564,8 +11778,8 @@ async function finalizeExtensionImport(projectDir, sourceDir, relPaths, fallback
12564
11778
  }
12565
11779
  const id = await uniqueExtensionId(projectDir, meta.name?.trim() || fallbackName);
12566
11780
  const dest = path21.join(projectDir, EXTENSIONS_DIR, id);
12567
- await mkdir13(path21.dirname(dest), { recursive: true });
12568
- await cp5(sourceDir, dest, { recursive: true });
11781
+ await mkdir12(path21.dirname(dest), { recursive: true });
11782
+ await cp4(sourceDir, dest, { recursive: true });
12569
11783
  await completeLandedManifest(dest, id, meta, metaExists);
12570
11784
  const entry = await addExtension(projectDir, `./${EXTENSIONS_DIR}/${id}`);
12571
11785
  return { entry, warnings };
@@ -12577,14 +11791,14 @@ async function completeLandedManifest(dest, id, meta, metaExists) {
12577
11791
  let pkg = {};
12578
11792
  if (metaExists) {
12579
11793
  try {
12580
- const parsed = JSON.parse(await readFile32(file, "utf8"));
11794
+ const parsed = JSON.parse(await readFile31(file, "utf8"));
12581
11795
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
12582
11796
  pkg = parsed;
12583
11797
  }
12584
11798
  } catch {}
12585
11799
  }
12586
11800
  const gutterpress = pkg.gutterpress && typeof pkg.gutterpress === "object" && !Array.isArray(pkg.gutterpress) ? pkg.gutterpress : {};
12587
- await writeFile12(file, JSON.stringify({
11801
+ await writeFile11(file, JSON.stringify({
12588
11802
  ...pkg,
12589
11803
  name: typeof pkg.name === "string" && pkg.name.trim() ? pkg.name : id,
12590
11804
  gutterpress: { ...gutterpress, styles: ["theme.css"] }
@@ -12631,7 +11845,7 @@ async function importExtensionFromZip(projectDir, archive) {
12631
11845
  throw new Error("No theme.css found in the package. A theme needs a theme.css at the package root or inside a single folder.");
12632
11846
  }
12633
11847
  const prefix = root === "" ? "" : `${root}/`;
12634
- const tmp = await mkdtemp3(path21.join(tmpdir3(), "gutterpress-theme-"));
11848
+ const tmp = await mkdtemp2(path21.join(tmpdir2(), "gutterpress-theme-"));
12635
11849
  try {
12636
11850
  const relPaths = [];
12637
11851
  for (const [name, data] of Object.entries(files)) {
@@ -12648,12 +11862,12 @@ async function importExtensionFromZip(projectDir, archive) {
12648
11862
  throw new Error(`The package contains an unsafe path and was rejected: ${name}`);
12649
11863
  }
12650
11864
  relPaths.push(rel);
12651
- await mkdir13(path21.dirname(dest), { recursive: true });
12652
- await writeFile12(dest, data);
11865
+ await mkdir12(path21.dirname(dest), { recursive: true });
11866
+ await writeFile11(dest, data);
12653
11867
  }
12654
11868
  return await finalizeExtensionImport(projectDir, tmp, relPaths, root || "imported-look");
12655
11869
  } finally {
12656
- await rm6(tmp, { recursive: true, force: true });
11870
+ await rm5(tmp, { recursive: true, force: true });
12657
11871
  }
12658
11872
  }
12659
11873
  async function importExtensionFromCssText(projectDir, css, name) {
@@ -12662,10 +11876,10 @@ async function importExtensionFromCssText(projectDir, css, name) {
12662
11876
  throw new Error(`The CSS could not be parsed — ${reject.message}`);
12663
11877
  }
12664
11878
  const displayName = name.trim() || "Imported theme";
12665
- const tmp = await mkdtemp3(path21.join(tmpdir3(), "gutterpress-theme-"));
11879
+ const tmp = await mkdtemp2(path21.join(tmpdir2(), "gutterpress-theme-"));
12666
11880
  try {
12667
- await writeFile12(path21.join(tmp, "theme.css"), css, "utf8");
12668
- await writeFile12(path21.join(tmp, EXTENSION_MANIFEST_FILENAME), JSON.stringify({ name: slugify(displayName, "look"), gutterpress: { styles: ["theme.css"] } }, null, 2), "utf8");
11881
+ await writeFile11(path21.join(tmp, "theme.css"), css, "utf8");
11882
+ await writeFile11(path21.join(tmp, EXTENSION_MANIFEST_FILENAME), JSON.stringify({ name: slugify(displayName, "look"), gutterpress: { styles: ["theme.css"] } }, null, 2), "utf8");
12669
11883
  const result = await finalizeExtensionImport(projectDir, tmp, ["theme.css", EXTENSION_MANIFEST_FILENAME], displayName);
12670
11884
  result.warnings.unshift({
12671
11885
  code: "no-theme-json",
@@ -12673,17 +11887,17 @@ async function importExtensionFromCssText(projectDir, css, name) {
12673
11887
  });
12674
11888
  return result;
12675
11889
  } finally {
12676
- await rm6(tmp, { recursive: true, force: true });
11890
+ await rm5(tmp, { recursive: true, force: true });
12677
11891
  }
12678
11892
  }
12679
11893
  async function importExtensionFromFile(projectDir, filePath) {
12680
11894
  const ext = path21.extname(filePath).toLowerCase();
12681
11895
  if (ext === ".zip") {
12682
- const buf = await readFile32(filePath);
11896
+ const buf = await readFile31(filePath);
12683
11897
  return importExtensionFromZip(projectDir, new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
12684
11898
  }
12685
11899
  if (ext === ".css") {
12686
- const css = await readFile32(filePath, "utf8");
11900
+ const css = await readFile31(filePath, "utf8");
12687
11901
  return importExtensionFromCssText(projectDir, css, prettify(path21.basename(filePath, ".css")));
12688
11902
  }
12689
11903
  throw new Error("Choose a .zip extension package or a .css stylesheet.");
@@ -12746,9 +11960,9 @@ async function importExtensionFromUrl(projectDir, url) {
12746
11960
  if (!css.trim())
12747
11961
  throw new Error(`Fetched CSS from ${trimmed} was empty.`);
12748
11962
  assertLooksLikeCss(css, trimmed);
12749
- const tmp = await mkdtemp3(path21.join(tmpdir3(), "gutterpress-ext-"));
11963
+ const tmp = await mkdtemp2(path21.join(tmpdir2(), "gutterpress-ext-"));
12750
11964
  try {
12751
- await writeFile12(path21.join(tmp, "theme.css"), css, "utf8");
11965
+ await writeFile11(path21.join(tmp, "theme.css"), css, "utf8");
12752
11966
  const gp = meta.gutterpress && typeof meta.gutterpress === "object" && !Array.isArray(meta.gutterpress) ? meta.gutterpress : {};
12753
11967
  const finalMeta = {
12754
11968
  name: typeof meta.name === "string" && meta.name || slugify(baseName, "look"),
@@ -12760,10 +11974,10 @@ async function importExtensionFromUrl(projectDir, url) {
12760
11974
  preview: typeof gp.preview === "string" ? gp.preview : null
12761
11975
  }
12762
11976
  };
12763
- await writeFile12(path21.join(tmp, EXTENSION_MANIFEST_FILENAME), JSON.stringify(finalMeta, null, 2), "utf8");
11977
+ await writeFile11(path21.join(tmp, EXTENSION_MANIFEST_FILENAME), JSON.stringify(finalMeta, null, 2), "utf8");
12764
11978
  return await finalizeExtensionImport(projectDir, tmp, ["theme.css", EXTENSION_MANIFEST_FILENAME], baseName);
12765
11979
  } finally {
12766
- await rm6(tmp, { recursive: true, force: true });
11980
+ await rm5(tmp, { recursive: true, force: true });
12767
11981
  }
12768
11982
  }
12769
11983
  // src/lib/extension-search.ts
@@ -13572,7 +12786,7 @@ async function listGitHubBranches(credential, owner, repo, options = {}) {
13572
12786
  return branches;
13573
12787
  }
13574
12788
  // src/lib/remote-auth/clone.ts
13575
- import { mkdir as mkdir14, readdir as readdir8, rm as rm7 } from "node:fs/promises";
12789
+ import { mkdir as mkdir13, readdir as readdir8, rm as rm6 } from "node:fs/promises";
13576
12790
  import path22 from "node:path";
13577
12791
  import git3 from "isomorphic-git";
13578
12792
 
@@ -13924,7 +13138,7 @@ async function cloneRepository(options) {
13924
13138
  return withRepoLock(dir, async () => {
13925
13139
  await assertCloneTarget(dir);
13926
13140
  const dirExistedBefore = gitFs.existsSync(dir);
13927
- await mkdir14(dir, { recursive: true });
13141
+ await mkdir13(dir, { recursive: true });
13928
13142
  try {
13929
13143
  await git3.clone({
13930
13144
  fs: gitFs,
@@ -13947,7 +13161,7 @@ async function cloneRepository(options) {
13947
13161
  const friendly = friendlyCloneError(e);
13948
13162
  if (!dirExistedBefore) {
13949
13163
  try {
13950
- await rm7(dir, { recursive: true, force: true });
13164
+ await rm6(dir, { recursive: true, force: true });
13951
13165
  } catch {
13952
13166
  throw new Error(`${friendly.message} A partial download was left at ${dir} — delete that folder before trying again.`, { cause: e });
13953
13167
  }
@@ -14217,7 +13431,7 @@ import git6 from "isomorphic-git";
14217
13431
  import { randomUUID as randomUUID4 } from "node:crypto";
14218
13432
 
14219
13433
  // src/lib/remote-auth/converge-merge.ts
14220
- import { mkdir as mkdir15, unlink as unlink3, writeFile as writeFile13 } from "node:fs/promises";
13434
+ import { mkdir as mkdir14, unlink as unlink3, writeFile as writeFile12 } from "node:fs/promises";
14221
13435
  import path23 from "node:path";
14222
13436
  import git5 from "isomorphic-git";
14223
13437
  import diff3Merge from "diff3";
@@ -14261,8 +13475,8 @@ async function readBlob(dir, cache2, oid, filepath) {
14261
13475
  }
14262
13476
  async function writeTreeFile(dir, filepath, content) {
14263
13477
  const abs = path23.join(dir, filepath);
14264
- await mkdir15(path23.dirname(abs), { recursive: true });
14265
- await writeFile13(abs, content);
13478
+ await mkdir14(path23.dirname(abs), { recursive: true });
13479
+ await writeFile12(abs, content);
14266
13480
  }
14267
13481
  async function bothAddedPaths(dir, cache2, ourTip, theirTip, allowUnrelated) {
14268
13482
  const bases = await git5.findMergeBase({ fs: gitFs, dir, cache: cache2, oids: [ourTip, theirTip] });
@@ -14714,18 +13928,18 @@ async function refreshRemoteCopies(options) {
14714
13928
  }
14715
13929
  // src/lib/remote-auth/repair.ts
14716
13930
  import git7 from "isomorphic-git";
14717
- import { cp as cp6, mkdir as mkdir16, rename as rename5, rm as rm8 } from "node:fs/promises";
13931
+ import { cp as cp5, mkdir as mkdir15, rename as rename5, rm as rm7 } from "node:fs/promises";
14718
13932
  import path24 from "node:path";
14719
13933
  var REPAIR_SNAPSHOT_MESSAGE = "Repaired online backup";
14720
13934
  async function moveDir(from, to) {
14721
- await mkdir16(path24.dirname(to), { recursive: true });
13935
+ await mkdir15(path24.dirname(to), { recursive: true });
14722
13936
  try {
14723
13937
  await rename5(from, to);
14724
13938
  } catch (e) {
14725
13939
  if (e.code !== "EXDEV")
14726
13940
  throw e;
14727
- await cp6(from, to, { recursive: true });
14728
- await rm8(from, { recursive: true, force: true });
13941
+ await cp5(from, to, { recursive: true });
13942
+ await rm7(from, { recursive: true, force: true });
14729
13943
  }
14730
13944
  }
14731
13945
  async function repairOnlineBackup(options) {
@@ -14756,11 +13970,11 @@ async function repairOnlineBackup(options) {
14756
13970
  try {
14757
13971
  await moveDir(path24.join(freshDir, ".git"), oldGit);
14758
13972
  } catch (e) {
14759
- await rm8(oldGit, { recursive: true, force: true });
13973
+ await rm7(oldGit, { recursive: true, force: true });
14760
13974
  await moveDir(movedGitTo, oldGit);
14761
13975
  throw e;
14762
13976
  }
14763
- await rm8(freshDir, { recursive: true, force: true });
13977
+ await rm7(freshDir, { recursive: true, force: true });
14764
13978
  const ref = fresh.branch ?? "HEAD";
14765
13979
  let missing = [];
14766
13980
  try {
@@ -14795,11 +14009,11 @@ async function repairOnlineBackup(options) {
14795
14009
  }
14796
14010
  // src/lib/remote-auth/scorched-earth.ts
14797
14011
  import git8 from "isomorphic-git";
14798
- import { cp as cp7, mkdir as mkdir17, readdir as readdir9, rm as rm9 } from "node:fs/promises";
14012
+ import { cp as cp6, mkdir as mkdir16, readdir as readdir9, rm as rm8 } from "node:fs/promises";
14799
14013
  import path25 from "node:path";
14800
14014
  async function emptyDir(dir) {
14801
14015
  for (const entry of await readdir9(dir)) {
14802
- await rm9(path25.join(dir, entry), { recursive: true, force: true });
14016
+ await rm8(path25.join(dir, entry), { recursive: true, force: true });
14803
14017
  }
14804
14018
  }
14805
14019
  async function copyFilesBack(from, to) {
@@ -14808,7 +14022,7 @@ async function copyFilesBack(from, to) {
14808
14022
  const src = path25.join(from, entry);
14809
14023
  if (src === skip)
14810
14024
  continue;
14811
- await cp7(src, path25.join(to, entry), { recursive: true, force: true });
14025
+ await cp6(src, path25.join(to, entry), { recursive: true, force: true });
14812
14026
  }
14813
14027
  }
14814
14028
  async function scorchedEarth(options) {
@@ -14825,8 +14039,8 @@ async function scorchedEarth(options) {
14825
14039
  branch2 = undefined;
14826
14040
  }
14827
14041
  logger.info("backup", "copying folder", { to: backupDir });
14828
- await mkdir17(backupDir, { recursive: true });
14829
- await cp7(dir, backupDir, { recursive: true });
14042
+ await mkdir16(backupDir, { recursive: true });
14043
+ await cp6(dir, backupDir, { recursive: true });
14830
14044
  logger.info("delete", "emptying folder", { dir });
14831
14045
  await emptyDir(dir);
14832
14046
  return { transport: transport2, branch: branch2 };
@@ -14845,7 +14059,7 @@ async function scorchedEarth(options) {
14845
14059
  } catch (e) {
14846
14060
  logger.warn("download", "failed — restoring the folder from the backup", errorLogData(e));
14847
14061
  await emptyDir(dir);
14848
- await cp7(backupDir, dir, { recursive: true });
14062
+ await cp6(backupDir, dir, { recursive: true });
14849
14063
  throw e;
14850
14064
  }
14851
14065
  await withRepoLock(dir, () => copyFilesBack(backupDir, dir));
@@ -15007,11 +14221,11 @@ ${tail}` : ""}`);
15007
14221
  };
15008
14222
 
15009
14223
  // src/lib/publish/providers/guided.ts
15010
- import { copyFile as copyFile2, mkdir as mkdir18, writeFile as writeFile14 } from "node:fs/promises";
14224
+ import { copyFile as copyFile2, mkdir as mkdir17, writeFile as writeFile13 } from "node:fs/promises";
15011
14225
  import path26 from "node:path";
15012
14226
  async function stageGuidedPackage(req, providerId, listingLines) {
15013
14227
  const packageDir = path26.join(path26.dirname(req.artifact.path), "publish", providerId);
15014
- await mkdir18(packageDir, { recursive: true });
14228
+ await mkdir17(packageDir, { recursive: true });
15015
14229
  await copyFile2(req.artifact.path, path26.join(packageDir, path26.basename(req.artifact.path)));
15016
14230
  const { title, authors } = req.project;
15017
14231
  const sheet = [
@@ -15025,7 +14239,7 @@ async function stageGuidedPackage(req, providerId, listingLines) {
15025
14239
  ""
15026
14240
  ].join(`
15027
14241
  `);
15028
- await writeFile14(path26.join(packageDir, "LISTING.md"), sheet, "utf8");
14242
+ await writeFile13(path26.join(packageDir, "LISTING.md"), sheet, "utf8");
15029
14243
  return packageDir;
15030
14244
  }
15031
14245
 
@@ -15088,8 +14302,8 @@ var drivethrurpgProvider = {
15088
14302
  };
15089
14303
 
15090
14304
  // src/lib/publish/providers/gdrive.ts
15091
- import { mkdtemp as mkdtemp4, readFile as readFile33, readdir as readdir10, rm as rm10, stat as stat9, writeFile as writeFile15 } from "node:fs/promises";
15092
- import { tmpdir as tmpdir4 } from "node:os";
14305
+ import { mkdtemp as mkdtemp3, readFile as readFile32, readdir as readdir10, rm as rm9, stat as stat9, writeFile as writeFile14 } from "node:fs/promises";
14306
+ import { tmpdir as tmpdir3 } from "node:os";
15093
14307
  import path27 from "node:path";
15094
14308
  import { Zip, ZipDeflate } from "fflate";
15095
14309
 
@@ -15480,12 +14694,12 @@ async function collectZipEntries(root, dir, out, onWarn) {
15480
14694
  await collectZipEntries(root, full, out, onWarn);
15481
14695
  } else if (entry.isFile()) {
15482
14696
  const rel = path27.relative(root, full).split(path27.sep).join("/");
15483
- out[rel] = await readFile33(full);
14697
+ out[rel] = await readFile32(full);
15484
14698
  } else if (entry.isSymbolicLink()) {
15485
14699
  const resolved = await stat9(full).catch(() => null);
15486
14700
  if (resolved?.isFile()) {
15487
14701
  const rel = path27.relative(root, full).split(path27.sep).join("/");
15488
- out[rel] = await readFile33(full);
14702
+ out[rel] = await readFile32(full);
15489
14703
  } else if (resolved?.isDirectory()) {
15490
14704
  await collectZipEntries(root, full, out, onWarn);
15491
14705
  } else {
@@ -15496,11 +14710,11 @@ async function collectZipEntries(root, dir, out, onWarn) {
15496
14710
  }
15497
14711
  }
15498
14712
  }
15499
- async function zipHtmlExport(exportDir, title, onWarn, writeArchiveImpl = writeFile15) {
14713
+ async function zipHtmlExport(exportDir, title, onWarn, writeArchiveImpl = writeFile14) {
15500
14714
  const entries = {};
15501
14715
  await collectZipEntries(exportDir, exportDir, entries, onWarn);
15502
14716
  const fileName = `${bookSlug(title)}-website.zip`;
15503
- const tmpRoot = await mkdtemp4(path27.join(tmpdir4(), "gutterpress-gdrive-"));
14717
+ const tmpRoot = await mkdtemp3(path27.join(tmpdir3(), "gutterpress-gdrive-"));
15504
14718
  try {
15505
14719
  const filePath = path27.join(tmpRoot, fileName);
15506
14720
  const zipped = await zipEntriesNonBlocking(entries, { level: 6 });
@@ -15509,10 +14723,10 @@ async function zipHtmlExport(exportDir, title, onWarn, writeArchiveImpl = writeF
15509
14723
  filePath,
15510
14724
  fileName,
15511
14725
  mimeType: "application/zip",
15512
- cleanup: () => rm10(tmpRoot, { recursive: true, force: true })
14726
+ cleanup: () => rm9(tmpRoot, { recursive: true, force: true })
15513
14727
  };
15514
14728
  } catch (e) {
15515
- await rm10(tmpRoot, { recursive: true, force: true }).catch(() => {});
14729
+ await rm9(tmpRoot, { recursive: true, force: true }).catch(() => {});
15516
14730
  throw e;
15517
14731
  }
15518
14732
  }
@@ -15600,7 +14814,7 @@ var gdriveProvider = {
15600
14814
  };
15601
14815
 
15602
14816
  // src/lib/publish/butler.ts
15603
- import { chmod as chmod2, mkdir as mkdir19, stat as stat10, writeFile as writeFile16 } from "node:fs/promises";
14817
+ import { chmod as chmod2, mkdir as mkdir18, stat as stat10, writeFile as writeFile15 } from "node:fs/promises";
15604
14818
  import path28 from "node:path";
15605
14819
  import { unzipSync as unzipSync2 } from "fflate";
15606
14820
  var BUTLER_DOWNLOAD_TIMEOUT_MS = 300000;
@@ -15661,13 +14875,13 @@ async function ensureButler(deps) {
15661
14875
  return new Uint8Array(await response.arrayBuffer());
15662
14876
  });
15663
14877
  const files = unzipSync2(archive);
15664
- await mkdir19(cacheDir, { recursive: true });
14878
+ await mkdir18(cacheDir, { recursive: true });
15665
14879
  let foundBinary = false;
15666
14880
  for (const [name, data] of Object.entries(files)) {
15667
14881
  if (name.endsWith("/"))
15668
14882
  continue;
15669
14883
  const target = path28.join(cacheDir, path28.basename(name));
15670
- await writeFile16(target, data);
14884
+ await writeFile15(target, data);
15671
14885
  if (path28.basename(name) === butlerBinaryName()) {
15672
14886
  await chmod2(target, 493).catch(() => {});
15673
14887
  foundBinary = true;
@@ -15864,7 +15078,7 @@ var kdpProvider = {
15864
15078
  };
15865
15079
 
15866
15080
  // src/lib/publish/providers/local-folder.ts
15867
- import { cp as cp8, mkdir as mkdir20, stat as stat11 } from "node:fs/promises";
15081
+ import { cp as cp7, mkdir as mkdir19, stat as stat11 } from "node:fs/promises";
15868
15082
  import path29 from "node:path";
15869
15083
  var LOCAL_PUBLISH_DEFAULT_DIR = "dist";
15870
15084
  var info7 = {
@@ -15902,10 +15116,10 @@ var localFolderProvider = {
15902
15116
  },
15903
15117
  async upload(req) {
15904
15118
  const dir = localPublishDir(req);
15905
- await mkdir20(dir, { recursive: true });
15119
+ await mkdir19(dir, { recursive: true });
15906
15120
  const dest = req.artifact.format === "html" ? dir : path29.join(dir, path29.basename(req.artifact.path));
15907
15121
  if (path29.resolve(dest) !== path29.resolve(req.artifact.path)) {
15908
- await cp8(req.artifact.path, dest, { recursive: true });
15122
+ await cp7(req.artifact.path, dest, { recursive: true });
15909
15123
  }
15910
15124
  return { kind: "published", detail: `Saved to ${dest}` };
15911
15125
  }
@@ -16351,7 +15565,7 @@ async function disconnectPublishCredential(key, deps, options = {}) {
16351
15565
  }
16352
15566
  }
16353
15567
  // src/lib/publish/selections.ts
16354
- import { chmod as chmod3, mkdir as mkdir21, readFile as readFile34, writeFile as writeFile17 } from "node:fs/promises";
15568
+ import { chmod as chmod3, mkdir as mkdir20, readFile as readFile33, writeFile as writeFile16 } from "node:fs/promises";
16355
15569
  import path31 from "node:path";
16356
15570
  class PublishSelectionsStore {
16357
15571
  filePath;
@@ -16361,7 +15575,7 @@ class PublishSelectionsStore {
16361
15575
  }
16362
15576
  async read() {
16363
15577
  try {
16364
- const raw = await readFile34(this.filePath, "utf8");
15578
+ const raw = await readFile33(this.filePath, "utf8");
16365
15579
  const parsed = JSON.parse(raw);
16366
15580
  if (parsed && typeof parsed === "object") {
16367
15581
  return {
@@ -16374,8 +15588,8 @@ class PublishSelectionsStore {
16374
15588
  return { version: 1, global: {}, projects: {} };
16375
15589
  }
16376
15590
  async write(data) {
16377
- await mkdir21(path31.dirname(this.filePath), { recursive: true });
16378
- await writeFile17(this.filePath, JSON.stringify(data, null, 2), {
15591
+ await mkdir20(path31.dirname(this.filePath), { recursive: true });
15592
+ await writeFile16(this.filePath, JSON.stringify(data, null, 2), {
16379
15593
  encoding: "utf8",
16380
15594
  mode: 384
16381
15595
  });
@@ -16477,4 +15691,4 @@ async function setPublishProviderConfig(projectDir, providerId, values) {
16477
15691
  await writeManifestDoc(file, doc);
16478
15692
  return settingsFromDoc(doc);
16479
15693
  }
16480
- export { BUNDLED_EXTENSIONS, isBundledExtension, isPathSpecifier, parseExtensionSpecifier, PRESET_IDS, PRESETS, TARGETS, TARGET_IDS, publishTargetFor, MANIFEST_FILENAMES, hasProjectManifest, loadManifest, loadManifestWithPath, resolveConfig, SYNC_SNAPSHOT_MESSAGE, log, resolveActiveStyles, listProjectStyles, EXTENSION_MANIFEST_FILENAME, readExtensionMeta, extensionStyleList, extensionEntry, extensionCarries, pathEscapesFolder, assertExtensionContained, resolveExtension, loadPluginsWithCss, getChecks, getCheckById, resolveCheckSelectors, formatReport, ruleRemoteUrls, ruleRiskyProps, ruleSyntax, rulePageContainment, checkCss, inspectImage, runChecks, checkToolAvailability, reportMissingTools, executeValidation, executeAndReport, splitOutPath, runBuild, openPath, startPreviewServer, defaultConfigDir, FileTokenStore, extractUrlCredential, getSystemDiagnostics, slugifyProjectName, escapeYamlScalar, scaffoldProject, adoptFolder, ensureGitignoreHasDist, EXTENSION_KINDS, RESERVED_PREFIX, resolveExtensionPrefix, scaffoldExtension, BUILT_IN_TEMPLATE_IDS, listBuiltInTemplates, saveProjectAsTemplate, listCustomTemplates, importTemplateFromFolder, EXTENSIONS_DIR, RECOMMENDED_EXTENSIONS, BUILT_IN_STYLE_SET_IDS, sameExtension, listProjectExtensions, describeExtension, setExtensionEnabled, reorderExtensions, removeExtension, addExtension, listBuiltInStyleSets, addBuiltInStyleSet, validateProjectExtensions, readExtensionCss, SNIPPETS_DIR, extractVariables, substituteVariables, listSnippets, readSnippet, saveSnippet, deleteSnippet, listMergedSnippets, readExtensionSnippet, importExtensionFromFile, importExtensionFromUrl, MAX_SEARCH_BYTES, SEARCH_KEYWORDS, searchNpmExtensions, setManifestFields, readManifestFields, setActiveStyles, AUTO_SNAPSHOT_DEFAULT_MINUTES, AUTO_SYNC_MIN_MINUTES, AUTO_SYNC_MAX_MINUTES, AUTO_SYNC_DEFAULT_MINUTES, AUTO_SYNC_PUSH_INTERVAL_MINUTES, autoSnapshotDelayMs, autoSyncDelayMs, isGitInternalPath, resolveGitHubClientId, GITHUB_HOST, GitHubAuthProvider, GDRIVE_HOST, resolveGoogleClientId, resolveGoogleClientSecret, GOOGLE_NOT_CONFIGURED_MESSAGE, requireGoogleClientCredentials, pkceChallengeFromVerifier, GoogleAuthProvider, revokeGoogleCredential, publishCredentialKey, publishConnectionStatus, listPublishAccounts, connectGoogleDrive, listGitHubRepositories, listRepoBooks, listGitHubBranches, sanitizeCloneFolderName, cloneRepository, isSshRemoteUrl, testRemoteAccess, knownForgeTokenUrl, connectGenericHost, parseRemoteOrigin, forgeKindForHost, diagnoseProjectRemote, syncProject, refreshRemoteCopies, REPAIR_SNAPSHOT_MESSAGE, repairOnlineBackup, scorchedEarth, listPublishProviders, publishProviderFor, resolvePublishFormat, resolvePublishRequest, runPublish, connectPublishProvider, disconnectPublishCredential, PublishSelectionsStore, readPublishSettings, setPublishProviderConfig };
15694
+ export { BUNDLED_EXTENSIONS, isBundledExtension, isPathSpecifier, parseExtensionSpecifier, PRESET_IDS, PRESETS, TARGETS, TARGET_IDS, publishTargetFor, MANIFEST_FILENAMES, hasProjectManifest, loadManifest, loadManifestWithPath, resolveConfig, SYNC_SNAPSHOT_MESSAGE, log, resolveActiveStyles, listProjectStyles, EXTENSION_MANIFEST_FILENAME, readExtensionMeta, extensionStyleList, extensionEntry, extensionCarries, pathEscapesFolder, assertExtensionContained, resolveExtension, getChecks, getCheckById, resolveCheckSelectors, formatReport, ruleRemoteUrls, ruleRiskyProps, ruleSyntax, checkCss, inspectImage, runChecks, checkToolAvailability, reportMissingTools, executeValidation, executeAndReport, splitOutPath, runBuild, openPath, startPreviewServer, defaultConfigDir, FileTokenStore, extractUrlCredential, getSystemDiagnostics, slugifyProjectName, escapeYamlScalar, scaffoldProject, adoptFolder, ensureGitignoreHasDist, EXTENSION_KINDS, RESERVED_PREFIX, resolveExtensionPrefix, scaffoldExtension, BUILT_IN_TEMPLATE_IDS, listBuiltInTemplates, saveProjectAsTemplate, listCustomTemplates, importTemplateFromFolder, DEFAULT_NPM_REGISTRY, npmRegistryUrl, EXTENSIONS_DIR, RECOMMENDED_EXTENSIONS, BUILT_IN_STYLE_SET_IDS, sameExtension, listProjectExtensions, describeExtension, setExtensionEnabled, reorderExtensions, removeExtension, addExtension, listBuiltInStyleSets, addBuiltInStyleSet, validateProjectExtensions, readExtensionCss, SNIPPETS_DIR, extractVariables, substituteVariables, listSnippets, readSnippet, saveSnippet, deleteSnippet, listMergedSnippets, readExtensionSnippet, importExtensionFromFile, importExtensionFromUrl, MAX_SEARCH_BYTES, SEARCH_KEYWORDS, searchNpmExtensions, setManifestFields, readManifestFields, setActiveStyles, AUTO_SNAPSHOT_DEFAULT_MINUTES, AUTO_SYNC_MIN_MINUTES, AUTO_SYNC_MAX_MINUTES, AUTO_SYNC_DEFAULT_MINUTES, AUTO_SYNC_PUSH_INTERVAL_MINUTES, autoSnapshotDelayMs, autoSyncDelayMs, isGitInternalPath, resolveGitHubClientId, GITHUB_HOST, GitHubAuthProvider, GDRIVE_HOST, resolveGoogleClientId, resolveGoogleClientSecret, GOOGLE_NOT_CONFIGURED_MESSAGE, requireGoogleClientCredentials, pkceChallengeFromVerifier, GoogleAuthProvider, revokeGoogleCredential, publishCredentialKey, publishConnectionStatus, listPublishAccounts, connectGoogleDrive, listGitHubRepositories, listRepoBooks, listGitHubBranches, sanitizeCloneFolderName, cloneRepository, isSshRemoteUrl, testRemoteAccess, knownForgeTokenUrl, connectGenericHost, parseRemoteOrigin, forgeKindForHost, diagnoseProjectRemote, syncProject, refreshRemoteCopies, REPAIR_SNAPSHOT_MESSAGE, repairOnlineBackup, scorchedEarth, listPublishProviders, publishProviderFor, resolvePublishFormat, resolvePublishRequest, runPublish, connectPublishProvider, disconnectPublishCredential, PublishSelectionsStore, readPublishSettings, setPublishProviderConfig };