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.
Files changed (146) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +113 -2
  3. package/dist/admin/config.d.ts +22 -0
  4. package/dist/admin/config.js +75 -0
  5. package/dist/admin/dist/assets/RichEditor-BlaCRrEX.css +1 -0
  6. package/dist/admin/dist/assets/RichEditor-IZKdt6MK.js +42 -0
  7. package/dist/admin/dist/assets/blank-line-CbGzlqBI.js +1 -0
  8. package/dist/admin/dist/assets/channel-CljeMIwA.js +1 -0
  9. package/dist/admin/dist/assets/db-CCMyPgQa.js +1 -0
  10. package/dist/admin/dist/assets/index-CWoJh4H8.js +257 -0
  11. package/dist/admin/dist/assets/index-DkRMnD_M.css +1 -0
  12. package/dist/admin/dist/assets/mdast-util-from-markdown-C79q1_d8.js +3 -0
  13. package/dist/admin/dist/assets/mdast-util-gfm-cM-_xFJE.js +19 -0
  14. package/dist/admin/dist/assets/micromark-extension-gfm-Wz6-oszS.js +1 -0
  15. package/dist/admin/dist/assets/micromark-util-classify-character-BgXaGAja.js +1 -0
  16. package/dist/admin/dist/assets/micromark-util-html-tag-name-B61T18yC.js +1 -0
  17. package/dist/admin/dist/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  18. package/dist/admin/dist/index.html +16 -0
  19. package/dist/admin/dist/preview.js +1 -0
  20. package/dist/admin/dist/window.js +1 -0
  21. package/dist/astro/content.d.ts +21 -0
  22. package/dist/astro/content.js +235 -0
  23. package/dist/astro/devServer.js +89 -0
  24. package/dist/astro/index.d.ts +15 -0
  25. package/dist/astro/index.js +98 -0
  26. package/dist/astro/nodeBridge.js +36 -0
  27. package/dist/astro/shared.js +10 -0
  28. package/dist/astro/stub/index.html +71 -0
  29. package/dist/auth/client.d.ts +24 -0
  30. package/dist/auth/client.js +120 -0
  31. package/dist/auth/handler.d.ts +16 -0
  32. package/dist/auth/handler.js +281 -0
  33. package/dist/auth/protocol.d.ts +25 -0
  34. package/dist/auth/protocol.js +3 -0
  35. package/dist/core/assets.d.ts +73 -0
  36. package/dist/core/assets.js +405 -0
  37. package/dist/core/devApi.d.ts +28 -0
  38. package/dist/core/devApi.js +3 -0
  39. package/dist/core/entryFile.d.ts +13 -0
  40. package/dist/core/entryFile.js +81 -0
  41. package/dist/core/fields.js +147 -0
  42. package/dist/core/generate.d.ts +3 -0
  43. package/dist/core/generate.js +70 -0
  44. package/dist/core/gitStyle.d.ts +92 -0
  45. package/dist/core/gitStyle.js +206 -0
  46. package/dist/core/index.d.ts +16 -0
  47. package/dist/core/index.js +16 -0
  48. package/dist/core/issues.d.ts +10 -0
  49. package/dist/core/issues.js +10 -0
  50. package/dist/core/paths.d.ts +31 -0
  51. package/dist/core/paths.js +114 -0
  52. package/dist/core/project.js +56 -0
  53. package/dist/core/references.d.ts +68 -0
  54. package/dist/core/references.js +103 -0
  55. package/dist/core/rename.d.ts +60 -0
  56. package/dist/core/rename.js +133 -0
  57. package/dist/core/schema.d.ts +117 -0
  58. package/dist/core/schema.js +299 -0
  59. package/dist/core/sha.d.ts +2 -0
  60. package/dist/core/sha.js +13 -0
  61. package/dist/core/source.d.ts +48 -0
  62. package/dist/core/source.js +57 -0
  63. package/dist/core/validate.d.ts +22 -0
  64. package/dist/core/validate.js +148 -0
  65. package/dist/core/walk.d.ts +23 -0
  66. package/dist/core/walk.js +94 -0
  67. package/dist/core/writes.d.ts +37 -0
  68. package/dist/core/writes.js +166 -0
  69. package/dist/github/base64.js +16 -0
  70. package/dist/github/cache.d.ts +34 -0
  71. package/dist/github/cache.js +126 -0
  72. package/dist/github/client.d.ts +38 -0
  73. package/dist/github/client.js +228 -0
  74. package/dist/github/codeowners.d.ts +23 -0
  75. package/dist/github/codeowners.js +96 -0
  76. package/dist/github/commitReader.d.ts +25 -0
  77. package/dist/github/commitReader.js +38 -0
  78. package/dist/github/deploy.d.ts +15 -0
  79. package/dist/github/deploy.js +33 -0
  80. package/dist/github/index.d.ts +9 -0
  81. package/dist/github/index.js +8 -0
  82. package/dist/github/repo.d.ts +95 -0
  83. package/dist/github/repo.js +375 -0
  84. package/dist/github/source.d.ts +115 -0
  85. package/dist/github/source.js +558 -0
  86. package/dist/loader/index.d.ts +27 -0
  87. package/dist/loader/index.js +151 -0
  88. package/dist/loader/protocol.d.ts +95 -0
  89. package/dist/loader/protocol.js +120 -0
  90. package/dist/loader/window/geometry.js +9 -0
  91. package/dist/next/EditletLoader.d.ts +5 -0
  92. package/dist/next/EditletLoader.js +33 -0
  93. package/dist/next/assetUrl.d.ts +9 -0
  94. package/dist/next/assetUrl.js +13 -0
  95. package/dist/next/buildGuard.js +26 -0
  96. package/dist/next/config.d.ts +18 -0
  97. package/dist/next/config.js +255 -0
  98. package/dist/next/devServer.js +70 -0
  99. package/dist/next/editletField.d.ts +7 -0
  100. package/dist/next/editletField.js +7 -0
  101. package/dist/next/index.d.ts +8 -0
  102. package/dist/next/index.js +6 -0
  103. package/dist/next/preview.d.ts +18 -0
  104. package/dist/next/preview.js +100 -0
  105. package/dist/next/previewCookie.d.ts +5 -0
  106. package/dist/next/previewCookie.js +72 -0
  107. package/dist/next/previewEnv.js +25 -0
  108. package/dist/next/previewRef.d.ts +8 -0
  109. package/dist/next/previewRef.js +17 -0
  110. package/dist/next/publicDir.js +65 -0
  111. package/dist/next/reader.d.ts +49 -0
  112. package/dist/next/reader.js +161 -0
  113. package/dist/next/stub/index.html +56 -0
  114. package/dist/node/devHandler.d.ts +6 -0
  115. package/dist/node/devHandler.js +430 -0
  116. package/dist/node/fs.js +37 -0
  117. package/dist/node/index.d.ts +3 -0
  118. package/dist/node/index.js +3 -0
  119. package/dist/node/project.d.ts +12 -0
  120. package/dist/node/project.js +43 -0
  121. package/package.json +187 -4
  122. package/skills/README.md +84 -0
  123. package/skills/editlet/SKILL.md +119 -0
  124. package/skills/editlet/references/content-format.md +191 -0
  125. package/skills/editlet/references/preview.md +75 -0
  126. package/skills/editlet/references/publishing.md +137 -0
  127. package/skills/editlet/references/schema-changes.md +127 -0
  128. package/skills/editlet/scripts/guard.mjs +1061 -0
  129. package/skills/editlet/scripts/link.mjs +193 -0
  130. package/skills/editlet/scripts/refs.mjs +1480 -0
  131. package/skills/editlet/scripts/schema.mjs +1340 -0
  132. package/skills/editlet/scripts/style.mjs +657 -0
  133. package/skills/editlet/scripts/types.mjs +525 -0
  134. package/skills/editlet/scripts/validate.mjs +724 -0
  135. package/skills/editlet-migrate/SKILL.md +92 -0
  136. package/skills/editlet-migrate/references/mapping.md +73 -0
  137. package/skills/editlet-migrate/references/sources.md +70 -0
  138. package/skills/editlet-setup/SKILL.md +108 -0
  139. package/skills/editlet-setup/references/astro.md +83 -0
  140. package/skills/editlet-setup/references/doctor.md +89 -0
  141. package/skills/editlet-setup/references/next.md +140 -0
  142. package/skills/editlet-setup/references/preview.md +54 -0
  143. package/skills/editlet-setup/references/production.md +153 -0
  144. package/skills/editlet-setup/references/roles.md +238 -0
  145. package/skills/editlet-setup/references/skills.md +99 -0
  146. package/skills/editlet-setup/scripts/doctor.mjs +1378 -0
@@ -0,0 +1,299 @@
1
+ import { fieldValueSchema } from "./fields.js";
2
+ import { EditletError } from "./issues.js";
3
+ import { isCanonicalPath } from "./paths.js";
4
+ import { z } from "zod";
5
+ // core/schema.ts
6
+ /** Key that names the kind of a `blocks` item; reserved as a field key inside blocks. */
7
+ const BLOCK_KEY = "block";
8
+ /** Placeholders of `git.commitMessage`. */
9
+ const COMMIT_PLACEHOLDERS = [
10
+ "action",
11
+ "Action",
12
+ "collection",
13
+ "slug",
14
+ "target"
15
+ ];
16
+ /** Placeholders of `git.pullRequest.title`. */
17
+ const TITLE_PLACEHOLDERS = [
18
+ "branch",
19
+ "name",
20
+ "login"
21
+ ];
22
+ /** One or more `/`-separated ref segments (letters, digits, `.`, `_`, `-`; no `..`, no `.lock` segment end). */
23
+ const REF_SEGMENTS = /^[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
24
+ function isRefPath(value) {
25
+ return REF_SEGMENTS.test(value) && !value.includes("..") && !value.split("/").some((s) => s.endsWith(".lock"));
26
+ }
27
+ /** Template text with only the given `{placeholders}`, one line. */
28
+ function template(placeholders, max) {
29
+ return z.string().trim().min(1).max(max).refine((t) => !/[\r\n]/.test(t), "must be one line").superRefine((t, ctx) => {
30
+ for (const [, name] of t.matchAll(/\{([^{}]*)\}/g)) if (!placeholders.includes(name)) ctx.addIssue({
31
+ code: "custom",
32
+ message: `unknown placeholder "{${name}}" (use ${placeholders.map((p) => `{${p}}`).join(", ")})`
33
+ });
34
+ });
35
+ }
36
+ const gitSchema = z.strictObject({
37
+ baseBranch: z.string().min(1),
38
+ branchPrefix: z.string().refine((p) => p.endsWith("/") && isRefPath(p.slice(0, -1)), "must be branch name segments ending in \"/\", for example \"editlet/\"").optional(),
39
+ commitMessage: template(COMMIT_PLACEHOLDERS, 200).optional(),
40
+ pullRequest: z.strictObject({
41
+ title: template(TITLE_PLACEHOLDERS, 256).optional(),
42
+ labels: z.array(z.string().trim().min(1).max(50).refine((l) => !l.includes(","), "must not contain \",\"")).max(10).optional(),
43
+ draft: z.boolean().optional()
44
+ }).optional()
45
+ });
46
+ const IDENT = /^[a-zA-Z][a-zA-Z0-9]*$/;
47
+ const identMsg = "must start with a letter and contain only letters and digits";
48
+ const base = {
49
+ label: z.string(),
50
+ hint: z.string().optional(),
51
+ required: z.boolean().optional()
52
+ };
53
+ const strOrList = z.union([z.string(), z.array(z.string())]);
54
+ /** Fields of an `object` or of a block: the same field types, nested (`z.lazy`: a field can hold fields). */
55
+ const nestedFields = z.lazy(() => z.record(z.string().regex(IDENT, `field key ${identMsg}`), fieldSchema).refine((o) => Object.keys(o).length > 0, "fields must not be empty"));
56
+ const fieldSchema = z.discriminatedUnion("type", [
57
+ z.strictObject({
58
+ ...base,
59
+ type: z.literal("string"),
60
+ list: z.boolean().optional(),
61
+ default: strOrList.optional()
62
+ }),
63
+ z.strictObject({
64
+ ...base,
65
+ type: z.literal("text"),
66
+ rows: z.number().int().positive().optional(),
67
+ default: z.string().optional()
68
+ }),
69
+ z.strictObject({
70
+ ...base,
71
+ type: z.literal("markdown")
72
+ }),
73
+ z.strictObject({
74
+ ...base,
75
+ type: z.literal("boolean"),
76
+ default: z.boolean().optional(),
77
+ labels: z.strictObject({
78
+ true: z.string(),
79
+ false: z.string()
80
+ }).optional()
81
+ }),
82
+ z.strictObject({
83
+ ...base,
84
+ type: z.literal("select"),
85
+ options: z.array(z.strictObject({
86
+ label: z.string(),
87
+ value: z.string()
88
+ })).min(1, "options must not be empty"),
89
+ multiple: z.boolean().optional(),
90
+ default: strOrList.optional()
91
+ }),
92
+ z.strictObject({
93
+ ...base,
94
+ type: z.literal("number"),
95
+ min: z.number().optional(),
96
+ max: z.number().optional(),
97
+ step: z.number().optional(),
98
+ integer: z.boolean().optional(),
99
+ default: z.number().optional()
100
+ }),
101
+ z.strictObject({
102
+ ...base,
103
+ type: z.literal("datetime"),
104
+ dateOnly: z.boolean().optional(),
105
+ defaultNow: z.boolean().optional()
106
+ }),
107
+ z.strictObject({
108
+ ...base,
109
+ type: z.literal("json")
110
+ }),
111
+ z.strictObject({
112
+ ...base,
113
+ type: z.literal("url")
114
+ }),
115
+ z.strictObject({
116
+ ...base,
117
+ type: z.literal("color"),
118
+ default: z.string().optional()
119
+ }),
120
+ z.strictObject({
121
+ ...base,
122
+ type: z.literal("image")
123
+ }),
124
+ z.strictObject({
125
+ ...base,
126
+ type: z.literal("reference"),
127
+ collections: z.array(z.string()).min(1, "collections must not be empty"),
128
+ multiple: z.boolean().optional(),
129
+ min: z.number().int().nonnegative().optional(),
130
+ max: z.number().int().nonnegative().optional()
131
+ }),
132
+ z.strictObject({
133
+ ...base,
134
+ type: z.literal("object"),
135
+ fields: nestedFields,
136
+ list: z.boolean().optional(),
137
+ min: z.number().int().nonnegative().optional(),
138
+ max: z.number().int().nonnegative().optional()
139
+ }),
140
+ z.strictObject({
141
+ ...base,
142
+ type: z.literal("blocks"),
143
+ blocks: z.record(z.string().regex(IDENT, `block key ${identMsg}`), z.strictObject({
144
+ label: z.string(),
145
+ fields: nestedFields
146
+ })).refine((o) => Object.keys(o).length > 0, "blocks must not be empty"),
147
+ min: z.number().int().nonnegative().optional(),
148
+ max: z.number().int().nonnegative().optional()
149
+ })
150
+ ]);
151
+ const collectionSchema = z.strictObject({
152
+ label: z.string(),
153
+ singleton: z.boolean().optional(),
154
+ titleField: z.string().optional(),
155
+ slugFrom: z.string().optional(),
156
+ fields: z.record(z.string().regex(IDENT, `field key ${identMsg}`), fieldSchema)
157
+ });
158
+ /**
159
+ * Rules for a set of fields, at the top of a collection (`nested: false`) or inside an `object` / a block, where
160
+ * `draft` is an ordinary key and `markdown` is a Markdown string.
161
+ */
162
+ function checkFields(schema, fields, at, nested, add) {
163
+ for (const [fk, f] of Object.entries(fields)) {
164
+ const path = [...at, fk];
165
+ if (fk === "draft" && !nested) add(path, "field key \"draft\" is reserved for the draft flag");
166
+ if ("default" in f && f.default !== void 0) {
167
+ const checked = fieldValueSchema(f)?.safeParse(f.default);
168
+ for (const issue of checked?.success === false ? checked.error.issues : []) add([
169
+ ...path,
170
+ "default",
171
+ ...issue.path.map(String)
172
+ ], `default: ${issue.message}`);
173
+ }
174
+ if (f.type === "reference") {
175
+ f.collections.forEach((target, i) => {
176
+ if (!Object.hasOwn(schema.collections, target)) add([
177
+ ...path,
178
+ "collections",
179
+ i
180
+ ], `unknown collection "${target}"`);
181
+ });
182
+ if (!f.multiple && (f.min !== void 0 || f.max !== void 0)) add(path, "min/max require multiple: true");
183
+ }
184
+ if (f.type === "object") {
185
+ if (!f.list && (f.min !== void 0 || f.max !== void 0)) add(path, "min/max require list: true");
186
+ checkFields(schema, f.fields, [...path, "fields"], true, add);
187
+ }
188
+ if (f.type === "blocks") for (const [bk, block] of Object.entries(f.blocks)) {
189
+ if (Object.hasOwn(block.fields, "block")) add([
190
+ ...path,
191
+ "blocks",
192
+ bk,
193
+ "fields",
194
+ BLOCK_KEY
195
+ ], `field key "${BLOCK_KEY}" is reserved for the block type`);
196
+ checkFields(schema, block.fields, [
197
+ ...path,
198
+ "blocks",
199
+ bk,
200
+ "fields"
201
+ ], true, add);
202
+ }
203
+ if ((f.type === "reference" || f.type === "object" || f.type === "blocks") && f.min !== void 0 && f.max !== void 0 && f.min > f.max) add([...path, "min"], "min must not exceed max");
204
+ }
205
+ }
206
+ const schemaSchema = z.strictObject({
207
+ $schema: z.string().optional(),
208
+ contentDir: z.string().min(1).refine(isCanonicalPath, "must be a relative posix path without empty, \".\" or \"..\" segments, backslashes, NUL or \":\""),
209
+ git: gitSchema,
210
+ collections: z.record(z.string().regex(IDENT, `collection key ${identMsg}`), collectionSchema)
211
+ }).superRefine((schema, ctx) => {
212
+ const add = (path, message) => ctx.addIssue({
213
+ code: "custom",
214
+ path,
215
+ message
216
+ });
217
+ const { baseBranch, branchPrefix } = schema.git;
218
+ if (branchPrefix !== void 0 && (baseBranch.startsWith(branchPrefix) || branchPrefix.startsWith(`${baseBranch}/`))) add(["git", "branchPrefix"], `branchPrefix "${branchPrefix}" clashes with the base branch "${baseBranch}"`);
219
+ const lowerKeys = /* @__PURE__ */ new Map();
220
+ for (const [ck, col] of Object.entries(schema.collections)) {
221
+ const other = lowerKeys.get(ck.toLowerCase());
222
+ if (other !== void 0) add(["collections", ck], `collection key "${ck}" differs from "${other}" only in case`);
223
+ else lowerKeys.set(ck.toLowerCase(), ck);
224
+ if (Object.entries(col.fields).filter(([, f]) => f.type === "markdown").length > 1) add([
225
+ "collections",
226
+ ck,
227
+ "fields"
228
+ ], "a collection can have at most one markdown field");
229
+ if (col.titleField !== void 0 && !Object.hasOwn(col.fields, col.titleField)) add([
230
+ "collections",
231
+ ck,
232
+ "titleField"
233
+ ], `titleField "${col.titleField}" is not a field of ${ck}`);
234
+ if (col.slugFrom !== void 0 && !Object.hasOwn(col.fields, col.slugFrom)) add([
235
+ "collections",
236
+ ck,
237
+ "slugFrom"
238
+ ], `slugFrom "${col.slugFrom}" is not a field of ${ck}`);
239
+ checkFields(schema, col.fields, [
240
+ "collections",
241
+ ck,
242
+ "fields"
243
+ ], false, add);
244
+ }
245
+ });
246
+ function toIssues(error) {
247
+ const out = [];
248
+ for (const issue of error.issues) {
249
+ let path = issue.path.map(String);
250
+ let message = issue.message;
251
+ if (issue.code === "invalid_union" && ("discriminator" in issue || path.at(-1) !== "type")) {
252
+ if (path.at(-1) !== "type") path = [...path, "type"];
253
+ message = "unknown field type";
254
+ }
255
+ if (issue.code === "unrecognized_keys") {
256
+ for (const key of issue.keys) out.push({
257
+ path: [...path, key].join("."),
258
+ message: `unknown key "${key}"`
259
+ });
260
+ continue;
261
+ }
262
+ out.push({
263
+ path: path.join("."),
264
+ message
265
+ });
266
+ }
267
+ return out;
268
+ }
269
+ function loadSchema(input) {
270
+ const parsed = schemaSchema.safeParse(input);
271
+ if (!parsed.success) throw new EditletError(toIssues(parsed.error));
272
+ return parsed.data;
273
+ }
274
+ /** Parses schema JSON text; issues (bad JSON or bad schema) carry `file`. */
275
+ function parseSchemaText(text, file) {
276
+ let json;
277
+ try {
278
+ json = JSON.parse(text);
279
+ } catch (error) {
280
+ throw new EditletError([{
281
+ file,
282
+ path: "",
283
+ message: `Invalid JSON: ${error instanceof Error ? error.message : error}`
284
+ }]);
285
+ }
286
+ try {
287
+ return loadSchema(json);
288
+ } catch (error) {
289
+ if (error instanceof EditletError) throw new EditletError(error.issues.map((issue) => ({
290
+ ...issue,
291
+ file
292
+ })));
293
+ throw error;
294
+ }
295
+ }
296
+ function markdownFieldKey(collection) {
297
+ return Object.entries(collection.fields).find(([, f]) => f.type === "markdown")?.[0];
298
+ }
299
+ export { BLOCK_KEY, COMMIT_PLACEHOLDERS, TITLE_PLACEHOLDERS, isRefPath, loadSchema, markdownFieldKey, parseSchemaText };
@@ -0,0 +1,2 @@
1
+ /** Git blob object id (SHA-1 over `blob <byteLength>\0<bytes>`), as printed by `git hash-object`. */
2
+ export declare function gitBlobSha(content: Uint8Array | string): Promise<string>;
@@ -0,0 +1,13 @@
1
+ // core/sha.ts
2
+ const encoder = new TextEncoder();
3
+ /** Git blob object id (SHA-1 over `blob <byteLength>\0<bytes>`), as printed by `git hash-object`. */
4
+ async function gitBlobSha(content) {
5
+ const bytes = typeof content === "string" ? encoder.encode(content) : content;
6
+ const header = encoder.encode(`blob ${bytes.byteLength}\0`);
7
+ const buffer = new Uint8Array(header.byteLength + bytes.byteLength);
8
+ buffer.set(header);
9
+ buffer.set(bytes, header.byteLength);
10
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-1", buffer));
11
+ return Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("");
12
+ }
13
+ export { gitBlobSha };
@@ -0,0 +1,48 @@
1
+ import { Issue } from "./issues.js";
2
+ export interface FileRef {
3
+ path: string;
4
+ sha: string;
5
+ }
6
+ export interface FileChange {
7
+ path: string;
8
+ /** New file content; `null` deletes the file. */
9
+ content: Uint8Array | string | null;
10
+ }
11
+ /** Who did something to a file: a git author (GitHub adds `login` and `avatarUrl` when the author has an account). */
12
+ export interface FileActor {
13
+ name: string;
14
+ login?: string;
15
+ avatarUrl?: string;
16
+ }
17
+ /** One commit that touched a file. */
18
+ export interface FileEvent {
19
+ actor: FileActor;
20
+ /** ISO 8601. */
21
+ date: string;
22
+ /** First line of the commit message. */
23
+ message: string;
24
+ /** The commit on GitHub; absent for the local source. */
25
+ url?: string;
26
+ }
27
+ /** The git history of one file, for the Meta block. `updated` / `created` are `null` while no commit touched it. */
28
+ export interface FileHistory {
29
+ updated: FileEvent | null;
30
+ created: FileEvent | null;
31
+ commits: number;
32
+ }
33
+ /**
34
+ * Where content lives (the local dev API or GitHub). Validation and conflict problems (invalid entries, stale shas,
35
+ * an empty message) come back as `issues`; transport and auth failures (network, 401/403, 5xx) reject the promise.
36
+ * A missing file on `readFile` rejects with an `EditletError`.
37
+ */
38
+ export interface ContentSource {
39
+ readonly kind: 'local' | 'github';
40
+ listFiles(): Promise<FileRef[]>;
41
+ readFile(path: string): Promise<Uint8Array>;
42
+ /** Atomic: a non-empty `issues` means nothing was written. */
43
+ commit(changes: FileChange[], message: string): Promise<{
44
+ issues: Issue[];
45
+ }>;
46
+ }
47
+ /** In-memory `ContentSource` (test double for the local and github sources). */
48
+ export declare function createMemorySource(files: Record<string, string | Uint8Array>, schemaPath?: string): ContentSource;
@@ -0,0 +1,57 @@
1
+ import { decodeUtf8 } from "./entryFile.js";
2
+ import { EditletError } from "./issues.js";
3
+ import { parseSchemaText } from "./schema.js";
4
+ import { gitBlobSha } from "./sha.js";
5
+ import { validateCommit } from "./writes.js";
6
+ // core/source.ts
7
+ /** In-memory `ContentSource` (test double for the local and github sources). */
8
+ function createMemorySource(files, schemaPath = "cms/schema.json") {
9
+ const encoder = new TextEncoder();
10
+ const toBytes = (content) => typeof content === "string" ? encoder.encode(content) : content.slice();
11
+ const store = /* @__PURE__ */ new Map();
12
+ for (const [path, content] of Object.entries(files)) store.set(path, toBytes(content));
13
+ return {
14
+ kind: "local",
15
+ async listFiles() {
16
+ return (await Promise.all([...store].map(async ([path, bytes]) => ({
17
+ path,
18
+ sha: await gitBlobSha(bytes)
19
+ })))).toSorted((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
20
+ },
21
+ async readFile(path) {
22
+ const bytes = store.get(path);
23
+ if (!bytes) throw new EditletError([{
24
+ file: path,
25
+ path: "",
26
+ message: `File not found: ${path}`
27
+ }]);
28
+ return bytes.slice();
29
+ },
30
+ async commit(changes, message) {
31
+ const stored = store.get(schemaPath);
32
+ let schema = null;
33
+ if (stored) try {
34
+ schema = parseSchemaText(new TextDecoder().decode(stored), schemaPath);
35
+ } catch {
36
+ schema = null;
37
+ }
38
+ const read = (path) => {
39
+ const bytes = store.get(path);
40
+ const decoded = bytes && decodeUtf8(bytes, path);
41
+ return decoded && "text" in decoded ? decoded.text : void 0;
42
+ };
43
+ const issues = validateCommit({
44
+ schema,
45
+ schemaPath,
46
+ exists: (p) => store.has(p),
47
+ read,
48
+ list: () => store.keys()
49
+ }, changes, message);
50
+ if (issues.length > 0) return { issues };
51
+ for (const change of changes) if (change.content === null) store.delete(change.path);
52
+ else store.set(change.path, toBytes(change.content));
53
+ return { issues: [] };
54
+ }
55
+ };
56
+ }
57
+ export { createMemorySource };
@@ -0,0 +1,22 @@
1
+ import { Issue } from "./issues.js";
2
+ import { Collection, Schema } from "./schema.js";
3
+ import { z } from "zod";
4
+ export interface Entry {
5
+ collection: string;
6
+ slug: string;
7
+ data: Record<string, unknown>;
8
+ body: string;
9
+ }
10
+ export interface ValidateContext {
11
+ entryExists?: (ref: string) => boolean;
12
+ fileExists?: (path: string) => boolean;
13
+ }
14
+ export declare function buildDataSchema(collection: Collection): z.ZodObject;
15
+ export declare function validateEntry(schema: Schema, entry: Entry, ctx?: ValidateContext): Issue[];
16
+ /**
17
+ * Copy of `data` without absent values: keys whose value is `null` (any field) or `''` (string-valued fields), by
18
+ * the same rule validation uses to accept them on optional fields. For a valid entry the result matches the
19
+ * generated `<Collection>Data` type (`generateTypes`), so adapters and the admin read entry data through this.
20
+ */
21
+ export declare function normalizeData(collection: Collection, data: Record<string, unknown>): Record<string, unknown>;
22
+ export declare function initialData(collection: Collection, now?: Date): Record<string, unknown>;
@@ -0,0 +1,148 @@
1
+ import { fieldValueSchema, isAbsentValue } from "./fields.js";
2
+ import { entryFilePath, isHiddenContentPath, isImagePath, isValidSlug, resolveAssetPath } from "./paths.js";
3
+ import { BLOCK_KEY, markdownFieldKey } from "./schema.js";
4
+ import { blockFields, visitFields } from "./walk.js";
5
+ import { z } from "zod";
6
+ // core/validate.ts
7
+ function buildDataSchema(collection) {
8
+ const shape = {};
9
+ for (const [key, field] of Object.entries(collection.fields)) {
10
+ const s = fieldValueSchema(field);
11
+ if (s) shape[key] = s;
12
+ }
13
+ shape.draft = z.boolean({ error: "Expected true or false" }).optional();
14
+ return z.strictObject(shape);
15
+ }
16
+ function toIssues(error, file) {
17
+ const out = [];
18
+ for (const issue of error.issues) {
19
+ const path = issue.path.map(String);
20
+ if (issue.code === "unrecognized_keys") {
21
+ for (const key of issue.keys) out.push({
22
+ file,
23
+ path: [...path, key].join("."),
24
+ message: "Unknown field"
25
+ });
26
+ continue;
27
+ }
28
+ out.push({
29
+ file,
30
+ path: path.join("."),
31
+ message: issue.message
32
+ });
33
+ }
34
+ return out;
35
+ }
36
+ function validateEntry(schema, entry, ctx = {}) {
37
+ if (!Object.hasOwn(schema.collections, entry.collection)) return [{
38
+ path: "",
39
+ message: `Unknown collection "${entry.collection}"`
40
+ }];
41
+ const collection = schema.collections[entry.collection];
42
+ const file = entryFilePath(schema, entry.collection, entry.slug);
43
+ if (collection.singleton ? entry.slug !== "index" : !isValidSlug(entry.slug)) return [{
44
+ file,
45
+ path: "",
46
+ message: collection.singleton ? "Slug of a singleton must be \"index\"" : `Invalid slug "${entry.slug}": use lowercase letters, digits and single hyphens`
47
+ }];
48
+ if (typeof entry.data !== "object" || entry.data === null || Array.isArray(entry.data)) return [{
49
+ file,
50
+ path: "",
51
+ message: "Entry data must be an object"
52
+ }];
53
+ const parsed = buildDataSchema(collection).safeParse(entry.data);
54
+ const issues = parsed.success ? [] : toIssues(parsed.error, file);
55
+ const mdKey = markdownFieldKey(collection);
56
+ if (mdKey === void 0) {
57
+ if (entry.body.trim() !== "") issues.push({
58
+ file,
59
+ path: "",
60
+ message: "This collection has no markdown field, but the entry has body content"
61
+ });
62
+ } else if (collection.fields[mdKey].required && entry.body.trim() === "") issues.push({
63
+ file,
64
+ path: mdKey,
65
+ message: "Required"
66
+ });
67
+ const shapeIssues = [...issues];
68
+ const bad = (key) => shapeIssues.some((i) => i.path === key || i.path.startsWith(`${key}.`) || key.startsWith(`${i.path}.`));
69
+ visitFields(collection.fields, entry.data, (field, value, at) => {
70
+ const key = at.join(".");
71
+ if (bad(key)) return;
72
+ if (field.type === "image" && value !== null && value !== void 0) {
73
+ const src = value.src;
74
+ const resolved = resolveAssetPath(schema, file, src);
75
+ if (resolved === null) issues.push({
76
+ file,
77
+ path: `${key}.src`,
78
+ message: "Image path points outside the content directory"
79
+ });
80
+ else if (!isImagePath(resolved)) issues.push({
81
+ file,
82
+ path: `${key}.src`,
83
+ message: "Image path must end in an image extension"
84
+ });
85
+ else if (isHiddenContentPath(schema, resolved)) issues.push({
86
+ file,
87
+ path: `${key}.src`,
88
+ message: "Image path must not be hidden (a segment starts with \".\")"
89
+ });
90
+ else if (ctx.fileExists?.(resolved) === false) issues.push({
91
+ file,
92
+ path: `${key}.src`,
93
+ message: `Image file not found: ${resolved}`
94
+ });
95
+ } else if (field.type === "reference" && !isAbsentValue(field, value)) (Array.isArray(value) ? value : [value]).forEach((ref, i) => {
96
+ if (ctx.entryExists?.(ref) === false) issues.push({
97
+ file,
98
+ path: Array.isArray(value) ? `${key}.${i}` : key,
99
+ message: `Referenced entry not found: ${ref}`
100
+ });
101
+ });
102
+ });
103
+ return issues;
104
+ }
105
+ /**
106
+ * Copy of `data` without absent values: keys whose value is `null` (any field) or `''` (string-valued fields), by
107
+ * the same rule validation uses to accept them on optional fields. For a valid entry the result matches the
108
+ * generated `<Collection>Data` type (`generateTypes`), so adapters and the admin read entry data through this.
109
+ */
110
+ function normalizeData(collection, data) {
111
+ return normalizeFields(collection.fields, data);
112
+ }
113
+ const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
114
+ /** `normalizeData` for one level of fields: absent values go, `object` and `blocks` values are normalized inside. */
115
+ function normalizeFields(fields, data) {
116
+ const out = {};
117
+ for (const [key, value] of Object.entries(data)) {
118
+ const field = Object.hasOwn(fields, key) ? fields[key] : void 0;
119
+ if (value === null || field !== void 0 && isAbsentValue(field, value)) continue;
120
+ out[key] = field === void 0 ? value : normalizeValue(field, value);
121
+ }
122
+ return out;
123
+ }
124
+ function normalizeValue(field, value) {
125
+ if (field.type === "object") {
126
+ const one = (v) => isPlainObject(v) ? normalizeFields(field.fields, v) : v;
127
+ return field.list && Array.isArray(value) ? value.map(one) : one(value);
128
+ }
129
+ if (field.type === "blocks" && Array.isArray(value)) return value.map((item) => {
130
+ const fields = blockFields(field, item);
131
+ if (!fields) return item;
132
+ const { [BLOCK_KEY]: kind, ...rest } = item;
133
+ return {
134
+ [BLOCK_KEY]: kind,
135
+ ...normalizeFields(fields, rest)
136
+ };
137
+ });
138
+ return value;
139
+ }
140
+ function initialData(collection, now = /* @__PURE__ */ new Date()) {
141
+ const data = {};
142
+ for (const [key, field] of Object.entries(collection.fields)) if (field.type === "datetime") {
143
+ if (field.defaultNow) data[key] = field.dateOnly ? now.toISOString().slice(0, 10) : now.toISOString();
144
+ } else if ("default" in field && field.default !== void 0) data[key] = structuredClone(field.default);
145
+ data.draft = true;
146
+ return data;
147
+ }
148
+ export { buildDataSchema, initialData, normalizeData, validateEntry };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Walking entry data together with its fields, into `object` fields, their lists and `blocks` items. Leaf values (every
3
+ * other field type) are what callers see; containers are handled here. Data that does not match the schema (a list
4
+ * that is not an array, an item that is not an object, an unknown block kind) is skipped, never thrown on.
5
+ */
6
+ import { Field } from "./schema.js";
7
+ export type FieldPath = (string | number)[];
8
+ /** The fields of one `blocks` item (by its `block` key), or `undefined` for an unknown kind. */
9
+ export declare function blockFields(field: Extract<Field, {
10
+ type: 'blocks';
11
+ }>, item: unknown): Record<string, Field> | undefined;
12
+ /**
13
+ * Calls `visit` for every leaf value present in `data` (keys of `fields` that `data` has), depth first in field order:
14
+ * `path` is the dot path parts from the entry's data (`['content', 2, 'image']`).
15
+ */
16
+ export declare function visitFields(fields: Record<string, Field>, data: Record<string, unknown>, visit: (field: Field, value: unknown, path: FieldPath) => void, at?: FieldPath): void;
17
+ /**
18
+ * A copy of `data` with every leaf value replaced by `map(field, value, path)`; `undefined` drops the key. Containers
19
+ * are copied (objects, lists, block items keep their `block` key); keys outside `fields` are kept as they are.
20
+ */
21
+ export declare function mapFields(fields: Record<string, Field>, data: Record<string, unknown>, map: (field: Field, value: unknown, path: FieldPath) => unknown, at?: FieldPath): Record<string, unknown>;
22
+ /** Every field, nested ones too, with its path in the schema's field tree (`['content', 'hero', 'title']`). */
23
+ export declare function allFields(fields: Record<string, Field>, at?: string[]): [string[], Field][];