linopress-cli 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,170 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { mkdtemp, readFile, readdir, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join, relative, resolve, sep } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ // ../typedoc/src/pages.ts
7
+ const H1 = /^\s*#[ \t]+(.+?)(?:[ \t]+#+)?[ \t]*(?:\n+|$)/;
8
+ /**
9
+ * Splits a leading `# Title` off a Markdown page. Linear shows the doc title separately, so
10
+ * keeping TypeDoc's H1 would duplicate it.
11
+ */
12
+ function splitTitle(markdown) {
13
+ const normalized = markdown.replace(/\r\n?/g, "\n");
14
+ const match = H1.exec(normalized);
15
+ if (!match?.[1]) return {
16
+ title: null,
17
+ content: normalized
18
+ };
19
+ return {
20
+ title: match[1].replace(/\\(.)/g, "$1"),
21
+ content: normalized.slice(match[0].length)
22
+ };
23
+ }
24
+ async function walk(dir) {
25
+ const out = [];
26
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
27
+ const full = join(dir, entry.name);
28
+ if (entry.isDirectory()) out.push(...await walk(full));
29
+ else if (entry.isFile() && entry.name.endsWith(".md")) out.push(full);
30
+ }
31
+ return out;
32
+ }
33
+ /**
34
+ * Reads a folder of Markdown (e.g. typedoc-plugin-markdown output) as pages.
35
+ * Titles come from each page's H1, falling back to the file path without `.md`.
36
+ */
37
+ async function readMarkdownPages(dir) {
38
+ const files = await walk(dir);
39
+ return (await Promise.all(files.map(async (file) => {
40
+ const path = relative(dir, file).split(sep).join("/");
41
+ const { title, content } = splitTitle(await readFile(file, "utf8"));
42
+ return {
43
+ path,
44
+ title: title ?? path.replace(/\.md$/, ""),
45
+ content
46
+ };
47
+ }))).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
48
+ }
49
+ // ../typedoc/src/generate.ts
50
+ const MARKDOWN_PLUGIN = "typedoc-plugin-markdown";
51
+ /**
52
+ * Absolute, symlink-free path, so it compares with the repo root and the footer's display base
53
+ * (also resolved with `realpath`), e.g. under macOS's `/var` → `/private/var`.
54
+ */
55
+ function canonical(file) {
56
+ const abs = resolve(file);
57
+ try {
58
+ return realpathSync(abs);
59
+ } catch {
60
+ return abs;
61
+ }
62
+ }
63
+ /**
64
+ * Source files of a page's reflection. Uses the symbol TypeDoc converted it from, which is known
65
+ * even with `disableSources: true`; falls back to `reflection.sources` when that's recorded.
66
+ */
67
+ function sourcesOf(event) {
68
+ const fromSymbol = event.project?.getSymbolIdFromReflection?.(event.model)?.fileName;
69
+ if (fromSymbol) return [canonical(fromSymbol)];
70
+ const sources = event.model?.sources;
71
+ return [...new Set((sources ?? []).flatMap((s) => s.fullFileName ? [canonical(s.fullFileName)] : []))];
72
+ }
73
+ /** Resolves a plugin from this package first, so it works even when it isn't hoisted. */
74
+ function resolvePlugin(name) {
75
+ try {
76
+ return fileURLToPath(import.meta.resolve(name));
77
+ } catch {
78
+ return name;
79
+ }
80
+ }
81
+ /** Reads the options file's `plugin` list, so ours can be added to it rather than replace it. */
82
+ async function configuredPlugins(options) {
83
+ const override = options.overrides?.["plugin"];
84
+ if (override !== void 0) {
85
+ const base = resolve(options.overridesBase ?? ".");
86
+ return (Array.isArray(override) ? override.map(String) : []).map((name) => name.startsWith(".") ? resolve(base, name) : name);
87
+ }
88
+ try {
89
+ const file = resolve(options.options);
90
+ const plugin = JSON.parse(await readFile(file, "utf8"))?.plugin;
91
+ if (!Array.isArray(plugin)) return [];
92
+ return plugin.map((p) => {
93
+ const name = String(p);
94
+ return name.startsWith(".") ? resolve(dirname(file), name) : name;
95
+ });
96
+ } catch {
97
+ return [];
98
+ }
99
+ }
100
+ /**
101
+ * Runs TypeDoc with typedoc-plugin-markdown and reads the result as pages.
102
+ * `typedoc` and `typedoc-plugin-markdown` are peer dependencies, loaded lazily.
103
+ */
104
+ async function generateMarkdown(options) {
105
+ const typedoc = await import("typedoc").catch((error) => {
106
+ const missing = error?.code === "ERR_MODULE_NOT_FOUND";
107
+ throw new Error(missing ? "The TypeDoc source needs `typedoc` and `typedoc-plugin-markdown` installed" : "Failed to load `typedoc`", { cause: error });
108
+ });
109
+ const plugins = [resolvePlugin(MARKDOWN_PLUGIN), ...(await configuredPlugins(options)).filter((p) => p !== MARKDOWN_PLUGIN)];
110
+ const tempOut = options.out === void 0;
111
+ const out = resolve(options.out ?? await mkdtemp(join(tmpdir(), "linopress-")));
112
+ const { plugin: _plugin, ...overrides } = options.overrides ?? {};
113
+ const base = resolve(options.overridesBase ?? ".");
114
+ const overridesReader = {
115
+ name: "linopress-overrides",
116
+ order: 1e3,
117
+ supportsPackages: false,
118
+ read(container) {
119
+ for (const [name, value] of Object.entries(overrides)) container.setValue(name, value, base);
120
+ }
121
+ };
122
+ try {
123
+ const app = await typedoc.Application.bootstrapWithPlugins({
124
+ options: resolve(options.options),
125
+ plugin: [...new Set(plugins)],
126
+ out,
127
+ cleanOutputDir: true
128
+ }, [
129
+ new typedoc.TypeDocReader(),
130
+ new typedoc.TSConfigReader(),
131
+ overridesReader
132
+ ]);
133
+ const sources = /* @__PURE__ */ new Map();
134
+ app.renderer.on("endPage", (event) => {
135
+ const files = sourcesOf(event);
136
+ if (files.length > 0) sources.set(event.url.split(sep).join("/"), files);
137
+ });
138
+ const strict = app.options.getValue("treatWarningsAsErrors");
139
+ const failOnWarnings = (step) => {
140
+ if (app.logger.hasErrors()) throw new Error(`TypeDoc reported errors ${step}, see above`);
141
+ if (strict && app.logger.hasWarnings()) throw new Error(`TypeDoc reported warnings ${step} (treatWarningsAsErrors), see above`);
142
+ };
143
+ const project = await app.convert();
144
+ if (!project) throw new Error(`TypeDoc failed to convert the project (${options.options})`);
145
+ failOnWarnings("while converting");
146
+ const before = app.logger.warningCount;
147
+ app.validate(project);
148
+ failOnWarnings("while validating");
149
+ if (app.options.getValue("treatValidationWarningsAsErrors") && (app.logger.warningCount !== before || app.logger.validationWarningCount !== 0)) throw new Error("TypeDoc reported warnings while validating (treatValidationWarningsAsErrors), see above");
150
+ await app.generateOutputs(project);
151
+ failOnWarnings("while rendering");
152
+ return {
153
+ out,
154
+ pages: (await readMarkdownPages(out)).map((page) => {
155
+ const files = sources.get(page.path);
156
+ return files ? {
157
+ ...page,
158
+ sources: files
159
+ } : page;
160
+ })
161
+ };
162
+ } catch (error) {
163
+ if (tempOut) await rm(out, {
164
+ recursive: true,
165
+ force: true
166
+ });
167
+ throw error;
168
+ }
169
+ }
170
+ export { readMarkdownPages as n, splitTitle as r, generateMarkdown as t };
@@ -0,0 +1,226 @@
1
+ import { d as stripHtmlAnchors, f as unlinkInPageLinks, r as DocNotFoundError } from "./src-BU0LDvW9.js";
2
+ // ../linear/src/client.ts
3
+ const LINEAR_ENDPOINT = "https://api.linear.app/graphql";
4
+ var LinearApiError = class extends Error {
5
+ status;
6
+ errors;
7
+ constructor(message, status, errors = []) {
8
+ super(message);
9
+ this.name = "LinearApiError";
10
+ this.status = status;
11
+ this.errors = errors;
12
+ }
13
+ };
14
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
15
+ /**
16
+ * Rate-limited requests were rejected before running, so retrying them is safe even for mutations.
17
+ * Other failures (5xx, timeouts) are not retried: a create may already have happened.
18
+ */
19
+ function isRateLimited(status, errors) {
20
+ return status === 429 || (errors ?? []).some((e) => e.extensions?.["code"] === "RATELIMITED");
21
+ }
22
+ /**
23
+ * Minimal Linear GraphQL client. We don't use `@linear/sdk` for document mutations because its
24
+ * published schema lacks `parentDocumentId`, `subDocumentSortOrder` and `teamId`, which the live
25
+ * API accepts (check with `pnpm linear:introspect`).
26
+ */
27
+ function createGraphQLClient(options) {
28
+ const doFetch = options.fetch ?? fetch;
29
+ const endpoint = options.endpoint ?? "https://api.linear.app/graphql";
30
+ const maxRetries = options.maxRetries ?? 3;
31
+ const retryDelayMs = options.retryDelayMs ?? 1e3;
32
+ const timeoutMs = options.timeoutMs ?? 3e4;
33
+ const authorization = options.apiKey.startsWith("lin_api_") ? options.apiKey : `Bearer ${options.apiKey}`;
34
+ return async (query, variables = {}) => {
35
+ for (let attempt = 0;; attempt++) {
36
+ const res = await doFetch(endpoint, {
37
+ method: "POST",
38
+ headers: {
39
+ "Content-Type": "application/json",
40
+ Authorization: authorization
41
+ },
42
+ body: JSON.stringify({
43
+ query,
44
+ variables
45
+ }),
46
+ signal: AbortSignal.timeout(timeoutMs)
47
+ });
48
+ const text = await res.text();
49
+ let body;
50
+ let parseError;
51
+ try {
52
+ body = JSON.parse(text);
53
+ } catch (error) {
54
+ parseError = error;
55
+ }
56
+ if (attempt < maxRetries && isRateLimited(res.status, body?.errors)) {
57
+ const retryAfter = Number(res.headers.get("retry-after"));
58
+ await sleep(retryAfter > 0 ? retryAfter * 1e3 : retryDelayMs * 2 ** attempt);
59
+ continue;
60
+ }
61
+ if (body?.errors?.length) throw new LinearApiError(body.errors.map((e) => e.message).join("\n"), res.status, body.errors);
62
+ if (parseError !== void 0) {
63
+ const reason = parseError instanceof Error ? parseError.message : String(parseError);
64
+ throw new LinearApiError(`Linear API returned HTTP ${res.status} with a non-JSON body (${reason}): ${text.slice(0, 200)}`, res.status);
65
+ }
66
+ if (!res.ok || body?.data == null) throw new LinearApiError(`Linear API request failed with HTTP ${res.status}${res.ok ? " (no data in response)" : ""}`, res.status);
67
+ return body.data;
68
+ }
69
+ };
70
+ }
71
+ // ../linear/src/target.ts
72
+ const CREATE = `mutation LinopressCreate($input: DocumentCreateInput!) {
73
+ documentCreate(input: $input) { success document { id url } }
74
+ }`;
75
+ const UPDATE = `mutation LinopressUpdate($id: String!, $input: DocumentUpdateInput!) {
76
+ documentUpdate(id: $id, input: $input) { success document { id trashed archivedAt } }
77
+ }`;
78
+ /** Linear's "delete" is its trash: the doc is archived, flagged `trashed`, and restorable from the UI. */
79
+ const TRASH = `mutation LinopressTrash($id: String!) {
80
+ documentDelete(id: $id) { success }
81
+ }`;
82
+ const UPLOAD = `mutation LinopressUpload($filename: String!, $contentType: String!, $size: Int!) {
83
+ fileUpload(filename: $filename, contentType: $contentType, size: $size) {
84
+ success uploadFile { uploadUrl assetUrl headers { key value } }
85
+ }
86
+ }`;
87
+ const READ = `query LinopressDoc($id: String!) {
88
+ document(id: $id) { id trashed archivedAt }
89
+ }`;
90
+ /**
91
+ * Maps a position to Linear's fields. Top-level docs are ordered by `sortOrder`; sub-documents by
92
+ * `subDocumentSortOrder` under `parentDocumentId`. We send `parentDocumentId: null` to un-nest.
93
+ */
94
+ function positionFields(position) {
95
+ return position.parentId === null ? {
96
+ parentDocumentId: null,
97
+ sortOrder: position.sortOrder
98
+ } : {
99
+ parentDocumentId: position.parentId,
100
+ subDocumentSortOrder: position.sortOrder,
101
+ sortOrder: position.sortOrder
102
+ };
103
+ }
104
+ const NOT_FOUND = /entity not found|could not find|not[ _-]?found/i;
105
+ /**
106
+ * True when every error Linear returned reads as "not found". This alone doesn't say *which*
107
+ * entity is missing (it may be a parent doc), so callers confirm with a read of the doc itself.
108
+ */
109
+ function looksNotFound(error) {
110
+ return error instanceof LinearApiError && error.errors.length > 0 && error.errors.every((e) => NOT_FOUND.test(e.message) || NOT_FOUND.test(String(e.extensions?.["code"] ?? "")));
111
+ }
112
+ const isGone = (doc) => !doc || !!doc.trashed || !!doc.archivedAt;
113
+ /** Linear Documents as a Linopress target, scoped to one team or project. */
114
+ var LinearTarget = class {
115
+ container;
116
+ #request;
117
+ #fetch;
118
+ #timeoutMs;
119
+ constructor(options) {
120
+ this.container = options.container;
121
+ this.#fetch = options.fetch ?? fetch;
122
+ this.#timeoutMs = options.timeoutMs ?? 3e4;
123
+ if (options.request) this.#request = options.request;
124
+ else if (options.apiKey) this.#request = createGraphQLClient({
125
+ ...options,
126
+ apiKey: options.apiKey
127
+ });
128
+ else throw new Error("LinearTarget needs an apiKey (LINEAR_API_KEY) or a request function");
129
+ }
130
+ async create(input) {
131
+ const containerField = this.container.type === "team" ? "teamId" : "projectId";
132
+ const { parentDocumentId, ...position } = positionFields(input);
133
+ const data = await this.#request(CREATE, { input: {
134
+ title: input.title,
135
+ content: input.content,
136
+ [containerField]: this.container.id,
137
+ ...position,
138
+ ...parentDocumentId !== null && { parentDocumentId }
139
+ } });
140
+ const doc = data.documentCreate?.document;
141
+ if (!data.documentCreate?.success || !doc) throw new Error(`documentCreate failed for "${input.title}"`);
142
+ return {
143
+ id: doc.id,
144
+ url: doc.url
145
+ };
146
+ }
147
+ /** Throws `DocNotFoundError` when the doc is deleted, or trashed/archived outside Linopress. */
148
+ async update(id, input) {
149
+ const doc = await this.#mutateUpdate(id, {
150
+ ...input.title !== void 0 && { title: input.title },
151
+ ...input.content !== void 0 && { content: input.content },
152
+ ...input.position && positionFields(input.position)
153
+ });
154
+ if (doc && isGone(doc)) throw new DocNotFoundError(id);
155
+ }
156
+ /**
157
+ * Moves the doc to Linear's trash, which is recoverable from the UI. Linear rejects
158
+ * `documentUpdate` with `trashed: true` ("invalid trashed state"); `documentDelete` is its trash
159
+ * action, and calling it on an already-trashed doc succeeds.
160
+ */
161
+ async archive(id) {
162
+ if (!(await this.#notFoundAware(id, () => this.#request(TRASH, { id }))).documentDelete?.success) throw new Error(`documentDelete failed for ${id}`);
163
+ }
164
+ /**
165
+ * Uploads a file to Linear's storage: `fileUpload` returns a signed URL, the bytes go there with
166
+ * a PUT, and docs reference the returned asset URL (visible to workspace members).
167
+ */
168
+ async uploadAsset(asset) {
169
+ const filename = asset.path.split("/").pop() || asset.path;
170
+ const data = await this.#request(UPLOAD, {
171
+ filename,
172
+ contentType: asset.contentType,
173
+ size: asset.data.byteLength
174
+ });
175
+ const file = data.fileUpload?.uploadFile;
176
+ if (!data.fileUpload?.success || !file) throw new Error(`fileUpload failed for "${asset.path}"`);
177
+ const headers = {
178
+ "Content-Type": asset.contentType,
179
+ "Cache-Control": "public, max-age=31536000"
180
+ };
181
+ for (const { key, value } of file.headers) headers[key] = value;
182
+ const res = await this.#fetch(file.uploadUrl, {
183
+ method: "PUT",
184
+ headers,
185
+ body: asset.data,
186
+ signal: AbortSignal.timeout(this.#timeoutMs)
187
+ });
188
+ if (!res.ok) throw new LinearApiError(`Uploading "${asset.path}" failed with HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`, res.status);
189
+ return file.assetUrl;
190
+ }
191
+ /**
192
+ * Returns the doc's state after the update. Throws `DocNotFoundError` only when a read confirms
193
+ * this doc is gone (deleted, purged, trashed or archived); other "not found" errors pass through.
194
+ */
195
+ async #mutateUpdate(id, input) {
196
+ const data = await this.#notFoundAware(id, () => this.#request(UPDATE, {
197
+ id,
198
+ input
199
+ }));
200
+ if (!data.documentUpdate?.success) throw new Error(`documentUpdate failed for ${id}`);
201
+ return data.documentUpdate.document ?? null;
202
+ }
203
+ async #notFoundAware(id, run) {
204
+ try {
205
+ return await run();
206
+ } catch (error) {
207
+ if (looksNotFound(error) && await this.#confirmGone(id)) throw new DocNotFoundError(id);
208
+ throw error;
209
+ }
210
+ }
211
+ async #confirmGone(id) {
212
+ try {
213
+ const data = await this.#request(READ, { id });
214
+ return isGone(data.document);
215
+ } catch (error) {
216
+ return looksNotFound(error);
217
+ }
218
+ }
219
+ };
220
+ // ../linear/src/transforms.ts
221
+ /**
222
+ * The Markdown clean-up Linear needs: Linear shows `<a id>` anchors as literal text, and its heading
223
+ * ids are UUIDs, so `#slug` links are dead. Pass these to `plan` / `apply` when the target is a `LinearTarget`.
224
+ */
225
+ const linearTransforms = [stripHtmlAnchors, unlinkInPageLinks];
226
+ export { createGraphQLClient as a, LinearApiError as i, LinearTarget as n, LINEAR_ENDPOINT as r, linearTransforms as t };
@@ -0,0 +1,249 @@
1
+ import { C as rewriteLinks, l as applyTransforms, v as findImages } from "./src-BU0LDvW9.js";
2
+ import { mkdir, readFile, readdir, rename, rmdir, unlink, writeFile } from "node:fs/promises";
3
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
4
+ // ../markdown/src/files.ts
5
+ /**
6
+ * The file in the output folder that lists what Linopress wrote there. Only those files are ever
7
+ * deleted; anything else in the folder (a VitePress config, hand-written guides) is left alone.
8
+ */
9
+ const RECORD_FILE = ".linopress.json";
10
+ function sameBytes(a, b) {
11
+ if (a.length !== b.length) return false;
12
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
13
+ return true;
14
+ }
15
+ /**
16
+ * Diffs the files an edition writes against the output folder. Pure.
17
+ *
18
+ * - not on disk → **create**; different bytes on disk → **update**; same bytes → **unchanged**.
19
+ * Compared with the disk, not a stored hash, so a file edited by hand is put back.
20
+ * - in the record, no longer written, still on disk → **delete**.
21
+ */
22
+ function planFiles(files, state) {
23
+ const owned = new Set(state.owned);
24
+ const wanted = /* @__PURE__ */ new Set();
25
+ const writes = [];
26
+ const unchanged = [];
27
+ for (const file of files) {
28
+ if (wanted.has(file.path)) throw new Error(`Two output files at "${file.path}"`);
29
+ wanted.add(file.path);
30
+ const current = state.existing.get(file.path);
31
+ if (current === void 0) writes.push({
32
+ kind: "create",
33
+ path: file.path
34
+ });
35
+ else if (sameBytes(current, file.data)) unchanged.push({
36
+ kind: "unchanged",
37
+ path: file.path
38
+ });
39
+ else writes.push({
40
+ kind: "update",
41
+ path: file.path,
42
+ ...!owned.has(file.path) && { adopted: true }
43
+ });
44
+ }
45
+ const deletes = [...owned].filter((path) => !wanted.has(path) && state.existing.has(path)).sort().map((path) => ({
46
+ kind: "delete",
47
+ path
48
+ }));
49
+ const actions = [
50
+ ...writes,
51
+ ...deletes,
52
+ ...unchanged
53
+ ];
54
+ const counts = {
55
+ create: 0,
56
+ update: 0,
57
+ delete: 0,
58
+ unchanged: 0
59
+ };
60
+ for (const a of actions) counts[a.kind]++;
61
+ return {
62
+ actions,
63
+ counts,
64
+ owned: files.map((f) => f.path)
65
+ };
66
+ }
67
+ /** True when applying the plan would write or delete nothing. */
68
+ function isEmptyFilePlan(p) {
69
+ return p.actions.every((a) => a.kind === "unchanged");
70
+ }
71
+ /**
72
+ * Absolute path of an edition-relative `path` inside `out`. Throws for paths that would land
73
+ * outside it (a tampered record must not make Linopress delete files elsewhere).
74
+ */
75
+ function outputPath(out, path) {
76
+ const full = resolve(out, ...path.split("/"));
77
+ const rel = relative(out, full);
78
+ if (!rel || rel.startsWith("..") || isAbsolute(rel) || path === ".linopress.json") throw new Error(`Refusing to touch "${path}": not a file inside ${out}`);
79
+ return full;
80
+ }
81
+ async function readIfFile(path) {
82
+ try {
83
+ return await readFile(path);
84
+ } catch (error) {
85
+ const code = error.code;
86
+ if (code === "ENOENT" || code === "EISDIR" || code === "ENOTDIR") return void 0;
87
+ throw error;
88
+ }
89
+ }
90
+ /** Reads the record; an empty list when there is none yet. */
91
+ async function readRecord(out) {
92
+ const raw = await readIfFile(join(out, RECORD_FILE));
93
+ if (raw === void 0) return [];
94
+ let parsed;
95
+ try {
96
+ parsed = JSON.parse(new TextDecoder().decode(raw));
97
+ } catch (error) {
98
+ throw new Error(`${join(out, RECORD_FILE)} isn't valid JSON`, { cause: error });
99
+ }
100
+ const files = parsed?.files;
101
+ if (!Array.isArray(files) || !files.every((f) => typeof f === "string")) throw new Error(`${join(out, RECORD_FILE)} needs a "files" array of paths`);
102
+ for (const path of files) outputPath(out, path);
103
+ return files;
104
+ }
105
+ /** Reads the record and the current bytes of every file `files` writes or the record lists. */
106
+ async function readOutputState(out, files) {
107
+ const owned = await readRecord(out);
108
+ const existing = /* @__PURE__ */ new Map();
109
+ for (const path of /* @__PURE__ */ new Set([...files.map((f) => f.path), ...owned])) {
110
+ const data = await readIfFile(outputPath(out, path));
111
+ if (data !== void 0) existing.set(path, data);
112
+ }
113
+ return {
114
+ owned,
115
+ existing
116
+ };
117
+ }
118
+ async function writeRecord(out, files) {
119
+ const body = {
120
+ $comment: "Files Linopress wrote here. It deletes only these, when their pages go away.",
121
+ files: [...new Set(files)].sort()
122
+ };
123
+ const path = join(out, RECORD_FILE);
124
+ await writeFile(`${path}.tmp`, `${JSON.stringify(body, null, 2)}\n`);
125
+ await rename(`${path}.tmp`, path);
126
+ }
127
+ /** Removes `dir` and its parents up to (not including) `out` while they are empty. */
128
+ async function pruneEmptyDirs(out, dir) {
129
+ for (let d = dir; relative(out, d) && !relative(out, d).startsWith(".."); d = dirname(d)) {
130
+ if ((await readdir(d)).length > 0) return;
131
+ await rmdir(d);
132
+ }
133
+ }
134
+ /** Paths of files the plan would replace although Linopress didn't write them. */
135
+ function adoptedPaths(p) {
136
+ return p.actions.filter((a) => a.adopted).map((a) => a.path);
137
+ }
138
+ /**
139
+ * Writes created and updated files, deletes files of removed pages (and directories that become
140
+ * empty), and updates the record. The record is widened before the first write, so a run that
141
+ * stops halfway still knows which files are its own.
142
+ */
143
+ async function applyFiles(options) {
144
+ const { out, plan } = options;
145
+ const byPath = new Map(options.files.map((f) => [f.path, f]));
146
+ const adopted = adoptedPaths(plan);
147
+ if (adopted.length > 0 && !options.force) throw new Error(`Refusing to replace files Linopress didn't write: ${adopted.join(", ")} (pass force to replace them)`);
148
+ await mkdir(out, { recursive: true });
149
+ await writeRecord(out, [...options.owned, ...plan.owned]);
150
+ for (const action of plan.actions) {
151
+ if (action.kind !== "create" && action.kind !== "update") continue;
152
+ const file = byPath.get(action.path);
153
+ if (!file) throw new Error(`Plan writes "${action.path}", which isn't an output file`);
154
+ const full = outputPath(out, action.path);
155
+ await mkdir(dirname(full), { recursive: true });
156
+ await writeFile(full, file.data);
157
+ options.onEvent?.({
158
+ kind: action.kind === "create" ? "created" : "updated",
159
+ path: action.path
160
+ });
161
+ }
162
+ for (const action of plan.actions) {
163
+ if (action.kind !== "delete") continue;
164
+ const full = outputPath(out, action.path);
165
+ try {
166
+ await unlink(full);
167
+ } catch (error) {
168
+ if (error.code !== "ENOENT") throw error;
169
+ }
170
+ await pruneEmptyDirs(out, dirname(full));
171
+ options.onEvent?.({
172
+ kind: "deleted",
173
+ path: action.path
174
+ });
175
+ }
176
+ await writeRecord(out, plan.owned);
177
+ }
178
+ const SYMBOL = {
179
+ create: "+",
180
+ update: "~",
181
+ delete: "-",
182
+ unchanged: "="
183
+ };
184
+ /** Human-readable file plan, one line per file, in the style of `formatPlan`. */
185
+ function formatFilePlan(p, options = {}) {
186
+ const { create, update, delete: del, unchanged } = p.counts;
187
+ const lines = [`${create} to create, ${update} to update, ${del} to delete, ${unchanged} unchanged`];
188
+ const shown = p.actions.filter((a) => options.verbose || a.kind !== "unchanged");
189
+ if (shown.length > 0) lines.push("");
190
+ for (const a of shown) {
191
+ const note = a.adopted ? " (exists, not written by Linopress: push needs --force to replace it)" : "";
192
+ lines.push(` ${SYMBOL[a.kind]} ${a.kind.padEnd(9)} ${a.path}${note}`);
193
+ }
194
+ return lines.join("\n");
195
+ }
196
+ // ../markdown/src/render.ts
197
+ /**
198
+ * Transforms for a Markdown docs site: none. TypeDoc's `<a id>` anchors and `#fragment` links work
199
+ * on a normal site, so they are kept.
200
+ */
201
+ const markdownTransforms = [];
202
+ const encoder = new TextEncoder();
203
+ /**
204
+ * Renders an edition as files: each page gets its title back as an H1 (sources split it off for
205
+ * Linear), links stay relative with their `#fragment`s, and every embedded image that exists is
206
+ * copied to the same relative path, so references keep working.
207
+ */
208
+ function renderMarkdownEdition(nodes, assets, options = {}) {
209
+ const paths = new Set(nodes.map((n) => n.path));
210
+ const unresolvedLinks = {};
211
+ const missingImages = {};
212
+ const files = [];
213
+ for (const node of nodes) {
214
+ const body = applyTransforms(node.content, options.transforms ?? markdownTransforms);
215
+ const { unresolved } = rewriteLinks(body, node.path, (p) => paths.has(p) ? p : void 0);
216
+ if (unresolved.length > 0) unresolvedLinks[node.path] = unresolved;
217
+ const missing = findImages(body, node.path).filter((p) => !assets.has(p));
218
+ if (missing.length > 0) missingImages[node.path] = missing.sort();
219
+ const header = options.header?.(node) ?? "";
220
+ const title = `# ${escapeTitle(node.title)}\n\n`;
221
+ const content = `${header ? `${header.trimEnd()}\n\n` : ""}${title}${body.trimStart()}`;
222
+ files.push({
223
+ path: node.path,
224
+ kind: "page",
225
+ data: encoder.encode(withFinalNewline(content))
226
+ });
227
+ }
228
+ for (const asset of [...assets.values()].sort((a, b) => a.path < b.path ? -1 : 1)) {
229
+ if (paths.has(asset.path)) continue;
230
+ files.push({
231
+ path: asset.path,
232
+ kind: "asset",
233
+ data: asset.data
234
+ });
235
+ }
236
+ return {
237
+ files,
238
+ unresolvedLinks,
239
+ missingImages
240
+ };
241
+ }
242
+ /** Escapes what would make the title something other than plain heading text. */
243
+ function escapeTitle(title) {
244
+ return title.replace(/[\\`*_[\]<>]/g, "\\$&").replace(/\s+#+\s*$/, (m) => m.replace(/#/g, "\\#"));
245
+ }
246
+ function withFinalNewline(text) {
247
+ return text.endsWith("\n") ? text : `${text}\n`;
248
+ }
249
+ export { applyFiles as a, outputPath as c, readRecord as d, adoptedPaths as i, planFiles as l, renderMarkdownEdition as n, formatFilePlan as o, RECORD_FILE as r, isEmptyFilePlan as s, markdownTransforms as t, readOutputState as u };
@@ -0,0 +1,48 @@
1
+ import { o as Asset } from "./transforms-BBEyouxz.js";
2
+ /** Where a doc sits: under `parentId` (or top-level when `null`), at `sortOrder`. */
3
+ interface DocPosition {
4
+ readonly parentId: string | null;
5
+ readonly sortOrder: number;
6
+ }
7
+ interface CreateDocInput extends DocPosition {
8
+ readonly title: string;
9
+ readonly content: string;
10
+ }
11
+ /** Only the fields present are changed. */
12
+ interface UpdateDocInput {
13
+ readonly title?: string;
14
+ readonly content?: string;
15
+ readonly position?: DocPosition;
16
+ }
17
+ interface RemoteDoc {
18
+ readonly id: string;
19
+ readonly url: string;
20
+ }
21
+ /**
22
+ * Thrown by a target when a doc is gone: deleted, or archived outside Linopress.
23
+ * `apply` treats it as recoverable (re-creates the doc, or skips an archive that already happened).
24
+ */
25
+ declare class DocNotFoundError extends Error {
26
+ readonly docId: string;
27
+ constructor(docId: string, message?: string);
28
+ }
29
+ /**
30
+ * A place that stores documents (Linear, a fake in tests, ...).
31
+ * A target is bound to one container; the engine never deletes, it archives.
32
+ */
33
+ interface DocumentTarget {
34
+ create(input: CreateDocInput): Promise<RemoteDoc>;
35
+ /** Throws `DocNotFoundError` when the doc is deleted or archived. */
36
+ update(id: string, input: UpdateDocInput): Promise<void>;
37
+ /**
38
+ * Soft-removes a doc (recoverable in the target's UI). Throws `DocNotFoundError` (or resolves)
39
+ * when the doc is already deleted or archived.
40
+ */
41
+ archive(id: string): Promise<void>;
42
+ /**
43
+ * Stores a file (an image a doc embeds) and returns the URL docs should reference.
44
+ * Optional: without it, `apply` fails when there is an image to upload.
45
+ */
46
+ uploadAsset?(asset: Asset): Promise<string>;
47
+ }
48
+ export { RemoteDoc as a, DocumentTarget as i, DocNotFoundError as n, UpdateDocInput as o, DocPosition as r, CreateDocInput as t };