editlet 0.0.0-stage → 0.1.0-alpha.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.
- package/LICENSE +21 -0
- package/README.md +140 -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,1378 @@
|
|
|
1
|
+
// skills/editlet-setup/scripts/doctor.ts
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
|
|
4
|
+
import { basename, join as join4, resolve as resolve3 } from "node:path";
|
|
5
|
+
|
|
6
|
+
// skills/editlet-setup/scripts/doctorLocal.ts
|
|
7
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
8
|
+
import { join as join3 } from "node:path";
|
|
9
|
+
|
|
10
|
+
// core/issues.ts
|
|
11
|
+
var EditletError = class extends Error {
|
|
12
|
+
issues;
|
|
13
|
+
constructor(issues, message) {
|
|
14
|
+
super(message ?? issues.map((i) => i.path ? `${i.path}: ${i.message}` : i.message).join("; "));
|
|
15
|
+
this.name = "EditletError";
|
|
16
|
+
this.issues = issues;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// node/project.ts
|
|
21
|
+
import { mkdir, readFile as readFile2, writeFile } from "node:fs/promises";
|
|
22
|
+
import { dirname, join as join2, resolve as resolve2 } from "node:path";
|
|
23
|
+
|
|
24
|
+
// node/fs.ts
|
|
25
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
26
|
+
import { join, resolve } from "node:path";
|
|
27
|
+
|
|
28
|
+
// core/schema.ts
|
|
29
|
+
import { z as z2 } from "zod";
|
|
30
|
+
|
|
31
|
+
// core/fields.ts
|
|
32
|
+
import { z } from "zod";
|
|
33
|
+
|
|
34
|
+
// core/paths.ts
|
|
35
|
+
var SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
36
|
+
function isValidSlug(slug) {
|
|
37
|
+
return SLUG_RE.test(slug);
|
|
38
|
+
}
|
|
39
|
+
function hasCollection(schema, collection) {
|
|
40
|
+
return Object.hasOwn(schema.collections, collection);
|
|
41
|
+
}
|
|
42
|
+
function entryFilePath(schema, collection, slug) {
|
|
43
|
+
const singleton = hasCollection(schema, collection) && schema.collections[collection].singleton;
|
|
44
|
+
return `${schema.contentDir}/${collection}/${singleton ? "index" : slug}.md`;
|
|
45
|
+
}
|
|
46
|
+
function isCanonicalPath(path) {
|
|
47
|
+
if (path === "" || /[\\\0:]/.test(path)) return false;
|
|
48
|
+
return path.split("/").every((seg) => seg !== "" && seg !== "." && seg !== "..");
|
|
49
|
+
}
|
|
50
|
+
function isHiddenContentPath(schema, path) {
|
|
51
|
+
const prefix = `${schema.contentDir}/`;
|
|
52
|
+
const rest = path.startsWith(prefix) ? path.slice(prefix.length) : path;
|
|
53
|
+
return rest.split("/").some((seg) => seg.startsWith("."));
|
|
54
|
+
}
|
|
55
|
+
function parseEntryPath(schema, path) {
|
|
56
|
+
const prefix = `${schema.contentDir}/`;
|
|
57
|
+
if (!path.startsWith(prefix) || !isCanonicalPath(path)) return null;
|
|
58
|
+
const parts = path.slice(prefix.length).split("/");
|
|
59
|
+
if (parts.length !== 2) return null;
|
|
60
|
+
const [collection, file] = parts;
|
|
61
|
+
if (!hasCollection(schema, collection) || !file.endsWith(".md")) return null;
|
|
62
|
+
const name = file.slice(0, -3);
|
|
63
|
+
if (name === "") return null;
|
|
64
|
+
if (schema.collections[collection].singleton) return file === "index.md" ? { collection, slug: "index" } : null;
|
|
65
|
+
return { collection, slug: name };
|
|
66
|
+
}
|
|
67
|
+
function resolveAssetPath(schema, entryFile, src) {
|
|
68
|
+
if (src === "" || src.startsWith("/") || src.includes("\\") || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(src)) return null;
|
|
69
|
+
const srcSegs = src.split("/");
|
|
70
|
+
const last = srcSegs[srcSegs.length - 1];
|
|
71
|
+
if (last === "" || last === "." || last === "..") return null;
|
|
72
|
+
const out = entryFile.split("/").slice(0, -1);
|
|
73
|
+
for (const seg of srcSegs) {
|
|
74
|
+
if (seg === "" || seg === ".") continue;
|
|
75
|
+
if (seg === "..") {
|
|
76
|
+
if (out.length === 0) return null;
|
|
77
|
+
out.pop();
|
|
78
|
+
} else out.push(seg);
|
|
79
|
+
}
|
|
80
|
+
const result = out.join("/");
|
|
81
|
+
return result.startsWith(`${schema.contentDir}/`) ? result : null;
|
|
82
|
+
}
|
|
83
|
+
function refKey(collection, slug) {
|
|
84
|
+
return `${collection}/${slug}`;
|
|
85
|
+
}
|
|
86
|
+
var IMAGE_EXTENSIONS = ["webp", "png", "jpg", "jpeg", "avif", "gif", "svg"];
|
|
87
|
+
function isImagePath(path) {
|
|
88
|
+
const name = path.slice(path.lastIndexOf("/") + 1);
|
|
89
|
+
const dot = name.lastIndexOf(".");
|
|
90
|
+
return dot > 0 && IMAGE_EXTENSIONS.includes(name.slice(dot + 1).toLowerCase());
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// core/fields.ts
|
|
94
|
+
function isStringValued(field) {
|
|
95
|
+
switch (field.type) {
|
|
96
|
+
case "string":
|
|
97
|
+
return !field.list;
|
|
98
|
+
case "select":
|
|
99
|
+
case "reference":
|
|
100
|
+
return !field.multiple;
|
|
101
|
+
case "text":
|
|
102
|
+
case "datetime":
|
|
103
|
+
case "url":
|
|
104
|
+
case "color":
|
|
105
|
+
return true;
|
|
106
|
+
default:
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function isAbsentValue(field, value) {
|
|
111
|
+
return value === void 0 || value === null || value === "" && isStringValued(field);
|
|
112
|
+
}
|
|
113
|
+
function err(field, message) {
|
|
114
|
+
return (iss) => field.required && isAbsentValue(field, iss.input) ? "Required" : message;
|
|
115
|
+
}
|
|
116
|
+
function optional(field, schema, message) {
|
|
117
|
+
if (field.required) return schema;
|
|
118
|
+
return isStringValued(field) ? z.union([schema, z.literal("")], { error: message }).nullish() : schema.nullish();
|
|
119
|
+
}
|
|
120
|
+
function isUrl(v) {
|
|
121
|
+
return v.startsWith("/") || URL.canParse(v);
|
|
122
|
+
}
|
|
123
|
+
function noRepeats(message) {
|
|
124
|
+
return (items, ctx) => {
|
|
125
|
+
const seen = /* @__PURE__ */ new Set();
|
|
126
|
+
items.forEach((item, i) => {
|
|
127
|
+
if (seen.has(item)) ctx.addIssue({ code: "custom", path: [i], message: message(item) });
|
|
128
|
+
seen.add(item);
|
|
129
|
+
});
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function listField(field, item, min, max, unique) {
|
|
133
|
+
const effective = Math.max(field.required ? 1 : 0, min);
|
|
134
|
+
let arr = z.array(item, { error: err(field, "Expected a list") });
|
|
135
|
+
if (effective > 0) {
|
|
136
|
+
arr = arr.min(effective, {
|
|
137
|
+
error: (iss) => Array.isArray(iss.input) && iss.input.length === 0 && field.required ? "Required" : `Must have at least ${effective}`
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
if (max !== void 0) arr = arr.max(max, { error: `Must have at most ${max}` });
|
|
141
|
+
return optional(field, unique ? arr.superRefine(noRepeats(unique)) : arr, "Expected a list");
|
|
142
|
+
}
|
|
143
|
+
var escapeRegex = (v) => v.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
144
|
+
function fieldsShape(fields) {
|
|
145
|
+
const shape = {};
|
|
146
|
+
for (const [key, field] of Object.entries(fields)) shape[key] = nestedValueSchema(field);
|
|
147
|
+
return shape;
|
|
148
|
+
}
|
|
149
|
+
function nestedValueSchema(field) {
|
|
150
|
+
if (field.type !== "markdown") return fieldValueSchema(field);
|
|
151
|
+
const base2 = z.string({ error: err(field, "Expected text") });
|
|
152
|
+
return field.required ? base2.regex(/\S/, "Required") : base2.nullish();
|
|
153
|
+
}
|
|
154
|
+
function fieldValueSchema(field) {
|
|
155
|
+
switch (field.type) {
|
|
156
|
+
case "markdown":
|
|
157
|
+
return null;
|
|
158
|
+
case "object": {
|
|
159
|
+
const obj = z.strictObject(fieldsShape(field.fields), { error: err(field, "Expected an object") });
|
|
160
|
+
if (field.list) return listField(field, obj, field.min ?? 0, field.max);
|
|
161
|
+
return optional(field, obj, "");
|
|
162
|
+
}
|
|
163
|
+
case "blocks": {
|
|
164
|
+
const kinds = Object.keys(field.blocks);
|
|
165
|
+
const message = `Expected ${BLOCK_KEY}: ${kinds.join(", ")}`;
|
|
166
|
+
const options = Object.entries(field.blocks).map(
|
|
167
|
+
([kind, block]) => z.strictObject({ [BLOCK_KEY]: z.literal(kind), ...fieldsShape(block.fields) })
|
|
168
|
+
);
|
|
169
|
+
const item = z.discriminatedUnion(BLOCK_KEY, options, {
|
|
170
|
+
error: message
|
|
171
|
+
});
|
|
172
|
+
return listField(field, item, field.min ?? 0, field.max);
|
|
173
|
+
}
|
|
174
|
+
case "string":
|
|
175
|
+
case "text": {
|
|
176
|
+
if (field.type === "string" && field.list) return listField(field, z.string({ error: "Expected text" }), 0);
|
|
177
|
+
const base2 = z.string({ error: err(field, "Expected text") });
|
|
178
|
+
return field.required ? base2.regex(/\S/, "Required") : base2.nullish();
|
|
179
|
+
}
|
|
180
|
+
case "boolean":
|
|
181
|
+
return optional(field, z.boolean({ error: err(field, "Expected true or false") }), "");
|
|
182
|
+
case "select": {
|
|
183
|
+
const values = field.options.map((o) => o.value);
|
|
184
|
+
const message = `Expected one of: ${values.join(", ")}`;
|
|
185
|
+
if (field.multiple) return listField(field, z.enum(values, { error: message }), 0);
|
|
186
|
+
return optional(field, z.enum(values, { error: err(field, message) }), message);
|
|
187
|
+
}
|
|
188
|
+
case "number": {
|
|
189
|
+
let n = z.number({ error: err(field, "Expected a number") });
|
|
190
|
+
if (field.integer) n = n.int("Must be a whole number");
|
|
191
|
+
if (field.min !== void 0) n = n.min(field.min, `Must be at least ${field.min}`);
|
|
192
|
+
if (field.max !== void 0) n = n.max(field.max, `Must be at most ${field.max}`);
|
|
193
|
+
return optional(field, n, "");
|
|
194
|
+
}
|
|
195
|
+
case "datetime": {
|
|
196
|
+
const base2 = field.dateOnly ? z.iso.date({ error: err(field, "Invalid date") }) : z.iso.datetime({ offset: true, local: true, error: err(field, "Invalid date") });
|
|
197
|
+
return optional(field, base2, "Invalid date");
|
|
198
|
+
}
|
|
199
|
+
case "json": {
|
|
200
|
+
if (!field.required) return z.unknown().optional();
|
|
201
|
+
return z.union([z.string(), z.number(), z.boolean(), z.array(z.unknown()), z.record(z.string(), z.unknown())], {
|
|
202
|
+
error: "Required"
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
case "url": {
|
|
206
|
+
const message = "Must be an http(s) URL or start with /";
|
|
207
|
+
const base2 = z.string({ error: err(field, "Expected text") }).regex(/^(?:https?:\/\/|\/(?!\/))/i, { error: err(field, message) }).refine(isUrl, { error: message });
|
|
208
|
+
return optional(field, base2, message);
|
|
209
|
+
}
|
|
210
|
+
case "color": {
|
|
211
|
+
const message = "Must be a hex color like #a1b2c3";
|
|
212
|
+
const base2 = z.string({ error: err(field, "Expected text") }).regex(/^#[0-9a-fA-F]{6}$/, { error: err(field, message) });
|
|
213
|
+
return optional(field, base2, message);
|
|
214
|
+
}
|
|
215
|
+
case "image": {
|
|
216
|
+
const nonEmpty = z.string({ error: (iss) => iss.input === void 0 || iss.input === null ? "Required" : "Expected text" }).regex(/\S/, "Required");
|
|
217
|
+
const obj = z.strictObject({ src: nonEmpty, alt: nonEmpty }, { error: err(field, "Expected { src, alt }") });
|
|
218
|
+
return optional(field, obj, "");
|
|
219
|
+
}
|
|
220
|
+
case "reference": {
|
|
221
|
+
const message = `Must reference an entry in: ${field.collections.join(", ")}`;
|
|
222
|
+
const slug = SLUG_RE.source.slice(1, -1);
|
|
223
|
+
const ref = z.string({ error: err(field, 'Expected a reference like "collection/slug"') }).regex(new RegExp(`^(?:${field.collections.map(escapeRegex).join("|")})/${slug}$`), {
|
|
224
|
+
error: err(field, message)
|
|
225
|
+
});
|
|
226
|
+
if (field.multiple) return listField(field, ref, field.min ?? 0, field.max, (r) => `Duplicate reference: ${r}`);
|
|
227
|
+
return optional(field, ref, message);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// core/schema.ts
|
|
233
|
+
var BLOCK_KEY = "block";
|
|
234
|
+
var COMMIT_PLACEHOLDERS = ["action", "Action", "collection", "slug", "target"];
|
|
235
|
+
var TITLE_PLACEHOLDERS = ["branch", "name", "login"];
|
|
236
|
+
var REF_SEGMENTS = /^[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
|
|
237
|
+
function isRefPath(value) {
|
|
238
|
+
return REF_SEGMENTS.test(value) && !value.includes("..") && !value.split("/").some((s) => s.endsWith(".lock"));
|
|
239
|
+
}
|
|
240
|
+
function template(placeholders, max) {
|
|
241
|
+
return z2.string().trim().min(1).max(max).refine((t) => !/[\r\n]/.test(t), "must be one line").superRefine((t, ctx) => {
|
|
242
|
+
for (const [, name] of t.matchAll(/\{([^{}]*)\}/g)) {
|
|
243
|
+
if (!placeholders.includes(name)) {
|
|
244
|
+
ctx.addIssue({
|
|
245
|
+
code: "custom",
|
|
246
|
+
message: `unknown placeholder "{${name}}" (use ${placeholders.map((p) => `{${p}}`).join(", ")})`
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
var gitSchema = z2.strictObject({
|
|
253
|
+
baseBranch: z2.string().min(1),
|
|
254
|
+
branchPrefix: z2.string().refine(
|
|
255
|
+
(p) => p.endsWith("/") && isRefPath(p.slice(0, -1)),
|
|
256
|
+
'must be branch name segments ending in "/", for example "editlet/"'
|
|
257
|
+
).optional(),
|
|
258
|
+
commitMessage: template(COMMIT_PLACEHOLDERS, 200).optional(),
|
|
259
|
+
pullRequest: z2.strictObject({
|
|
260
|
+
title: template(TITLE_PLACEHOLDERS, 256).optional(),
|
|
261
|
+
labels: z2.array(
|
|
262
|
+
z2.string().trim().min(1).max(50).refine((l) => !l.includes(","), 'must not contain ","')
|
|
263
|
+
).max(10).optional(),
|
|
264
|
+
draft: z2.boolean().optional()
|
|
265
|
+
}).optional()
|
|
266
|
+
});
|
|
267
|
+
var IDENT = /^[a-zA-Z][a-zA-Z0-9]*$/;
|
|
268
|
+
var identMsg = "must start with a letter and contain only letters and digits";
|
|
269
|
+
var base = {
|
|
270
|
+
label: z2.string(),
|
|
271
|
+
hint: z2.string().optional(),
|
|
272
|
+
required: z2.boolean().optional()
|
|
273
|
+
};
|
|
274
|
+
var strOrList = z2.union([z2.string(), z2.array(z2.string())]);
|
|
275
|
+
var nestedFields = z2.lazy(
|
|
276
|
+
() => z2.record(z2.string().regex(IDENT, `field key ${identMsg}`), fieldSchema).refine((o) => Object.keys(o).length > 0, "fields must not be empty")
|
|
277
|
+
);
|
|
278
|
+
var fieldSchema = z2.discriminatedUnion("type", [
|
|
279
|
+
z2.strictObject({ ...base, type: z2.literal("string"), list: z2.boolean().optional(), default: strOrList.optional() }),
|
|
280
|
+
z2.strictObject({
|
|
281
|
+
...base,
|
|
282
|
+
type: z2.literal("text"),
|
|
283
|
+
rows: z2.number().int().positive().optional(),
|
|
284
|
+
default: z2.string().optional()
|
|
285
|
+
}),
|
|
286
|
+
z2.strictObject({ ...base, type: z2.literal("markdown") }),
|
|
287
|
+
z2.strictObject({
|
|
288
|
+
...base,
|
|
289
|
+
type: z2.literal("boolean"),
|
|
290
|
+
default: z2.boolean().optional(),
|
|
291
|
+
labels: z2.strictObject({ true: z2.string(), false: z2.string() }).optional()
|
|
292
|
+
}),
|
|
293
|
+
z2.strictObject({
|
|
294
|
+
...base,
|
|
295
|
+
type: z2.literal("select"),
|
|
296
|
+
options: z2.array(z2.strictObject({ label: z2.string(), value: z2.string() })).min(1, "options must not be empty"),
|
|
297
|
+
multiple: z2.boolean().optional(),
|
|
298
|
+
default: strOrList.optional()
|
|
299
|
+
}),
|
|
300
|
+
z2.strictObject({
|
|
301
|
+
...base,
|
|
302
|
+
type: z2.literal("number"),
|
|
303
|
+
min: z2.number().optional(),
|
|
304
|
+
max: z2.number().optional(),
|
|
305
|
+
step: z2.number().optional(),
|
|
306
|
+
integer: z2.boolean().optional(),
|
|
307
|
+
default: z2.number().optional()
|
|
308
|
+
}),
|
|
309
|
+
z2.strictObject({
|
|
310
|
+
...base,
|
|
311
|
+
type: z2.literal("datetime"),
|
|
312
|
+
dateOnly: z2.boolean().optional(),
|
|
313
|
+
defaultNow: z2.boolean().optional()
|
|
314
|
+
}),
|
|
315
|
+
z2.strictObject({ ...base, type: z2.literal("json") }),
|
|
316
|
+
z2.strictObject({ ...base, type: z2.literal("url") }),
|
|
317
|
+
z2.strictObject({ ...base, type: z2.literal("color"), default: z2.string().optional() }),
|
|
318
|
+
z2.strictObject({ ...base, type: z2.literal("image") }),
|
|
319
|
+
z2.strictObject({
|
|
320
|
+
...base,
|
|
321
|
+
type: z2.literal("reference"),
|
|
322
|
+
collections: z2.array(z2.string()).min(1, "collections must not be empty"),
|
|
323
|
+
multiple: z2.boolean().optional(),
|
|
324
|
+
min: z2.number().int().nonnegative().optional(),
|
|
325
|
+
max: z2.number().int().nonnegative().optional()
|
|
326
|
+
}),
|
|
327
|
+
z2.strictObject({
|
|
328
|
+
...base,
|
|
329
|
+
type: z2.literal("object"),
|
|
330
|
+
fields: nestedFields,
|
|
331
|
+
list: z2.boolean().optional(),
|
|
332
|
+
min: z2.number().int().nonnegative().optional(),
|
|
333
|
+
max: z2.number().int().nonnegative().optional()
|
|
334
|
+
}),
|
|
335
|
+
z2.strictObject({
|
|
336
|
+
...base,
|
|
337
|
+
type: z2.literal("blocks"),
|
|
338
|
+
blocks: z2.record(
|
|
339
|
+
z2.string().regex(IDENT, `block key ${identMsg}`),
|
|
340
|
+
z2.strictObject({ label: z2.string(), fields: nestedFields })
|
|
341
|
+
).refine((o) => Object.keys(o).length > 0, "blocks must not be empty"),
|
|
342
|
+
min: z2.number().int().nonnegative().optional(),
|
|
343
|
+
max: z2.number().int().nonnegative().optional()
|
|
344
|
+
})
|
|
345
|
+
]);
|
|
346
|
+
var collectionSchema = z2.strictObject({
|
|
347
|
+
label: z2.string(),
|
|
348
|
+
singleton: z2.boolean().optional(),
|
|
349
|
+
titleField: z2.string().optional(),
|
|
350
|
+
slugFrom: z2.string().optional(),
|
|
351
|
+
fields: z2.record(z2.string().regex(IDENT, `field key ${identMsg}`), fieldSchema)
|
|
352
|
+
});
|
|
353
|
+
function checkFields(schema, fields, at, nested, add) {
|
|
354
|
+
for (const [fk, f] of Object.entries(fields)) {
|
|
355
|
+
const path = [...at, fk];
|
|
356
|
+
if (fk === "draft" && !nested) add(path, 'field key "draft" is reserved for the draft flag');
|
|
357
|
+
if ("default" in f && f.default !== void 0) {
|
|
358
|
+
const checked = fieldValueSchema(f)?.safeParse(f.default);
|
|
359
|
+
for (const issue of checked?.success === false ? checked.error.issues : []) {
|
|
360
|
+
add([...path, "default", ...issue.path.map(String)], `default: ${issue.message}`);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
if (f.type === "reference") {
|
|
364
|
+
f.collections.forEach((target, i) => {
|
|
365
|
+
if (!Object.hasOwn(schema.collections, target))
|
|
366
|
+
add([...path, "collections", i], `unknown collection "${target}"`);
|
|
367
|
+
});
|
|
368
|
+
if (!f.multiple && (f.min !== void 0 || f.max !== void 0)) add(path, "min/max require multiple: true");
|
|
369
|
+
}
|
|
370
|
+
if (f.type === "object") {
|
|
371
|
+
if (!f.list && (f.min !== void 0 || f.max !== void 0)) add(path, "min/max require list: true");
|
|
372
|
+
checkFields(schema, f.fields, [...path, "fields"], true, add);
|
|
373
|
+
}
|
|
374
|
+
if (f.type === "blocks") {
|
|
375
|
+
for (const [bk, block] of Object.entries(f.blocks)) {
|
|
376
|
+
if (Object.hasOwn(block.fields, BLOCK_KEY)) {
|
|
377
|
+
add([...path, "blocks", bk, "fields", BLOCK_KEY], `field key "${BLOCK_KEY}" is reserved for the block type`);
|
|
378
|
+
}
|
|
379
|
+
checkFields(schema, block.fields, [...path, "blocks", bk, "fields"], true, add);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if ((f.type === "reference" || f.type === "object" || f.type === "blocks") && f.min !== void 0 && f.max !== void 0 && f.min > f.max) {
|
|
383
|
+
add([...path, "min"], "min must not exceed max");
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
var schemaSchema = z2.strictObject({
|
|
388
|
+
$schema: z2.string().optional(),
|
|
389
|
+
contentDir: z2.string().min(1).refine(
|
|
390
|
+
isCanonicalPath,
|
|
391
|
+
'must be a relative posix path without empty, "." or ".." segments, backslashes, NUL or ":"'
|
|
392
|
+
),
|
|
393
|
+
git: gitSchema,
|
|
394
|
+
collections: z2.record(z2.string().regex(IDENT, `collection key ${identMsg}`), collectionSchema)
|
|
395
|
+
}).superRefine((schema, ctx) => {
|
|
396
|
+
const add = (path, message) => ctx.addIssue({ code: "custom", path, message });
|
|
397
|
+
const { baseBranch, branchPrefix } = schema.git;
|
|
398
|
+
if (branchPrefix !== void 0 && (baseBranch.startsWith(branchPrefix) || branchPrefix.startsWith(`${baseBranch}/`))) {
|
|
399
|
+
add(["git", "branchPrefix"], `branchPrefix "${branchPrefix}" clashes with the base branch "${baseBranch}"`);
|
|
400
|
+
}
|
|
401
|
+
const lowerKeys = /* @__PURE__ */ new Map();
|
|
402
|
+
for (const [ck, col] of Object.entries(schema.collections)) {
|
|
403
|
+
const other = lowerKeys.get(ck.toLowerCase());
|
|
404
|
+
if (other !== void 0) add(["collections", ck], `collection key "${ck}" differs from "${other}" only in case`);
|
|
405
|
+
else lowerKeys.set(ck.toLowerCase(), ck);
|
|
406
|
+
const fields = Object.entries(col.fields);
|
|
407
|
+
if (fields.filter(([, f]) => f.type === "markdown").length > 1) {
|
|
408
|
+
add(["collections", ck, "fields"], "a collection can have at most one markdown field");
|
|
409
|
+
}
|
|
410
|
+
if (col.titleField !== void 0 && !Object.hasOwn(col.fields, col.titleField)) {
|
|
411
|
+
add(["collections", ck, "titleField"], `titleField "${col.titleField}" is not a field of ${ck}`);
|
|
412
|
+
}
|
|
413
|
+
if (col.slugFrom !== void 0 && !Object.hasOwn(col.fields, col.slugFrom)) {
|
|
414
|
+
add(["collections", ck, "slugFrom"], `slugFrom "${col.slugFrom}" is not a field of ${ck}`);
|
|
415
|
+
}
|
|
416
|
+
checkFields(schema, col.fields, ["collections", ck, "fields"], false, add);
|
|
417
|
+
}
|
|
418
|
+
});
|
|
419
|
+
function toIssues(error) {
|
|
420
|
+
const out = [];
|
|
421
|
+
for (const issue of error.issues) {
|
|
422
|
+
let path = issue.path.map(String);
|
|
423
|
+
let message = issue.message;
|
|
424
|
+
if (issue.code === "invalid_union" && ("discriminator" in issue || path.at(-1) !== "type")) {
|
|
425
|
+
if (path.at(-1) !== "type") path = [...path, "type"];
|
|
426
|
+
message = "unknown field type";
|
|
427
|
+
}
|
|
428
|
+
if (issue.code === "unrecognized_keys") {
|
|
429
|
+
for (const key of issue.keys) out.push({ path: [...path, key].join("."), message: `unknown key "${key}"` });
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
out.push({ path: path.join("."), message });
|
|
433
|
+
}
|
|
434
|
+
return out;
|
|
435
|
+
}
|
|
436
|
+
function loadSchema(input) {
|
|
437
|
+
const parsed = schemaSchema.safeParse(input);
|
|
438
|
+
if (!parsed.success) throw new EditletError(toIssues(parsed.error));
|
|
439
|
+
return parsed.data;
|
|
440
|
+
}
|
|
441
|
+
function parseSchemaText(text, file) {
|
|
442
|
+
let json;
|
|
443
|
+
try {
|
|
444
|
+
json = JSON.parse(text);
|
|
445
|
+
} catch (error) {
|
|
446
|
+
throw new EditletError([
|
|
447
|
+
{ file, path: "", message: `Invalid JSON: ${error instanceof Error ? error.message : error}` }
|
|
448
|
+
]);
|
|
449
|
+
}
|
|
450
|
+
try {
|
|
451
|
+
return loadSchema(json);
|
|
452
|
+
} catch (error) {
|
|
453
|
+
if (error instanceof EditletError) throw new EditletError(error.issues.map((issue) => ({ ...issue, file })));
|
|
454
|
+
throw error;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
function markdownFieldKey(collection) {
|
|
458
|
+
return Object.entries(collection.fields).find(([, f]) => f.type === "markdown")?.[0];
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// node/fs.ts
|
|
462
|
+
var DEFAULT_SCHEMA_PATH = "cms/schema.json";
|
|
463
|
+
async function loadProjectSchema(root, schemaPath) {
|
|
464
|
+
let raw;
|
|
465
|
+
try {
|
|
466
|
+
raw = await readFile(join(root, schemaPath), "utf8");
|
|
467
|
+
} catch (error) {
|
|
468
|
+
throw new EditletError([
|
|
469
|
+
{ file: schemaPath, path: "", message: `Cannot read schema: ${error instanceof Error ? error.message : error}` }
|
|
470
|
+
]);
|
|
471
|
+
}
|
|
472
|
+
return parseSchemaText(raw, schemaPath);
|
|
473
|
+
}
|
|
474
|
+
async function listFiles(root, contentDir) {
|
|
475
|
+
let dirents;
|
|
476
|
+
try {
|
|
477
|
+
dirents = await readdir(join(root, contentDir), { recursive: true, withFileTypes: true });
|
|
478
|
+
} catch (error) {
|
|
479
|
+
if (error.code === "ENOENT") return [];
|
|
480
|
+
throw error;
|
|
481
|
+
}
|
|
482
|
+
return dirents.filter((d) => d.isFile()).map((d) => `${relativeDir(root, d.parentPath)}/${d.name}`.split("\\").join("/")).toSorted();
|
|
483
|
+
}
|
|
484
|
+
function relativeDir(root, dir) {
|
|
485
|
+
return resolve(dir).slice(resolve(root).length + 1);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// core/generate.ts
|
|
489
|
+
import { z as z4 } from "zod";
|
|
490
|
+
|
|
491
|
+
// core/validate.ts
|
|
492
|
+
import { z as z3 } from "zod";
|
|
493
|
+
|
|
494
|
+
// core/walk.ts
|
|
495
|
+
var isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
496
|
+
function blockFields(field, item) {
|
|
497
|
+
if (!isPlainObject(item)) return void 0;
|
|
498
|
+
const kind = item[BLOCK_KEY];
|
|
499
|
+
return typeof kind === "string" && Object.hasOwn(field.blocks, kind) ? field.blocks[kind].fields : void 0;
|
|
500
|
+
}
|
|
501
|
+
function children(field, value, path) {
|
|
502
|
+
if (field.type === "object") {
|
|
503
|
+
if (!field.list) return isPlainObject(value) ? [[field.fields, value, path]] : [];
|
|
504
|
+
if (!Array.isArray(value)) return [];
|
|
505
|
+
return value.flatMap((item, i) => isPlainObject(item) ? [[field.fields, item, [...path, i]]] : []);
|
|
506
|
+
}
|
|
507
|
+
if (field.type === "blocks") {
|
|
508
|
+
if (!Array.isArray(value)) return [];
|
|
509
|
+
return value.flatMap((item, i) => {
|
|
510
|
+
const fields = blockFields(field, item);
|
|
511
|
+
return fields ? [[fields, item, [...path, i]]] : [];
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
return [];
|
|
515
|
+
}
|
|
516
|
+
var isContainer = (field) => field.type === "object" || field.type === "blocks";
|
|
517
|
+
function visitFields(fields, data, visit, at = []) {
|
|
518
|
+
for (const [key, field] of Object.entries(fields)) {
|
|
519
|
+
if (!Object.hasOwn(data, key)) continue;
|
|
520
|
+
const path = [...at, key];
|
|
521
|
+
if (!isContainer(field)) {
|
|
522
|
+
visit(field, data[key], path);
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
for (const [childFields, child, childPath] of children(field, data[key], path)) {
|
|
526
|
+
visitFields(childFields, child, visit, childPath);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// core/validate.ts
|
|
532
|
+
function buildDataSchema(collection) {
|
|
533
|
+
const shape = {};
|
|
534
|
+
for (const [key, field] of Object.entries(collection.fields)) {
|
|
535
|
+
const s = fieldValueSchema(field);
|
|
536
|
+
if (s) shape[key] = s;
|
|
537
|
+
}
|
|
538
|
+
shape.draft = z3.boolean({ error: "Expected true or false" }).optional();
|
|
539
|
+
return z3.strictObject(shape);
|
|
540
|
+
}
|
|
541
|
+
function toIssues2(error, file) {
|
|
542
|
+
const out = [];
|
|
543
|
+
for (const issue of error.issues) {
|
|
544
|
+
const path = issue.path.map(String);
|
|
545
|
+
if (issue.code === "unrecognized_keys") {
|
|
546
|
+
for (const key of issue.keys) out.push({ file, path: [...path, key].join("."), message: "Unknown field" });
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
out.push({ file, path: path.join("."), message: issue.message });
|
|
550
|
+
}
|
|
551
|
+
return out;
|
|
552
|
+
}
|
|
553
|
+
function validateEntry(schema, entry, ctx = {}) {
|
|
554
|
+
if (!Object.hasOwn(schema.collections, entry.collection)) {
|
|
555
|
+
return [{ path: "", message: `Unknown collection "${entry.collection}"` }];
|
|
556
|
+
}
|
|
557
|
+
const collection = schema.collections[entry.collection];
|
|
558
|
+
const file = entryFilePath(schema, entry.collection, entry.slug);
|
|
559
|
+
if (collection.singleton ? entry.slug !== "index" : !isValidSlug(entry.slug)) {
|
|
560
|
+
const message = collection.singleton ? 'Slug of a singleton must be "index"' : `Invalid slug "${entry.slug}": use lowercase letters, digits and single hyphens`;
|
|
561
|
+
return [{ file, path: "", message }];
|
|
562
|
+
}
|
|
563
|
+
if (typeof entry.data !== "object" || entry.data === null || Array.isArray(entry.data)) {
|
|
564
|
+
return [{ file, path: "", message: "Entry data must be an object" }];
|
|
565
|
+
}
|
|
566
|
+
const parsed = buildDataSchema(collection).safeParse(entry.data);
|
|
567
|
+
const issues = parsed.success ? [] : toIssues2(parsed.error, file);
|
|
568
|
+
const mdKey = markdownFieldKey(collection);
|
|
569
|
+
if (mdKey === void 0) {
|
|
570
|
+
if (entry.body.trim() !== "") {
|
|
571
|
+
issues.push({ file, path: "", message: "This collection has no markdown field, but the entry has body content" });
|
|
572
|
+
}
|
|
573
|
+
} else if (collection.fields[mdKey].required && entry.body.trim() === "") {
|
|
574
|
+
issues.push({ file, path: mdKey, message: "Required" });
|
|
575
|
+
}
|
|
576
|
+
const shapeIssues = [...issues];
|
|
577
|
+
const bad = (key) => shapeIssues.some((i) => i.path === key || i.path.startsWith(`${key}.`) || key.startsWith(`${i.path}.`));
|
|
578
|
+
visitFields(collection.fields, entry.data, (field, value, at) => {
|
|
579
|
+
const key = at.join(".");
|
|
580
|
+
if (bad(key)) return;
|
|
581
|
+
if (field.type === "image" && value !== null && value !== void 0) {
|
|
582
|
+
const src = value.src;
|
|
583
|
+
const resolved = resolveAssetPath(schema, file, src);
|
|
584
|
+
if (resolved === null) {
|
|
585
|
+
issues.push({ file, path: `${key}.src`, message: "Image path points outside the content directory" });
|
|
586
|
+
} else if (!isImagePath(resolved)) {
|
|
587
|
+
issues.push({ file, path: `${key}.src`, message: "Image path must end in an image extension" });
|
|
588
|
+
} else if (isHiddenContentPath(schema, resolved)) {
|
|
589
|
+
issues.push({ file, path: `${key}.src`, message: 'Image path must not be hidden (a segment starts with ".")' });
|
|
590
|
+
} else if (ctx.fileExists?.(resolved) === false) {
|
|
591
|
+
issues.push({ file, path: `${key}.src`, message: `Image file not found: ${resolved}` });
|
|
592
|
+
}
|
|
593
|
+
} else if (field.type === "reference" && !isAbsentValue(field, value)) {
|
|
594
|
+
const refs = Array.isArray(value) ? value : [value];
|
|
595
|
+
refs.forEach((ref, i) => {
|
|
596
|
+
if (ctx.entryExists?.(ref) === false) {
|
|
597
|
+
issues.push({
|
|
598
|
+
file,
|
|
599
|
+
path: Array.isArray(value) ? `${key}.${i}` : key,
|
|
600
|
+
message: `Referenced entry not found: ${ref}`
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
});
|
|
606
|
+
return issues;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// core/entryFile.ts
|
|
610
|
+
import { parse, Schema as YamlSchema, stringify } from "yaml";
|
|
611
|
+
var YAML_11_SCALARS = new YamlSchema({ schema: "yaml-1.1" }).tags.filter((tag) => !tag.collection);
|
|
612
|
+
function fail(message) {
|
|
613
|
+
throw new EditletError([{ path: "", message }]);
|
|
614
|
+
}
|
|
615
|
+
var utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
616
|
+
function decodeUtf8(content, file) {
|
|
617
|
+
if (typeof content === "string") return { text: content };
|
|
618
|
+
try {
|
|
619
|
+
return { text: utf8.decode(content) };
|
|
620
|
+
} catch {
|
|
621
|
+
return { issue: { file, path: "", message: "File is not valid UTF-8" } };
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
function parseEntryFile(source) {
|
|
625
|
+
let text = source.startsWith("\uFEFF") ? source.slice(1) : source;
|
|
626
|
+
text = text.replace(/\r\n/g, "\n");
|
|
627
|
+
if (!text.startsWith("---\n")) return { data: {}, body: text };
|
|
628
|
+
const rest = text.slice(4);
|
|
629
|
+
const lines = rest.split("\n");
|
|
630
|
+
const close = lines.indexOf("---");
|
|
631
|
+
if (close === -1) fail('Frontmatter is not closed with a "---" line');
|
|
632
|
+
const yamlSrc = lines.slice(0, close).join("\n");
|
|
633
|
+
let body = lines.slice(close + 1).join("\n");
|
|
634
|
+
if (body.startsWith("\n")) body = body.slice(1);
|
|
635
|
+
let data;
|
|
636
|
+
try {
|
|
637
|
+
data = parse(yamlSrc, { schema: "core", logLevel: "error" });
|
|
638
|
+
} catch (error) {
|
|
639
|
+
fail(`Invalid YAML frontmatter: ${error instanceof Error ? error.message : String(error)}`);
|
|
640
|
+
}
|
|
641
|
+
if (data === null || data === void 0) data = {};
|
|
642
|
+
if (typeof data !== "object" || Array.isArray(data)) fail("Frontmatter must be a YAML mapping");
|
|
643
|
+
return { data, body };
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// core/project.ts
|
|
647
|
+
var byFile = (a, b) => (a.file ?? "").localeCompare(b.file ?? "");
|
|
648
|
+
function isSkippedPath(schema, schemaPath, file) {
|
|
649
|
+
return file === schemaPath || isHiddenContentPath(schema, file) || isImagePath(file);
|
|
650
|
+
}
|
|
651
|
+
function entryCandidate(schema, file) {
|
|
652
|
+
return file.endsWith(".md") ? parseEntryPath(schema, file) : null;
|
|
653
|
+
}
|
|
654
|
+
function entriesFromFiles(schema, schemaPath, files) {
|
|
655
|
+
const entries = [];
|
|
656
|
+
const issues = [];
|
|
657
|
+
for (const [file, content] of files) {
|
|
658
|
+
if (isSkippedPath(schema, schemaPath, file)) continue;
|
|
659
|
+
const parsed = entryCandidate(schema, file);
|
|
660
|
+
if (!parsed) {
|
|
661
|
+
issues.push({ file, path: "", message: "Not an entry file" });
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
const decoded = decodeUtf8(content, file);
|
|
665
|
+
if ("issue" in decoded) {
|
|
666
|
+
issues.push(decoded.issue);
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
try {
|
|
670
|
+
const { data, body } = parseEntryFile(decoded.text);
|
|
671
|
+
entries.push({ collection: parsed.collection, slug: parsed.slug, data, body });
|
|
672
|
+
} catch (error) {
|
|
673
|
+
if (!(error instanceof EditletError)) throw error;
|
|
674
|
+
issues.push(...error.issues.map((issue) => ({ ...issue, file })));
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
const fileOf = (e) => entryFilePath(schema, e.collection, e.slug);
|
|
678
|
+
return {
|
|
679
|
+
entries: entries.toSorted((a, b) => fileOf(a).localeCompare(fileOf(b))),
|
|
680
|
+
issues: issues.toSorted(byFile)
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// node/project.ts
|
|
685
|
+
async function readProject(root, schemaPath = DEFAULT_SCHEMA_PATH) {
|
|
686
|
+
const schema = await loadProjectSchema(root, schemaPath);
|
|
687
|
+
const files = await listFiles(root, schema.contentDir);
|
|
688
|
+
const contents = /* @__PURE__ */ new Map();
|
|
689
|
+
for (const file of files) {
|
|
690
|
+
if (isSkippedPath(schema, schemaPath, file)) continue;
|
|
691
|
+
contents.set(
|
|
692
|
+
file,
|
|
693
|
+
entryCandidate(schema, file) ? new Uint8Array(await readFile2(join2(root, file))) : new Uint8Array()
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
return { root, schema, ...entriesFromFiles(schema, schemaPath, contents) };
|
|
697
|
+
}
|
|
698
|
+
async function validateProject(root, schemaPath = DEFAULT_SCHEMA_PATH) {
|
|
699
|
+
const project = await readProject(root, schemaPath);
|
|
700
|
+
const { schema, entries } = project;
|
|
701
|
+
const refs = new Set(entries.map((e) => refKey(e.collection, e.slug)));
|
|
702
|
+
const files = new Set(await listFiles(root, schema.contentDir));
|
|
703
|
+
const issues = [...project.issues];
|
|
704
|
+
for (const entry of entries) {
|
|
705
|
+
issues.push(
|
|
706
|
+
...validateEntry(schema, entry, { entryExists: (ref) => refs.has(ref), fileExists: (p) => files.has(p) })
|
|
707
|
+
);
|
|
708
|
+
}
|
|
709
|
+
return issues.toSorted(byFile);
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// skills/editlet-setup/scripts/doctorLocal.ts
|
|
713
|
+
var read = (path) => existsSync(path) ? readFileSync(path, "utf8") : null;
|
|
714
|
+
function firstFile(root, names) {
|
|
715
|
+
return names.find((name) => existsSync(join3(root, name))) ?? null;
|
|
716
|
+
}
|
|
717
|
+
var major = (version) => Number(/(\d+)/.exec(version ?? "")?.[1] ?? NaN);
|
|
718
|
+
function installedVersion(root, pkg) {
|
|
719
|
+
const text = read(join3(root, "node_modules", pkg, "package.json"));
|
|
720
|
+
return text ? JSON.parse(text).version : void 0;
|
|
721
|
+
}
|
|
722
|
+
var NEXT_CONFIGS = ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.cjs"];
|
|
723
|
+
var ASTRO_CONFIGS = ["astro.config.mjs", "astro.config.ts", "astro.config.js"];
|
|
724
|
+
function projectFacts(root) {
|
|
725
|
+
const nextFile = firstFile(root, NEXT_CONFIGS);
|
|
726
|
+
const astroFile = firstFile(root, ASTRO_CONFIGS);
|
|
727
|
+
const file = nextFile ?? astroFile;
|
|
728
|
+
const text = file ? read(join3(root, file)) ?? "" : "";
|
|
729
|
+
return {
|
|
730
|
+
framework: nextFile ? "next" : astroFile ? "astro" : null,
|
|
731
|
+
config: file ? { file, text } : null,
|
|
732
|
+
authUrl: /authUrl\s*:\s*['"`]([^'"`]+)['"`]/.exec(text)?.[1],
|
|
733
|
+
preview: /preview\s*:\s*true/.test(text),
|
|
734
|
+
admin: /\badmin\s*:\s*\{/.test(text)
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
function checkProject(ctx, facts) {
|
|
738
|
+
const out = [];
|
|
739
|
+
const [maj = 0, min = 0] = ctx.nodeVersion.split(".").map(Number);
|
|
740
|
+
out.push(
|
|
741
|
+
maj > 22 || maj === 22 && min >= 12 ? { status: "ok", id: "project.node", message: `Node ${ctx.nodeVersion}` } : { status: "fail", id: "project.node", message: `Node ${ctx.nodeVersion}; Editlet needs 22.12 or newer` }
|
|
742
|
+
);
|
|
743
|
+
const editlet = installedVersion(ctx.root, "editlet");
|
|
744
|
+
out.push(
|
|
745
|
+
editlet ? { status: "ok", id: "project.package", message: `editlet ${editlet}` } : { status: "fail", id: "project.package", message: "editlet is not installed in node_modules" }
|
|
746
|
+
);
|
|
747
|
+
if (facts.framework === "next") {
|
|
748
|
+
const next = installedVersion(ctx.root, "next");
|
|
749
|
+
const react = installedVersion(ctx.root, "react");
|
|
750
|
+
const ok = major(next) >= 16 && major(react) >= 19;
|
|
751
|
+
out.push({
|
|
752
|
+
status: ok ? "ok" : "fail",
|
|
753
|
+
id: "project.framework",
|
|
754
|
+
message: `next ${next ?? "missing"}, react ${react ?? "missing"}${ok ? "" : " (needs next >=16, react >=19)"}`
|
|
755
|
+
});
|
|
756
|
+
} else if (facts.framework === "astro") {
|
|
757
|
+
const astro = installedVersion(ctx.root, "astro");
|
|
758
|
+
const ok = [6, 7].includes(major(astro));
|
|
759
|
+
out.push({
|
|
760
|
+
status: ok ? "ok" : "fail",
|
|
761
|
+
id: "project.framework",
|
|
762
|
+
message: `astro ${astro ?? "missing"}${ok ? "" : " (needs astro ^6 || ^7)"}`
|
|
763
|
+
});
|
|
764
|
+
} else {
|
|
765
|
+
out.push({ status: "fail", id: "project.framework", message: "no next.config.* or astro.config.* in the root" });
|
|
766
|
+
}
|
|
767
|
+
const link = ["node_modules/editlet/skills/editlet/scripts/link.mjs", ".claude/skills/editlet/scripts/link.mjs"].map((rel) => join3(ctx.root, rel)).find((path) => existsSync(path));
|
|
768
|
+
if (!link) {
|
|
769
|
+
out.push({ status: "fail", id: "project.skills", message: "link.mjs not found: the skills are not installed" });
|
|
770
|
+
} else {
|
|
771
|
+
const res = ctx.exec(process.execPath, [link, "--check", "--hooks", "--root", ctx.root]);
|
|
772
|
+
const lines = res.stdout.trim().split("\n").filter(Boolean);
|
|
773
|
+
const bad = lines.filter((l) => !/: (already linked|hook present|copy kept)$/.test(l));
|
|
774
|
+
out.push(
|
|
775
|
+
res.status === 0 && bad.length === 0 ? { status: "ok", id: "project.skills", message: "skills linked, guard hook present" } : {
|
|
776
|
+
status: res.status === 0 ? "warn" : "fail",
|
|
777
|
+
id: "project.skills",
|
|
778
|
+
message: bad.join("; ") || res.stderr.trim()
|
|
779
|
+
}
|
|
780
|
+
);
|
|
781
|
+
}
|
|
782
|
+
return out;
|
|
783
|
+
}
|
|
784
|
+
async function checkContent(root) {
|
|
785
|
+
if (!existsSync(join3(root, "cms/schema.json"))) {
|
|
786
|
+
return { status: "fail", id: "content.valid", message: "cms/schema.json is missing" };
|
|
787
|
+
}
|
|
788
|
+
let issues;
|
|
789
|
+
try {
|
|
790
|
+
issues = await validateProject(root);
|
|
791
|
+
} catch (error) {
|
|
792
|
+
if (!(error instanceof EditletError)) throw error;
|
|
793
|
+
issues = error.issues;
|
|
794
|
+
}
|
|
795
|
+
if (issues.length === 0) return { status: "ok", id: "content.valid", message: "schema and entries valid" };
|
|
796
|
+
const shown = issues.slice(0, 5).map((i) => `${i.file ?? "schema"}: ${i.path} \u2014 ${i.message}`);
|
|
797
|
+
return { status: "fail", id: "content.valid", message: `${issues.length} issue(s): ${shown.join("; ")}` };
|
|
798
|
+
}
|
|
799
|
+
function routeFile(root, segments, needle, exts = ["ts", "js", "tsx", "jsx"]) {
|
|
800
|
+
for (const base2 of ["src/app", "app", "src/pages", "pages"]) {
|
|
801
|
+
for (const ext of exts) {
|
|
802
|
+
for (const name of [`${segments}/route.${ext}`, `${segments}.${ext}`]) {
|
|
803
|
+
const text = read(join3(root, base2, name));
|
|
804
|
+
if (text?.includes(needle)) return `${base2}/${name}`;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return null;
|
|
809
|
+
}
|
|
810
|
+
var COOP_SAME_ORIGIN = /Cross-Origin-Opener-Policy['"]?\s*,\s*value\s*:\s*['"]same-origin['"]/;
|
|
811
|
+
function checkNext(root, facts) {
|
|
812
|
+
const out = [];
|
|
813
|
+
const text = facts.config?.text ?? "";
|
|
814
|
+
out.push(
|
|
815
|
+
text.includes("withEditlet") ? { status: "ok", id: "next.config", message: `${facts.config?.file} uses withEditlet` } : {
|
|
816
|
+
status: "fail",
|
|
817
|
+
id: "next.config",
|
|
818
|
+
message: `${facts.config?.file} does not wrap its export with withEditlet`
|
|
819
|
+
}
|
|
820
|
+
);
|
|
821
|
+
const layoutFile = firstFile(root, ["src/app/layout.tsx", "app/layout.tsx", "src/app/layout.jsx", "app/layout.jsx"]);
|
|
822
|
+
const layout = layoutFile ? read(join3(root, layoutFile)) ?? "" : "";
|
|
823
|
+
out.push(
|
|
824
|
+
layout.includes("<EditletLoader") && layout.includes("editlet/next") ? { status: "ok", id: "next.loader", message: `${layoutFile} renders <EditletLoader />` } : {
|
|
825
|
+
status: "fail",
|
|
826
|
+
id: "next.loader",
|
|
827
|
+
message: `${layoutFile ?? "the root layout"} does not render <EditletLoader />`
|
|
828
|
+
}
|
|
829
|
+
);
|
|
830
|
+
const gitignore = read(join3(root, ".gitignore")) ?? "";
|
|
831
|
+
const missing = [
|
|
832
|
+
[/^\/?\.editlet\/?$/m, "/.editlet/"],
|
|
833
|
+
[/^\/?public\/editlet\/?$/m, "/public/editlet/"]
|
|
834
|
+
].filter(([re]) => !re.test(gitignore)).map(([, line]) => line);
|
|
835
|
+
out.push(
|
|
836
|
+
missing.length === 0 ? { status: "ok", id: "next.gitignore", message: ".gitignore covers the generated folders" } : { status: "fail", id: "next.gitignore", message: `.gitignore lacks ${missing.join(" and ")}` }
|
|
837
|
+
);
|
|
838
|
+
if (facts.preview) {
|
|
839
|
+
const route = routeFile(root, "api/editlet/preview", "editlet/next/preview");
|
|
840
|
+
out.push(
|
|
841
|
+
route ? { status: "ok", id: "next.preview-route", message: route } : {
|
|
842
|
+
status: "fail",
|
|
843
|
+
id: "next.preview-route",
|
|
844
|
+
message: "admin.preview is on, but app/api/editlet/preview/route.ts is missing"
|
|
845
|
+
}
|
|
846
|
+
);
|
|
847
|
+
}
|
|
848
|
+
out.push(...checkAuthRoute(root, facts));
|
|
849
|
+
out.push(
|
|
850
|
+
COOP_SAME_ORIGIN.test(text) ? { status: "fail", id: "next.coop", message: "Cross-Origin-Opener-Policy: same-origin breaks the sign-in popup" } : { status: "ok", id: "next.coop", message: "no COOP same-origin header in the config" }
|
|
851
|
+
);
|
|
852
|
+
return out;
|
|
853
|
+
}
|
|
854
|
+
function checkAuthRoute(root, facts) {
|
|
855
|
+
if (!facts.authUrl) {
|
|
856
|
+
return [
|
|
857
|
+
{
|
|
858
|
+
status: "warn",
|
|
859
|
+
id: "admin.auth-url",
|
|
860
|
+
message: "no admin.authUrl: on the live site editors can sign in only with a token"
|
|
861
|
+
}
|
|
862
|
+
];
|
|
863
|
+
}
|
|
864
|
+
if (!facts.authUrl.startsWith("/") && !/^https?:\/\/[^/]+\/api\/editlet\/oauth/.test(facts.authUrl)) {
|
|
865
|
+
return [{ status: "ok", id: "admin.auth-url", message: `${facts.authUrl} (hosted outside this app)` }];
|
|
866
|
+
}
|
|
867
|
+
const route = routeFile(root, "api/editlet/oauth/[...path]", "editlet/auth");
|
|
868
|
+
return [
|
|
869
|
+
{ status: "ok", id: "admin.auth-url", message: facts.authUrl },
|
|
870
|
+
route ? { status: "ok", id: "admin.auth-route", message: route } : {
|
|
871
|
+
status: "fail",
|
|
872
|
+
id: "admin.auth-route",
|
|
873
|
+
message: `authUrl points into this app, but no route imports editlet/auth`
|
|
874
|
+
}
|
|
875
|
+
];
|
|
876
|
+
}
|
|
877
|
+
function checkAstro(root, facts) {
|
|
878
|
+
const text = facts.config?.text ?? "";
|
|
879
|
+
const out = [];
|
|
880
|
+
out.push(
|
|
881
|
+
text.includes("editlet/astro") && /editlet\s*\(/.test(text) ? { status: "ok", id: "astro.integration", message: `${facts.config?.file} adds the integration` } : {
|
|
882
|
+
status: "fail",
|
|
883
|
+
id: "astro.integration",
|
|
884
|
+
message: `${facts.config?.file} does not add editlet() to integrations`
|
|
885
|
+
}
|
|
886
|
+
);
|
|
887
|
+
const contentFile = firstFile(root, ["src/content.config.ts", "src/content.config.mjs", "src/content.config.js"]);
|
|
888
|
+
const content = contentFile ? read(join3(root, contentFile)) ?? "" : "";
|
|
889
|
+
out.push(
|
|
890
|
+
/editletCollections|editletLoader/.test(content) ? { status: "ok", id: "astro.collections", message: `${contentFile} uses the Editlet loader` } : {
|
|
891
|
+
status: "fail",
|
|
892
|
+
id: "astro.collections",
|
|
893
|
+
message: "src/content.config.ts does not use editletCollections or editletLoader"
|
|
894
|
+
}
|
|
895
|
+
);
|
|
896
|
+
if (/\bbase\s*:\s*['"`]/.test(text)) {
|
|
897
|
+
out.push({
|
|
898
|
+
status: "fail",
|
|
899
|
+
id: "astro.base",
|
|
900
|
+
message: "Astro `base` is not supported: the admin lives at /editlet/"
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
out.push(...checkAuthRoute(root, facts));
|
|
904
|
+
return out;
|
|
905
|
+
}
|
|
906
|
+
function checkEnv(ctx, facts) {
|
|
907
|
+
const out = [];
|
|
908
|
+
const needed = [];
|
|
909
|
+
if (facts.authUrl && routeFile(ctx.root, "api/editlet/oauth/[...path]", "editlet/auth")) {
|
|
910
|
+
needed.push("GITHUB_CLIENT_ID", "GITHUB_CLIENT_SECRET", "ALLOWED_ORIGINS");
|
|
911
|
+
}
|
|
912
|
+
if (facts.preview) needed.push("CMS_PREVIEW_SECRET", "CMS_GITHUB_TOKEN");
|
|
913
|
+
const example = read(join3(ctx.root, ".env.example")) ?? "";
|
|
914
|
+
const missing = needed.filter((name) => !new RegExp(`^\\s*${name}\\s*=`, "m").test(example));
|
|
915
|
+
if (needed.length > 0) {
|
|
916
|
+
out.push(
|
|
917
|
+
missing.length === 0 ? { status: "ok", id: "env.example", message: `.env.example names ${needed.join(", ")}` } : { status: "warn", id: "env.example", message: `.env.example lacks ${missing.join(", ")}` }
|
|
918
|
+
);
|
|
919
|
+
}
|
|
920
|
+
for (const file of [".env", ".env.local", ".env.production"]) {
|
|
921
|
+
if (!existsSync(join3(ctx.root, file))) continue;
|
|
922
|
+
const ignored = ctx.exec("git", ["-C", ctx.root, "check-ignore", "-q", file]).status === 0;
|
|
923
|
+
if (!ignored)
|
|
924
|
+
out.push({
|
|
925
|
+
status: "fail",
|
|
926
|
+
id: "env.ignored",
|
|
927
|
+
message: `${file} is not git-ignored: its secrets would be committed`
|
|
928
|
+
});
|
|
929
|
+
}
|
|
930
|
+
if (needed.length > 0 && existsSync(join3(ctx.root, ".vercel/project.json"))) {
|
|
931
|
+
const res = ctx.exec("vercel", ["env", "ls", "--cwd", ctx.root]);
|
|
932
|
+
if (res.status === 0) {
|
|
933
|
+
const absent = needed.filter((name) => !res.stdout.includes(name));
|
|
934
|
+
out.push(
|
|
935
|
+
absent.length === 0 ? { status: "ok", id: "env.vercel", message: `Vercel has ${needed.join(", ")}` } : { status: "fail", id: "env.vercel", message: `Vercel project lacks ${absent.join(", ")}` }
|
|
936
|
+
);
|
|
937
|
+
} else {
|
|
938
|
+
out.push({
|
|
939
|
+
status: "manual",
|
|
940
|
+
id: "env.vercel",
|
|
941
|
+
message: `check ${needed.join(", ")} in the Vercel project settings`
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
return out;
|
|
946
|
+
}
|
|
947
|
+
async function localChecks(ctx, facts) {
|
|
948
|
+
const out = checkProject(ctx, facts);
|
|
949
|
+
out.push(await checkContent(ctx.root));
|
|
950
|
+
if (facts.framework === "next") out.push(...checkNext(ctx.root, facts));
|
|
951
|
+
if (facts.framework === "astro") out.push(...checkAstro(ctx.root, facts));
|
|
952
|
+
out.push(...checkEnv(ctx, facts));
|
|
953
|
+
return out;
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
// auth/client.ts
|
|
957
|
+
var DEFAULT_TIMEOUT_MS = 5 * 6e4;
|
|
958
|
+
var REFRESH_SKEW_MS = 5 * 6e4;
|
|
959
|
+
|
|
960
|
+
// github/codeowners.ts
|
|
961
|
+
var CODEOWNERS_PATHS = [".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS"];
|
|
962
|
+
var escape = (c) => c.replace(/[.+^${}()|\\]/g, "\\$&");
|
|
963
|
+
function compilePattern(pattern) {
|
|
964
|
+
if (pattern.startsWith("!") || /[[\]\\]/.test(pattern)) return null;
|
|
965
|
+
let p = pattern;
|
|
966
|
+
const dirOnly = p.endsWith("/");
|
|
967
|
+
if (dirOnly) p = p.slice(0, -1);
|
|
968
|
+
const anchored = p.includes("/");
|
|
969
|
+
if (p.startsWith("/")) p = p.slice(1);
|
|
970
|
+
if (p === "") return null;
|
|
971
|
+
let re = "";
|
|
972
|
+
for (let i = 0; i < p.length; ) {
|
|
973
|
+
if (p.startsWith("**/", i)) {
|
|
974
|
+
re += "(?:.*/)?";
|
|
975
|
+
i += 3;
|
|
976
|
+
} else if (p.startsWith("/**", i) && i + 3 === p.length) {
|
|
977
|
+
re += "(?:/.*)?";
|
|
978
|
+
i += 3;
|
|
979
|
+
} else if (p.startsWith("**", i)) {
|
|
980
|
+
re += ".*";
|
|
981
|
+
i += 2;
|
|
982
|
+
} else if (p[i] === "*") {
|
|
983
|
+
re += "[^/]*";
|
|
984
|
+
i += 1;
|
|
985
|
+
} else if (p[i] === "?") {
|
|
986
|
+
re += "[^/]";
|
|
987
|
+
i += 1;
|
|
988
|
+
} else {
|
|
989
|
+
re += escape(p[i]);
|
|
990
|
+
i += 1;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
const literalLast = !/[*?]/.test(p.split("/").pop());
|
|
994
|
+
const tail = dirOnly ? "/.*" : literalLast ? "(?:/.*)?" : "";
|
|
995
|
+
return new RegExp(`^${anchored ? "" : "(?:.*/)?"}${re}${tail}$`);
|
|
996
|
+
}
|
|
997
|
+
function parseCodeowners(text) {
|
|
998
|
+
const rules = [];
|
|
999
|
+
text.split(/\r?\n/).forEach((raw, i) => {
|
|
1000
|
+
const tokens = raw.trim().split(/\s+/);
|
|
1001
|
+
const [pattern, ...rest] = tokens;
|
|
1002
|
+
if (!pattern || pattern.startsWith("#")) return;
|
|
1003
|
+
const regex = compilePattern(pattern);
|
|
1004
|
+
if (!regex) return;
|
|
1005
|
+
const comment = rest.findIndex((t) => t.startsWith("#"));
|
|
1006
|
+
const owners = (comment < 0 ? rest : rest.slice(0, comment)).filter((t) => t.includes("@"));
|
|
1007
|
+
rules.push({ pattern, owners, line: i + 1, regex });
|
|
1008
|
+
});
|
|
1009
|
+
return rules;
|
|
1010
|
+
}
|
|
1011
|
+
function ownersOf(rules, path) {
|
|
1012
|
+
for (let i = rules.length - 1; i >= 0; i--) if (rules[i].regex.test(path)) return rules[i].owners;
|
|
1013
|
+
return null;
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
// skills/editlet-setup/scripts/doctorRemote.ts
|
|
1017
|
+
async function get(ctx, url, init = {}) {
|
|
1018
|
+
try {
|
|
1019
|
+
return await ctx.fetch(url, { redirect: "manual", signal: AbortSignal.timeout(15e3), ...init });
|
|
1020
|
+
} catch {
|
|
1021
|
+
return null;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
var COOP_BAD = (value) => value?.trim().toLowerCase() === "same-origin";
|
|
1025
|
+
async function siteChecks(ctx) {
|
|
1026
|
+
const site = new URL(ctx.url);
|
|
1027
|
+
const out = [];
|
|
1028
|
+
let config = null;
|
|
1029
|
+
const cfg = await get(ctx, new URL("/editlet/config.json", site).href);
|
|
1030
|
+
if (cfg?.status === 200) {
|
|
1031
|
+
try {
|
|
1032
|
+
config = await cfg.json();
|
|
1033
|
+
} catch {
|
|
1034
|
+
config = null;
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
if (!config) {
|
|
1038
|
+
out.push({ status: "fail", id: "site.config", message: `/editlet/config.json: ${cfg ? cfg.status : "no answer"}` });
|
|
1039
|
+
} else if (!config.github?.owner || !config.github.repo || !config.github.baseBranch) {
|
|
1040
|
+
out.push({
|
|
1041
|
+
status: "fail",
|
|
1042
|
+
id: "site.config",
|
|
1043
|
+
message: 'config.json has no repository: "Editing on the live site is not set up"'
|
|
1044
|
+
});
|
|
1045
|
+
} else {
|
|
1046
|
+
const { owner, repo, baseBranch } = config.github;
|
|
1047
|
+
out.push({ status: "ok", id: "site.config", message: `${owner}/${repo}, base ${baseBranch}` });
|
|
1048
|
+
}
|
|
1049
|
+
const admin = await get(ctx, new URL("/editlet/index.html", site).href);
|
|
1050
|
+
out.push(
|
|
1051
|
+
admin?.status === 200 ? { status: "ok", id: "site.admin", message: "/editlet/index.html is served" } : { status: "fail", id: "site.admin", message: `/editlet/index.html: ${admin ? admin.status : "no answer"}` }
|
|
1052
|
+
);
|
|
1053
|
+
const devApi = await get(ctx, new URL("/__editlet/files", site).href);
|
|
1054
|
+
out.push(
|
|
1055
|
+
devApi?.status === 200 ? {
|
|
1056
|
+
status: "fail",
|
|
1057
|
+
id: "site.dev-api",
|
|
1058
|
+
message: "the dev file API answers on the live site: anyone can write files"
|
|
1059
|
+
} : { status: "ok", id: "site.dev-api", message: "no dev file API" }
|
|
1060
|
+
);
|
|
1061
|
+
const page = await get(ctx, site.href);
|
|
1062
|
+
const coop = page?.headers.get("cross-origin-opener-policy") ?? null;
|
|
1063
|
+
out.push(
|
|
1064
|
+
COOP_BAD(coop) ? { status: "fail", id: "site.coop", message: "the page sends Cross-Origin-Opener-Policy: same-origin" } : { status: "ok", id: "site.coop", message: `COOP ${coop ?? "not set"}` }
|
|
1065
|
+
);
|
|
1066
|
+
out.push(...await authChecks(ctx, site, config?.authUrl));
|
|
1067
|
+
if (config?.preview) {
|
|
1068
|
+
out.push({
|
|
1069
|
+
status: "manual",
|
|
1070
|
+
id: "site.preview",
|
|
1071
|
+
message: "draft preview is on: open ?editlet on a editlet/* branch and check the page shows the branch content"
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
return { findings: out, config };
|
|
1075
|
+
}
|
|
1076
|
+
async function authChecks(ctx, site, authUrl) {
|
|
1077
|
+
if (!authUrl) {
|
|
1078
|
+
return [{ status: "warn", id: "auth.url", message: "config.json has no authUrl: only token sign-in is offered" }];
|
|
1079
|
+
}
|
|
1080
|
+
const base2 = new URL(authUrl, site).href.replace(/\/+$/, "");
|
|
1081
|
+
const out = [];
|
|
1082
|
+
const health = await get(ctx, `${base2}/health`);
|
|
1083
|
+
out.push(
|
|
1084
|
+
health?.status === 204 ? { status: "ok", id: "auth.health", message: `${base2}/health answers 204` } : {
|
|
1085
|
+
status: "fail",
|
|
1086
|
+
id: "auth.health",
|
|
1087
|
+
message: `${base2}/health: ${health ? health.status : "no answer"} (expected 204)`
|
|
1088
|
+
}
|
|
1089
|
+
);
|
|
1090
|
+
const start = await get(ctx, `${base2}/auth?origin=${encodeURIComponent(site.origin)}`);
|
|
1091
|
+
const location2 = start?.headers.get("location") ?? "";
|
|
1092
|
+
if (start?.status === 302 && location2.startsWith("https://github.com/login/oauth/authorize")) {
|
|
1093
|
+
const clientId = new URL(location2).searchParams.get("client_id");
|
|
1094
|
+
out.push(
|
|
1095
|
+
clientId ? { status: "ok", id: "auth.origin", message: `${site.origin} is allowed; GitHub App client ${clientId}` } : {
|
|
1096
|
+
status: "fail",
|
|
1097
|
+
id: "auth.origin",
|
|
1098
|
+
message: "the redirect to GitHub has no client_id: GITHUB_CLIENT_ID is empty"
|
|
1099
|
+
}
|
|
1100
|
+
);
|
|
1101
|
+
} else if (start?.status === 400) {
|
|
1102
|
+
out.push({ status: "fail", id: "auth.origin", message: `ALLOWED_ORIGINS does not list ${site.origin}` });
|
|
1103
|
+
} else {
|
|
1104
|
+
out.push({
|
|
1105
|
+
status: "fail",
|
|
1106
|
+
id: "auth.origin",
|
|
1107
|
+
message: `/auth: ${start ? start.status : "no answer"} (expected 302 to GitHub)`
|
|
1108
|
+
});
|
|
1109
|
+
}
|
|
1110
|
+
out.push({
|
|
1111
|
+
status: "manual",
|
|
1112
|
+
id: "auth.github-app",
|
|
1113
|
+
message: `GitHub App: callback URL ${base2}/callback; Contents and Pull requests read/write, Deployments read; installed on the repo`
|
|
1114
|
+
});
|
|
1115
|
+
return out;
|
|
1116
|
+
}
|
|
1117
|
+
function repoOf(ctx, facts, config) {
|
|
1118
|
+
if (config?.github?.owner && config.github.repo) return { owner: config.github.owner, repo: config.github.repo };
|
|
1119
|
+
const fromConfig = /repo\s*:\s*['"`]([\w.-]+)\/([\w.-]+)['"`]/.exec(facts.config?.text ?? "");
|
|
1120
|
+
if (fromConfig) return { owner: fromConfig[1], repo: fromConfig[2] };
|
|
1121
|
+
const remote = ctx.exec("git", ["-C", ctx.root, "remote", "get-url", "origin"]).stdout.trim();
|
|
1122
|
+
const m = /github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?$/.exec(remote);
|
|
1123
|
+
return m ? { owner: m[1], repo: m[2] } : null;
|
|
1124
|
+
}
|
|
1125
|
+
var ghJson = (ctx, path) => {
|
|
1126
|
+
const res = ctx.exec("gh", ["api", path]);
|
|
1127
|
+
if (res.status !== 0) return void 0;
|
|
1128
|
+
try {
|
|
1129
|
+
return JSON.parse(res.stdout);
|
|
1130
|
+
} catch {
|
|
1131
|
+
return void 0;
|
|
1132
|
+
}
|
|
1133
|
+
};
|
|
1134
|
+
var types = (rules) => Array.isArray(rules) ? rules.map((r) => String(r.type)) : [];
|
|
1135
|
+
function codeownersText(ctx, slug, base2) {
|
|
1136
|
+
for (const path of CODEOWNERS_PATHS) {
|
|
1137
|
+
const file = ghJson(ctx, `repos/${slug}/contents/${path}?ref=${encodeURIComponent(base2)}`);
|
|
1138
|
+
if (typeof file?.content === "string") return { path, text: Buffer.from(file.content, "base64").toString("utf8") };
|
|
1139
|
+
}
|
|
1140
|
+
return null;
|
|
1141
|
+
}
|
|
1142
|
+
function roleChecks(ctx, slug, info, baseRules, style) {
|
|
1143
|
+
const out = [];
|
|
1144
|
+
const { base: base2, prefix } = style;
|
|
1145
|
+
const owners = codeownersText(ctx, slug, base2);
|
|
1146
|
+
if (!owners) {
|
|
1147
|
+
out.push({
|
|
1148
|
+
status: "manual",
|
|
1149
|
+
id: "github.roles",
|
|
1150
|
+
message: "roles not set up (optional): no CODEOWNERS on the base branch; see references/roles.md"
|
|
1151
|
+
});
|
|
1152
|
+
} else {
|
|
1153
|
+
const errors = ghJson(ctx, `repos/${slug}/codeowners/errors?ref=${encodeURIComponent(base2)}`);
|
|
1154
|
+
const list = errors?.errors ?? [];
|
|
1155
|
+
const rules = parseCodeowners(owners.text);
|
|
1156
|
+
const content = ownersOf(rules, `${style.contentDir}/x.md`) ?? [];
|
|
1157
|
+
const schema = ownersOf(rules, style.schemaPath) ?? [];
|
|
1158
|
+
out.push(
|
|
1159
|
+
list.length > 0 ? {
|
|
1160
|
+
status: "fail",
|
|
1161
|
+
id: "github.codeowners",
|
|
1162
|
+
message: `${owners.path}: ${list.slice(0, 3).map((e) => `line ${e.line}: ${e.message.split("\n")[0]}`).join("; ")}`
|
|
1163
|
+
} : {
|
|
1164
|
+
status: "ok",
|
|
1165
|
+
id: "github.codeowners",
|
|
1166
|
+
message: `${owners.path}: content by ${content.join(" ") || "nobody"}, schema by ${schema.join(" ") || "nobody"}`
|
|
1167
|
+
}
|
|
1168
|
+
);
|
|
1169
|
+
const pr = Array.isArray(baseRules) ? baseRules.find((r) => r.type === "pull_request")?.parameters : void 0;
|
|
1170
|
+
if (pr && (pr.require_code_owner_review !== true || pr.require_last_push_approval !== true)) {
|
|
1171
|
+
const missing = [
|
|
1172
|
+
pr.require_code_owner_review === true ? null : "Require review from Code Owners",
|
|
1173
|
+
pr.require_last_push_approval === true ? null : "Require approval of the most recent reviewable push"
|
|
1174
|
+
].filter(Boolean);
|
|
1175
|
+
out.push({
|
|
1176
|
+
status: "warn",
|
|
1177
|
+
id: "github.code-owner-review",
|
|
1178
|
+
message: `${base2} ruleset lacks: ${missing.join(", ")}`
|
|
1179
|
+
});
|
|
1180
|
+
} else if (pr) {
|
|
1181
|
+
out.push({ status: "ok", id: "github.code-owner-review", message: `${base2} requires Code Owners review` });
|
|
1182
|
+
}
|
|
1183
|
+
const outside = types(ghJson(ctx, `repos/${slug}/rules/branches/doctor-probe`));
|
|
1184
|
+
const inside = types(ghJson(ctx, `repos/${slug}/rules/branches/${prefix}doctor-probe`));
|
|
1185
|
+
if (inside.includes("creation")) {
|
|
1186
|
+
out.push({
|
|
1187
|
+
status: "fail",
|
|
1188
|
+
id: "github.creations",
|
|
1189
|
+
message: `a creation rule also covers ${prefix}*: the editor cannot create branches (exclude ${prefix}**/*)`
|
|
1190
|
+
});
|
|
1191
|
+
} else {
|
|
1192
|
+
out.push(
|
|
1193
|
+
outside.includes("creation") ? { status: "ok", id: "github.creations", message: `only ${prefix}* branches can be created without bypass` } : {
|
|
1194
|
+
status: "warn",
|
|
1195
|
+
id: "github.creations",
|
|
1196
|
+
message: `anyone with write access can create any branch (add Restrict creations outside ${prefix}**/*)`
|
|
1197
|
+
}
|
|
1198
|
+
);
|
|
1199
|
+
}
|
|
1200
|
+
if (info.private !== true) {
|
|
1201
|
+
out.push({
|
|
1202
|
+
status: "manual",
|
|
1203
|
+
id: "github.push-rules",
|
|
1204
|
+
message: "push rules need a private or internal repository; CODEOWNERS keeps code changes waiting for owners"
|
|
1205
|
+
});
|
|
1206
|
+
} else {
|
|
1207
|
+
const sets = ghJson(ctx, `repos/${slug}/rulesets?targets=push`);
|
|
1208
|
+
const paths = [];
|
|
1209
|
+
let bypassHidden = false;
|
|
1210
|
+
for (const set of Array.isArray(sets) ? sets : []) {
|
|
1211
|
+
if (set.enforcement !== "active") continue;
|
|
1212
|
+
const full = ghJson(ctx, `repos/${slug}/rulesets/${set.id}`);
|
|
1213
|
+
if (full && full.bypass_actors === void 0) bypassHidden = true;
|
|
1214
|
+
for (const rule of full?.rules ?? []) {
|
|
1215
|
+
if (rule.type !== "file_path_restriction") continue;
|
|
1216
|
+
const restricted = rule.parameters?.restricted_file_paths;
|
|
1217
|
+
if (Array.isArray(restricted)) paths.push(...restricted.map(String));
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
const covers = paths.some((p) => p === "**/*" || p === style.schemaPath);
|
|
1221
|
+
out.push(
|
|
1222
|
+
covers ? { status: "ok", id: "github.push-rules", message: `push rules restrict ${paths.join(", ")}` } : {
|
|
1223
|
+
status: "warn",
|
|
1224
|
+
id: "github.push-rules",
|
|
1225
|
+
message: `no push rule keeps editors out of ${style.schemaPath} and code (Restrict file paths)`
|
|
1226
|
+
}
|
|
1227
|
+
);
|
|
1228
|
+
if (bypassHidden) {
|
|
1229
|
+
out.push({
|
|
1230
|
+
status: "manual",
|
|
1231
|
+
id: "github.bypass",
|
|
1232
|
+
message: "GitHub hides who bypasses the push rules from this account: check that only admins do"
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
for (const label of style.labels) {
|
|
1238
|
+
const found = ghJson(ctx, `repos/${slug}/labels/${encodeURIComponent(label)}`);
|
|
1239
|
+
out.push(
|
|
1240
|
+
found ? { status: "ok", id: "github.labels", message: `label ${label} exists` } : {
|
|
1241
|
+
status: "warn",
|
|
1242
|
+
id: "github.labels",
|
|
1243
|
+
message: `label ${label} does not exist: pull requests may open without it (gh label create ${label})`
|
|
1244
|
+
}
|
|
1245
|
+
);
|
|
1246
|
+
}
|
|
1247
|
+
return out;
|
|
1248
|
+
}
|
|
1249
|
+
function githubChecks(ctx, facts, config, style) {
|
|
1250
|
+
const { base: base2 } = style;
|
|
1251
|
+
const repo = repoOf(ctx, facts, config);
|
|
1252
|
+
if (!repo)
|
|
1253
|
+
return [
|
|
1254
|
+
{ status: "manual", id: "github.repo", message: "no GitHub repository found (admin.repo or the origin remote)" }
|
|
1255
|
+
];
|
|
1256
|
+
if (ctx.exec("gh", ["auth", "status"]).status !== 0) {
|
|
1257
|
+
return [
|
|
1258
|
+
{ status: "manual", id: "github.repo", message: `gh is not logged in: check ${repo.owner}/${repo.repo} by hand` }
|
|
1259
|
+
];
|
|
1260
|
+
}
|
|
1261
|
+
const slug = `${repo.owner}/${repo.repo}`;
|
|
1262
|
+
const info = ghJson(ctx, `repos/${slug}`);
|
|
1263
|
+
if (!info) return [{ status: "fail", id: "github.repo", message: `${slug}: not found or no access` }];
|
|
1264
|
+
const out = [
|
|
1265
|
+
info.permissions?.push ? { status: "ok", id: "github.repo", message: `${slug}: you can push` } : { status: "warn", id: "github.repo", message: `${slug}: your account cannot push` }
|
|
1266
|
+
];
|
|
1267
|
+
const rules = ghJson(ctx, `repos/${slug}/rules/branches/${base2}`);
|
|
1268
|
+
const hasPrRule = Array.isArray(rules) && rules.some((r) => r.type === "pull_request");
|
|
1269
|
+
const classic = hasPrRule ? void 0 : ghJson(ctx, `repos/${slug}/branches/${base2}/protection`);
|
|
1270
|
+
out.push(
|
|
1271
|
+
hasPrRule || classic?.required_pull_request_reviews ? { status: "ok", id: "github.protection", message: `${base2} requires a pull request` } : { status: "warn", id: "github.protection", message: `${base2} has no rule that requires a pull request` }
|
|
1272
|
+
);
|
|
1273
|
+
const deployments = ghJson(ctx, `repos/${slug}/deployments?per_page=30`);
|
|
1274
|
+
const envs = Array.isArray(deployments) ? deployments.map((d) => String(d.environment)) : [];
|
|
1275
|
+
out.push(
|
|
1276
|
+
envs.some((e) => !/production/i.test(e)) ? { status: "ok", id: "github.deployments", message: "the host reports branch preview deployments" } : {
|
|
1277
|
+
status: "warn",
|
|
1278
|
+
id: "github.deployments",
|
|
1279
|
+
message: "no preview deployments reported: the branch screen shows no preview"
|
|
1280
|
+
}
|
|
1281
|
+
);
|
|
1282
|
+
out.push(...roleChecks(ctx, slug, info, rules, style));
|
|
1283
|
+
return out;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
// core/gitStyle.ts
|
|
1287
|
+
var DEFAULT_BRANCH_PREFIX = "editlet/";
|
|
1288
|
+
var DEFAULT_COMMIT_MESSAGE = "{Action} {target}";
|
|
1289
|
+
var DEFAULT_PULL_REQUEST_TITLE = "Update {branch}";
|
|
1290
|
+
var DEFAULT_LABELS = ["editlet"];
|
|
1291
|
+
function resolveGitStyle(git) {
|
|
1292
|
+
return {
|
|
1293
|
+
branchPrefix: git?.branchPrefix ?? DEFAULT_BRANCH_PREFIX,
|
|
1294
|
+
commitMessage: git?.commitMessage ?? DEFAULT_COMMIT_MESSAGE,
|
|
1295
|
+
pullRequest: {
|
|
1296
|
+
title: git?.pullRequest?.title ?? DEFAULT_PULL_REQUEST_TITLE,
|
|
1297
|
+
labels: [...git?.pullRequest?.labels ?? DEFAULT_LABELS],
|
|
1298
|
+
draft: git?.pullRequest?.draft ?? false
|
|
1299
|
+
}
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
// skills/editlet-setup/scripts/doctor.ts
|
|
1304
|
+
var SCHEMA_PATH = "cms/schema.json";
|
|
1305
|
+
function repoStyle(root) {
|
|
1306
|
+
let schema = {};
|
|
1307
|
+
try {
|
|
1308
|
+
schema = JSON.parse(readFileSync2(join4(root, SCHEMA_PATH), "utf8"));
|
|
1309
|
+
} catch {
|
|
1310
|
+
}
|
|
1311
|
+
const git = schema.git ?? {};
|
|
1312
|
+
const style = resolveGitStyle({ ...git, baseBranch: git.baseBranch ?? "main" });
|
|
1313
|
+
return {
|
|
1314
|
+
base: git.baseBranch ?? "main",
|
|
1315
|
+
prefix: style.branchPrefix,
|
|
1316
|
+
contentDir: schema.contentDir ?? "cms/content",
|
|
1317
|
+
schemaPath: SCHEMA_PATH,
|
|
1318
|
+
labels: style.pullRequest.labels
|
|
1319
|
+
};
|
|
1320
|
+
}
|
|
1321
|
+
async function doctor(ctx) {
|
|
1322
|
+
const facts = projectFacts(ctx.root);
|
|
1323
|
+
const findings = await localChecks(ctx, facts);
|
|
1324
|
+
let config = null;
|
|
1325
|
+
if (ctx.url) {
|
|
1326
|
+
const site = await siteChecks(ctx);
|
|
1327
|
+
findings.push(...site.findings);
|
|
1328
|
+
config = site.config;
|
|
1329
|
+
}
|
|
1330
|
+
if (ctx.url || facts.admin) findings.push(...githubChecks(ctx, facts, config, repoStyle(ctx.root)));
|
|
1331
|
+
return findings;
|
|
1332
|
+
}
|
|
1333
|
+
function formatFinding(f) {
|
|
1334
|
+
return `${f.status.padEnd(6)} ${f.id}: ${f.message}`;
|
|
1335
|
+
}
|
|
1336
|
+
var USAGE = "usage: doctor.mjs [--root <dir>] [--url <https://site>] [--json]\n";
|
|
1337
|
+
async function main() {
|
|
1338
|
+
const args = process.argv.slice(2);
|
|
1339
|
+
let root = process.cwd();
|
|
1340
|
+
let url;
|
|
1341
|
+
let json = false;
|
|
1342
|
+
for (let i = 0; i < args.length; i++) {
|
|
1343
|
+
const arg = args[i];
|
|
1344
|
+
if (arg === "--json") json = true;
|
|
1345
|
+
else if (arg === "--root" && args[i + 1]) root = resolve3(args[++i]);
|
|
1346
|
+
else if (arg === "--url" && args[i + 1] && URL.canParse(args[i + 1])) url = args[++i];
|
|
1347
|
+
else {
|
|
1348
|
+
process.stderr.write(USAGE);
|
|
1349
|
+
process.exitCode = 2;
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
if (!existsSync2(join4(root, "package.json"))) {
|
|
1354
|
+
process.stderr.write(`no package.json in ${root}
|
|
1355
|
+
`);
|
|
1356
|
+
process.exitCode = 2;
|
|
1357
|
+
return;
|
|
1358
|
+
}
|
|
1359
|
+
const findings = await doctor({
|
|
1360
|
+
root,
|
|
1361
|
+
url,
|
|
1362
|
+
nodeVersion: process.versions.node,
|
|
1363
|
+
exec: (cmd, cmdArgs) => {
|
|
1364
|
+
const res = spawnSync(cmd, cmdArgs, { cwd: root, encoding: "utf8", timeout: 3e4 });
|
|
1365
|
+
return { status: res.status, stdout: res.stdout ?? "", stderr: res.stderr ?? "" };
|
|
1366
|
+
},
|
|
1367
|
+
fetch: globalThis.fetch
|
|
1368
|
+
});
|
|
1369
|
+
process.stdout.write(json ? `${JSON.stringify(findings, null, 2)}
|
|
1370
|
+
` : `${findings.map(formatFinding).join("\n")}
|
|
1371
|
+
`);
|
|
1372
|
+
if (findings.some((f) => f.status === "fail")) process.exitCode = 1;
|
|
1373
|
+
}
|
|
1374
|
+
if (/^doctor\.(ts|mjs)$/.test(basename(process.argv[1] ?? ""))) await main();
|
|
1375
|
+
export {
|
|
1376
|
+
doctor,
|
|
1377
|
+
formatFinding
|
|
1378
|
+
};
|