@pirateandfox/pagestack 0.1.0-beta.11 → 0.1.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pirate & Fox LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,41 +1,99 @@
1
- # PageStack
1
+ <p align="center">
2
+ <img src="docs/media/logo.svg" width="72" height="72" alt="">
3
+ </p>
4
+ <h1 align="center">PageStack</h1>
5
+
6
+ <p align="center">
7
+ <strong>A block editor for Astro sites. Your content stays in your repo.</strong><br>
8
+ Click a heading on the real page and type. Drag sections around. Press Save, and it's a git commit.
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://www.npmjs.com/package/@pirateandfox/pagestack"><img src="https://img.shields.io/npm/v/@pirateandfox/pagestack/beta?label=npm%20%40beta&color=2563eb" alt="npm beta version"></a>
13
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-1e1e1e" alt="MIT license"></a>
14
+ <img src="https://img.shields.io/badge/status-beta-f59e0b" alt="Beta">
15
+ </p>
16
+
17
+ <p align="center">
18
+ <img src="docs/media/demo.gif" width="860" alt="Editing a bakery's home page in PageStack: clicking a heading to change it, adding a section, and saving">
19
+ </p>
20
+
21
+ ## Why
22
+
23
+ Static Astro sites are fast, cheap and hard to break, and the people who write for them usually
24
+ can't touch them. The usual fix is a headless CMS: another service, another login, content in
25
+ someone else's database, and a site that no longer builds from the repo alone.
26
+
27
+ PageStack takes the other route. It adds an editor **to the site itself**:
28
+
29
+ - **Edit on the real page.** The preview is your site, rendered by your own components. Click text to
30
+ change it, click an image to swap it, press **+** or **/** to add a block. If you've used the
31
+ WordPress block editor, you already know it.
32
+ - **Content is files in your repo.** Pages are JSON, posts are Markdown. Saving writes a file in dev
33
+ and makes **one commit** in production. No database, nothing stored anywhere else. `git log` is
34
+ your revision history.
35
+ - **The public site stays fully static.** `astro build` is unchanged and ships no editor code. The
36
+ editor is a separate small deployment (a Cloudflare Worker or any Node host) that only exists
37
+ when you build it with `EDITOR=1`.
38
+ - **Passkey sign-in.** Touch ID, Face ID, Windows Hello or a security key. No passwords, no user
39
+ database: invite someone with a single-use link.
40
+ - **Draft, stage, publish.** Saves can go to a staging branch, and **Publish changes** puts them live
41
+ in one step, so a dozen edits make one production build.
42
+
43
+ ## How it works
2
44
 
3
- A visual editor for Astro sites where pages are a stack of sections. Git-only: saving is a commit,
4
- the public site stays static, and nothing lives outside the repo.
5
-
6
- - The public site stays **fully static**. `astro build` is unchanged.
7
- - The editor (`/edit/*`, `/api/editor/*`) is on-demand rendered and only exists when asked for:
8
- `EDITOR=dev astro dev`, or a build made with `EDITOR=1` (which adds `@astrojs/node` unless the site has an adapter).
9
- - Pages are JSON documents in the repo (`src/content/pages/<slug>.json`). Saving writes a file
10
- (dev) or makes **one commit** through the GitHub API (production). Nothing is stored anywhere else.
11
- - Login is **passkeys** (WebAuthn). Users' public keys live in a committed `editor-users.json`;
12
- the only server secret is `EDITOR_SECRET`. No database, no session store.
13
- - Live preview renders the real page with the site's own components, in the browser's iframe.
45
+ ```
46
+ your repo on GitHub the editor (edit.example.com)
47
+ ┌──────────────────────────┐ reads ┌───────────────────────────────────┐
48
+ │ src/content/pages/*.json │ ───────────▶ │ your Astro site + PageStack, │
49
+ │ src/content/posts/*.md │ │ built with EDITOR=1 │
50
+ │ public/images/… │ ◀─────────── │ previews use your own components │
51
+ └────────────┬─────────────┘ one commit │ passkey sign-in │
52
+ │ per save └───────────────────────────────────┘
53
+ │ your normal deploy (Pages, Netlify, Vercel…)
54
+ ▼
55
+ ┌──────────────────────────┐
56
+ │ public site: astro build │ static files, no editor code
57
+ └──────────────────────────┘
58
+ ```
14
59
 
15
- Status: **early beta** (`0.1.0-beta.x`). The API will move; pin a version. See [ROADMAP.md](ROADMAP.md)
16
- and [CHANGELOG.md](CHANGELOG.md).
60
+ The editor only needs a GitHub token with *Contents: read and write* on the one repo. It never
61
+ leaves the server.
17
62
 
18
- ## Versions
63
+ ## Try it in two minutes
19
64
 
20
- Published on npm as **`@pirateandfox/pagestack`** (betas under the `beta` dist-tag):
65
+ The repo includes a demo site, an invented bakery called **Crumb & Co.**
21
66
 
22
67
  ```bash
23
- npm install @pirateandfox/pagestack@beta
68
+ git clone https://github.com/pirateandfox/pagestack.git
69
+ cd pagestack/examples/bakery
70
+ npm install
71
+ npm run dev:editor # then open http://localhost:4321/edit
24
72
  ```
25
73
 
26
- Or install from a git tag and bump the tag to upgrade:
74
+ In dev there is no sign-in, and saving writes straight to `examples/bakery/src/content`. Run
75
+ `git diff` afterwards to see exactly what the editor wrote.
27
76
 
28
- ```json
29
- "dependencies": { "@pirateandfox/pagestack": "github:pirateandfox/pagestack#v0.1.0-beta.4" }
30
- ```
77
+ ## Status
78
+
79
+ **Beta** (`0.1.0-beta.x`). It runs real sites today, and the API can still change between betas, so
80
+ pin an exact version. What's solid: block pages, Markdown collections edited in place, media,
81
+ global content, synced patterns, revisions, Browse, passkeys, staging and publish. What's next is
82
+ in the [roadmap](ROADMAP.md); every release is in the [changelog](CHANGELOG.md). Found a security
83
+ problem? See [SECURITY.md](SECURITY.md).
84
+
85
+ ---
86
+
87
+ # Guide
88
+
89
+ ## Install
31
90
 
32
91
  ```bash
33
- npm install # after changing the tag
92
+ npm install @pirateandfox/pagestack@beta --save-exact
34
93
  ```
35
94
 
36
- Releases are tags `vX.Y.Z[-beta.N]` on `main`; each one has a CHANGELOG entry.
95
+ Requires Node 22.23.4+ and Astro 7.2.1+.
37
96
 
38
- ## Install
39
97
 
40
98
  ```js
41
99
  // astro.config.mjs
@@ -152,6 +210,17 @@ const { node, edit } = Astro.props;
152
210
  passes `child(edit, i)` to each child. The `renderer` component takes `{ page, editing }` and
153
211
  renders the page inside the site's normal layout.
154
212
 
213
+ A few things worth knowing while you set up the schema:
214
+
215
+ - **Components can live in the schema or beside it.** The editor strips `component` before sending
216
+ the registry to the browser, so either works. `examples/bakery` keeps them in a separate map
217
+ (`src/sections/components.ts`) so the schema stays plain data.
218
+ - **List View names a block after its first non-empty inline text field**, so put the field people
219
+ recognise (the title) first.
220
+ - **`text` fields are plain text.** Typing in them replaces any markup they held. For a styled word
221
+ in a heading, give the block its own field for it (the bakery's hero has *Word in italics*).
222
+ - **The home page is `src/content/pages/index.json`**, edited at `/edit/index`.
223
+
155
224
  ## Editing
156
225
 
157
226
  Coming from the WordPress block editor:
@@ -336,6 +405,8 @@ than setting a hard limit. Passkeys are what actually stops guessing.
336
405
  With `github.live`, saves stay on `github.branch` (staging) and the public site builds from `live`.
337
406
  Every screen gets a **Publish changes** button (Go live) counting the saved changes the live site doesn't have yet;
338
407
  it lists them, links to `github.stagingUrl` if you give one, and puts them all on `live` in one step.
408
+ Only admins can publish; editors see what's waiting, and their saves stay on staging until an admin
409
+ publishes.
339
410
  That is a fast-forward when nobody committed to `live` directly. When someone did, it makes a merge
340
411
  commit and moves staging to it; when their change conflicts, it refuses and says so, and a person
341
412
  merges in GitHub. A burst of saves becomes one production build. Drafts (the **Ready to publish**
@@ -363,7 +434,9 @@ like any other push.
363
434
  invite links (3 days). Tokens are `base64url(json).base64url(hmac-sha256)` with the expiry inside,
364
435
  so there is no server state.
365
436
  - **Invites** are single-use: the invite id is recorded on the credential it created. Make the first
366
- one from the CLI, later ones from the "Invite another editor" panel on `/edit`:
437
+ one from the CLI, later ones from **Users** (`/edit/users`), which lists invites not used yet and
438
+ lets an admin withdraw one; a withdrawn link stops working at once. Links made with the CLI aren't
439
+ listed there.
367
440
 
368
441
  ```bash
369
442
  EDITOR_SECRET=… npx pagestack-invite --name "Jane Doe" --email jane@example.com --origin https://example.com
@@ -373,6 +446,10 @@ like any other push.
373
446
  - Set `EDITOR_ORIGIN` when a proxy rewrites `Host`; WebAuthn binds credentials to the origin the
374
447
  browser sees.
375
448
  - The signature counter is not persisted (it would mean a commit per login; synced passkeys report 0).
449
+ - Changes to the users file are conditional: when two of them race (two admins, or an invite used
450
+ while an admin edits roles), the later one is re-read and re-applied, so neither is lost.
451
+ - Signing out is a POST from the editor's own pages. Opening `/api/editor/auth/logout` from a link
452
+ only shows a Sign out button, so another site can't sign anyone out.
376
453
 
377
454
  ### `auth: "none-behind-proxy"`
378
455
 
@@ -390,13 +467,36 @@ Dev only. A build with `auth: "none"` is refused.
390
467
 
391
468
  ## Deploying the editor
392
469
 
393
- Requires Node 22.23.4+ and Astro 7.2.1+. On Cloudflare, add `@astrojs/cloudflare` as the host's
394
- adapter and set `EDITOR_SECRET`, `EDITOR_ORIGIN` and `GITHUB_TOKEN` as secrets.
470
+ Requires Node 22.23.4+ and Astro 7.2.1+.
471
+
472
+ **On Cloudflare Workers**, add `@astrojs/cloudflare` as the host's adapter in the editor build only,
473
+ and give the Worker three secrets: `EDITOR_SECRET` (32+ random characters), `EDITOR_ORIGIN` (its
474
+ https address) and `GITHUB_TOKEN`. Until `EDITOR_SECRET` and `GITHUB_TOKEN` are set, every editor page says
475
+ which one is missing. PageStack takes care of the rest: in the editor build it wraps the adapter's Worker entry
476
+ and sets `assets.run_worker_first` in the generated `dist/server/wrangler.json`, so the built copies
477
+ of your site pages need a sign-in and, opened directly, land in Browse.
478
+
479
+ ```js
480
+ // astro.config.mjs: the adapter only in the editor's build
481
+ const editorBuild = process.env.EDITOR === '1' && process.argv.includes('build');
482
+ const { default: cloudflare } = editorBuild ? await import('@astrojs/cloudflare') : {};
483
+ export default defineConfig({
484
+ ...(cloudflare ? { adapter: cloudflare({ configPath: 'wrangler.editor.jsonc' }) } : {}),
485
+ // …
486
+ });
487
+ ```
488
+
489
+ ```bash
490
+ EDITOR=1 astro build && wrangler deploy --config dist/server/wrangler.json
491
+ EDITOR_SECRET=… npx pagestack-invite --name "You" --email you@example.com --origin https://edit.example.com
492
+ ```
395
493
 
396
- The editor server is a normal `@astrojs/node` standalone build. Run `node dist/server/entry.mjs`
494
+ **On a Node host**, the editor server is a normal `@astrojs/node` standalone build. Run `node dist/server/entry.mjs`
397
495
  on any small Node host (Fly, Railway, a VPS…) with `EDITOR_SECRET`, `GITHUB_TOKEN` and
398
496
  `EDITOR_ORIGIN` set, behind HTTPS. It serves the editor routes and the static pages it was built
399
- with; the public site is still deployed separately from the same repo as static files. Every
497
+ with; the public site is still deployed separately from the same repo as static files. (Here the
498
+ built site pages are served as plain files, without a sign-in; put the host behind an access proxy
499
+ if staged work must stay private.) Every
400
500
  editor response is `noindex` and `no-store`.
401
501
 
402
502
  ## Options
@@ -429,4 +529,4 @@ editor response is `noindex` and `no-store`.
429
529
  - [@astrojs/node](https://docs.astro.build/en/guides/integrations-guide/node/) (MIT) as the editor's adapter.
430
530
  - [Puck](https://puckeditor.com) was used as a design reference for JSON page editing only; no code.
431
531
 
432
- MIT.
532
+ MIT © Pirate & Fox LLC. See [LICENSE](LICENSE).
package/index.mjs CHANGED
@@ -21,11 +21,29 @@ function writeEditorHeaders(clientDir, previewScripts) {
21
21
  if (!fs.existsSync(clientDir)) return;
22
22
  const file = path.join(clientDir, '_headers');
23
23
  const scripts = previewScripts === 'all' ? "script-src-attr 'none'" : "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:; script-src-attr 'none'";
24
- const block = `\n# pagestack: built pages served by the editor\n/*\n Content-Security-Policy: ${scripts}; object-src 'none'; base-uri 'self'; frame-ancestors 'self'\n X-Frame-Options: SAMEORIGIN\n`;
24
+ const block = `\n# pagestack: built pages served by the editor\n/*\n Content-Security-Policy: ${scripts}; object-src 'none'; base-uri 'self'; frame-ancestors 'self'\n X-Frame-Options: SAMEORIGIN\n X-Robots-Tag: noindex\n`;
25
25
  const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
26
26
  if (!existing.includes('# pagestack: built pages served by the editor')) fs.writeFileSync(file, existing + block);
27
27
  }
28
28
 
29
+ /**
30
+ * Cloudflare serves files in the assets directory before the Worker runs, which would put every
31
+ * built site page on the editor's domain with no sign-in. Send everything but hashed build assets
32
+ * through the Worker (src/worker.ts decides). Leaves a host's own `run_worker_first` alone.
33
+ */
34
+ function routeThroughWorker(serverDir, logger) {
35
+ const file = path.join(serverDir, 'wrangler.json');
36
+ if (!fs.existsSync(file)) return;
37
+ const conf = JSON.parse(fs.readFileSync(file, 'utf8'));
38
+ if (!conf.assets) return;
39
+ if (conf.assets.run_worker_first === undefined) {
40
+ conf.assets.run_worker_first = ['/*', '!/_astro/*'];
41
+ fs.writeFileSync(file, JSON.stringify(conf));
42
+ } else if (conf.assets.run_worker_first === false) {
43
+ logger?.warn('wrangler assets.run_worker_first is false: built site pages on the editor are served without sign-in.');
44
+ }
45
+ }
46
+
29
47
  const VIRTUAL = 'virtual:pagestack/site';
30
48
  const VIRTUAL_RENDERER = 'virtual:pagestack/renderer';
31
49
  const VIRTUAL_PREVIEWS = 'virtual:pagestack/previews';
@@ -107,13 +125,18 @@ export default function sectionEditor(userOptions) {
107
125
  hooks: {
108
126
  ...forwarded,
109
127
  'astro:config:done': async (params) => {
110
- if (editorBuild) editorBuild.dirs = [params.config.build.client, params.config.outDir]; // with an adapter, files go to build.client
128
+ if (editorBuild) {
129
+ editorBuild.dirs = [params.config.build.client, params.config.outDir]; // with an adapter, files go to build.client
130
+ editorBuild.server = params.config.build.server;
131
+ editorBuild.logger = params.logger;
132
+ }
111
133
  await forwarded['astro:config:done'](params);
112
134
  },
113
135
  'astro:build:done': async (params) => {
114
136
  await forwarded['astro:build:done'](params);
115
137
  const dir = editorBuild?.dirs?.map((u) => fileURLToPath(u)).find((d) => fs.existsSync(d));
116
138
  if (dir) writeEditorHeaders(dir, editorBuild.previewScripts);
139
+ if (editorBuild?.cloudflare && editorBuild.server) routeThroughWorker(fileURLToPath(editorBuild.server), editorBuild.logger);
117
140
  },
118
141
  // List pages named in `liveRoutes` render on request on the editor's server, reading what
119
142
  // has been saved. Only in the editor build: the public build never gets here.
@@ -169,7 +192,37 @@ export default function sectionEditor(userOptions) {
169
192
  vite: {
170
193
  plugins: [{
171
194
  name: 'pagestack:virtual',
172
- resolveId(id) { if (id === VIRTUAL || id === VIRTUAL_RENDERER || id === VIRTUAL_PREVIEWS) return '\0' + id; },
195
+ enforce: 'pre',
196
+ // A save in dev writes files the site's routes import, and Vite answers with a full
197
+ // reload of every open page, the editor included. Drop reloads caused by the editor's
198
+ // own writes (src/core/storage-local.ts); the editor refreshes its preview itself.
199
+ configureServer(server) {
200
+ const recent = () => {
201
+ const writes = globalThis.__PS_WRITES__;
202
+ if (!writes) return false;
203
+ const now = Date.now();
204
+ for (const [f, t] of writes) if (now - t > 3000) writes.delete(f);
205
+ return writes.size > 0;
206
+ };
207
+ const own = (payload) => {
208
+ if (payload?.type !== 'full-reload' || !recent()) return false;
209
+ const by = payload.triggeredBy ? path.resolve(payload.triggeredBy) : null;
210
+ return !by || globalThis.__PS_WRITES__.has(by) || /\.(json|md|mdx)$/.test(by);
211
+ };
212
+ const channels = [server.ws, ...Object.values(server.environments ?? {}).map((e) => e.hot)].filter(Boolean);
213
+ for (const ch of new Set(channels)) {
214
+ const send = ch.send.bind(ch);
215
+ ch.send = (payload, ...rest) => { if (!own(payload)) send(payload, ...rest); };
216
+ }
217
+ },
218
+ resolveId(id) {
219
+ if (id === VIRTUAL || id === VIRTUAL_RENDERER || id === VIRTUAL_PREVIEWS) return '\0' + id;
220
+ // On Cloudflare the editor's Worker checks site pages before the adapter (src/worker.ts).
221
+ if (isBuild && /^@astrojs\/cloudflare\/entrypoints\/server(\.js)?$/.test(id)) {
222
+ editorBuild.cloudflare = true;
223
+ return fileURLToPath(new URL('./src/worker.ts', import.meta.url));
224
+ }
225
+ },
173
226
  load(id) {
174
227
  // The renderer (and the site layout/CSS behind it) is only imported by the preview
175
228
  // route, so the editor shell doesn't drag the whole site's CSS into its page.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@pirateandfox/pagestack",
3
- "version": "0.1.0-beta.11",
4
- "description": "PageStack: visual section editor for Astro sites. Git-only, static public site, passkey login, saves are commits.",
3
+ "version": "0.1.0-beta.13",
4
+ "description": "A block editor for Astro sites. Content stays in your repo, saves are git commits, the public site stays static, sign-in is passkeys.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "bin": {
@@ -23,7 +23,8 @@
23
23
  "test": "vitest run"
24
24
  },
25
25
  "peerDependencies": {
26
- "astro": ">=7.2.1"
26
+ "astro": ">=7.2.1",
27
+ "@astrojs/cloudflare": ">=13"
27
28
  },
28
29
  "dependencies": {
29
30
  "@astrojs/node": "11.1.11",
@@ -46,7 +47,14 @@
46
47
  "visual-editor",
47
48
  "cms",
48
49
  "git-based-cms",
49
- "sections"
50
+ "sections",
51
+ "astro",
52
+ "block-editor",
53
+ "page-builder",
54
+ "static-site",
55
+ "passkeys",
56
+ "webauthn",
57
+ "cloudflare-workers"
50
58
  ],
51
59
  "repository": {
52
60
  "type": "git",
@@ -58,5 +66,14 @@
58
66
  },
59
67
  "engines": {
60
68
  "node": ">=22.23.4"
61
- }
69
+ },
70
+ "peerDependenciesMeta": {
71
+ "@astrojs/cloudflare": {
72
+ "optional": true
73
+ }
74
+ },
75
+ "bugs": {
76
+ "url": "https://github.com/pirateandfox/pagestack/issues"
77
+ },
78
+ "author": "Pirate & Fox LLC (https://pirateandfox.com)"
62
79
  }
@@ -784,7 +784,7 @@ $('#ps-more').addEventListener('click', (e) => {
784
784
  { label: 'Revisions', run: showRevisions },
785
785
  { label: 'All pages', run: () => { location.href = '/edit'; }, separator: true },
786
786
  ];
787
- if (boot.options.auth === 'passkey' && boot.options.user) items.push({ label: `Sign out ${boot.options.user}`, run: () => { location.href = '/api/editor/auth/logout'; } });
787
+ if (boot.options.auth === 'passkey' && boot.options.user) items.push({ label: `Sign out ${boot.options.user}`, run: async () => { await fetch('/api/editor/auth/logout', { method: 'POST', headers: { accept: 'application/json' } }).catch(() => {}); location.href = '/edit/login'; } });
788
788
  openMenu(e.currentTarget as HTMLElement, items);
789
789
  });
790
790
 
@@ -14,4 +14,5 @@ form?.addEventListener('submit', async (e) => {
14
14
  copy.addEventListener('click', async () => { await navigator.clipboard.writeText(data.url); copy.textContent = 'Copied'; });
15
15
  const hint = Object.assign(document.createElement('small'), { className: 'ps-muted', textContent: `Send this link to ${fd.get('name')}. It works once and expires in ${Math.round(data.expiresIn / 86400)} days.` });
16
16
  out.append(input, copy, hint);
17
+ document.dispatchEvent(new CustomEvent('ps:invited'));
17
18
  });
@@ -3,7 +3,7 @@
3
3
  // on the public site. It refreshes itself after any save, wherever on the screen that happened.
4
4
  import { dialog, toast } from './ui';
5
5
 
6
- interface Pending { enabled: true; branch: string; live: string; count: number; changes: { sha: string; message: string; author: string; date: string }[]; stagingUrl: string | null }
6
+ interface Pending { enabled: true; branch: string; live: string; count: number; changes: { sha: string; message: string; author: string; date: string }[]; stagingUrl: string | null; canPublish?: boolean }
7
7
 
8
8
  const btn = document.getElementById('ps-live') as HTMLButtonElement | null;
9
9
  let state: Pending | null = null;
@@ -24,7 +24,8 @@ function draw() {
24
24
  btn.disabled = n === 0;
25
25
  btn.textContent = 'Publish changes';
26
26
  if (n) { const b = document.createElement('span'); b.className = 'ps-live__count'; b.textContent = String(n); btn.append(b); }
27
- btn.title = n ? `${n} saved change${n === 1 ? '' : 's'} not on the live site yet` : 'Everything saved is on the live site';
27
+ btn.title = !n ? 'Everything saved is on the live site'
28
+ : `${n} saved change${n === 1 ? '' : 's'} not on the live site yet${state.canPublish === false ? '. An admin publishes them.' : ''}`;
28
29
  }
29
30
 
30
31
  let inflight: Promise<void> | null = null;
@@ -54,6 +55,7 @@ async function goLive() {
54
55
  const meta = document.createElement('span'); meta.className = 'ps-muted'; meta.textContent = [c.author, ago(c.date)].filter(Boolean).join(' · ');
55
56
  li.append(what, meta); list.append(li);
56
57
  }
58
+ if (state.canPublish === false) intro.textContent = `${state.count} saved change${state.count === 1 ? ' is' : 's are'} waiting for the public site. Only an admin can publish them; nothing is lost in the meantime.`;
57
59
  body.append(intro, list);
58
60
  if (state.count > state.changes.length) { const more = document.createElement('p'); more.className = 'ps-muted'; more.textContent = `…and ${state.count - state.changes.length} earlier.`; body.append(more); }
59
61
  if (state.stagingUrl) {
@@ -61,6 +63,7 @@ async function goLive() {
61
63
  a.href = state.stagingUrl; a.target = '_blank'; a.rel = 'noopener'; a.textContent = 'See them on the staging site first ↗';
62
64
  p.append(a); body.append(p);
63
65
  }
66
+ if (state.canPublish === false) { dialog('Waiting to publish', body, [{ label: 'Close', kind: 'primary' }], { wide: true }); return; }
64
67
  dialog('Publish changes?', body, [
65
68
  { label: 'Cancel' },
66
69
  {
@@ -62,3 +62,6 @@ body[data-ps-typing] .ps-toolbar { display: none; }
62
62
  .ps-popmenu button.is-danger { color: #b91c1c; }
63
63
  .ps-popmenu kbd { font: inherit; color: #6b7280; }
64
64
  .ps-popmenu hr { width: 100%; border: 0; border-top: 1px solid #e2e4e8; margin: 4px 0; }
65
+
66
+ /* Astro's dev toolbar belongs to the site's developer, not the person editing in the preview. */
67
+ astro-dev-toolbar { display: none !important; }
@@ -332,8 +332,12 @@ body.ps-browse { margin: 0; height: 100vh; display: grid; grid-template-rows: au
332
332
  .ps-browse__actions { display: flex; align-items: center; gap: 10px; }
333
333
  .ps-browse__actions .ps-btn { padding: 5px 12px; }
334
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; }
335
+ /* Sign out is a form (a POST), drawn as a link. */
336
+ .ps-signout { display: inline; margin: 0; }
337
+ .ps-signout button { all: unset; cursor: pointer; color: inherit; text-decoration: underline; }
338
+ .ps-signout button:focus-visible { outline: 2px solid #3b82f6; outline-offset: 2px; }
339
+ .ps-browse__out button { color: #9ca3af; text-decoration: none; }
340
+ .ps-browse__out button:hover { color: #fff; }
337
341
  .ps-browse__frame { width: 100%; height: 100%; border: 0; background: #fff; grid-row: 2; grid-column: 1; }
338
342
  /* While the frame loads: a moving strip under the bar and a word in the middle, not a blank page. */
339
343
  .ps-browse__bar { position: relative; }
@@ -361,3 +365,8 @@ body.ps-browse { margin: 0; height: 100vh; display: grid; grid-template-rows: au
361
365
  .ps-switch input:focus-visible + .ps-switch__track { outline: 2px solid #2563eb; outline-offset: 2px; }
362
366
  .ps-switch:has(input:disabled) { cursor: default; opacity: .6; }
363
367
  @media (prefers-reduced-motion: reduce) { .ps-switch__track, .ps-switch__track::after { transition: none; } }
368
+
369
+ /* Users: invites not used yet */
370
+ .ps-invites { margin: 28px 0 8px; }
371
+ .ps-invites[hidden] { display: none; }
372
+ .ps-invites h2 { font-size: 15px; font-weight: 600; margin: 0 0 8px; }
@@ -1,17 +1,21 @@
1
- // The Users screen.
1
+ // The Users screen: people, their passkeys, and invites not used yet.
2
2
  import { confirmDialog, toast } from './ui';
3
3
 
4
4
  interface Passkey { id: string; label: string | null; createdAt: string; synced: boolean }
5
5
  interface User { id: string; name: string; email: string; role: 'admin' | 'editor'; passkeys: Passkey[] }
6
+ interface Invite { id: string; name: string; email: string; role: 'admin' | 'editor'; createdAt: string; expiresAt: string; by?: string }
6
7
  const list = document.getElementById('ps-users')!;
8
+ const waiting = document.getElementById('ps-invites');
7
9
 
8
10
  async function call(method: string, body?: unknown) {
9
11
  const res = await fetch('/api/editor/users', { method, headers: { 'content-type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}) });
10
12
  const data = await res.json();
11
13
  if (!res.ok) { toast(data.error || 'That did not work.', 'error'); return load(); }
12
- draw(data.users);
14
+ draw(data.users); drawInvites(data.invites ?? []);
13
15
  }
14
- async function load() { const r = await fetch('/api/editor/users'); draw((await r.json()).users ?? []); }
16
+ async function load() { const r = await fetch('/api/editor/users'); const d = await r.json(); draw(d.users ?? []); drawInvites(d.invites ?? []); }
17
+ // The invite form says when it made a new link.
18
+ document.addEventListener('ps:invited', () => { load(); });
15
19
 
16
20
  const text = (tag: string, s: string, cls?: string) => { const e = document.createElement(tag); e.textContent = s; if (cls) e.className = cls; return e; };
17
21
 
@@ -37,4 +41,24 @@ function draw(users: User[]) {
37
41
  return li;
38
42
  }));
39
43
  }
44
+
45
+ function timeLeft(iso: string): string {
46
+ const h = Math.max(0, Math.round((Date.parse(iso) - Date.now()) / 3_600_000));
47
+ return h >= 24 ? `${Math.round(h / 24)} day${Math.round(h / 24) === 1 ? '' : 's'} left` : `${h} h left`;
48
+ }
49
+
50
+ function drawInvites(invites: Invite[]) {
51
+ if (!waiting) return;
52
+ waiting.hidden = !invites.length;
53
+ waiting.querySelector('ul')!.replaceChildren(...invites.map((i) => {
54
+ const li = document.createElement('li'); li.dataset.invite = i.email;
55
+ const who = document.createElement('div'); who.className = 'ps-pagelist__edit';
56
+ who.append(text('strong', i.name), text('span', [i.email, i.role === 'admin' ? 'Admin' : 'Editor', timeLeft(i.expiresAt), i.by ? `invited by ${i.by}` : ''].filter(Boolean).join(' · '), 'ps-muted'));
57
+ const del = text('button', 'Withdraw', 'ps-btn ps-btn--small ps-btn--ghost ps-btn--danger') as HTMLButtonElement; del.type = 'button';
58
+ del.addEventListener('click', async () => { if (await confirmDialog('Withdraw invite', `The link sent to ${i.name} stops working at once. You can invite them again later.`, 'Withdraw', 'danger')) call('DELETE', { invite: i.id }); });
59
+ li.append(who, del);
60
+ return li;
61
+ }));
62
+ }
63
+
40
64
  load();
@@ -8,7 +8,7 @@
8
8
  // branch goes away. Keeping them in the repo rather than in memory means an upload and the save
9
9
  // after it can land on different server instances (Workers), and a restart loses nothing.
10
10
  import type { CommitResult, FileChange, PendingChanges, Revision, Storage } from './storage';
11
- import { fromBase64, isSha, safeRelPath, toBase64 } from './storage';
11
+ import { fromBase64, isSha, safeRelPath, StaleWrite, toBase64 } from './storage';
12
12
 
13
13
  export interface GitHubOptions {
14
14
  /** "owner/name" */
@@ -199,13 +199,16 @@ export class GitHubStorage implements Storage {
199
199
  }
200
200
 
201
201
  async readAt(p: string, sha: string): Promise<string | null> {
202
- if (!isSha(sha)) return null;
203
- const data = await this.req<any>('GET', `${this.repoUrl}/contents/${encodePath(safeRelPath(p))}?ref=${sha}`, undefined, true);
202
+ return isSha(sha) ? this.textAt(p, sha) : null;
203
+ }
204
+ /** `ref` here is trusted: a branch name or a sha this adapter got from GitHub itself. */
205
+ private async textAt(p: string, ref: string): Promise<string | null> {
206
+ const data = await this.req<any>('GET', `${this.repoUrl}/contents/${encodePath(safeRelPath(p))}?ref=${encodeURIComponent(ref)}`, undefined, true);
204
207
  if (!data || data.type !== 'file') return null;
205
208
  return new TextDecoder().decode(fromBase64(String(data.content).replace(/\n/g, '')));
206
209
  }
207
210
 
208
- async commit({ message, files, deletes = [] }: { message: string; files: FileChange[]; deletes?: string[] }): Promise<CommitResult> {
211
+ async commit({ message, files, deletes = [], expect }: { message: string; files: FileChange[]; deletes?: string[]; expect?: Record<string, string | null> }): Promise<CommitResult> {
209
212
  const all: FileChange[] = files.map((f) => ({ ...f, path: safeRelPath(f.path) }));
210
213
  const removed = deletes.map(safeRelPath);
211
214
  const uploads = (await this.waiting()).filter((u) => !removed.includes(u.path));
@@ -213,6 +216,9 @@ export class GitHubStorage implements Storage {
213
216
  const base = await this.req<any>('GET', `${this.repoUrl}/git/ref/heads/${encodeURIComponent(this.branch)}`);
214
217
  const baseSha: string = base.object.sha;
215
218
  const baseCommit = await this.req<any>('GET', `${this.repoUrl}/git/commits/${baseSha}`);
219
+ for (const [p, want] of Object.entries(expect ?? {})) {
220
+ if ((await this.textAt(p, baseSha)) !== want) throw new StaleWrite(p);
221
+ }
216
222
 
217
223
  const tree: { path: string; mode: string; type: string; sha: string | null }[] = [...removed.map((path) => ({ path, mode: '100644', type: 'blob', sha: null })), ...uploads];
218
224
  for (const f of all) {
@@ -230,7 +236,10 @@ export class GitHubStorage implements Storage {
230
236
  const pr = await this.req<any>('POST', `${this.repoUrl}/pulls`, { title: message, head: branch, base: this.branch, body: `Opened by the site editor.\n\nFiles:\n${[...all.map((f) => f.path), ...uploads.map((u) => u.path), ...removed].map((f) => `- ${f}`).join('\n')}` });
231
237
  pullRequest = pr.html_url;
232
238
  } else {
233
- await this.req('PATCH', `${this.repoUrl}/git/refs/heads/${encodeURIComponent(this.branch)}`, { sha: commit.sha, force: false });
239
+ const moved = await this.raw('PATCH', `${this.repoUrl}/git/refs/heads/${encodeURIComponent(this.branch)}`, { sha: commit.sha, force: false });
240
+ // Not a fast-forward: another save landed after this one read the branch.
241
+ if (moved.status === 422 && expect) throw new StaleWrite(Object.keys(expect)[0]);
242
+ if (!moved.ok) throw new Error(`GitHub PATCH ${this.branch} -> ${moved.status} ${(await moved.text()).slice(0, 300)}`);
234
243
  }
235
244
  if (uploads.length) await this.req('DELETE', `${this.repoUrl}/git/refs/heads/${UPLOADS}`, undefined, true).catch(() => { /* an empty next commit is harmless */ });
236
245
  return { kind: 'github', files: [...all.map((f) => f.path), ...uploads.map((u) => u.path), ...removed], commit: commit.sha, url: commit.html_url ?? `https://github.com/${this.opts.repo}/commit/${commit.sha}`, branch, pullRequest };
@@ -6,7 +6,7 @@ import path from 'node:path';
6
6
  import { execFile } from 'node:child_process';
7
7
  import { promisify } from 'node:util';
8
8
  import type { CommitResult, FileChange, Revision, Storage } from './storage';
9
- import { isSha, safeRelPath } from './storage';
9
+ import { isSha, safeRelPath, StaleWrite } from './storage';
10
10
 
11
11
  const run = promisify(execFile);
12
12
 
@@ -42,16 +42,22 @@ export class LocalStorage implements Storage {
42
42
  }
43
43
  async putAsset(p: string, bytes: Uint8Array): Promise<void> {
44
44
  const f = this.abs(p);
45
+ noteWrite(f);
45
46
  await fs.mkdir(path.dirname(f), { recursive: true });
46
47
  await fs.writeFile(f, bytes);
47
48
  }
48
- async commit({ files, deletes = [] }: { message: string; files: FileChange[]; deletes?: string[] }): Promise<CommitResult> {
49
+ async commit({ files, deletes = [], expect }: { message: string; files: FileChange[]; deletes?: string[]; expect?: Record<string, string | null> }): Promise<CommitResult> {
50
+ for (const [p, want] of Object.entries(expect ?? {})) {
51
+ const now = await fs.readFile(this.abs(p), 'utf8').catch(() => null);
52
+ if (now !== want) throw new StaleWrite(p);
53
+ }
49
54
  for (const f of files) {
50
55
  const abs = this.abs(f.path);
56
+ noteWrite(abs);
51
57
  await fs.mkdir(path.dirname(abs), { recursive: true });
52
58
  await fs.writeFile(abs, f.content);
53
59
  }
54
- for (const p of deletes) await fs.rm(this.abs(p), { force: true });
60
+ for (const p of deletes) { noteWrite(this.abs(p)); await fs.rm(this.abs(p), { force: true }); }
55
61
  return { kind: 'local', files: [...files.map((f) => f.path), ...deletes] };
56
62
  }
57
63
  /** Reads the working tree's git log; a folder that isn't a repository simply has no history. */
@@ -69,3 +75,12 @@ export class LocalStorage implements Storage {
69
75
  async pendingAsset(): Promise<undefined> { return undefined; }
70
76
  async asset(): Promise<undefined> { return undefined; } // the dev server serves the working tree
71
77
  }
78
+
79
+ /**
80
+ * Files the editor just wrote, so the dev server doesn't answer its own save with a full page
81
+ * reload (which would throw away the editor's selection and undo history). Read in index.mjs.
82
+ */
83
+ function noteWrite(abs: string) {
84
+ const g = globalThis as any;
85
+ (g.__PS_WRITES__ ??= new Map<string, number>()).set(path.resolve(abs), Date.now());
86
+ }