editlet 0.0.0-stage → 0.1.0-alpha.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.
- package/LICENSE +21 -0
- package/README.md +113 -2
- package/dist/admin/config.d.ts +22 -0
- package/dist/admin/config.js +75 -0
- package/dist/admin/dist/assets/RichEditor-BlaCRrEX.css +1 -0
- package/dist/admin/dist/assets/RichEditor-IZKdt6MK.js +42 -0
- package/dist/admin/dist/assets/blank-line-CbGzlqBI.js +1 -0
- package/dist/admin/dist/assets/channel-CljeMIwA.js +1 -0
- package/dist/admin/dist/assets/db-CCMyPgQa.js +1 -0
- package/dist/admin/dist/assets/index-CWoJh4H8.js +257 -0
- package/dist/admin/dist/assets/index-DkRMnD_M.css +1 -0
- package/dist/admin/dist/assets/mdast-util-from-markdown-C79q1_d8.js +3 -0
- package/dist/admin/dist/assets/mdast-util-gfm-cM-_xFJE.js +19 -0
- package/dist/admin/dist/assets/micromark-extension-gfm-Wz6-oszS.js +1 -0
- package/dist/admin/dist/assets/micromark-util-classify-character-BgXaGAja.js +1 -0
- package/dist/admin/dist/assets/micromark-util-html-tag-name-B61T18yC.js +1 -0
- package/dist/admin/dist/assets/rolldown-runtime-XKyaHtl9.js +1 -0
- package/dist/admin/dist/index.html +16 -0
- package/dist/admin/dist/preview.js +1 -0
- package/dist/admin/dist/window.js +1 -0
- package/dist/astro/content.d.ts +21 -0
- package/dist/astro/content.js +235 -0
- package/dist/astro/devServer.js +89 -0
- package/dist/astro/index.d.ts +15 -0
- package/dist/astro/index.js +98 -0
- package/dist/astro/nodeBridge.js +36 -0
- package/dist/astro/shared.js +10 -0
- package/dist/astro/stub/index.html +71 -0
- package/dist/auth/client.d.ts +24 -0
- package/dist/auth/client.js +120 -0
- package/dist/auth/handler.d.ts +16 -0
- package/dist/auth/handler.js +281 -0
- package/dist/auth/protocol.d.ts +25 -0
- package/dist/auth/protocol.js +3 -0
- package/dist/core/assets.d.ts +73 -0
- package/dist/core/assets.js +405 -0
- package/dist/core/devApi.d.ts +28 -0
- package/dist/core/devApi.js +3 -0
- package/dist/core/entryFile.d.ts +13 -0
- package/dist/core/entryFile.js +81 -0
- package/dist/core/fields.js +147 -0
- package/dist/core/generate.d.ts +3 -0
- package/dist/core/generate.js +70 -0
- package/dist/core/gitStyle.d.ts +92 -0
- package/dist/core/gitStyle.js +206 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +16 -0
- package/dist/core/issues.d.ts +10 -0
- package/dist/core/issues.js +10 -0
- package/dist/core/paths.d.ts +31 -0
- package/dist/core/paths.js +114 -0
- package/dist/core/project.js +56 -0
- package/dist/core/references.d.ts +68 -0
- package/dist/core/references.js +103 -0
- package/dist/core/rename.d.ts +60 -0
- package/dist/core/rename.js +133 -0
- package/dist/core/schema.d.ts +117 -0
- package/dist/core/schema.js +299 -0
- package/dist/core/sha.d.ts +2 -0
- package/dist/core/sha.js +13 -0
- package/dist/core/source.d.ts +48 -0
- package/dist/core/source.js +57 -0
- package/dist/core/validate.d.ts +22 -0
- package/dist/core/validate.js +148 -0
- package/dist/core/walk.d.ts +23 -0
- package/dist/core/walk.js +94 -0
- package/dist/core/writes.d.ts +37 -0
- package/dist/core/writes.js +166 -0
- package/dist/github/base64.js +16 -0
- package/dist/github/cache.d.ts +34 -0
- package/dist/github/cache.js +126 -0
- package/dist/github/client.d.ts +38 -0
- package/dist/github/client.js +228 -0
- package/dist/github/codeowners.d.ts +23 -0
- package/dist/github/codeowners.js +96 -0
- package/dist/github/commitReader.d.ts +25 -0
- package/dist/github/commitReader.js +38 -0
- package/dist/github/deploy.d.ts +15 -0
- package/dist/github/deploy.js +33 -0
- package/dist/github/index.d.ts +9 -0
- package/dist/github/index.js +8 -0
- package/dist/github/repo.d.ts +95 -0
- package/dist/github/repo.js +375 -0
- package/dist/github/source.d.ts +115 -0
- package/dist/github/source.js +558 -0
- package/dist/loader/index.d.ts +27 -0
- package/dist/loader/index.js +151 -0
- package/dist/loader/protocol.d.ts +95 -0
- package/dist/loader/protocol.js +120 -0
- package/dist/loader/window/geometry.js +9 -0
- package/dist/next/EditletLoader.d.ts +5 -0
- package/dist/next/EditletLoader.js +33 -0
- package/dist/next/assetUrl.d.ts +9 -0
- package/dist/next/assetUrl.js +13 -0
- package/dist/next/buildGuard.js +26 -0
- package/dist/next/config.d.ts +18 -0
- package/dist/next/config.js +255 -0
- package/dist/next/devServer.js +70 -0
- package/dist/next/editletField.d.ts +7 -0
- package/dist/next/editletField.js +7 -0
- package/dist/next/index.d.ts +8 -0
- package/dist/next/index.js +6 -0
- package/dist/next/preview.d.ts +18 -0
- package/dist/next/preview.js +100 -0
- package/dist/next/previewCookie.d.ts +5 -0
- package/dist/next/previewCookie.js +72 -0
- package/dist/next/previewEnv.js +25 -0
- package/dist/next/previewRef.d.ts +8 -0
- package/dist/next/previewRef.js +17 -0
- package/dist/next/publicDir.js +65 -0
- package/dist/next/reader.d.ts +49 -0
- package/dist/next/reader.js +161 -0
- package/dist/next/stub/index.html +56 -0
- package/dist/node/devHandler.d.ts +6 -0
- package/dist/node/devHandler.js +430 -0
- package/dist/node/fs.js +37 -0
- package/dist/node/index.d.ts +3 -0
- package/dist/node/index.js +3 -0
- package/dist/node/project.d.ts +12 -0
- package/dist/node/project.js +43 -0
- package/package.json +187 -4
- package/skills/README.md +84 -0
- package/skills/editlet/SKILL.md +119 -0
- package/skills/editlet/references/content-format.md +191 -0
- package/skills/editlet/references/preview.md +75 -0
- package/skills/editlet/references/publishing.md +137 -0
- package/skills/editlet/references/schema-changes.md +127 -0
- package/skills/editlet/scripts/guard.mjs +1061 -0
- package/skills/editlet/scripts/link.mjs +193 -0
- package/skills/editlet/scripts/refs.mjs +1480 -0
- package/skills/editlet/scripts/schema.mjs +1340 -0
- package/skills/editlet/scripts/style.mjs +657 -0
- package/skills/editlet/scripts/types.mjs +525 -0
- package/skills/editlet/scripts/validate.mjs +724 -0
- package/skills/editlet-migrate/SKILL.md +92 -0
- package/skills/editlet-migrate/references/mapping.md +73 -0
- package/skills/editlet-migrate/references/sources.md +70 -0
- package/skills/editlet-setup/SKILL.md +108 -0
- package/skills/editlet-setup/references/astro.md +83 -0
- package/skills/editlet-setup/references/doctor.md +89 -0
- package/skills/editlet-setup/references/next.md +140 -0
- package/skills/editlet-setup/references/preview.md +54 -0
- package/skills/editlet-setup/references/production.md +153 -0
- package/skills/editlet-setup/references/roles.md +238 -0
- package/skills/editlet-setup/references/skills.md +99 -0
- package/skills/editlet-setup/scripts/doctor.mjs +1378 -0
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
import { listFiles, loadProjectSchema } from "./fs.js";
|
|
2
|
+
import { DEV_API_BASE } from "../core/devApi.js";
|
|
3
|
+
import { decodeUtf8 } from "../core/entryFile.js";
|
|
4
|
+
import { EditletError } from "../core/issues.js";
|
|
5
|
+
import { isHiddenContentPath } from "../core/paths.js";
|
|
6
|
+
import { parseSchemaText } from "../core/schema.js";
|
|
7
|
+
import { gitBlobSha } from "../core/sha.js";
|
|
8
|
+
import { isWritablePath, validateChanges, validateCommit } from "../core/writes.js";
|
|
9
|
+
import { fromBase64 } from "../github/base64.js";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import { mkdir, readFile, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
12
|
+
import { basename, dirname, join, sep } from "node:path";
|
|
13
|
+
import { execFile } from "node:child_process";
|
|
14
|
+
import { readFileSync } from "node:fs";
|
|
15
|
+
import { promisify } from "node:util";
|
|
16
|
+
// node/devHandler.ts
|
|
17
|
+
const FILES_ROUTE = `${DEV_API_BASE}/files`;
|
|
18
|
+
const FILE_ROUTE = `${DEV_API_BASE}/file`;
|
|
19
|
+
const COMMIT_ROUTE = `${DEV_API_BASE}/commit`;
|
|
20
|
+
const HISTORY_ROUTE = `${DEV_API_BASE}/history`;
|
|
21
|
+
const GIT_ROUTE = `${DEV_API_BASE}/git`;
|
|
22
|
+
const execFileAsync = promisify(execFile);
|
|
23
|
+
const commitBody = z.strictObject({
|
|
24
|
+
message: z.string(),
|
|
25
|
+
changes: z.array(z.strictObject({
|
|
26
|
+
path: z.string(),
|
|
27
|
+
content: z.string().nullable(),
|
|
28
|
+
encoding: z.enum(["utf8", "base64"]).optional(),
|
|
29
|
+
sha: z.string().nullable().optional()
|
|
30
|
+
}))
|
|
31
|
+
});
|
|
32
|
+
const LOCAL_HOSTS = [
|
|
33
|
+
"localhost",
|
|
34
|
+
"127.0.0.1",
|
|
35
|
+
"[::1]"
|
|
36
|
+
];
|
|
37
|
+
const CONTENT_TYPES = {
|
|
38
|
+
md: "text/markdown; charset=utf-8",
|
|
39
|
+
json: "application/json",
|
|
40
|
+
webp: "image/webp",
|
|
41
|
+
png: "image/png",
|
|
42
|
+
gif: "image/gif",
|
|
43
|
+
avif: "image/avif",
|
|
44
|
+
jpg: "image/jpeg",
|
|
45
|
+
jpeg: "image/jpeg",
|
|
46
|
+
svg: "image/svg+xml"
|
|
47
|
+
};
|
|
48
|
+
/** Served files must never run as documents on the app origin (an SVG can carry script). */
|
|
49
|
+
const FILE_HEADERS = {
|
|
50
|
+
"Content-Security-Policy": "sandbox; default-src 'none'",
|
|
51
|
+
"X-Content-Type-Options": "nosniff"
|
|
52
|
+
};
|
|
53
|
+
function contentType(path) {
|
|
54
|
+
const ext = path.slice(path.lastIndexOf(".") + 1).toLowerCase();
|
|
55
|
+
return CONTENT_TYPES[ext] ?? "application/octet-stream";
|
|
56
|
+
}
|
|
57
|
+
function json(status, body, headers = {}) {
|
|
58
|
+
return new Response(JSON.stringify(body), {
|
|
59
|
+
status,
|
|
60
|
+
headers: {
|
|
61
|
+
"Content-Type": "application/json",
|
|
62
|
+
...headers
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
function fail(status, message, headers) {
|
|
67
|
+
return json(status, { issues: [{
|
|
68
|
+
path: "",
|
|
69
|
+
message
|
|
70
|
+
}] }, headers);
|
|
71
|
+
}
|
|
72
|
+
/** Issue when a file's current sha (`null` = missing) is not the expected one (`null` = must not exist). */
|
|
73
|
+
function shaIssue(file, expected, actual) {
|
|
74
|
+
if (expected === actual) return null;
|
|
75
|
+
return {
|
|
76
|
+
file,
|
|
77
|
+
path: "",
|
|
78
|
+
message: actual === null ? "File not found" : expected === null ? "File already exists" : "File changed since it was read"
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** `If-Match` value without surrounding quotes; `undefined` when the header is absent. */
|
|
82
|
+
function ifMatch(req) {
|
|
83
|
+
return req.headers.get("if-match")?.trim().replace(/^"(.*)"$/, "$1");
|
|
84
|
+
}
|
|
85
|
+
/** UTF-8 text of a file, or `undefined` when it cannot be read or is not valid UTF-8. */
|
|
86
|
+
function readText(target) {
|
|
87
|
+
try {
|
|
88
|
+
const decoded = decodeUtf8(new Uint8Array(readFileSync(target)), target);
|
|
89
|
+
return "text" in decoded ? decoded.text : void 0;
|
|
90
|
+
} catch {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const errorCode = (error) => error?.code ?? "";
|
|
95
|
+
var HttpError = class extends Error {
|
|
96
|
+
status;
|
|
97
|
+
constructor(status, message) {
|
|
98
|
+
super(message);
|
|
99
|
+
this.status = status;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
/** Realpath of the deepest existing ancestor of `path`, with the missing tail appended. */
|
|
103
|
+
async function realpathDeepest(path) {
|
|
104
|
+
const tail = [];
|
|
105
|
+
let current = path;
|
|
106
|
+
for (;;) try {
|
|
107
|
+
return join(await realpath(current), ...tail.toReversed());
|
|
108
|
+
} catch (error) {
|
|
109
|
+
const parent = dirname(current);
|
|
110
|
+
if (!["ENOENT", "ENOTDIR"].includes(errorCode(error)) || parent === current) throw error;
|
|
111
|
+
tail.push(basename(current));
|
|
112
|
+
current = parent;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async function isInside(target, base) {
|
|
116
|
+
const [realTarget, realBase] = await Promise.all([realpathDeepest(target), realpathDeepest(base)]);
|
|
117
|
+
return realTarget.startsWith(realBase + sep);
|
|
118
|
+
}
|
|
119
|
+
/** Whether `target` exists as a regular file; throws a 400 for directories and paths through a file. */
|
|
120
|
+
async function fileExists(target) {
|
|
121
|
+
try {
|
|
122
|
+
if ((await stat(target)).isDirectory()) throw new HttpError(400, "Path is a directory");
|
|
123
|
+
return true;
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (errorCode(error) === "ENOENT") return false;
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Stages every write to a temp file next to its target, then renames them all into place, then runs the deletes.
|
|
131
|
+
* If staging fails the temp files are removed and nothing is applied.
|
|
132
|
+
*/
|
|
133
|
+
async function applyChanges(root, changes) {
|
|
134
|
+
const staged = [];
|
|
135
|
+
try {
|
|
136
|
+
for (const { path, content } of changes) {
|
|
137
|
+
if (content === null) continue;
|
|
138
|
+
const target = join(root, path);
|
|
139
|
+
await mkdir(dirname(target), { recursive: true });
|
|
140
|
+
const temp = join(dirname(target), `.${basename(target)}.${crypto.randomUUID()}.tmp`);
|
|
141
|
+
staged.push({
|
|
142
|
+
temp,
|
|
143
|
+
target
|
|
144
|
+
});
|
|
145
|
+
await writeFile(temp, content);
|
|
146
|
+
}
|
|
147
|
+
} catch (error) {
|
|
148
|
+
await Promise.all(staged.map(({ temp }) => rm(temp, { force: true })));
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
for (const { temp, target } of staged) await rename(temp, target);
|
|
152
|
+
for (const { path, content } of changes) {
|
|
153
|
+
if (content !== null) continue;
|
|
154
|
+
await rm(join(root, path), { force: true });
|
|
155
|
+
await pruneEmptyDirs(root, dirname(path));
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Removes `dir` (relative to `root`) and its parents while they are empty, like Git, which keeps no empty folders: a
|
|
160
|
+
* moved or deleted image folder does not linger. Stops at the first folder that still has files, or at `root`.
|
|
161
|
+
*/
|
|
162
|
+
async function pruneEmptyDirs(root, dir) {
|
|
163
|
+
for (let d = dir; d !== "." && d !== "" && d !== "/"; d = dirname(d)) try {
|
|
164
|
+
await rmdir(join(root, d));
|
|
165
|
+
} catch {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async function currentSha(target, exists) {
|
|
170
|
+
return exists ? gitBlobSha(await readFile(target)) : null;
|
|
171
|
+
}
|
|
172
|
+
function isAllowedHost(hostname, extra) {
|
|
173
|
+
return LOCAL_HOSTS.includes(hostname) || hostname.endsWith(".localhost") || extra.includes(hostname);
|
|
174
|
+
}
|
|
175
|
+
function createDevHandler(opts) {
|
|
176
|
+
const { root } = opts;
|
|
177
|
+
const schemaPath = opts.schemaPath ?? "cms/schema.json";
|
|
178
|
+
const allowedHosts = opts.allowedHosts ?? [];
|
|
179
|
+
async function currentSchema() {
|
|
180
|
+
try {
|
|
181
|
+
return {
|
|
182
|
+
schema: await loadProjectSchema(root, schemaPath),
|
|
183
|
+
issues: []
|
|
184
|
+
};
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (error instanceof EditletError) return {
|
|
187
|
+
schema: null,
|
|
188
|
+
issues: error.issues
|
|
189
|
+
};
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
async function listFilesRoute(schema) {
|
|
194
|
+
const content = (await listFiles(root, schema.contentDir)).filter((p) => !isHiddenContentPath(schema, p));
|
|
195
|
+
const paths = [.../* @__PURE__ */ new Set([...content, schemaPath])].toSorted();
|
|
196
|
+
return json(200, { files: await Promise.all(paths.map(async (path) => ({
|
|
197
|
+
path,
|
|
198
|
+
sha: await gitBlobSha(await readFile(join(root, path)))
|
|
199
|
+
}))) });
|
|
200
|
+
}
|
|
201
|
+
/** Repo state for `validateChanges`: the files under contentDir plus the schema file. */
|
|
202
|
+
async function changeContext(schema) {
|
|
203
|
+
const existing = new Set(schema === null ? [] : await listFiles(root, schema.contentDir)).add(schemaPath);
|
|
204
|
+
return {
|
|
205
|
+
schema,
|
|
206
|
+
schemaPath,
|
|
207
|
+
exists: (p) => existing.has(p),
|
|
208
|
+
list: () => existing,
|
|
209
|
+
read: (p) => readText(join(root, p))
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
/** The schema a batch writes to the schema file, when it parses; `null` otherwise. */
|
|
213
|
+
function batchSchema(changes) {
|
|
214
|
+
const content = changes.find((c) => c.path === schemaPath)?.content;
|
|
215
|
+
const decoded = content === void 0 || content === null ? null : decodeUtf8(content, schemaPath);
|
|
216
|
+
if (decoded === null || "issue" in decoded) return null;
|
|
217
|
+
try {
|
|
218
|
+
return parseSchemaText(decoded.text, schemaPath);
|
|
219
|
+
} catch {
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/** Directory a writable path must resolve inside (after symlinks): the schema's folder or contentDir. */
|
|
224
|
+
function baseOf(path, schema) {
|
|
225
|
+
return path === schemaPath || schema === null ? dirname(join(root, schemaPath)) : join(root, schema.contentDir);
|
|
226
|
+
}
|
|
227
|
+
/** `schema` is null only when the schema on disk is broken; then `path` is the schema file. */
|
|
228
|
+
async function fileRoute(req, path, schema) {
|
|
229
|
+
const target = join(root, path);
|
|
230
|
+
if (!await isInside(target, baseOf(path, schema))) return fail(400, "Path resolves outside the content directory");
|
|
231
|
+
const exists = await fileExists(target);
|
|
232
|
+
if (req.method === "GET") {
|
|
233
|
+
if (!exists) return fail(404, "File not found");
|
|
234
|
+
const bytes = new Uint8Array(await readFile(target));
|
|
235
|
+
return new Response(bytes, {
|
|
236
|
+
status: 200,
|
|
237
|
+
headers: {
|
|
238
|
+
"Content-Type": contentType(path),
|
|
239
|
+
...FILE_HEADERS
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
if (req.method === "DELETE" && path === schemaPath) return fail(400, "The schema file cannot be deleted");
|
|
244
|
+
const expected = ifMatch(req);
|
|
245
|
+
const conflict = expected === void 0 ? null : shaIssue(path, expected, await currentSha(target, exists));
|
|
246
|
+
if (conflict) return json(412, { issues: [conflict] });
|
|
247
|
+
if (req.method === "DELETE" && !exists) return fail(404, "File not found");
|
|
248
|
+
const change = {
|
|
249
|
+
path,
|
|
250
|
+
content: req.method === "PUT" ? new Uint8Array(await req.arrayBuffer()) : null
|
|
251
|
+
};
|
|
252
|
+
const issues = validateChanges(await changeContext(schema), [change]);
|
|
253
|
+
if (issues.length > 0) return json(422, { issues });
|
|
254
|
+
await applyChanges(root, [change]);
|
|
255
|
+
return new Response(null, { status: 204 });
|
|
256
|
+
}
|
|
257
|
+
async function commitRoute(req) {
|
|
258
|
+
let raw;
|
|
259
|
+
try {
|
|
260
|
+
raw = await req.json();
|
|
261
|
+
} catch {
|
|
262
|
+
return fail(400, "Body must be JSON");
|
|
263
|
+
}
|
|
264
|
+
const body = commitBody.safeParse(raw);
|
|
265
|
+
if (!body.success) return json(400, { issues: body.error.issues.map((i) => ({
|
|
266
|
+
path: i.path.join("."),
|
|
267
|
+
message: i.message
|
|
268
|
+
})) });
|
|
269
|
+
const { message, changes: requested } = body.data;
|
|
270
|
+
const { schema, issues: schemaIssues } = await currentSchema();
|
|
271
|
+
if (schema === null && requested.some((c) => c.path !== schemaPath)) return json(500, { issues: schemaIssues });
|
|
272
|
+
const changes = [];
|
|
273
|
+
for (const { path, content, encoding } of requested) {
|
|
274
|
+
if (content === null || encoding !== "base64") {
|
|
275
|
+
changes.push({
|
|
276
|
+
path,
|
|
277
|
+
content
|
|
278
|
+
});
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
changes.push({
|
|
283
|
+
path,
|
|
284
|
+
content: fromBase64(content)
|
|
285
|
+
});
|
|
286
|
+
} catch {
|
|
287
|
+
return json(400, { issues: [{
|
|
288
|
+
file: path,
|
|
289
|
+
path: "",
|
|
290
|
+
message: "Content is not valid base64"
|
|
291
|
+
}] });
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
const schemas = [schema, batchSchema(changes)].filter((s) => s !== null);
|
|
295
|
+
const owners = /* @__PURE__ */ new Map();
|
|
296
|
+
const notWritable = [];
|
|
297
|
+
for (const { path } of changes) {
|
|
298
|
+
const owner = path === schemaPath ? null : schemas.find((s) => isWritablePath(s, schemaPath, path));
|
|
299
|
+
if (owner === void 0) notWritable.push({
|
|
300
|
+
file: path,
|
|
301
|
+
path: "",
|
|
302
|
+
message: "Path not writable"
|
|
303
|
+
});
|
|
304
|
+
else owners.set(path, owner);
|
|
305
|
+
}
|
|
306
|
+
if (notWritable.length > 0) return json(400, { issues: notWritable });
|
|
307
|
+
const conflicts = [];
|
|
308
|
+
for (const { path, sha } of requested) {
|
|
309
|
+
const target = join(root, path);
|
|
310
|
+
if (!await isInside(target, baseOf(path, owners.get(path) ?? null))) return json(400, { issues: [{
|
|
311
|
+
file: path,
|
|
312
|
+
path: "",
|
|
313
|
+
message: "Path resolves outside the content directory"
|
|
314
|
+
}] });
|
|
315
|
+
const exists = await fileExists(target);
|
|
316
|
+
const conflict = sha === void 0 ? null : shaIssue(path, sha, await currentSha(target, exists));
|
|
317
|
+
if (conflict) conflicts.push(conflict);
|
|
318
|
+
}
|
|
319
|
+
if (conflicts.length > 0) return json(409, { issues: conflicts });
|
|
320
|
+
const issues = validateCommit(await changeContext(schema), changes, message);
|
|
321
|
+
if (issues.length > 0) return json(422, { issues });
|
|
322
|
+
await applyChanges(root, changes);
|
|
323
|
+
return new Response(null, { status: 204 });
|
|
324
|
+
}
|
|
325
|
+
/** The checkout's branch and the number of uncommitted files under `contentDir`; empty when git is not usable. */
|
|
326
|
+
async function gitRoute() {
|
|
327
|
+
const git = async (...args) => (await execFileAsync("git", [
|
|
328
|
+
"-C",
|
|
329
|
+
root,
|
|
330
|
+
...args
|
|
331
|
+
])).stdout;
|
|
332
|
+
let body = {
|
|
333
|
+
branch: null,
|
|
334
|
+
changes: 0
|
|
335
|
+
};
|
|
336
|
+
try {
|
|
337
|
+
const branch = (await git("branch", "--show-current")).trim();
|
|
338
|
+
const { schema } = await currentSchema();
|
|
339
|
+
const status = await git("status", "--porcelain", "-uall", "--", schema?.contentDir ?? ".");
|
|
340
|
+
body = {
|
|
341
|
+
branch: branch === "" ? null : branch,
|
|
342
|
+
changes: status.split("\n").filter(Boolean).length
|
|
343
|
+
};
|
|
344
|
+
} catch {}
|
|
345
|
+
return json(200, body);
|
|
346
|
+
}
|
|
347
|
+
/** `git log` of one file: newest and oldest commit plus the count; empty when git is not usable. */
|
|
348
|
+
async function historyRoute(path) {
|
|
349
|
+
let body = {
|
|
350
|
+
updated: null,
|
|
351
|
+
created: null,
|
|
352
|
+
commits: 0
|
|
353
|
+
};
|
|
354
|
+
try {
|
|
355
|
+
const events = (await execFileAsync("git", [
|
|
356
|
+
"-C",
|
|
357
|
+
root,
|
|
358
|
+
"log",
|
|
359
|
+
"--format=%an%x1f%aI%x1f%s",
|
|
360
|
+
"--",
|
|
361
|
+
path
|
|
362
|
+
], { maxBuffer: 1 << 24 })).stdout.split("\n").filter(Boolean).map((line) => {
|
|
363
|
+
const [name = "", date = "", message = ""] = line.split("");
|
|
364
|
+
return {
|
|
365
|
+
actor: { name },
|
|
366
|
+
date,
|
|
367
|
+
message
|
|
368
|
+
};
|
|
369
|
+
});
|
|
370
|
+
body = {
|
|
371
|
+
updated: events[0] ?? null,
|
|
372
|
+
created: events.at(-1) ?? null,
|
|
373
|
+
commits: events.length
|
|
374
|
+
};
|
|
375
|
+
} catch {}
|
|
376
|
+
return json(200, body);
|
|
377
|
+
}
|
|
378
|
+
async function handle(req) {
|
|
379
|
+
if (process.env.NODE_ENV === "production") return fail(403, "The Editlet dev API is disabled in production");
|
|
380
|
+
const url = new URL(req.url);
|
|
381
|
+
if (!isAllowedHost(url.hostname, allowedHosts)) return fail(403, `Host "${url.hostname}" is not allowed`);
|
|
382
|
+
const origin = req.headers.get("origin");
|
|
383
|
+
if (origin !== null && origin !== url.origin) return fail(403, "Cross-origin requests are not allowed");
|
|
384
|
+
if (url.pathname === FILES_ROUTE) {
|
|
385
|
+
if (req.method !== "GET") return fail(405, "Method not allowed", { Allow: "GET" });
|
|
386
|
+
const { schema, issues } = await currentSchema();
|
|
387
|
+
return schema === null ? json(500, { issues }) : listFilesRoute(schema);
|
|
388
|
+
}
|
|
389
|
+
if (url.pathname === FILE_ROUTE) {
|
|
390
|
+
if (![
|
|
391
|
+
"GET",
|
|
392
|
+
"PUT",
|
|
393
|
+
"DELETE"
|
|
394
|
+
].includes(req.method)) return fail(405, "Method not allowed", { Allow: "GET, PUT, DELETE" });
|
|
395
|
+
const path = url.searchParams.get("path");
|
|
396
|
+
if (path === null || path === "") return fail(400, "Missing \"path\" query parameter");
|
|
397
|
+
const { schema, issues } = await currentSchema();
|
|
398
|
+
if (path === schemaPath) return fileRoute(req, path, schema);
|
|
399
|
+
if (schema === null) return json(500, { issues });
|
|
400
|
+
if (!isWritablePath(schema, schemaPath, path)) return fail(400, "Path not writable");
|
|
401
|
+
return fileRoute(req, path, schema);
|
|
402
|
+
}
|
|
403
|
+
if (url.pathname === GIT_ROUTE) {
|
|
404
|
+
if (req.method !== "GET") return fail(405, "Method not allowed", { Allow: "GET" });
|
|
405
|
+
return gitRoute();
|
|
406
|
+
}
|
|
407
|
+
if (url.pathname === HISTORY_ROUTE) {
|
|
408
|
+
if (req.method !== "GET") return fail(405, "Method not allowed", { Allow: "GET" });
|
|
409
|
+
const path = url.searchParams.get("path");
|
|
410
|
+
if (path === null || path === "") return fail(400, "Missing \"path\" query parameter");
|
|
411
|
+
if (path.startsWith("/") || path.split("/").includes("..")) return fail(400, "Path not readable");
|
|
412
|
+
return historyRoute(path);
|
|
413
|
+
}
|
|
414
|
+
if (url.pathname === COMMIT_ROUTE) {
|
|
415
|
+
if (req.method !== "POST") return fail(405, "Method not allowed", { Allow: "POST" });
|
|
416
|
+
return commitRoute(req);
|
|
417
|
+
}
|
|
418
|
+
return fail(404, "Not found");
|
|
419
|
+
}
|
|
420
|
+
return async (req) => {
|
|
421
|
+
try {
|
|
422
|
+
return await handle(req);
|
|
423
|
+
} catch (error) {
|
|
424
|
+
if (error instanceof HttpError) return fail(error.status, error.message);
|
|
425
|
+
if (["ENOTDIR", "EISDIR"].includes(errorCode(error))) return fail(400, "Path is not a file");
|
|
426
|
+
return fail(500, error instanceof Error ? error.message : String(error));
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
export { createDevHandler };
|
package/dist/node/fs.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { EditletError } from "../core/issues.js";
|
|
2
|
+
import { parseSchemaText } from "../core/schema.js";
|
|
3
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
// node/fs.ts
|
|
6
|
+
const DEFAULT_SCHEMA_PATH = "cms/schema.json";
|
|
7
|
+
async function loadProjectSchema(root, schemaPath) {
|
|
8
|
+
let raw;
|
|
9
|
+
try {
|
|
10
|
+
raw = await readFile(join(root, schemaPath), "utf8");
|
|
11
|
+
} catch (error) {
|
|
12
|
+
throw new EditletError([{
|
|
13
|
+
file: schemaPath,
|
|
14
|
+
path: "",
|
|
15
|
+
message: `Cannot read schema: ${error instanceof Error ? error.message : error}`
|
|
16
|
+
}]);
|
|
17
|
+
}
|
|
18
|
+
return parseSchemaText(raw, schemaPath);
|
|
19
|
+
}
|
|
20
|
+
/** All regular files under `root/contentDir` as sorted repo-relative posix paths (dot files included). */
|
|
21
|
+
async function listFiles(root, contentDir) {
|
|
22
|
+
let dirents;
|
|
23
|
+
try {
|
|
24
|
+
dirents = await readdir(join(root, contentDir), {
|
|
25
|
+
recursive: true,
|
|
26
|
+
withFileTypes: true
|
|
27
|
+
});
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (error.code === "ENOENT") return [];
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
return dirents.filter((d) => d.isFile()).map((d) => `${relativeDir(root, d.parentPath)}/${d.name}`.split("\\").join("/")).toSorted();
|
|
33
|
+
}
|
|
34
|
+
function relativeDir(root, dir) {
|
|
35
|
+
return resolve(dir).slice(resolve(root).length + 1);
|
|
36
|
+
}
|
|
37
|
+
export { DEFAULT_SCHEMA_PATH, listFiles, loadProjectSchema };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Issue } from "../core/issues.js";
|
|
2
|
+
import { Schema } from "../core/schema.js";
|
|
3
|
+
import { Entry } from "../core/validate.js";
|
|
4
|
+
export interface Project {
|
|
5
|
+
root: string;
|
|
6
|
+
schema: Schema;
|
|
7
|
+
entries: Entry[];
|
|
8
|
+
issues: Issue[];
|
|
9
|
+
}
|
|
10
|
+
export declare function readProject(root: string, schemaPath?: string): Promise<Project>;
|
|
11
|
+
export declare function validateProject(root: string, schemaPath?: string): Promise<Issue[]>;
|
|
12
|
+
export declare function writeTypes(root: string, outFile?: string, schemaPath?: string): Promise<string>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { DEFAULT_SCHEMA_PATH, listFiles, loadProjectSchema } from "./fs.js";
|
|
2
|
+
import { generateTypes } from "../core/generate.js";
|
|
3
|
+
import { refKey } from "../core/paths.js";
|
|
4
|
+
import { byFile, entriesFromFiles, entryCandidate, isSkippedPath } from "../core/project.js";
|
|
5
|
+
import { validateEntry } from "../core/validate.js";
|
|
6
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
7
|
+
import { dirname, join, resolve } from "node:path";
|
|
8
|
+
// node/project.ts
|
|
9
|
+
const DEFAULT_TYPES_FILE = ".editlet/content.d.ts";
|
|
10
|
+
async function readProject(root, schemaPath = DEFAULT_SCHEMA_PATH) {
|
|
11
|
+
const schema = await loadProjectSchema(root, schemaPath);
|
|
12
|
+
const files = await listFiles(root, schema.contentDir);
|
|
13
|
+
const contents = /* @__PURE__ */ new Map();
|
|
14
|
+
for (const file of files) {
|
|
15
|
+
if (isSkippedPath(schema, schemaPath, file)) continue;
|
|
16
|
+
contents.set(file, entryCandidate(schema, file) ? new Uint8Array(await readFile(join(root, file))) : /* @__PURE__ */ new Uint8Array());
|
|
17
|
+
}
|
|
18
|
+
return {
|
|
19
|
+
root,
|
|
20
|
+
schema,
|
|
21
|
+
...entriesFromFiles(schema, schemaPath, contents)
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
async function validateProject(root, schemaPath = DEFAULT_SCHEMA_PATH) {
|
|
25
|
+
const project = await readProject(root, schemaPath);
|
|
26
|
+
const { schema, entries } = project;
|
|
27
|
+
const refs = new Set(entries.map((e) => refKey(e.collection, e.slug)));
|
|
28
|
+
const files = new Set(await listFiles(root, schema.contentDir));
|
|
29
|
+
const issues = [...project.issues];
|
|
30
|
+
for (const entry of entries) issues.push(...validateEntry(schema, entry, {
|
|
31
|
+
entryExists: (ref) => refs.has(ref),
|
|
32
|
+
fileExists: (p) => files.has(p)
|
|
33
|
+
}));
|
|
34
|
+
return issues.toSorted(byFile);
|
|
35
|
+
}
|
|
36
|
+
async function writeTypes(root, outFile = DEFAULT_TYPES_FILE, schemaPath = DEFAULT_SCHEMA_PATH) {
|
|
37
|
+
const schema = await loadProjectSchema(root, schemaPath);
|
|
38
|
+
const target = resolve(root, outFile);
|
|
39
|
+
await mkdir(dirname(target), { recursive: true });
|
|
40
|
+
await writeFile(target, generateTypes(schema));
|
|
41
|
+
return target;
|
|
42
|
+
}
|
|
43
|
+
export { readProject, validateProject, writeTypes };
|