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,558 @@
1
+ import { toBase64 } from "./base64.js";
2
+ import { openGitHubCache } from "./cache.js";
3
+ import { GitHubError, createGitHubClient } from "./client.js";
4
+ import { makeRepoOps } from "./repo.js";
5
+ import { decodeUtf8 } from "../core/entryFile.js";
6
+ import { resolveGitStyle } from "../core/gitStyle.js";
7
+ import { EditletError } from "../core/issues.js";
8
+ import { isHiddenContentPath } from "../core/paths.js";
9
+ import { parseSchemaText } from "../core/schema.js";
10
+ import { gitBlobSha } from "../core/sha.js";
11
+ import { validateCommit } from "../core/writes.js";
12
+ // github/source.ts
13
+ const BLOB_BATCH = 50;
14
+ const RAW_ACCEPT = "application/vnd.github.raw+json";
15
+ const SHA_RE = /^[0-9a-f]{40}$/;
16
+ const SYMLINK_MODE = "120000";
17
+ const encoder = new TextEncoder();
18
+ const byPath = (a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
19
+ function notFoundIssues(paths) {
20
+ return new EditletError(paths.map((p) => ({
21
+ file: p,
22
+ path: "",
23
+ message: `File not found: ${p}`
24
+ })));
25
+ }
26
+ function blobsQuery(shas) {
27
+ return `query Blobs($owner: String!, $name: String!) {\n repository(owner: $owner, name: $name) {\n ${shas.map((sha, i) => `b${i}: object(oid: "${sha}") { ... on Blob { text isBinary isTruncated } }`).join("\n ")}\n }\n}`;
28
+ }
29
+ /**
30
+ * Reads blobs by sha: cache first, then batched GraphQL text (accepted only when its git sha matches), then raw REST
31
+ * for binary, truncated or mismatching blobs. Every fetched blob is sha-verified and cached.
32
+ */
33
+ async function readBlobs(ctx, shas) {
34
+ const unique = [...new Set(shas)];
35
+ for (const sha of unique) if (!SHA_RE.test(sha)) throw new GitHubError("not_found", `Blob not found: ${sha}`);
36
+ const out = await ctx.cache.getBlobs(unique);
37
+ const missing = unique.filter((sha) => !out.has(sha));
38
+ if (missing.length === 0) return out;
39
+ const fetched = [];
40
+ const raw = [];
41
+ const chunks = [];
42
+ for (let i = 0; i < missing.length; i += BLOB_BATCH) chunks.push(missing.slice(i, i + BLOB_BATCH));
43
+ await Promise.all(chunks.map(async (chunk) => {
44
+ const data = await ctx.client.graphql(blobsQuery(chunk), {
45
+ owner: ctx.owner,
46
+ name: ctx.repo
47
+ });
48
+ await Promise.all(chunk.map(async (sha, i) => {
49
+ const node = data.repository?.[`b${i}`];
50
+ if (node && !node.isBinary && !node.isTruncated && typeof node.text === "string") {
51
+ const bytes = encoder.encode(node.text);
52
+ if (await gitBlobSha(bytes) === sha) {
53
+ fetched.push({
54
+ sha,
55
+ bytes
56
+ });
57
+ return;
58
+ }
59
+ }
60
+ raw.push(sha);
61
+ }));
62
+ }));
63
+ await Promise.all(raw.map(async (sha) => {
64
+ const body = await ctx.client.rest("GET", `/repos/${ctx.owner}/${ctx.repo}/git/blobs/${sha}`, {
65
+ raw: true,
66
+ accept: RAW_ACCEPT
67
+ });
68
+ const bytes = new Uint8Array(body);
69
+ if (await gitBlobSha(bytes) !== sha) throw new GitHubError("http_error", "Blob sha mismatch");
70
+ fetched.push({
71
+ sha,
72
+ bytes
73
+ });
74
+ }));
75
+ await ctx.cache.putBlobs(fetched);
76
+ for (const { sha, bytes } of fetched) out.set(sha, bytes);
77
+ return out;
78
+ }
79
+ const SNAPSHOT_QUERY = `query Snapshot($owner: String!, $name: String!, $ref: String!, $schemaPath: String!) {
80
+ repository(owner: $owner, name: $name) {
81
+ ref(qualifiedName: $ref) {
82
+ target {
83
+ oid
84
+ ... on Commit { schema: file(path: $schemaPath) { oid } }
85
+ }
86
+ }
87
+ }
88
+ }`;
89
+ const DIR_QUERY = `query Dir($owner: String!, $name: String!, $oid: GitObjectID!, $path: String!) {
90
+ repository(owner: $owner, name: $name) {
91
+ object(oid: $oid) {
92
+ ... on Commit { file(path: $path) { oid type } }
93
+ }
94
+ }
95
+ }`;
96
+ /** GraphQL wrapper that turns "repository not found" into `GitHubError('not_found')`. */
97
+ async function repoQuery(ctx, query, variables) {
98
+ let data;
99
+ try {
100
+ data = await ctx.client.graphql(query, {
101
+ owner: ctx.owner,
102
+ name: ctx.repo,
103
+ ...variables
104
+ });
105
+ } catch (error) {
106
+ if (error instanceof GitHubError && error.code === "graphql_error" && error.graphqlErrors?.length && error.graphqlErrors.every((e) => e.type === "NOT_FOUND")) throw new GitHubError("not_found", `Repository not found: ${ctx.owner}/${ctx.repo}`);
107
+ throw error;
108
+ }
109
+ if (!data.repository) throw new GitHubError("not_found", `Repository not found: ${ctx.owner}/${ctx.repo}`);
110
+ return data.repository;
111
+ }
112
+ /** `Commit.file(path:)` at a commit oid: the tree entry's oid and type, or null when the path does not exist. */
113
+ async function entryAt(ctx, oid, path) {
114
+ const repo = await repoQuery(ctx, DIR_QUERY, {
115
+ oid,
116
+ path
117
+ });
118
+ if (!repo.object) throw new GitHubError("not_found", `Commit not found: ${oid}`);
119
+ return repo.object.file ?? null;
120
+ }
121
+ function addBlobs(files, dir, entries) {
122
+ const subtrees = [];
123
+ for (const entry of entries) if (entry.type === "tree") subtrees.push(entry);
124
+ else if (entry.type === "blob" && entry.mode !== SYMLINK_MODE) files.set(`${dir}/${entry.path}`, entry.sha);
125
+ return subtrees;
126
+ }
127
+ function getTree(ctx, sha, recursive) {
128
+ return ctx.client.rest("GET", `/repos/${ctx.owner}/${ctx.repo}/git/trees/${sha}`, { query: recursive ? { recursive: 1 } : void 0 });
129
+ }
130
+ /** Non-recursive walk, one request per directory (used when a recursive listing comes back truncated). */
131
+ async function walkTree(ctx, sha, dir, files) {
132
+ const res = await getTree(ctx, sha, false);
133
+ if (res.truncated) throw new GitHubError("http_error", `Tree listing truncated: ${dir}`);
134
+ const subtrees = addBlobs(files, dir, res.tree);
135
+ await Promise.all(subtrees.map((t) => walkTree(ctx, t.sha, `${dir}/${t.path}`, files)));
136
+ }
137
+ async function readTreeInto(ctx, sha, dir, files) {
138
+ const res = await getTree(ctx, sha, true);
139
+ if (!res.truncated) {
140
+ addBlobs(files, dir, res.tree);
141
+ return;
142
+ }
143
+ const walked = /* @__PURE__ */ new Map();
144
+ await walkTree(ctx, sha, dir, walked);
145
+ for (const [path, blob] of walked) files.set(path, blob);
146
+ }
147
+ /** Builds the snapshot of commit `headOid` given its schema blob sha (null = no schema file). */
148
+ async function buildSnapshot(ctx, headOid, schemaSha) {
149
+ const files = /* @__PURE__ */ new Map();
150
+ const snapshot = {
151
+ headOid,
152
+ schemaPath: ctx.schemaPath,
153
+ schemaSha,
154
+ schema: null,
155
+ contentDir: null,
156
+ files
157
+ };
158
+ if (schemaSha === null) return snapshot;
159
+ files.set(ctx.schemaPath, schemaSha);
160
+ const bytes = (await readBlobs(ctx, [schemaSha])).get(schemaSha);
161
+ const decoded = decodeUtf8(bytes, ctx.schemaPath);
162
+ if (!("text" in decoded)) return snapshot;
163
+ try {
164
+ snapshot.schema = parseSchemaText(decoded.text, ctx.schemaPath);
165
+ } catch (error) {
166
+ if (error instanceof EditletError) return snapshot;
167
+ throw error;
168
+ }
169
+ const contentDir = snapshot.schema.contentDir;
170
+ snapshot.contentDir = contentDir;
171
+ const dir = await entryAt(ctx, headOid, contentDir);
172
+ if (dir?.type === "tree") await readTreeInto(ctx, dir.oid, contentDir, files);
173
+ files.set(ctx.schemaPath, schemaSha);
174
+ return snapshot;
175
+ }
176
+ /** Snapshot of the head of `branch` (`refs/heads/<branch>`). */
177
+ async function loadSnapshot(ctx, branch) {
178
+ const repo = await repoQuery(ctx, SNAPSHOT_QUERY, {
179
+ ref: `refs/heads/${branch}`,
180
+ schemaPath: ctx.schemaPath
181
+ });
182
+ if (!repo.ref) throw new GitHubError("not_found", `Branch not found: ${branch}`);
183
+ return buildSnapshot(ctx, repo.ref.target.oid, repo.ref.target.schema?.oid ?? null);
184
+ }
185
+ /** Snapshot at a commit oid (e.g. a merge base). */
186
+ async function loadSnapshotAt(ctx, oid) {
187
+ const schema = await entryAt(ctx, oid, ctx.schemaPath);
188
+ return buildSnapshot(ctx, oid, schema?.type === "blob" ? schema.oid : null);
189
+ }
190
+ const MAX_COMMIT_BYTES = 20971520;
191
+ const MAX_COMMIT_ATTEMPTS = 3;
192
+ const HISTORY_QUERY = `query History($owner: String!, $name: String!, $ref: String!, $path: String!) {
193
+ repository(owner: $owner, name: $name) {
194
+ ref(qualifiedName: $ref) {
195
+ target { ... on Commit { history(first: 1, path: $path) { totalCount nodes {
196
+ url messageHeadline committedDate author { name user { login avatarUrl } }
197
+ } } } }
198
+ }
199
+ }
200
+ }`;
201
+ function nodeEvent(n) {
202
+ const user = n.author?.user;
203
+ return {
204
+ actor: {
205
+ name: n.author?.name ?? user?.login ?? "Unknown",
206
+ login: user?.login,
207
+ avatarUrl: user?.avatarUrl
208
+ },
209
+ date: n.committedDate,
210
+ message: n.messageHeadline,
211
+ url: n.url
212
+ };
213
+ }
214
+ function restEvent(c) {
215
+ return {
216
+ actor: {
217
+ name: c.commit.author?.name ?? c.author?.login ?? "Unknown",
218
+ login: c.author?.login,
219
+ avatarUrl: c.author?.avatar_url
220
+ },
221
+ date: c.commit.author?.date ?? "",
222
+ message: c.commit.message.split("\n")[0] ?? "",
223
+ url: c.html_url
224
+ };
225
+ }
226
+ const CONFLICT_MESSAGE = "Changed on GitHub since it was read; reload and review";
227
+ const COMMIT_MUTATION = `mutation Commit($input: CreateCommitOnBranchInput!) {
228
+ createCommitOnBranch(input: $input) {
229
+ commit { oid url }
230
+ }
231
+ }`;
232
+ async function prepareChange(change, served, base) {
233
+ const { path, content } = change;
234
+ const bytes = content === null ? null : typeof content === "string" ? encoder.encode(content) : new Uint8Array(content);
235
+ return {
236
+ path,
237
+ bytes,
238
+ expected: change.sha !== void 0 ? change.sha : served.get(path) ?? base.files.get(path) ?? null,
239
+ next: bytes === null ? null : await gitBlobSha(bytes)
240
+ };
241
+ }
242
+ /** First line → `headline`; the rest (trimmed) → `body` when non-empty. */
243
+ function commitMessage(message) {
244
+ const [first = "", ...rest] = message.trim().split(/\r?\n/);
245
+ const body = rest.join("\n").trim();
246
+ return body === "" ? { headline: first.trim() } : {
247
+ headline: first.trim(),
248
+ body
249
+ };
250
+ }
251
+ const isStale = (error) => error instanceof GitHubError && (error.graphqlErrors ?? []).some((e) => e.type === "STALE_DATA");
252
+ /** The schema a batch writes, when it parses (else `null`: no schema change, or validation rejects it). */
253
+ function batchSchema(schemaPath, prepared) {
254
+ const bytes = prepared.find((c) => c.path === schemaPath)?.bytes;
255
+ if (!bytes) return null;
256
+ const decoded = decodeUtf8(bytes, schemaPath);
257
+ if (!("text" in decoded)) return null;
258
+ try {
259
+ return parseSchemaText(decoded.text, schemaPath);
260
+ } catch (error) {
261
+ if (error instanceof EditletError) return null;
262
+ throw error;
263
+ }
264
+ }
265
+ /**
266
+ * `snap` plus every blob under the batch schema's `contentDir` at `snap.headOid` when the batch moves `contentDir`
267
+ * (the snapshot only tracks the old directory), so the conflict check, `exists`, `list` and `read` see the files
268
+ * that are already there and an addition never silently replaces one.
269
+ */
270
+ async function withMovedContentDir(ctx, snap, next) {
271
+ if (next === null || next.contentDir === snap.contentDir) return snap;
272
+ const files = new Map(snap.files);
273
+ const dir = await entryAt(ctx, snap.headOid, next.contentDir);
274
+ if (dir?.type === "tree") await readTreeInto(ctx, dir.oid, next.contentDir, files);
275
+ return {
276
+ ...snap,
277
+ files
278
+ };
279
+ }
280
+ /** UTF-8 text of every non-hidden `.md` under the `contentDir` of any of `schemas` (for the wide re-check). */
281
+ async function readEntryTexts(ctx, snap, schemas) {
282
+ const texts = /* @__PURE__ */ new Map();
283
+ const paths = [...snap.files.keys()].filter((p) => p.endsWith(".md") && schemas.some((s) => p.startsWith(`${s.contentDir}/`) && !isHiddenContentPath(s, p)));
284
+ const blobs = await readBlobs(ctx, paths.map((p) => snap.files.get(p)));
285
+ for (const p of paths) {
286
+ const decoded = decodeUtf8(blobs.get(snap.files.get(p)), p);
287
+ if ("text" in decoded) texts.set(p, decoded.text);
288
+ }
289
+ return texts;
290
+ }
291
+ /** `validateCommit` against `snap`, plus the GitHub-only rules (deleting a missing file, the size cap). */
292
+ async function validateOn(ctx, snap, todo, message, next) {
293
+ const texts = todo.some((c) => c.bytes === null || c.path === snap.schemaPath) ? await readEntryTexts(ctx, snap, [snap.schema, next].filter((x) => x !== null)) : /* @__PURE__ */ new Map();
294
+ const issues = validateCommit({
295
+ schema: snap.schema,
296
+ schemaPath: snap.schemaPath,
297
+ exists: (p) => snap.files.has(p),
298
+ read: (p) => texts.get(p),
299
+ list: () => snap.files.keys()
300
+ }, todo.map((c) => ({
301
+ path: c.path,
302
+ content: c.bytes
303
+ })), message);
304
+ for (const c of todo) if (c.bytes === null && !snap.files.has(c.path)) issues.push({
305
+ file: c.path,
306
+ path: "",
307
+ message: "File not found"
308
+ });
309
+ if (todo.reduce((sum, c) => sum + (c.bytes?.byteLength ?? 0), 0) > MAX_COMMIT_BYTES) issues.push({
310
+ path: "",
311
+ message: "Changes are too large for one commit (max 20 MB)"
312
+ });
313
+ return issues;
314
+ }
315
+ /** `snap` with `todo` applied at `headOid`; `null` when `contentDir` moved (the file set must be reloaded). */
316
+ function applyToSnapshot(snap, todo, headOid) {
317
+ const files = new Map(snap.files);
318
+ for (const c of todo) if (c.next === null) files.delete(c.path);
319
+ else files.set(c.path, c.next);
320
+ const next = {
321
+ ...snap,
322
+ headOid,
323
+ files
324
+ };
325
+ const schemaChange = todo.find((c) => c.path === snap.schemaPath);
326
+ if (schemaChange?.bytes) {
327
+ const decoded = decodeUtf8(schemaChange.bytes, snap.schemaPath);
328
+ next.schema = "text" in decoded ? parseSchemaText(decoded.text, snap.schemaPath) : null;
329
+ next.schemaSha = schemaChange.next;
330
+ next.contentDir = next.schema?.contentDir ?? null;
331
+ if (next.contentDir !== snap.contentDir) return null;
332
+ }
333
+ return next;
334
+ }
335
+ function createGitHubSource(options) {
336
+ if (options.token === void 0 === (options.client === void 0)) throw new TypeError("createGitHubSource: pass exactly one of `token` or `client`");
337
+ return makeSource({
338
+ client: options.client ?? createGitHubClient({ token: options.token }),
339
+ cache: options.cache ?? openGitHubCache(),
340
+ owner: options.owner,
341
+ repo: options.repo,
342
+ schemaPath: options.schemaPath ?? "cms/schema.json",
343
+ baseBranch: options.baseBranch,
344
+ branchPrefix: options.branchPrefix
345
+ }, options.branch);
346
+ }
347
+ function makeSource(ctx, branch) {
348
+ let snapshot = null;
349
+ let loading = null;
350
+ let generation = 0;
351
+ /** path → blob sha of what this source last handed out (read) or wrote (commit): the default expected sha. */
352
+ const served = /* @__PURE__ */ new Map();
353
+ /** Starts a fresh load; only the latest started load updates `snapshot`. */
354
+ function reload() {
355
+ const gen = ++generation;
356
+ const promise = loadSnapshot(ctx, branch).then((s) => {
357
+ if (gen === generation) {
358
+ snapshot = s;
359
+ loading = null;
360
+ }
361
+ return s;
362
+ }, (error) => {
363
+ if (gen === generation) loading = null;
364
+ throw error;
365
+ });
366
+ loading = promise;
367
+ return promise;
368
+ }
369
+ /** The current snapshot, loading it when there is none. */
370
+ function current() {
371
+ if (snapshot) return Promise.resolve(snapshot);
372
+ return loading ?? reload();
373
+ }
374
+ async function readFiles(paths) {
375
+ const snap = await current();
376
+ const missing = paths.filter((p) => !snap.files.has(p));
377
+ if (missing.length > 0) throw notFoundIssues([...new Set(missing)]);
378
+ const blobs = await readBlobs(ctx, paths.map((p) => snap.files.get(p)));
379
+ const out = /* @__PURE__ */ new Map();
380
+ for (const p of paths) {
381
+ const sha = snap.files.get(p);
382
+ out.set(p, blobs.get(sha).slice());
383
+ served.set(p, sha);
384
+ }
385
+ return out;
386
+ }
387
+ async function baseBranch() {
388
+ if (ctx.baseBranch !== void 0) return ctx.baseBranch;
389
+ const base = (await current()).schema?.git.baseBranch;
390
+ if (base === void 0) throw new GitHubError("not_found", "Base branch unknown: schema missing or invalid");
391
+ return base;
392
+ }
393
+ async function branchPrefix() {
394
+ if (ctx.branchPrefix !== void 0) return ctx.branchPrefix;
395
+ return resolveGitStyle((await current()).schema?.git).branchPrefix;
396
+ }
397
+ const withBranch = (next) => makeSource(ctx, next);
398
+ return {
399
+ kind: "github",
400
+ owner: ctx.owner,
401
+ repo: ctx.repo,
402
+ branch,
403
+ pending: ctx.cache.pending(`${ctx.owner}/${ctx.repo}#${branch}`),
404
+ async listFiles() {
405
+ const snap = await reload();
406
+ const refs = [];
407
+ for (const [path, sha] of snap.files) if (path === snap.schemaPath || snap.schema && !isHiddenContentPath(snap.schema, path)) refs.push({
408
+ path,
409
+ sha
410
+ });
411
+ return refs.toSorted(byPath);
412
+ },
413
+ async readFile(path) {
414
+ return (await readFiles([path])).get(path);
415
+ },
416
+ readFiles,
417
+ async readBlob(sha) {
418
+ return (await readBlobs(ctx, [sha])).get(sha).slice();
419
+ },
420
+ async head() {
421
+ return (await current()).headOid;
422
+ },
423
+ async commit(changes, message) {
424
+ const base = await current();
425
+ const prefix = ctx.branchPrefix ?? resolveGitStyle(base.schema?.git).branchPrefix;
426
+ const refused = { issues: [{
427
+ path: "",
428
+ message: `Commits must go to a branch named ${prefix}*, not "${branch}"`
429
+ }] };
430
+ if (!branch.startsWith(prefix)) return refused;
431
+ if (branch === (ctx.baseBranch ?? base.schema?.git.baseBranch)) return refused;
432
+ const seen = /* @__PURE__ */ new Set();
433
+ const duplicates = /* @__PURE__ */ new Set();
434
+ for (const { path } of changes) (seen.has(path) ? duplicates : seen).add(path);
435
+ if (duplicates.size > 0) return { issues: [...duplicates].map((file) => ({
436
+ file,
437
+ path: "",
438
+ message: "Duplicate path in changes"
439
+ })) };
440
+ const prepared = await Promise.all(changes.map((c) => prepareChange(c, served, base)));
441
+ /** The editor's content is now what GitHub has: later commits are based on it. */
442
+ const markServed = () => {
443
+ for (const c of prepared) if (c.next === null) served.delete(c.path);
444
+ else served.set(c.path, c.next);
445
+ };
446
+ const nextSchema = batchSchema(base.schemaPath, prepared);
447
+ let snap = base;
448
+ for (let attempt = 1;; attempt++) {
449
+ const view = await withMovedContentDir(ctx, snap, nextSchema);
450
+ const conflicts = [];
451
+ const todo = [];
452
+ for (const c of prepared) {
453
+ const now = view.files.get(c.path) ?? null;
454
+ if (c.next !== null && now === c.next) continue;
455
+ if (now === c.expected) todo.push(c);
456
+ else if (now !== c.next) conflicts.push({
457
+ file: c.path,
458
+ path: "",
459
+ message: CONFLICT_MESSAGE
460
+ });
461
+ }
462
+ if (conflicts.length > 0) return { issues: conflicts };
463
+ if (todo.length === 0) {
464
+ markServed();
465
+ return { issues: [] };
466
+ }
467
+ const issues = await validateOn(ctx, view, todo, message, nextSchema);
468
+ if (issues.length > 0) return { issues };
469
+ const input = {
470
+ branch: {
471
+ repositoryNameWithOwner: `${ctx.owner}/${ctx.repo}`,
472
+ branchName: branch
473
+ },
474
+ expectedHeadOid: snap.headOid,
475
+ message: commitMessage(message),
476
+ fileChanges: {
477
+ additions: todo.flatMap((c) => c.bytes === null ? [] : [{
478
+ path: c.path,
479
+ contents: toBase64(c.bytes)
480
+ }]),
481
+ deletions: todo.flatMap((c) => c.bytes === null ? [{ path: c.path }] : [])
482
+ }
483
+ };
484
+ let commit;
485
+ try {
486
+ commit = (await ctx.client.graphql(COMMIT_MUTATION, { input })).createCommitOnBranch.commit;
487
+ } catch (error) {
488
+ if (!isStale(error)) throw error;
489
+ if (attempt >= MAX_COMMIT_ATTEMPTS) return { issues: [{
490
+ path: "",
491
+ message: "Branch keeps changing; try again"
492
+ }] };
493
+ snap = await reload();
494
+ continue;
495
+ }
496
+ ++generation;
497
+ loading = null;
498
+ snapshot = applyToSnapshot(snap, todo, commit.oid);
499
+ const blobs = todo.flatMap((c) => c.bytes === null ? [] : [{
500
+ sha: c.next,
501
+ bytes: c.bytes
502
+ }]);
503
+ await ctx.cache.putBlobs(blobs).catch(() => void 0);
504
+ markServed();
505
+ return {
506
+ issues: [],
507
+ commit: {
508
+ oid: commit.oid,
509
+ url: commit.url
510
+ }
511
+ };
512
+ }
513
+ },
514
+ async history(path) {
515
+ const history = (await repoQuery(ctx, HISTORY_QUERY, {
516
+ ref: `refs/heads/${branch}`,
517
+ path
518
+ })).ref?.target?.history;
519
+ const [latest] = history?.nodes ?? [];
520
+ if (!history || !latest) return {
521
+ updated: null,
522
+ created: null,
523
+ commits: 0
524
+ };
525
+ const total = history.totalCount;
526
+ let created = nodeEvent(latest);
527
+ if (total > 1) {
528
+ const query = new URLSearchParams({
529
+ sha: branch,
530
+ path,
531
+ per_page: "1",
532
+ page: String(total)
533
+ });
534
+ const [oldest] = await ctx.client.rest("GET", `/repos/${ctx.owner}/${ctx.repo}/commits?${query}`);
535
+ if (oldest) created = restEvent(oldest);
536
+ }
537
+ return {
538
+ updated: nodeEvent(latest),
539
+ created,
540
+ commits: total
541
+ };
542
+ },
543
+ baseBranch,
544
+ branchPrefix,
545
+ withBranch,
546
+ ...makeRepoOps({
547
+ ctx,
548
+ branch,
549
+ baseBranch,
550
+ branchPrefix,
551
+ withBranch,
552
+ repoQuery: (query, variables) => repoQuery(ctx, query, variables),
553
+ loadSnapshot: (b) => loadSnapshot(ctx, b),
554
+ loadSnapshotAt: (oid) => loadSnapshotAt(ctx, oid)
555
+ })
556
+ };
557
+ }
558
+ export { buildSnapshot, createGitHubSource, loadSnapshot, loadSnapshotAt, readBlobs };
@@ -0,0 +1,27 @@
1
+ import { AdminLayout, AdminNavigateMessage, AdminToSiteMessage, CloseMessage, CloseRequestMessage, DEFAULT_ADMIN_URL, EDITLET_PARAM, EDITLET_PROTOCOL_VERSION, EDITLET_SOURCE, ENTRY_ATTR, FIELD_ATTR, HIGHLIGHT_ATTR, HighlightMessage, InitMessage, LayoutMessage, MessageBody, PREVIEW_CHANNEL, PREVIEW_DB, PREVIEW_FLAG_KEY, PREVIEW_KEY, PREVIEW_ROUTE, PREVIEW_SCRIPT, PREVIEW_STORE, PreviewChannelMessage, PreviewSnapshot, PreviewValue, ReadyMessage, RefreshMessage, SiteNavigateMessage, SiteToAdminMessage, WINDOW_SCRIPT, adminMessage, fieldMark, isAdminToSiteMessage, isPreviewChannelMessage, isPreviewSnapshot, isSiteToAdminMessage, readEditletRoute, siteMessage, withEditletRoute } from "./protocol.js";
2
+ export interface EditletLoaderOptions {
3
+ /** Admin page URL, absolute or relative to the site. Default DEFAULT_ADMIN_URL ('/editlet/'). */
4
+ adminUrl?: string;
5
+ /**
6
+ * Query parameter of the site's pages that opens the editor. Default EDITLET_PARAM ('editlet'). The admin's own URL
7
+ * always uses `editlet`.
8
+ */
9
+ param?: string;
10
+ /** Called when the admin reports saved content. Default: location.reload(). */
11
+ onRefresh?: () => void;
12
+ /**
13
+ * Writes the parent URL. Default `history.replaceState(history.state, '', url)`. Next.js App Router adapters
14
+ * pass `(url) => history.replaceState(null, '', url)` so the router syncs.
15
+ */
16
+ replaceUrl?: (url: string) => void;
17
+ }
18
+ export interface EditletLoader {
19
+ /** Re-read location: open, re-route or close the editor to match the query parameter. Idempotent. */
20
+ sync(): void;
21
+ /** Close the editor and remove the query parameter from the URL (replaceState). */
22
+ close(): void;
23
+ /** Close without touching the URL, remove listeners, allow a fresh mount. */
24
+ destroy(): void;
25
+ }
26
+ export declare function mountEditletLoader(options?: EditletLoaderOptions): EditletLoader;
27
+ export { AdminLayout, AdminNavigateMessage, AdminToSiteMessage, CloseMessage, CloseRequestMessage, DEFAULT_ADMIN_URL, EDITLET_PARAM, EDITLET_PROTOCOL_VERSION, EDITLET_SOURCE, ENTRY_ATTR, FIELD_ATTR, HIGHLIGHT_ATTR, HighlightMessage, InitMessage, LayoutMessage, MessageBody, PREVIEW_CHANNEL, PREVIEW_DB, PREVIEW_FLAG_KEY, PREVIEW_KEY, PREVIEW_ROUTE, PREVIEW_SCRIPT, PREVIEW_STORE, PreviewChannelMessage, PreviewSnapshot, PreviewValue, ReadyMessage, RefreshMessage, SiteNavigateMessage, SiteToAdminMessage, WINDOW_SCRIPT, adminMessage, fieldMark, isAdminToSiteMessage, isPreviewChannelMessage, isPreviewSnapshot, isSiteToAdminMessage, readEditletRoute, siteMessage, withEditletRoute };