@v1nvn/readability 0.45.0 → 0.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +3 -3
  2. package/package.json +4 -4
  3. package/src/cli.js +99 -0
  4. package/src/config.js +29 -0
  5. package/src/dev.js +55 -0
  6. package/src/errors.js +16 -0
  7. package/src/handler.js +4 -0
  8. package/src/host-sampling.js +57 -0
  9. package/src/index.js +23 -0
  10. package/src/index.ts +0 -0
  11. package/src/logger.js +2 -0
  12. package/src/output/format.js +92 -0
  13. package/src/pipeline/cell-text.js +51 -0
  14. package/src/pipeline/context.js +1 -0
  15. package/src/pipeline/dom.js +16 -0
  16. package/src/pipeline/footnotes.js +148 -0
  17. package/src/pipeline/math.js +113 -0
  18. package/src/pipeline/normalize.js +507 -0
  19. package/src/pipeline/readability.js +10 -0
  20. package/src/pipeline/resolver.js +113 -0
  21. package/src/pipeline/sanitize.js +26 -0
  22. package/src/pipeline/tables.js +239 -0
  23. package/src/pipeline/turndown.js +153 -0
  24. package/src/pipeline/urls.js +14 -0
  25. package/src/policy/chunk.js +365 -0
  26. package/src/policy/diagnostics.js +53 -0
  27. package/src/policy/explain.js +104 -0
  28. package/src/policy/fallback.js +68 -0
  29. package/src/policy/gating.js +90 -0
  30. package/src/policy/grid-detector.js +207 -0
  31. package/src/policy/identifiers.js +62 -0
  32. package/src/policy/images.js +49 -0
  33. package/src/policy/list-detector.js +232 -0
  34. package/src/policy/lost-signal.js +44 -0
  35. package/src/policy/markdown.js +58 -0
  36. package/src/policy/metadata.js +216 -0
  37. package/src/policy/outline-chains.js +165 -0
  38. package/src/policy/outline.js +71 -0
  39. package/src/policy/pagination.js +79 -0
  40. package/src/policy/presets.js +100 -0
  41. package/src/policy/section.js +111 -0
  42. package/src/policy/selector-lint.js +143 -0
  43. package/src/policy/sibling-scan.js +92 -0
  44. package/src/policy/text.js +18 -0
  45. package/src/policy/truncate.js +45 -0
  46. package/src/preset-cache.js +165 -0
  47. package/src/resources.js +227 -0
  48. package/src/sampling.js +45 -0
  49. package/src/server.js +73 -0
  50. package/src/tools/chunk_text.js +40 -0
  51. package/src/tools/explain.js +200 -0
  52. package/src/tools/extract.js +263 -0
  53. package/src/tools/extract_grid.js +56 -0
  54. package/src/tools/extract_links.js +98 -0
  55. package/src/tools/extract_list.js +66 -0
  56. package/src/tools/extract_metadata.js +67 -0
  57. package/src/tools/extract_section.js +56 -0
  58. package/src/tools/extract_tables.js +59 -0
  59. package/src/tools/html-source.js +30 -0
  60. package/src/tools/html_to_markdown.js +113 -0
  61. package/src/tools/outline.js +47 -0
  62. package/src/tools/output-schema.js +504 -0
  63. package/src/tools/schemas.js +288 -0
  64. package/src/tools/suggest-preset.js +504 -0
@@ -0,0 +1,111 @@
1
+ import { isElement } from "../pipeline/dom.js";
2
+ import { normalizeHeadingText } from "./outline.js";
3
+ // Match the first heading by normalized text. Exact equality wins; otherwise
4
+ // fall back to the first substring match so a short query ("auth") still
5
+ // lands on a longer heading ("Authentication") without forcing an exact match.
6
+ function findHeading(document, query) {
7
+ const needle = normalizeHeadingText(query).toLowerCase();
8
+ if (!needle) {
9
+ return undefined;
10
+ }
11
+ const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
12
+ let substring;
13
+ for (const heading of headings) {
14
+ const text = normalizeHeadingText(heading.textContent).toLowerCase();
15
+ if (!text) {
16
+ continue;
17
+ }
18
+ const level = Number.parseInt(heading.tagName.slice(1), 10);
19
+ if (text === needle) {
20
+ return { heading, level };
21
+ }
22
+ if (!substring && text.includes(needle)) {
23
+ substring = { heading, level };
24
+ }
25
+ }
26
+ return substring;
27
+ }
28
+ // Elements whose direct children form the section flow. The matched heading's
29
+ // nearest such ancestor is the level at which the section's content lives as
30
+ // siblings: on docs sites (GitHub markdown, etc.) the heading is wrapped in
31
+ // <div class="markdown-heading">, so the body <p> is a sibling of the wrapper
32
+ // div, not of the <h2>. Walking the <h2>'s own siblings would capture only the
33
+ // permalink anchor and miss the body.
34
+ const FLOW_CONTAINERS = new Set([
35
+ 'ARTICLE',
36
+ 'ASIDE',
37
+ 'BLOCKQUOTE',
38
+ 'BODY',
39
+ 'DD',
40
+ 'DETAILS',
41
+ 'DT',
42
+ 'FOOTER',
43
+ 'HEADER',
44
+ 'LI',
45
+ 'MAIN',
46
+ 'NAV',
47
+ 'SECTION',
48
+ 'TD',
49
+ ]);
50
+ function findFlowContainer(heading) {
51
+ let ancestor = heading.parentElement;
52
+ while (ancestor) {
53
+ if (FLOW_CONTAINERS.has(ancestor.tagName)) {
54
+ return ancestor;
55
+ }
56
+ ancestor = ancestor.parentElement;
57
+ }
58
+ // BODY is in FLOW_CONTAINERS, so the loop reaches it for any attached
59
+ // heading; this fallback only covers a detached heading.
60
+ return heading.ownerDocument.body;
61
+ }
62
+ // Level of the first heading at or inside `el`, or undefined when `el` is
63
+ // neither a heading nor a wrapper around one. Used to test whether a following
64
+ // sibling terminates the section.
65
+ function firstHeadingLevel(el) {
66
+ const direct = /^H([1-6])$/.exec(el.tagName);
67
+ if (direct) {
68
+ return Number.parseInt(direct[1], 10);
69
+ }
70
+ const inner = el.querySelector('h1, h2, h3, h4, h5, h6');
71
+ if (inner) {
72
+ return Number.parseInt(inner.tagName.slice(1), 10);
73
+ }
74
+ return undefined;
75
+ }
76
+ // Wraps the matched heading and its subtree in a `<section data-rdrm-section-scope>`
77
+ // so the existing selectors.include path can isolate it. Returns false (and
78
+ // leaves the document untouched) when no heading matches.
79
+ export function scopeToHeading(document, headingText) {
80
+ const match = findHeading(document, headingText);
81
+ if (!match) {
82
+ return false;
83
+ }
84
+ const { heading, level } = match;
85
+ const container = findFlowContainer(heading);
86
+ let startChild = heading;
87
+ while (startChild.parentElement && startChild.parentElement !== container) {
88
+ startChild = startChild.parentElement;
89
+ }
90
+ const wrap = document.createElement('section');
91
+ wrap.setAttribute('data-rdrm-section-scope', '');
92
+ container.insertBefore(wrap, startChild);
93
+ let node = startChild;
94
+ while (node) {
95
+ const next = node.nextSibling;
96
+ wrap.appendChild(node);
97
+ // A section ends at the next same-or-higher-level heading (level <= L):
98
+ // deeper headings (h3 under an h2) belong to this section, peers and
99
+ // shallower headings start the next one. The terminating sibling may be a
100
+ // wrapper around the heading (e.g. <div class="markdown-heading">), so the
101
+ // check looks for a heading at OR inside the sibling.
102
+ if (next !== null && isElement(next)) {
103
+ const nextLevel = firstHeadingLevel(next);
104
+ if (nextLevel !== undefined && nextLevel <= level) {
105
+ break;
106
+ }
107
+ }
108
+ node = next;
109
+ }
110
+ return true;
111
+ }
@@ -0,0 +1,143 @@
1
+ import { isGeneratedIdentifier } from "./identifiers.js";
2
+ import { selectorMisses } from "./presets.js";
3
+ // nwsapi/jsdom accept `:contains` and silently apply it, so an engine error can
4
+ // reject nothing — the rejection has to happen here, before any selector
5
+ // reaches querySelector. Positional pseudos are rejected as a family: they
6
+ // describe this render's child order, not the site's structure.
7
+ const POSITIONAL_PSEUDO_RE = /:(?:nth(?:-last)?(?:-child|-of-type)|first(?:-child|-of-type)|last(?:-child|-of-type)|only(?:-child|-of-type))\b/i;
8
+ const CONTAINS_PSEUDO_RE = /:contains\s*\(/i;
9
+ function quotedSegmentsOut(selector) {
10
+ return selector.replace(/(["'])(?:\\.|(?!\1)[\s\S])*\1/g, '""');
11
+ }
12
+ // `.class` and `#id` tokens are identifiers; `[attr="value"]` values are
13
+ // substring matches against whatever the site emitted and are exempt.
14
+ function identifierTokens(selector) {
15
+ return [...quotedSegmentsOut(selector).matchAll(/[.#]([A-Za-z0-9_-]+)/g)].map(match => match[1]);
16
+ }
17
+ export function lintSelectorText(selector) {
18
+ if (CONTAINS_PSEUDO_RE.test(selector)) {
19
+ return {
20
+ kind: 'contains-pseudo',
21
+ selector,
22
+ detail: ':contains is not standard CSS and changes the result silently',
23
+ };
24
+ }
25
+ const positional = POSITIONAL_PSEUDO_RE.exec(selector);
26
+ if (positional) {
27
+ return {
28
+ kind: 'positional-pseudo',
29
+ selector,
30
+ detail: `${positional[0]} depends on this page's child order, not the site's layout`,
31
+ };
32
+ }
33
+ for (const token of identifierTokens(selector)) {
34
+ if (isGeneratedIdentifier(token)) {
35
+ return {
36
+ kind: 'generated-identifier',
37
+ selector,
38
+ detail: `"${token}" reads as a generated hash that changes on deploy`,
39
+ };
40
+ }
41
+ }
42
+ return undefined;
43
+ }
44
+ // Propose-time validation for a preset a suggester wants stored. Stricter than
45
+ // presetMatches: an exclude that matches nothing is tolerated at runtime (the
46
+ // debris is absent from some pages) but at propose time it is a mistake — the
47
+ // proposal names debris that is not there.
48
+ export function lintProposal({ document, detectors, scope, }) {
49
+ const violations = [];
50
+ const selectors = [
51
+ ...detectors,
52
+ ...(scope.include ? [scope.include] : []),
53
+ ...(scope.exclude ?? []),
54
+ ];
55
+ for (const selector of selectors) {
56
+ const violation = lintSelectorText(selector);
57
+ if (violation) {
58
+ violations.push(violation);
59
+ }
60
+ }
61
+ let includeRoot;
62
+ if (scope.include &&
63
+ !violations.some(violation => violation.selector === scope.include)) {
64
+ try {
65
+ includeRoot = document.body.querySelector(scope.include) ?? undefined;
66
+ }
67
+ catch {
68
+ violations.push({
69
+ kind: 'unparseable',
70
+ selector: scope.include,
71
+ detail: 'the selector engine rejects this selector',
72
+ });
73
+ }
74
+ }
75
+ for (const detector of detectors) {
76
+ if (violations.some(violation => violation.selector === detector)) {
77
+ continue;
78
+ }
79
+ if (selectorMisses(document, detector)) {
80
+ violations.push({
81
+ kind: 'no-match',
82
+ selector: detector,
83
+ detail: 'detector matches nothing on this page',
84
+ });
85
+ }
86
+ }
87
+ if (scope.include &&
88
+ !includeRoot &&
89
+ !violations.some(violation => violation.selector === scope.include)) {
90
+ violations.push({
91
+ kind: 'no-match',
92
+ selector: scope.include,
93
+ detail: 'include matches nothing inside <body>, where applySelectors searches',
94
+ });
95
+ }
96
+ for (const selector of scope.exclude ?? []) {
97
+ if (violations.some(violation => violation.selector === selector)) {
98
+ continue;
99
+ }
100
+ try {
101
+ if (document.querySelectorAll(selector).length === 0) {
102
+ violations.push({
103
+ kind: 'no-match',
104
+ selector,
105
+ detail: 'exclude matches nothing on this page',
106
+ });
107
+ }
108
+ }
109
+ catch {
110
+ violations.push({
111
+ kind: 'unparseable',
112
+ selector,
113
+ detail: 'the selector engine rejects this selector',
114
+ });
115
+ }
116
+ }
117
+ // Excludes are removed document-wide before the include is applied, so an
118
+ // exclude matching an ancestor of the include root (or the root itself)
119
+ // deletes it, and the include then quietly no-ops over a damaged body.
120
+ if (includeRoot) {
121
+ for (const selector of scope.exclude ?? []) {
122
+ if (violations.some(violation => violation.selector === selector)) {
123
+ continue;
124
+ }
125
+ try {
126
+ for (const match of document.querySelectorAll(selector)) {
127
+ if (match.contains(includeRoot)) {
128
+ violations.push({
129
+ kind: 'exclude-shadows-include',
130
+ selector,
131
+ detail: 'this exclude removes the include root itself',
132
+ });
133
+ break;
134
+ }
135
+ }
136
+ }
137
+ catch {
138
+ // Already reported as unparseable.
139
+ }
140
+ }
141
+ }
142
+ return violations;
143
+ }
@@ -0,0 +1,92 @@
1
+ import { isElement } from "../pipeline/dom.js";
2
+ // Shared pre-pass for the sibling-cluster detectors (list-detector,
3
+ // grid-detector). Both walk the document for a container whose direct children
4
+ // form a same-shape sibling group; the constants and helpers here are the
5
+ // heuristic-agnostic infrastructure that scan shares. Detector-specific scoring
6
+ // (anchor/pathname signals vs data-cell text) stays in each detector.
7
+ // Direct children are scanned only at these container levels. <tbody> covers
8
+ // HN's <table>-based layout; the rest cover semantic (<main>/<article>) and
9
+ // generic (<div>/<section>) wrappers. <table> is included for HTML that skips
10
+ // <tbody>; jsdom synthesizes one anyway, so this is mostly defensive.
11
+ export const CONTAINER_TAGS = new Set([
12
+ 'ARTICLE',
13
+ 'DIV',
14
+ 'MAIN',
15
+ 'OL',
16
+ 'SECTION',
17
+ 'TABLE',
18
+ 'TBODY',
19
+ 'UL',
20
+ ]);
21
+ // Subtrees that never carry a page's primary repeated structure. Stripping them
22
+ // is the false-positive guard: without it, an article's <nav> menu or footer
23
+ // link list would look identical to a feed/grid and the detectors would mis-fire
24
+ // on every page with chrome. Distinct from normalize.ts's stripChrome (which
25
+ // removes consent/overlay banners) — this is landmark chrome only.
26
+ const LANDMARK_CHROME_SELECTOR = 'nav, header, footer, aside, [role="navigation"], [role="banner"], ' +
27
+ '[role="contentinfo"], [role="complementary"], [role="search"], ' +
28
+ '[role="menu"], [role="menubar"]';
29
+ export function stripLandmarkChrome(document) {
30
+ for (const el of document.querySelectorAll(LANDMARK_CHROME_SELECTOR)) {
31
+ el.remove();
32
+ }
33
+ for (const el of document.querySelectorAll('script, style, template')) {
34
+ el.remove();
35
+ }
36
+ }
37
+ // Composite of tag + class signature so mixed siblings — e.g. HN's
38
+ // <tr class="athing"> title row vs classless <tr> subtext row, or a grid's
39
+ // header row vs data rows — split into separate candidate groups instead of
40
+ // blending into one ragged group.
41
+ export function shapeKey(el) {
42
+ const raw = el.getAttribute('class');
43
+ if (!raw) {
44
+ return el.tagName;
45
+ }
46
+ const normalized = raw.trim().split(/\s+/).sort().join(' ');
47
+ return normalized ? `${el.tagName}|${normalized}` : el.tagName;
48
+ }
49
+ // Group a container's direct element-children by shape so a homogeneous
50
+ // cluster surfaces as one candidate and mixed-shape siblings (header row vs
51
+ // data rows, HN's athing + subtext) split apart rather than blending.
52
+ export function groupChildrenByShape(container) {
53
+ const groups = new Map();
54
+ for (const child of Array.from(container.childNodes)) {
55
+ if (!isElement(child)) {
56
+ continue;
57
+ }
58
+ const key = shapeKey(child);
59
+ const bucket = groups.get(key);
60
+ if (bucket) {
61
+ bucket.push(child);
62
+ }
63
+ else {
64
+ groups.set(key, [child]);
65
+ }
66
+ }
67
+ return groups;
68
+ }
69
+ // tag#id.class hint for the winning container. Best-effort, not a unique
70
+ // locator — used only for diagnostics so a human can see which subtree won.
71
+ // `maxClasses` caps the class list for compact diagnostic output.
72
+ export function describeSelector(el, maxClasses) {
73
+ const parts = [el.tagName.toLowerCase()];
74
+ const id = el.getAttribute('id');
75
+ if (id) {
76
+ parts.push(`#${id}`);
77
+ }
78
+ const cls = el.getAttribute('class');
79
+ if (cls) {
80
+ let used = 0;
81
+ for (const token of cls.trim().split(/\s+/)) {
82
+ if (token) {
83
+ parts.push(`.${token}`);
84
+ used += 1;
85
+ }
86
+ if (maxClasses !== undefined && used >= maxClasses) {
87
+ break;
88
+ }
89
+ }
90
+ }
91
+ return parts.join('');
92
+ }
@@ -0,0 +1,18 @@
1
+ export const TOKEN_ESTIMATOR = 'chars/4';
2
+ export function estimateTokens(textContent) {
3
+ return {
4
+ tokenEstimate: Math.round(textContent.length / 4),
5
+ estimator: TOKEN_ESTIMATOR,
6
+ };
7
+ }
8
+ export function countWords(text) {
9
+ return (text.match(/\S+/g) ?? []).length;
10
+ }
11
+ export function nonEmpty(value) {
12
+ return value?.trim() ? value : undefined;
13
+ }
14
+ export function computeTextMetrics(text, wordsPerMinute) {
15
+ const wordCount = countWords(text);
16
+ const readingTimeMin = wordCount === 0 ? 0 : Math.max(1, Math.round(wordCount / wordsPerMinute));
17
+ return { wordCount, readingTimeMin, ...estimateTokens(text) };
18
+ }
@@ -0,0 +1,45 @@
1
+ import { hardSplitLines, parseBlocks } from "./markdown.js";
2
+ const TRUNCATION_MARKER = '\n\n…[truncated]';
3
+ // Cuts at a top-level block boundary. A fenced code block is a single mdast
4
+ // node, so a boundary cut never lands inside one — no open-fence rollback is
5
+ // needed. The kept span is sliced from the original string so the payload is a
6
+ // byte-for-byte prefix of the Turndown output.
7
+ export function truncateMarkdown(markdown, maxChars) {
8
+ if (markdown.length <= maxChars) {
9
+ return { text: markdown, truncated: false };
10
+ }
11
+ const blocks = parseBlocks(markdown);
12
+ let start = -1;
13
+ let end = -1;
14
+ let truncated = false;
15
+ for (const block of blocks) {
16
+ const from = start === -1 ? block.start : start;
17
+ if (block.end - from > maxChars) {
18
+ // First non-code block alone overflows: take a line-aware prefix instead
19
+ // of dropping everything. A code block is never split — a half-open fence
20
+ // is unrecoverable — so an oversized first code block stays dropped.
21
+ if (start === -1 && block.kind !== 'code') {
22
+ const firstPiece = hardSplitLines(markdown.slice(block.start, block.end), maxChars)[0] ??
23
+ '';
24
+ return {
25
+ text: firstPiece.replace(/\s+$/, '') + TRUNCATION_MARKER,
26
+ truncated: true,
27
+ };
28
+ }
29
+ truncated = true;
30
+ break;
31
+ }
32
+ if (start === -1) {
33
+ start = block.start;
34
+ }
35
+ end = block.end;
36
+ }
37
+ if (!truncated) {
38
+ return { text: markdown, truncated: false };
39
+ }
40
+ const kept = start === -1 ? '' : markdown.slice(start, end);
41
+ return {
42
+ text: kept.replace(/\s+$/, '') + TRUNCATION_MARKER,
43
+ truncated: true,
44
+ };
45
+ }
@@ -0,0 +1,165 @@
1
+ // Disk side of the preset store: one <site>.json file per preset, read into
2
+ // the in-memory store at boot. Local to the user's machine, ordinary files;
3
+ // the server never fetches and nothing expires by clock — staleness is
4
+ // detector-checked per page (policy/presets.ts), so eviction here is disk
5
+ // hygiene only.
6
+ import { describeError } from '@v1nvn/agentic-core';
7
+ import { mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
8
+ import { homedir } from 'node:os';
9
+ import { join } from 'node:path';
10
+ import { z } from 'zod';
11
+ import { logger } from "./logger.js";
12
+ import { addPreset, normalizeSiteKey } from "./policy/presets.js";
13
+ export const PRESETS_DIR_ENV = 'READABILITY_PRESETS_DIR';
14
+ export const MAX_PRESET_FILES = 64;
15
+ // An empty scope applies nothing while reporting applied:true, and detectors
16
+ // only mean something as a non-empty set — reject both at the file boundary.
17
+ const presetFileSchema = z.object({
18
+ site: z.string().min(1),
19
+ detectors: z.array(z.string().min(1)).min(1),
20
+ scope: z
21
+ .object({
22
+ include: z.string().min(1).optional(),
23
+ exclude: z.array(z.string().min(1)).min(1).optional(),
24
+ })
25
+ .refine(scope => scope.include !== undefined || scope.exclude !== undefined, {
26
+ message: 'scope must carry include or exclude',
27
+ }),
28
+ });
29
+ // Empty string disables preset loading; an absolute path wins over the
30
+ // platform default.
31
+ export function resolvePresetsDir(env = process.env) {
32
+ const override = env[PRESETS_DIR_ENV];
33
+ if (override !== undefined) {
34
+ return override.trim() === '' ? undefined : override;
35
+ }
36
+ const root = env.XDG_CACHE_HOME ||
37
+ join(homedir(), process.platform === 'darwin' ? 'Library/Caches' : '.cache');
38
+ return join(root, 'readability', 'presets');
39
+ }
40
+ // A preset that cannot load is a warning, never a boot failure — the pipeline
41
+ // is designed to run without one.
42
+ export function loadPresetDir(dir) {
43
+ let names;
44
+ try {
45
+ names = readdirSync(dir)
46
+ .filter(name => name.endsWith('.json'))
47
+ .sort();
48
+ }
49
+ catch (err) {
50
+ if (err.code === 'ENOENT') {
51
+ logger.debug(`no preset directory at ${dir}`);
52
+ }
53
+ else {
54
+ logger.warn(`preset directory unreadable: ${dir}`);
55
+ }
56
+ return { loaded: 0, pruned: 0, skipped: 0 };
57
+ }
58
+ const ranked = rankPresetFiles(dir, names);
59
+ const pruned = pruneRanked(dir, ranked.slice(MAX_PRESET_FILES));
60
+ let loaded = 0;
61
+ let skipped = 0;
62
+ for (const { name } of ranked.slice(0, MAX_PRESET_FILES)) {
63
+ const path = join(dir, name);
64
+ if (loadPresetFile(path)) {
65
+ loaded++;
66
+ }
67
+ else {
68
+ skipped++;
69
+ }
70
+ }
71
+ if (loaded > 0) {
72
+ logger.info(`loaded ${loaded} site preset(s) from ${dir}`);
73
+ }
74
+ if (pruned > 0) {
75
+ logger.info(`pruned ${pruned} preset file(s) beyond the ${MAX_PRESET_FILES}-file bound`);
76
+ }
77
+ return { loaded, pruned, skipped };
78
+ }
79
+ // Env-resolving entry point for the boot paths; undefined means disabled.
80
+ export function loadPresets(env = process.env) {
81
+ const dir = resolvePresetsDir(env);
82
+ return dir ? loadPresetDir(dir) : undefined;
83
+ }
84
+ function rankPresetFiles(dir, names) {
85
+ const ranked = [];
86
+ for (const name of names) {
87
+ try {
88
+ ranked.push({ name, mtimeMs: statSync(join(dir, name)).mtimeMs });
89
+ }
90
+ catch {
91
+ // Vanished between readdir and stat — nothing to load or prune.
92
+ }
93
+ }
94
+ ranked.sort((a, b) => b.mtimeMs - a.mtimeMs);
95
+ return ranked;
96
+ }
97
+ function pruneRanked(dir, ranked) {
98
+ let pruned = 0;
99
+ for (const { name } of ranked) {
100
+ try {
101
+ unlinkSync(join(dir, name));
102
+ pruned++;
103
+ }
104
+ catch (err) {
105
+ logger.warn(`could not prune preset file ${name}: ${describeError(err)}`);
106
+ }
107
+ }
108
+ return pruned;
109
+ }
110
+ // The writer the loader was waiting for: the suggest loop saves an accepted
111
+ // preset so the next server start loads it like any hand-placed file. A
112
+ // failure leaves the in-memory preset working — persistence is best-effort,
113
+ // exactly like loading.
114
+ export function savePreset(preset, env = process.env) {
115
+ const dir = resolvePresetsDir(env);
116
+ if (!dir) {
117
+ return { persisted: false, reason: 'preset-directory-disabled' };
118
+ }
119
+ const shape = presetFileSchema.safeParse(preset);
120
+ if (!shape.success) {
121
+ return {
122
+ persisted: false,
123
+ reason: shape.error.issues[0]?.message ?? 'invalid preset shape',
124
+ };
125
+ }
126
+ const key = normalizeSiteKey(preset.site);
127
+ if (!key) {
128
+ return { persisted: false, reason: 'site-is-not-a-hostname' };
129
+ }
130
+ const path = join(dir, `${key}.json`);
131
+ try {
132
+ mkdirSync(dir, { recursive: true });
133
+ writeFileSync(path, `${JSON.stringify(shape.data, null, 2)}\n`);
134
+ }
135
+ catch (err) {
136
+ return {
137
+ persisted: false,
138
+ reason: describeError(err),
139
+ };
140
+ }
141
+ const over = rankPresetFiles(dir, readdirSync(dir).filter(name => name.endsWith('.json')));
142
+ pruneRanked(dir, over.slice(MAX_PRESET_FILES));
143
+ return { path, persisted: true };
144
+ }
145
+ function loadPresetFile(path) {
146
+ let parsed;
147
+ try {
148
+ parsed = JSON.parse(readFileSync(path, 'utf8'));
149
+ }
150
+ catch (err) {
151
+ logger.warn(`${path}: not readable JSON (${describeError(err)}), preset skipped`);
152
+ return false;
153
+ }
154
+ const result = presetFileSchema.safeParse(parsed);
155
+ if (!result.success) {
156
+ logger.warn(`${path}: ${result.error.issues[0]?.message}, preset skipped`);
157
+ return false;
158
+ }
159
+ if (!normalizeSiteKey(result.data.site)) {
160
+ logger.warn(`${path}: site is not a hostname, preset skipped`);
161
+ return false;
162
+ }
163
+ addPreset(result.data);
164
+ return true;
165
+ }