@pirateandfox/pagestack 0.1.0-beta.8 → 0.1.0-beta.9
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/README.md +48 -2
- package/index.mjs +15 -1
- package/live.mjs +30 -0
- package/package.json +4 -2
- package/src/client/browse.ts +123 -0
- package/src/client/shell.css +23 -0
- package/src/core/pages.ts +1 -1
- package/src/core/storage-github.ts +37 -0
- package/src/core/storage-local.ts +9 -0
- package/src/core/storage.ts +10 -0
- package/src/routes/Nav.astro +1 -1
- package/src/routes/api/browse.ts +24 -0
- package/src/routes/edit-collection.astro +1 -1
- package/src/routes/edit-index.astro +1 -1
- package/src/routes/edit-item.astro +1 -1
- package/src/routes/edit-page.astro +1 -1
- package/src/routes/edit-site.astro +41 -0
- package/src/routes/preview-item.astro +1 -0
- package/src/routes/preview.astro +3 -1
- package/src/server/browse.ts +80 -0
- package/src/server/context.ts +4 -0
- package/src/server/live.ts +46 -0
- package/src/server/middleware.ts +19 -7
package/README.md
CHANGED
|
@@ -255,8 +255,9 @@ must run there: no `node:fs` reads of the project, no native modules (sharp, res
|
|
|
255
255
|
`content.config.ts` (its loaders only run in a build). `getCollection` works. The page's own scripts
|
|
256
256
|
are left out of the editor's frame.
|
|
257
257
|
|
|
258
|
-
In the block editor's preview the site's own scripts do run (tabs,
|
|
259
|
-
other origins are refused, so analytics, captchas and chat widgets
|
|
258
|
+
In the block editor's preview, Browse and live list pages, the site's own scripts do run (tabs,
|
|
259
|
+
accordions), but scripts from other origins are refused, so analytics, captchas and chat widgets
|
|
260
|
+
stay out of the editor.
|
|
260
261
|
`previewScripts: 'all'` lifts that for a site whose preview needs an outside script.
|
|
261
262
|
|
|
262
263
|
An image field stored as a bare URL can name its alt-text field, `{ type: 'image', asUrl: true,
|
|
@@ -265,6 +266,50 @@ altField: 'imageAlt' }`, and the picker fills it in.
|
|
|
265
266
|
Blocks can set `category` and `keywords` for the inserter. A `list` field is a repeatable group of
|
|
266
267
|
`fields`, with `itemLabel` naming the field that titles each row.
|
|
267
268
|
|
|
269
|
+
## Browsing the site
|
|
270
|
+
|
|
271
|
+
**Browse site** in the editor's top bar (`/edit/site`) shows the site as visitors see it, with a
|
|
272
|
+
slim bar on top. Click around as you would on the real site; **Edit this page** opens the editor
|
|
273
|
+
for whatever is showing, and **View on site** in the editor comes back to it. On a deployed editor,
|
|
274
|
+
opening a live page directly (below) lands in Browse too.
|
|
275
|
+
|
|
276
|
+
What each page shows:
|
|
277
|
+
|
|
278
|
+
- **Pages** and **collection items with a `previews` layout**: the latest saved version, through
|
|
279
|
+
their previews. A new item shows before the editor has been rebuilt.
|
|
280
|
+
- **List pages named in `liveRoutes`**: rendered on request from what has been saved (see below).
|
|
281
|
+
- **Anything else**: the copy built into this editor deployment. When something has been saved
|
|
282
|
+
since that build, the bar says so ("As of Nov 12, 4:28 PM. May not show changes saved since.").
|
|
283
|
+
|
|
284
|
+
### Live list pages (`liveRoutes`)
|
|
285
|
+
|
|
286
|
+
On a deployed editor, list pages (the home page, `/blog/`) are frozen when the editor is built, so a
|
|
287
|
+
new post wouldn't appear in them until the next deploy. Name them in `liveRoutes` and, in the
|
|
288
|
+
editor's build only, they render on request from storage instead:
|
|
289
|
+
|
|
290
|
+
```js
|
|
291
|
+
pagestack({ liveRoutes: ['/', '/blog'], /* … */ })
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
The page reads its collections through `liveEntries`, which gives the saved entries on the editor's
|
|
295
|
+
server and `null` everywhere else, so the public build is unchanged and stays fully static:
|
|
296
|
+
|
|
297
|
+
```ts
|
|
298
|
+
// src/lib/content.ts
|
|
299
|
+
import { getCollection } from 'astro:content';
|
|
300
|
+
import { liveEntries } from '@pirateandfox/pagestack/live';
|
|
301
|
+
import { postSchema } from './schemas'; // the same zod schema content.config.ts uses
|
|
302
|
+
|
|
303
|
+
export const posts = async () => (await liveEntries('posts', postSchema)) ?? (await getCollection('posts'));
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
The collection name is the editor's collection id. Pass the schema so dates and defaults come out as
|
|
307
|
+
they do at build time; an entry the schema rejects is left out of the list. These pages need to be
|
|
308
|
+
able to render where the editor runs (on Workers: no `node:fs`, and nothing from
|
|
309
|
+
`content.config.ts`, whose loaders only run at build time). On GitHub storage, entries are cached
|
|
310
|
+
until the branch moves, so a list costs one request to GitHub once the first one has warmed up.
|
|
311
|
+
These pages show unpublished work, so they need a signed-in editor.
|
|
312
|
+
|
|
268
313
|
## Security
|
|
269
314
|
|
|
270
315
|
Everything an editor sends is treated as untrusted. On save, every field is cleaned by its type,
|
|
@@ -367,6 +412,7 @@ editor response is `noindex` and `no-store`.
|
|
|
367
412
|
| `auth` | `passkey` | `passkey` \| `none-behind-proxy` \| `none` |
|
|
368
413
|
| `storage` | `local` in dev, `github` in build | |
|
|
369
414
|
| `github` | — | `{ repo, branch, live?, stagingUrl?, pullRequest? }`: see Staging and Go live |
|
|
415
|
+
| `liveRoutes` | `[]` | site paths rendered on request in the editor's build, from saved content (see Live list pages) |
|
|
370
416
|
| `previewScripts` | `'site'` | block-editor preview runs the site's own scripts only; `'all'` allows other origins too |
|
|
371
417
|
| `enabled` | `EDITOR=dev` (dev) or `EDITOR=1` | Off otherwise, so plain `astro dev` never writes content |
|
|
372
418
|
| `siteName`, `secretEnv` | `Site editor`, `EDITOR_SECRET` | |
|
package/index.mjs
CHANGED
|
@@ -81,12 +81,19 @@ export default function sectionEditor(userOptions) {
|
|
|
81
81
|
// integration hook to it (an integration added via updateConfig() doesn't get to call
|
|
82
82
|
// setAdapter() in time, so we proxy its hooks instead).
|
|
83
83
|
let adapter = null;
|
|
84
|
+
// Set in astro:config:setup when the editor is on: page files to render on request (liveRoutes).
|
|
85
|
+
let liveComponents = null;
|
|
84
86
|
const forward = (hook) => async (params) => { if (adapter?.hooks?.[hook]) await adapter.hooks[hook](params); };
|
|
85
87
|
const forwarded = Object.fromEntries(['astro:config:done', 'astro:server:setup', 'astro:server:start', 'astro:server:done', 'astro:build:start', 'astro:build:setup', 'astro:build:ssr', 'astro:build:generated', 'astro:build:done'].map((h) => [h, forward(h)]));
|
|
86
88
|
return {
|
|
87
89
|
name: 'pagestack',
|
|
88
90
|
hooks: {
|
|
89
91
|
...forwarded,
|
|
92
|
+
// List pages named in `liveRoutes` render on request on the editor's server, reading what
|
|
93
|
+
// has been saved. Only in the editor build: the public build never gets here.
|
|
94
|
+
'astro:route:setup': ({ route }) => {
|
|
95
|
+
if (liveComponents?.has(route.component.replace(/\\/g, '/'))) route.prerender = false;
|
|
96
|
+
},
|
|
90
97
|
'astro:config:setup': async (params) => {
|
|
91
98
|
const { config, command, injectRoute, updateConfig, addMiddleware, logger } = params;
|
|
92
99
|
const flag = process.env.EDITOR;
|
|
@@ -122,9 +129,14 @@ export default function sectionEditor(userOptions) {
|
|
|
122
129
|
throw new Error('pagestack: use github.live or github.pullRequest, not both');
|
|
123
130
|
}
|
|
124
131
|
const root = fileURLToPath(config.root);
|
|
132
|
+
const pagesRel = path.relative(root, path.join(fileURLToPath(config.srcDir), 'pages')).replace(/\\/g, '/');
|
|
133
|
+
liveComponents = new Set((options.liveRoutes ?? []).flatMap((r) => {
|
|
134
|
+
const base = r.replace(/^\/|\/$/g, '');
|
|
135
|
+
return base ? [`${pagesRel}/${base}.astro`, `${pagesRel}/${base}/index.astro`] : [`${pagesRel}/index.astro`];
|
|
136
|
+
}));
|
|
125
137
|
const abs = (p) => path.isAbsolute(p) ? p : path.resolve(root, p);
|
|
126
138
|
const reservedSlugs = [...new Set([...(options.reservedSlugs ?? []), ...staticRoutes(fileURLToPath(config.srcDir))])];
|
|
127
|
-
const serial = { ...options, reservedSlugs, root, renderer: options.renderer ? abs(options.renderer) : null, previews: Object.fromEntries(Object.entries(options.previews ?? {}).map(([k, v]) => [k, abs(v)])), sections: abs(options.sections), command };
|
|
139
|
+
const serial = { ...options, builtAt: Date.now(), reservedSlugs, root, renderer: options.renderer ? abs(options.renderer) : null, previews: Object.fromEntries(Object.entries(options.previews ?? {}).map(([k, v]) => [k, abs(v)])), sections: abs(options.sections), command };
|
|
128
140
|
|
|
129
141
|
updateConfig({
|
|
130
142
|
vite: {
|
|
@@ -171,6 +183,7 @@ export default function sectionEditor(userOptions) {
|
|
|
171
183
|
injectRoute({ pattern: '/edit/global/[id]', entrypoint: route('edit-global.astro'), prerender: false });
|
|
172
184
|
injectRoute({ pattern: '/edit/collection/[id]', entrypoint: route('edit-collection.astro'), prerender: false });
|
|
173
185
|
injectRoute({ pattern: '/edit/collection/[id]/[...slug]', entrypoint: route('edit-item.astro'), prerender: false });
|
|
186
|
+
injectRoute({ pattern: '/edit/site', entrypoint: route('edit-site.astro'), prerender: false });
|
|
174
187
|
injectRoute({ pattern: '/edit/media', entrypoint: route('edit-media.astro'), prerender: false });
|
|
175
188
|
injectRoute({ pattern: '/edit/users', entrypoint: route('edit-users.astro'), prerender: false });
|
|
176
189
|
injectRoute({ pattern: '/edit/[...slug]', entrypoint: route('edit-page.astro'), prerender: false });
|
|
@@ -181,6 +194,7 @@ export default function sectionEditor(userOptions) {
|
|
|
181
194
|
injectRoute({ pattern: '/api/editor/images', entrypoint: route('api/images.ts'), prerender: false });
|
|
182
195
|
injectRoute({ pattern: '/api/editor/collection/[id]/[...slug]', entrypoint: route('api/collection.ts'), prerender: false });
|
|
183
196
|
injectRoute({ pattern: '/api/editor/users', entrypoint: route('api/users.ts'), prerender: false });
|
|
197
|
+
injectRoute({ pattern: '/api/editor/browse', entrypoint: route('api/browse.ts'), prerender: false });
|
|
184
198
|
injectRoute({ pattern: '/api/editor/live', entrypoint: route('api/live.ts'), prerender: false });
|
|
185
199
|
injectRoute({ pattern: '/api/editor/asset/[...path]', entrypoint: route('api/asset.ts'), prerender: false });
|
|
186
200
|
injectRoute({ pattern: '/api/editor/auth/[action]', entrypoint: route('api/auth.ts'), prerender: false });
|
package/live.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// For host sites whose list pages should show what the editor has saved (the `liveRoutes` option).
|
|
2
|
+
//
|
|
3
|
+
// On the editor's server, for those pages, this returns a collection's entries as stored now (the
|
|
4
|
+
// staging branch). Everywhere else, including the public build and prerendering, it returns null,
|
|
5
|
+
// so the caller uses Astro's own getCollection and the public site is unchanged:
|
|
6
|
+
//
|
|
7
|
+
// import { getCollection } from 'astro:content';
|
|
8
|
+
// import { liveEntries } from '@pirateandfox/pagestack/live';
|
|
9
|
+
// const all = (await liveEntries('articles', articleSchema)) ?? (await getCollection('articles'));
|
|
10
|
+
//
|
|
11
|
+
// Plain JavaScript with no imports, so a public build that never loads the editor can import it.
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {string} collection The editor's collection id (normally the Astro collection name).
|
|
15
|
+
* @param {{ parse(data: unknown): any }} [schema] The collection's zod schema, so dates and defaults
|
|
16
|
+
* come out as they do at build time. Without one, `data` is the raw frontmatter.
|
|
17
|
+
* @returns {Promise<{ id: string; collection: string; data: any; body: string; filePath: string }[] | null>}
|
|
18
|
+
*/
|
|
19
|
+
export async function liveEntries(collection, schema) {
|
|
20
|
+
const live = /** @type {any} */ (globalThis).__PS_LIVE__;
|
|
21
|
+
if (typeof live !== 'function') return null;
|
|
22
|
+
const entries = await live(collection);
|
|
23
|
+
if (!entries) return null;
|
|
24
|
+
const out = [];
|
|
25
|
+
for (const e of entries) {
|
|
26
|
+
// An item the build would reject is left out rather than taking the list page down.
|
|
27
|
+
try { out.push(schema ? { ...e, data: schema.parse(e.data) } : e); } catch { /* skipped */ }
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pirateandfox/pagestack",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.9",
|
|
4
4
|
"description": "PageStack: visual section editor for Astro sites. Git-only, static public site, passkey login, saves are commits.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -10,10 +10,12 @@
|
|
|
10
10
|
"exports": {
|
|
11
11
|
".": "./index.mjs",
|
|
12
12
|
"./runtime": "./src/runtime.ts",
|
|
13
|
-
"./core/*": "./src/core/*.ts"
|
|
13
|
+
"./core/*": "./src/core/*.ts",
|
|
14
|
+
"./live": "./live.mjs"
|
|
14
15
|
},
|
|
15
16
|
"files": [
|
|
16
17
|
"index.mjs",
|
|
18
|
+
"live.mjs",
|
|
17
19
|
"bin",
|
|
18
20
|
"src"
|
|
19
21
|
],
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// Browse (/edit/site): keeps the bar in step with the page in the frame.
|
|
2
|
+
//
|
|
3
|
+
// Links inside the frame are caught and sent through /api/editor/browse, so an item opens through
|
|
4
|
+
// its preview (its latest saved version) instead of the copy this editor was built with, and the
|
|
5
|
+
// "Edit this page" button always points at whatever is showing. The address bar tracks the site
|
|
6
|
+
// path (/edit/site?path=…), so Back, Forward and reload work.
|
|
7
|
+
interface Resolved {
|
|
8
|
+
path: string;
|
|
9
|
+
kind: 'page' | 'item' | 'live' | 'snapshot';
|
|
10
|
+
frame: string;
|
|
11
|
+
edit: string | null;
|
|
12
|
+
label?: string;
|
|
13
|
+
builtAt?: string;
|
|
14
|
+
savedAt?: string | null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const frame = document.getElementById('ps-browse-frame') as HTMLIFrameElement;
|
|
18
|
+
const pathEl = document.getElementById('ps-browse-path')!;
|
|
19
|
+
const note = document.getElementById('ps-browse-note')!;
|
|
20
|
+
const edit = document.getElementById('ps-browse-edit') as HTMLAnchorElement;
|
|
21
|
+
let current = (window as any).__PS_BROWSE__ as Resolved;
|
|
22
|
+
|
|
23
|
+
const when = (iso: string) => new Date(iso).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
|
|
24
|
+
|
|
25
|
+
function drawBar(r: Resolved) {
|
|
26
|
+
pathEl.textContent = r.path;
|
|
27
|
+
pathEl.title = r.path;
|
|
28
|
+
edit.hidden = !r.edit;
|
|
29
|
+
if (r.edit) edit.href = r.edit;
|
|
30
|
+
note.classList.remove('is-stale');
|
|
31
|
+
note.title = '';
|
|
32
|
+
if (r.kind === 'page' || r.kind === 'item' || r.kind === 'live') {
|
|
33
|
+
note.textContent = 'Latest saved version';
|
|
34
|
+
} else if (r.builtAt && r.savedAt && Date.parse(r.savedAt) > Date.parse(r.builtAt)) {
|
|
35
|
+
note.textContent = `⚠ As of ${when(r.builtAt)}. May not show changes saved since.`;
|
|
36
|
+
note.title = 'This page is the copy built into the editor. Changes saved after that show here once the editor is redeployed, and on the public site after Go live.';
|
|
37
|
+
note.classList.add('is-stale');
|
|
38
|
+
} else {
|
|
39
|
+
note.textContent = '';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function lookup(path: string): Promise<Resolved | null> {
|
|
44
|
+
try {
|
|
45
|
+
const r = await fetch(`/api/editor/browse?path=${encodeURIComponent(path)}`, { headers: { accept: 'application/json' } });
|
|
46
|
+
if (r.status === 401) { location.href = `/edit/login?next=${encodeURIComponent(location.pathname + location.search)}`; return null; }
|
|
47
|
+
return r.ok ? await r.json() : null;
|
|
48
|
+
} catch { return null; }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Point the frame somewhere without adding to the tab's history: Browse keeps its own entries
|
|
53
|
+
* (one per site page, in the address bar), so Back goes back a page, not back inside the frame.
|
|
54
|
+
*/
|
|
55
|
+
function show(url: string) {
|
|
56
|
+
try { frame.contentWindow!.location.replace(url); } catch { frame.src = url; }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Show a site path: resolve it, point the frame at it, and (unless from history) record it. */
|
|
60
|
+
async function go(path: string, hash = '', push = true) {
|
|
61
|
+
const r = await lookup(path);
|
|
62
|
+
if (!r) { show(path + hash); return; }
|
|
63
|
+
current = r;
|
|
64
|
+
drawBar(r);
|
|
65
|
+
if (push) history.pushState({ path: r.path }, '', `/edit/site?path=${encodeURIComponent(r.path)}`);
|
|
66
|
+
show(r.frame + hash);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The site path the frame is showing, from its own address. */
|
|
70
|
+
function framePath(): string | null {
|
|
71
|
+
try {
|
|
72
|
+
const loc = frame.contentWindow!.location;
|
|
73
|
+
if (loc.pathname.startsWith('/edit/preview')) return null; // a preview: `current` already says which page
|
|
74
|
+
return loc.pathname;
|
|
75
|
+
} catch { return null; }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function isModified(e: MouseEvent) { return e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0; }
|
|
79
|
+
|
|
80
|
+
function wire() {
|
|
81
|
+
let doc: Document;
|
|
82
|
+
try { doc = frame.contentDocument!; } catch { return; }
|
|
83
|
+
if (!doc) return;
|
|
84
|
+
if (doc.title) document.title = doc.title;
|
|
85
|
+
doc.addEventListener('click', (e) => {
|
|
86
|
+
if (e.defaultPrevented || isModified(e)) return;
|
|
87
|
+
const a = (e.target as Element | null)?.closest?.('a[href]') as HTMLAnchorElement | null;
|
|
88
|
+
if (!a || a.hasAttribute('download')) return;
|
|
89
|
+
const href = a.getAttribute('href') ?? '';
|
|
90
|
+
if (href.startsWith('#') || /^(mailto|tel|javascript):/i.test(href)) return;
|
|
91
|
+
const url = new URL(a.href, doc.baseURI);
|
|
92
|
+
e.preventDefault();
|
|
93
|
+
if (url.origin !== location.origin) { window.open(url.href, '_blank', 'noopener'); return; }
|
|
94
|
+
if (url.pathname === '/edit' || url.pathname.startsWith('/edit/') || url.pathname.startsWith('/api/')) { location.href = url.href; return; }
|
|
95
|
+
if (a.target === '_blank') { window.open(`/edit/site?path=${encodeURIComponent(url.pathname)}`, '_blank'); return; }
|
|
96
|
+
void go(url.pathname, url.hash);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
frame.addEventListener('load', () => {
|
|
101
|
+
wire();
|
|
102
|
+
// Got here some other way (a form, a script, a redirect): bring the bar and address up to date.
|
|
103
|
+
const p = framePath();
|
|
104
|
+
if (p && p !== current.path && p.replace(/\/$/, '') !== current.path.replace(/\/$/, '')) {
|
|
105
|
+
void lookup(p).then((r) => {
|
|
106
|
+
if (!r) return;
|
|
107
|
+
current = r;
|
|
108
|
+
drawBar(r);
|
|
109
|
+
history.replaceState({ path: r.path }, '', `/edit/site?path=${encodeURIComponent(r.path)}`);
|
|
110
|
+
if (r.frame !== p) show(r.frame); // an item: show its saved version, not the old copy
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
window.addEventListener('popstate', (e) => {
|
|
116
|
+
const path = (e.state as { path?: string } | null)?.path ?? new URLSearchParams(location.search).get('path') ?? '/';
|
|
117
|
+
void go(path, '', false);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
history.replaceState({ path: current.path }, '', `/edit/site?path=${encodeURIComponent(current.path)}`);
|
|
121
|
+
drawBar(current);
|
|
122
|
+
// The first resolve came with the page; ask again for the snapshot dates the server left out.
|
|
123
|
+
if (current.kind === 'snapshot') void lookup(current.path).then((r) => { if (r && r.path === current.path) { current = r; drawBar(r); } });
|
package/src/client/shell.css
CHANGED
|
@@ -319,3 +319,26 @@ body.ps[data-left="add"] .ps-listview, body:not([data-left="add"]) .ps-inserter
|
|
|
319
319
|
.ps-live__list li { display: flex; justify-content: space-between; gap: 12px; padding: 8px 10px; border-top: 1px solid var(--ps-border); }
|
|
320
320
|
.ps-live__list li:first-child { border-top: 0; }
|
|
321
321
|
.ps-live__list .ps-muted { flex: none; font-size: 12px; }
|
|
322
|
+
|
|
323
|
+
/* ---- Browse (/edit/site): the site in a frame under a slim bar ---- */
|
|
324
|
+
body.ps-browse { margin: 0; height: 100vh; display: grid; grid-template-rows: auto minmax(0, 1fr); font: 13px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif; background: #1e1e1e; }
|
|
325
|
+
.ps-browse__bar { display: flex; align-items: center; gap: 16px; min-height: 44px; padding: 6px 16px; background: #1e1e1e; color: #ddd; }
|
|
326
|
+
.ps-browse__site { color: #fff; font-weight: 600; text-decoration: none; white-space: nowrap; }
|
|
327
|
+
.ps-browse__site:hover { text-decoration: underline; }
|
|
328
|
+
.ps-browse__where { display: flex; align-items: center; gap: 12px; min-width: 0; flex: 1; }
|
|
329
|
+
.ps-browse__path { color: #9ca3af; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
330
|
+
.ps-browse__note { color: #9ca3af; font-size: 12px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
331
|
+
.ps-browse__note.is-stale { color: #fbbf24; }
|
|
332
|
+
.ps-browse__actions { display: flex; align-items: center; gap: 10px; }
|
|
333
|
+
.ps-browse__actions .ps-btn { padding: 5px 12px; }
|
|
334
|
+
.ps-browse__actions .ps-live:not(.ps-btn--primary) { background: transparent; color: #fff; border-color: #4b5563; }
|
|
335
|
+
.ps-browse__out { color: #9ca3af; text-decoration: none; }
|
|
336
|
+
.ps-browse__out:hover { color: #fff; }
|
|
337
|
+
.ps-browse__frame { width: 100%; height: 100%; border: 0; background: #fff; }
|
|
338
|
+
@media (max-width: 640px) {
|
|
339
|
+
.ps-browse__bar { flex-wrap: wrap; gap: 4px 10px; padding: 6px 10px; }
|
|
340
|
+
.ps-browse__site { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
341
|
+
.ps-browse__where { order: 3; flex-basis: 100%; }
|
|
342
|
+
.ps-browse__where:not(:has(.is-stale)) { display: none; } /* only the warning earns a second line */
|
|
343
|
+
.ps-browse__path, .ps-browse__out { display: none; }
|
|
344
|
+
}
|
package/src/core/pages.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { cloneWithNewIds } from '../runtime';
|
|
|
7
7
|
* Paths the integration itself owns; hosts add theirs with `reservedSlugs`. The last four would be
|
|
8
8
|
* valid public URLs, but /edit/<slug> is how a page gets edited and those are editor screens.
|
|
9
9
|
*/
|
|
10
|
-
export const RESERVED_SLUGS = ['edit', 'api', '_astro', 'login', 'enroll', 'preview', 'global', 'media', 'users', 'collection'];
|
|
10
|
+
export const RESERVED_SLUGS = ['edit', 'api', '_astro', 'login', 'enroll', 'preview', 'global', 'media', 'users', 'collection', 'site'];
|
|
11
11
|
|
|
12
12
|
export function slugify(title: string): string {
|
|
13
13
|
return title
|
|
@@ -32,6 +32,10 @@ export interface GitHubOptions {
|
|
|
32
32
|
|
|
33
33
|
const UPLOADS = 'pagestack-uploads';
|
|
34
34
|
|
|
35
|
+
/** Blob contents by git hash. A hash names exactly one content, so entries never go stale. */
|
|
36
|
+
const blobs = new Map<string, string>();
|
|
37
|
+
const BLOB_CACHE_MAX = 2000;
|
|
38
|
+
|
|
35
39
|
export class GitHubStorage implements Storage {
|
|
36
40
|
readonly kind = 'github' as const;
|
|
37
41
|
private fetchImpl: typeof fetch;
|
|
@@ -79,6 +83,39 @@ export class GitHubStorage implements Storage {
|
|
|
79
83
|
return out;
|
|
80
84
|
}
|
|
81
85
|
|
|
86
|
+
async head(): Promise<string> {
|
|
87
|
+
const ref = await this.req<any>('GET', `${this.repoUrl}/git/ref/heads/${encodeURIComponent(this.branch)}`);
|
|
88
|
+
return ref.object.sha as string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async lastChange(): Promise<string | null> {
|
|
92
|
+
const c = await this.req<any>('GET', `${this.repoUrl}/commits/${encodeURIComponent(this.branch)}`, undefined, true);
|
|
93
|
+
return c?.commit?.committer?.date ?? c?.commit?.author?.date ?? null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async readDir(p: string): Promise<{ name: string; content: string }[]> {
|
|
97
|
+
const data = await this.req<any[]>('GET', `${this.repoUrl}/contents/${encodePath(safeRelPath(p))}?ref=${encodeURIComponent(this.branch)}`, undefined, true);
|
|
98
|
+
if (!Array.isArray(data)) return [];
|
|
99
|
+
const files = data.filter((e) => e.type === 'file');
|
|
100
|
+
const out: { name: string; content: string }[] = new Array(files.length);
|
|
101
|
+
let next = 0;
|
|
102
|
+
const worker = async () => {
|
|
103
|
+
while (next < files.length) {
|
|
104
|
+
const i = next++; const f = files[i];
|
|
105
|
+
let content = blobs.get(f.sha);
|
|
106
|
+
if (content === undefined) {
|
|
107
|
+
const blob = await this.req<any>('GET', `${this.repoUrl}/git/blobs/${f.sha}`);
|
|
108
|
+
content = new TextDecoder().decode(fromBase64(String(blob.content).replace(/\n/g, '')));
|
|
109
|
+
if (blobs.size >= BLOB_CACHE_MAX) blobs.delete(blobs.keys().next().value!);
|
|
110
|
+
blobs.set(f.sha, content);
|
|
111
|
+
}
|
|
112
|
+
out[i] = { name: f.name, content };
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
await Promise.all(Array.from({ length: Math.min(8, files.length) }, worker));
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
82
119
|
private async uploadsBranch() {
|
|
83
120
|
if (await this.req('GET', `${this.repoUrl}/git/ref/heads/${UPLOADS}`, undefined, true)) return;
|
|
84
121
|
const head = await this.req<any>('GET', `${this.repoUrl}/git/ref/heads/${encodeURIComponent(this.branch)}`);
|
|
@@ -31,6 +31,15 @@ export class LocalStorage implements Storage {
|
|
|
31
31
|
return out;
|
|
32
32
|
} catch (e: any) { if (e.code === 'ENOENT') return []; throw e; }
|
|
33
33
|
}
|
|
34
|
+
async readDir(p: string) {
|
|
35
|
+
const out: { name: string; content: string }[] = [];
|
|
36
|
+
for (const e of await this.listDir(p)) {
|
|
37
|
+
if (e.type !== 'file') continue;
|
|
38
|
+
const content = await this.readFile(`${p}/${e.name}`);
|
|
39
|
+
if (content !== null) out.push({ name: e.name, content });
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
34
43
|
async putAsset(p: string, bytes: Uint8Array): Promise<void> {
|
|
35
44
|
const f = this.abs(p);
|
|
36
45
|
await fs.mkdir(path.dirname(f), { recursive: true });
|
package/src/core/storage.ts
CHANGED
|
@@ -44,6 +44,16 @@ export interface Storage {
|
|
|
44
44
|
readFile(path: string): Promise<string | null>;
|
|
45
45
|
/** Names of entries in a repo-relative directory (files and dirs), [] when missing. */
|
|
46
46
|
listDir(path: string): Promise<{ name: string; type: 'file' | 'dir'; size?: number }[]>;
|
|
47
|
+
/**
|
|
48
|
+
* Every file directly in a folder, with its contents, as stored now. Optional; callers fall back
|
|
49
|
+
* to listDir + readFile. The GitHub adapter caches contents by blob hash, so repeated reads cost
|
|
50
|
+
* one request.
|
|
51
|
+
*/
|
|
52
|
+
readDir?(path: string): Promise<{ name: string; content: string }[]>;
|
|
53
|
+
/** The commit the branch is at now, when the store has one. Lets readers skip work when nothing changed. */
|
|
54
|
+
head?(): Promise<string>;
|
|
55
|
+
/** When the branch last changed (its head commit's date, ISO). */
|
|
56
|
+
lastChange?(): Promise<string | null>;
|
|
47
57
|
/** Stage a binary (upload). It must be reachable at its URL before the next commit. */
|
|
48
58
|
putAsset(path: string, bytes: Uint8Array): Promise<void>;
|
|
49
59
|
/** Make a set of text changes durable, together with any staged assets. `deletes` are repo-relative paths. */
|
package/src/routes/Nav.astro
CHANGED
|
@@ -16,7 +16,7 @@ const links = [
|
|
|
16
16
|
<a class="ps-nav__site" href="/edit">{opts.siteName}</a>
|
|
17
17
|
{links.map((l) => <a href={l.href} aria-current={l.id === current ? 'page' : undefined}>{l.label}</a>)}
|
|
18
18
|
<span class="ps-nav__user">
|
|
19
|
-
<a href="/"
|
|
19
|
+
<a href="/edit/site" aria-current={current === 'site' ? 'page' : undefined}>Browse site</a>
|
|
20
20
|
{opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-btn--primary ps-live" hidden>Go live</button>}
|
|
21
21
|
{user && opts.auth === 'passkey' && <span>Signed in as <strong>{user.name}</strong> · <a href="/api/editor/auth/logout">Sign out</a></span>}
|
|
22
22
|
</span>
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Browse mode: GET /api/editor/browse?path=/articles/x/ -> what to show for that site address.
|
|
2
|
+
// { path, kind, frame, edit, label?, builtAt?, savedAt? }. builtAt/savedAt come with a snapshot
|
|
3
|
+
// page, so the bar can say when the copy it shows may be older than what has been saved.
|
|
4
|
+
import type { APIRoute } from 'astro';
|
|
5
|
+
import { json, opts, storage } from '../../server/context';
|
|
6
|
+
import { resolve } from '../../server/browse';
|
|
7
|
+
export const prerender = false;
|
|
8
|
+
|
|
9
|
+
let lastChange: { at: number; value: Promise<string | null> } | null = null;
|
|
10
|
+
const SAVED_TTL = 10_000;
|
|
11
|
+
function savedAt(): Promise<string | null> {
|
|
12
|
+
const s = storage();
|
|
13
|
+
if (!s.lastChange) return Promise.resolve(null);
|
|
14
|
+
const now = Date.now();
|
|
15
|
+
if (!lastChange || now - lastChange.at > SAVED_TTL) lastChange = { at: now, value: s.lastChange().catch(() => null) };
|
|
16
|
+
return lastChange.value;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const GET: APIRoute = async ({ url }) => {
|
|
20
|
+
const r = await resolve(url.searchParams.get('path'));
|
|
21
|
+
// In `astro dev` every page is rendered fresh, so nothing is ever a stale snapshot.
|
|
22
|
+
if (r.kind !== 'snapshot' || opts.command !== 'build' || !opts.builtAt) return json(r);
|
|
23
|
+
return json({ ...r, builtAt: new Date(opts.builtAt).toISOString(), savedAt: await savedAt() });
|
|
24
|
+
};
|
|
@@ -32,7 +32,7 @@ const boot = { id, singular, slugs: items.map((i) => i.slug), reserved: reserved
|
|
|
32
32
|
<li data-slug={i.slug} data-search={`${i.title} ${i.slug}`.toLowerCase()}>
|
|
33
33
|
<a class="ps-pagelist__edit" href={`/edit/collection/${id}/${i.slug}`}><strong>{i.title}{i.draft && <span class="ps-pill">Draft</span>}</strong><span class="ps-muted">{i.date.slice(0, 10)}</span></a>
|
|
34
34
|
<div class="ps-pagelist__actions">
|
|
35
|
-
{!i.draft && c.url && <a class="ps-btn ps-btn--small ps-btn--ghost" href={c.url(i.slug)}
|
|
35
|
+
{!i.draft && c.url && <a class="ps-btn ps-btn--small ps-btn--ghost" href={`/edit/site?path=${encodeURIComponent(c.url(i.slug))}`}>View</a>}
|
|
36
36
|
<button type="button" class="ps-btn ps-btn--small ps-btn--ghost ps-btn--danger" data-delete={i.slug}>Delete</button>
|
|
37
37
|
</div>
|
|
38
38
|
</li>
|
|
@@ -48,7 +48,7 @@ const globalLinks = Object.entries(globals).map(([id, g]) => ({ id, label: g.lab
|
|
|
48
48
|
<li data-slug={p.slug} data-search={`${p.title} ${p.slug}`.toLowerCase()}>
|
|
49
49
|
<a class="ps-pagelist__edit" href={`/edit/${p.slug}`}><strong>{p.title}{p.status === 'draft' && <span class="ps-pill">Draft</span>}</strong><span class="ps-muted">{publicPath(p.slug)} · {p.sections} {p.sections === 1 ? 'section' : 'sections'}</span></a>
|
|
50
50
|
<div class="ps-pagelist__actions">
|
|
51
|
-
{p.status !== 'draft' && <a class="ps-btn ps-btn--small ps-btn--ghost" href={publicPath(p.slug)}
|
|
51
|
+
{p.status !== 'draft' && <a class="ps-btn ps-btn--small ps-btn--ghost" href={`/edit/site?path=${encodeURIComponent(publicPath(p.slug))}`}>View</a>}
|
|
52
52
|
<button type="button" class="ps-btn ps-btn--small ps-btn--ghost" data-duplicate={p.slug}>Duplicate</button>
|
|
53
53
|
{p.slug !== 'index' && <button type="button" class="ps-btn ps-btn--small ps-btn--ghost ps-btn--danger" data-delete={p.slug}>Delete</button>}
|
|
54
54
|
</div>
|
|
@@ -41,7 +41,7 @@ const boot = {
|
|
|
41
41
|
)}
|
|
42
42
|
<span id="ps-item-status" class="ps-muted"></span>
|
|
43
43
|
<span class="ps-item__actions">
|
|
44
|
-
{boot.viewUrl && <a id="ps-item-view" class="ps-btn ps-btn--ghost" href={boot.viewUrl}
|
|
44
|
+
{boot.viewUrl && <a id="ps-item-view" class="ps-btn ps-btn--ghost" href={`/edit/site?path=${encodeURIComponent(boot.viewUrl)}`} title="See the saved version on the site, and click around from there">View on site</a>}
|
|
45
45
|
{boot.preview && <button type="button" id="ps-item-tab" class="ps-btn ps-btn--ghost">Preview ↗</button>}
|
|
46
46
|
<button type="button" id="ps-item-draft" class="ps-btn ps-btn--ghost" hidden>Switch to draft</button>
|
|
47
47
|
<button type="button" id="ps-item-save" class="ps-btn" disabled>Save</button>
|
|
@@ -41,7 +41,7 @@ const boot = {
|
|
|
41
41
|
<span id="ps-status" class="ps-muted" role="status"></span>
|
|
42
42
|
<button type="button" id="ps-discard" class="ps-btn ps-btn--ghost" hidden>Discard</button>
|
|
43
43
|
<button type="button" id="ps-preview-tab" class="ps-btn ps-btn--ghost" title="See this draft as visitors will, in a new tab">Preview</button>
|
|
44
|
-
<a id="ps-view" class="ps-btn ps-btn--ghost" href={publicPath(slug)}
|
|
44
|
+
<a id="ps-view" class="ps-btn ps-btn--ghost" href={`/edit/site?path=${encodeURIComponent(publicPath(slug))}`} title="See the saved page on the site, and click around from there">View on site</a>
|
|
45
45
|
<button type="button" id="ps-save" class="ps-btn ps-btn--primary" disabled>Save</button>
|
|
46
46
|
<button type="button" id="ps-publish" class="ps-btn ps-btn--primary" hidden>Publish</button>
|
|
47
47
|
{opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-live" hidden>Go live</button>}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
---
|
|
2
|
+
// /edit/site?path=/x/ — Browse: the site as it is now, in a frame, with the editor's bar on top.
|
|
3
|
+
// Click around as a visitor would; "Edit this page" opens the editor for whatever is showing.
|
|
4
|
+
// Pages and items show their latest saved version (through their previews), list pages in
|
|
5
|
+
// `liveRoutes` render from storage, and anything else is the copy this editor was built with.
|
|
6
|
+
import { opts } from '../server/context';
|
|
7
|
+
import { resolve } from '../server/browse';
|
|
8
|
+
import '../client/shell.css';
|
|
9
|
+
export const prerender = false;
|
|
10
|
+
const first = await resolve(Astro.url.searchParams.get('path'));
|
|
11
|
+
const user = (Astro.locals as any).editorUser as { name: string } | undefined;
|
|
12
|
+
---
|
|
13
|
+
<!doctype html>
|
|
14
|
+
<html lang="en">
|
|
15
|
+
<head>
|
|
16
|
+
<meta charset="utf-8" />
|
|
17
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
18
|
+
<meta name="robots" content="noindex" />
|
|
19
|
+
<title>{opts.siteName}</title>
|
|
20
|
+
</head>
|
|
21
|
+
<body class="ps-browse">
|
|
22
|
+
<header class="ps-browse__bar">
|
|
23
|
+
<a class="ps-browse__site" href="/edit" title="Editor dashboard">← {opts.siteName}</a>
|
|
24
|
+
<span class="ps-browse__where">
|
|
25
|
+
<span id="ps-browse-path" class="ps-browse__path">{first.path}</span>
|
|
26
|
+
<span id="ps-browse-note" class="ps-browse__note" role="status"></span>
|
|
27
|
+
</span>
|
|
28
|
+
<span class="ps-browse__actions">
|
|
29
|
+
<a id="ps-browse-edit" class="ps-btn ps-btn--primary" href={first.edit ?? '#'} hidden={!first.edit}>✎ Edit this page</a>
|
|
30
|
+
{opts.github?.live && <button type="button" id="ps-live" class="ps-btn ps-live" hidden>Go live</button>}
|
|
31
|
+
{user && opts.auth === 'passkey' && <a class="ps-browse__out" href="/api/editor/auth/logout">Sign out</a>}
|
|
32
|
+
</span>
|
|
33
|
+
</header>
|
|
34
|
+
<iframe id="ps-browse-frame" class="ps-browse__frame" title="Site" src={first.frame}></iframe>
|
|
35
|
+
<script is:inline set:html={`window.__PS_BROWSE__ = ${JSON.stringify(first).replace(/</g, '\\u003c')};`} />
|
|
36
|
+
<script>
|
|
37
|
+
import '../client/browse.ts';
|
|
38
|
+
import '../client/live.ts';
|
|
39
|
+
</script>
|
|
40
|
+
</body>
|
|
41
|
+
</html>
|
|
@@ -23,6 +23,7 @@ try {
|
|
|
23
23
|
data = item?.data && typeof item.data === 'object' && !Array.isArray(item.data) ? item.data : {};
|
|
24
24
|
body = typeof item?.body === 'string' ? item.body : '';
|
|
25
25
|
} else {
|
|
26
|
+
editing = !Astro.url.searchParams.has('view'); // ?view=1 is Browse: no edit markers, scripts kept
|
|
26
27
|
const raw = await storage().readFile(`${collections[id].dir}/${slug}.md`);
|
|
27
28
|
if (raw === null) return new Response('Not found', { status: 404 });
|
|
28
29
|
({ data, body } = parseMarkdown(raw));
|
package/src/routes/preview.astro
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
---
|
|
2
|
-
// Live preview. GET renders the stored page; POST renders the draft in the request body.
|
|
2
|
+
// Live preview. GET renders the stored page (?view=1: without edit mode, for Browse); POST renders the draft in the request body.
|
|
3
3
|
// Both render in edit mode (data-ps-* attributes) through the site's own renderer component,
|
|
4
4
|
// so what the editor shows is exactly what the static build will produce. A form POST (the
|
|
5
5
|
// Preview button) renders the draft without edit mode, for a look at the finished page in a tab.
|
|
@@ -26,6 +26,8 @@ if (Astro.request.method === 'POST') {
|
|
|
26
26
|
else page = clean(page, locals, (await readPage(slug).catch(() => null))?.page);
|
|
27
27
|
} catch (e: any) { error = e.message; }
|
|
28
28
|
} else {
|
|
29
|
+
// ?view=1 is Browse: the saved page as visitors will see it, without edit markers.
|
|
30
|
+
editing = !Astro.url.searchParams.has('view');
|
|
29
31
|
const r = await readPage(slug);
|
|
30
32
|
if (!r) return new Response('No such page', { status: 404 });
|
|
31
33
|
page = r.page;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Browse mode: for a site address, what to show in the frame and which editor screen edits it.
|
|
2
|
+
//
|
|
3
|
+
// page a page the editor manages, shown through its preview (latest saved version)
|
|
4
|
+
// item a collection item, shown through its preview when the site has one
|
|
5
|
+
// live a host page in `liveRoutes`, rendered on request from what has been saved
|
|
6
|
+
// snapshot anything else: the copy built into this editor deployment, which can be older
|
|
7
|
+
import { collections, opts, readPage, slugRe, storage } from './context';
|
|
8
|
+
|
|
9
|
+
export interface Resolved {
|
|
10
|
+
path: string;
|
|
11
|
+
kind: 'page' | 'item' | 'live' | 'snapshot';
|
|
12
|
+
/** What the browse frame loads. */
|
|
13
|
+
frame: string;
|
|
14
|
+
/** The editor screen for this page, or null when it isn't editable here. */
|
|
15
|
+
edit: string | null;
|
|
16
|
+
/** Item or page name, when known. */
|
|
17
|
+
label?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const SLUG = '__ps_slug__';
|
|
21
|
+
const trim = (p: string) => p.replace(/\/+$/, '') || '/';
|
|
22
|
+
|
|
23
|
+
/** "/articles/x/?a#b" -> "/articles/x/"; only same-site paths, never the editor's own. */
|
|
24
|
+
export function normalizePath(input: string | null): string {
|
|
25
|
+
let p = (input ?? '/').trim();
|
|
26
|
+
try { p = new URL(p, 'http://x').pathname; } catch { p = '/'; }
|
|
27
|
+
if (!p.startsWith('/') || p.startsWith('//')) p = '/';
|
|
28
|
+
return p;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const isEditorPath = (p: string) => p === '/edit' || p.startsWith('/edit/') || p.startsWith('/api/');
|
|
32
|
+
|
|
33
|
+
export function isLiveRoute(pathname: string): boolean {
|
|
34
|
+
const p = trim(pathname.replace(/\/index\.html$/, '/'));
|
|
35
|
+
return (opts.liveRoutes ?? []).some((r) => trim(r) === p);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The collection item a site path belongs to, from each collection's `url` function. */
|
|
39
|
+
function itemFor(path: string): { id: string; slug: string } | null {
|
|
40
|
+
for (const [id, c] of Object.entries(collections)) {
|
|
41
|
+
if (!c.url) continue;
|
|
42
|
+
const pattern = c.url(SLUG);
|
|
43
|
+
const at = pattern.indexOf(SLUG);
|
|
44
|
+
if (at < 0) continue;
|
|
45
|
+
const before = pattern.slice(0, at), after = trim(pattern.slice(at + SLUG.length)) === '/' ? '' : trim(pattern.slice(at + SLUG.length));
|
|
46
|
+
const p = trim(path);
|
|
47
|
+
if (!p.startsWith(before)) continue;
|
|
48
|
+
const rest = p.slice(before.length);
|
|
49
|
+
if (after && !rest.endsWith(after)) continue;
|
|
50
|
+
const slug = after ? rest.slice(0, -after.length) : rest;
|
|
51
|
+
if (/^[a-z0-9][a-z0-9_-]*$/i.test(slug)) return { id, slug };
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function resolve(rawPath: string | null): Promise<Resolved> {
|
|
57
|
+
const path = normalizePath(rawPath);
|
|
58
|
+
const item = itemFor(path);
|
|
59
|
+
if (item) {
|
|
60
|
+
const c = collections[item.id];
|
|
61
|
+
const raw = await storage().readFile(`${c.dir}/${item.slug}.md`);
|
|
62
|
+
if (raw !== null) {
|
|
63
|
+
const title = /^title:\s*["']?(.*?)["']?\s*$/m.exec(raw)?.[1];
|
|
64
|
+
const preview = Object.hasOwn(opts.previews ?? {}, item.id);
|
|
65
|
+
return {
|
|
66
|
+
path, kind: preview ? 'item' : isLiveRoute(path) ? 'live' : 'snapshot',
|
|
67
|
+
frame: preview ? `/edit/preview-item/${item.id}/${item.slug}?view=1` : path,
|
|
68
|
+
edit: `/edit/collection/${item.id}/${item.slug}`, label: title,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (opts.pages !== false && opts.renderer) {
|
|
73
|
+
const slug = trim(path) === '/' ? 'index' : trim(path).slice(1);
|
|
74
|
+
if (slugRe.test(slug) && !slug.includes('..')) {
|
|
75
|
+
const r = await readPage(slug).catch(() => null);
|
|
76
|
+
if (r) return { path, kind: 'page', frame: `/edit/preview/${slug}?view=1`, edit: `/edit/${slug}`, label: r.page.title };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return { path, kind: isLiveRoute(path) ? 'live' : 'snapshot', frame: path, edit: null };
|
|
80
|
+
}
|
package/src/server/context.ts
CHANGED
|
@@ -21,6 +21,10 @@ export interface EditorOptions {
|
|
|
21
21
|
auth: 'none' | 'passkey' | 'none-behind-proxy'; storage: 'local' | 'github'; github: { repo: string; branch?: string; pullRequest?: boolean; live?: string; stagingUrl?: string } | null;
|
|
22
22
|
siteName: string; secretEnv: string; command: string; interactiveSelector: string;
|
|
23
23
|
reservedSlugs: string[]; redirectsFile: string; patternsFile: string;
|
|
24
|
+
/** When this editor was built (ms). Browse compares it with the last save. */
|
|
25
|
+
builtAt?: number;
|
|
26
|
+
/** Site pages rendered on request on the editor's server, so lists show saved content. URL paths. */
|
|
27
|
+
liveRoutes?: string[];
|
|
24
28
|
/** Header carrying the client's IP behind a proxy, e.g. cf-connecting-ip. */
|
|
25
29
|
clientIpHeader?: string;
|
|
26
30
|
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Collection entries straight from storage, for host list pages rendered on the editor's server
|
|
2
|
+
// (see live.mjs). The collection name is the editor's collection id.
|
|
3
|
+
//
|
|
4
|
+
// With a store that knows its head commit (GitHub), entries are kept until the branch moves, and
|
|
5
|
+
// the head is asked at most once a second, so a page that lists four collections costs one request.
|
|
6
|
+
import { collections, storage } from './context';
|
|
7
|
+
import { parseMarkdown } from '../core/frontmatter';
|
|
8
|
+
|
|
9
|
+
export interface LiveEntry { id: string; collection: string; data: Record<string, any>; body: string; filePath: string }
|
|
10
|
+
|
|
11
|
+
const HEAD_TTL = 1000;
|
|
12
|
+
let headCheck: { at: number; sha: Promise<string> } | null = null;
|
|
13
|
+
let cached: { sha: string; byName: Map<string, Promise<LiveEntry[]>> } | null = null;
|
|
14
|
+
|
|
15
|
+
async function currentHead(now: number): Promise<string | null> {
|
|
16
|
+
const s = storage();
|
|
17
|
+
if (!s.head) return null;
|
|
18
|
+
if (!headCheck || now - headCheck.at > HEAD_TTL) headCheck = { at: now, sha: s.head() };
|
|
19
|
+
try { return await headCheck.sha; } catch { headCheck = null; return null; }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function read(name: string, dir: string): Promise<LiveEntry[]> {
|
|
23
|
+
const s = storage();
|
|
24
|
+
const files = s.readDir
|
|
25
|
+
? await s.readDir(dir)
|
|
26
|
+
: await Promise.all((await s.listDir(dir)).filter((e) => e.type === 'file').map(async (e) => ({ name: e.name, content: (await s.readFile(`${dir}/${e.name}`)) ?? '' })));
|
|
27
|
+
return files.filter((f) => f.name.endsWith('.md')).map((f) => {
|
|
28
|
+
const { data, body } = parseMarkdown(f.content);
|
|
29
|
+
return { id: f.name.slice(0, -3), collection: name, data, body, filePath: `${dir}/${f.name}` };
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function liveCollection(name: string, now = Date.now()): Promise<LiveEntry[] | null> {
|
|
34
|
+
const c = Object.hasOwn(collections, name) ? collections[name] : null;
|
|
35
|
+
if (!c) return null;
|
|
36
|
+
const sha = await currentHead(now);
|
|
37
|
+
if (!sha) return read(name, c.dir);
|
|
38
|
+
if (cached?.sha !== sha) cached = { sha, byName: new Map() };
|
|
39
|
+
let entries = cached.byName.get(name);
|
|
40
|
+
if (!entries) {
|
|
41
|
+
entries = read(name, c.dir);
|
|
42
|
+
cached.byName.set(name, entries);
|
|
43
|
+
entries.catch(() => { if (cached?.byName.get(name) === entries) cached.byName.delete(name); });
|
|
44
|
+
}
|
|
45
|
+
return entries;
|
|
46
|
+
}
|
package/src/server/middleware.ts
CHANGED
|
@@ -5,6 +5,8 @@ import { activeUser, opts, secret, storage, publicUrl } from './context';
|
|
|
5
5
|
import { SESSION_COOKIE, clearCookieHeader, readSession } from '../core/auth';
|
|
6
6
|
import { roleOf } from '../core/users';
|
|
7
7
|
import { rateLimiter } from '../core/ratelimit';
|
|
8
|
+
import { liveCollection } from './live';
|
|
9
|
+
import { isLiveRoute } from './browse';
|
|
8
10
|
|
|
9
11
|
const PUBLIC = [/^\/edit\/login\/?$/, /^\/edit\/enroll\/?$/, /^\/api\/editor\/auth\//];
|
|
10
12
|
const authAttempts = rateLimiter({ limit: 30, windowMs: 5 * 60_000 });
|
|
@@ -28,10 +30,7 @@ function crossSite(request: Request, url: URL): boolean {
|
|
|
28
30
|
try { return new URL(origin).host !== request.headers.get('host'); } catch { return true; }
|
|
29
31
|
}
|
|
30
32
|
|
|
31
|
-
/**
|
|
32
|
-
* The block editor's preview frame runs the site's own scripts (tabs, accordions) but nothing from
|
|
33
|
-
* other origins: no analytics counting editors, no captchas or chat widgets inside the editor.
|
|
34
|
-
*/
|
|
33
|
+
/** See `frame` below. */
|
|
35
34
|
const SITE_SCRIPTS_ONLY = "; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:";
|
|
36
35
|
|
|
37
36
|
function harden(res: Response, url: URL, sandbox: boolean, frame = false): Response {
|
|
@@ -51,17 +50,25 @@ function harden(res: Response, url: URL, sandbox: boolean, frame = false): Respo
|
|
|
51
50
|
|
|
52
51
|
let warned = false;
|
|
53
52
|
|
|
53
|
+
|
|
54
54
|
export const onRequest = defineMiddleware(async (ctx, next) => {
|
|
55
55
|
if (ctx.isPrerendered) return next(); // public pages, which never carry a session
|
|
56
|
+
// Host list pages rendered here (liveRoutes) read collections from storage. Set on the first
|
|
57
|
+
// on-demand request, never while prerendering, so built pages keep the build's own content.
|
|
58
|
+
(globalThis as any).__PS_LIVE__ ??= liveCollection;
|
|
56
59
|
const { pathname } = ctx.url;
|
|
57
60
|
const { request } = ctx;
|
|
58
61
|
const isEditor = pathname === '/edit' || pathname.startsWith('/edit/') || pathname.startsWith('/api/editor/');
|
|
62
|
+
// A site page rendered live shows saved, unpublished work: editors only.
|
|
63
|
+
const isLive = !isEditor && isLiveRoute(pathname);
|
|
59
64
|
|
|
60
|
-
if (!isEditor) return next();
|
|
65
|
+
if (!isEditor && !isLive) return next();
|
|
61
66
|
|
|
62
67
|
// A form POST here is the Preview button: an unsaved draft shown in its own tab, walled off from the session.
|
|
63
68
|
const sandbox = pathname.startsWith('/edit/preview') && request.method === 'POST' && !(request.headers.get('content-type') ?? '').includes('json');
|
|
64
|
-
|
|
69
|
+
// Site pages shown inside the editor (previews, Browse, live list pages) run the site's own
|
|
70
|
+
// scripts but nothing from other origins: no analytics counting editors, no captchas or chat.
|
|
71
|
+
const frame = request.method === 'GET' && (isLive || /^\/edit\/preview(-item)?\//.test(pathname)) && opts.previewScripts !== 'all';
|
|
65
72
|
const done = (res: Response) => harden(res, ctx.url, sandbox, frame);
|
|
66
73
|
|
|
67
74
|
if (opts.command === 'build' && !warned) {
|
|
@@ -95,10 +102,15 @@ export const onRequest = defineMiddleware(async (ctx, next) => {
|
|
|
95
102
|
if (!who && opts.command === 'build') return done(json({ error: 'no identity from the proxy' }, 401));
|
|
96
103
|
if (who) ctx.locals.editorUser = { id: who, name: who, role: 'admin' };
|
|
97
104
|
}
|
|
105
|
+
// A live site page opened directly rather than inside Browse: show it with the editor's bar.
|
|
106
|
+
// Deployed editors only; in `astro dev` the site's pages stay plain pages.
|
|
107
|
+
if (isLive && opts.command === 'build' && request.method === 'GET' && request.headers.get('sec-fetch-dest') === 'document') {
|
|
108
|
+
return done(new Response(null, { status: 302, headers: { location: `/edit/site?path=${encodeURIComponent(pathname)}` } }));
|
|
109
|
+
}
|
|
98
110
|
const res = await next();
|
|
99
111
|
// The item frame is sandboxed with no scripts, so the site's scripts there would only fail
|
|
100
112
|
// (one console error each); leave them out.
|
|
101
|
-
if (!sandbox && pathname.startsWith('/edit/preview-item/') && (res.headers.get('content-type') ?? '').includes('text/html')) {
|
|
113
|
+
if (!sandbox && pathname.startsWith('/edit/preview-item/') && !ctx.url.searchParams.has('view') && (res.headers.get('content-type') ?? '').includes('text/html')) {
|
|
102
114
|
const html = (await res.text()).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '');
|
|
103
115
|
const headers = new Headers(res.headers); headers.delete('content-length');
|
|
104
116
|
return done(new Response(html, { status: res.status, headers }));
|