@unbase-app/pages 0.0.0-stage → 0.4.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jens van der Blij
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,3 +1,139 @@
1
- # Temporary Holding Version
1
+ # @unbase-app/pages
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Keeps draft pages out of a site's production build. A page marked as a draft stays off the live
4
+ site however often the rest is published, while previews and the dev server show it as it is.
5
+
6
+ It is a build step only: an Astro integration and a Vite plugin for React Router apps. Nothing it
7
+ does reaches a visitor's browser, and it never calls a hosted service. Made for
8
+ [Unbase](https://unbase.app), which writes the list of drafts; it works the same without it.
9
+
10
+ An Astro site with Unbase gets it through [`@unbase-app/astro`](../astro), which brings it with
11
+ comment mode in one line; use it on its own for a site without comment mode, or with Vite. Until
12
+ 03-11-2026 it was `@jens4m/unbase-pages`.
13
+
14
+ ```bash
15
+ npm install --save-exact @unbase-app/pages
16
+ ```
17
+
18
+ ## Astro
19
+
20
+ ```js
21
+ // astro.config.mjs
22
+ import { defineConfig } from "astro/config";
23
+ import sitemap from "@astrojs/sitemap";
24
+ import unbasePages from "@unbase-app/pages/astro";
25
+
26
+ export default defineConfig({
27
+ // Last, or at least after sitemap() and comment-modus: it cleans the page lists they write.
28
+ integrations: [sitemap(), unbasePages()],
29
+ });
30
+ ```
31
+
32
+ ## Vite + React Router
33
+
34
+ ```js
35
+ // vite.config.ts
36
+ import react from "@vitejs/plugin-react";
37
+ import { unbasePages } from "@unbase-app/pages/vite";
38
+
39
+ export default { plugins: [react(), unbasePages()] };
40
+ ```
41
+
42
+ [`@unbase-app/vite`](../vite) carries this plugin, an exact copy, together with comment mode's
43
+ loader: a Vite site Unbase installs gets that one package instead (`unbase()`), never both.
44
+
45
+ ## Which pages are drafts
46
+
47
+ `unbase.pages.json` at the app's root lists them. Without the file, or without a draft in it, the
48
+ build is untouched.
49
+
50
+ ```json
51
+ { "pages": { "/pricing-2027": { "draft": true } } }
52
+ ```
53
+
54
+ ## What a production build does with a draft
55
+
56
+ - **Its page is not built.** Astro: the page file compiles to an empty page, so nothing it imports
57
+ is bundled, and its HTML is removed. React Router: its `<Route />` leaves the router and its
58
+ module becomes empty, so the address falls to the app's own Not Found.
59
+ - **Its address leaves every page list:** sitemaps, comment-modus's `pages.json` and content map,
60
+ and the entries the page owns in Astro's content store.
61
+ - **The output is checked for its text.** If a sentence only the draft has is still in a served
62
+ file, the build stops.
63
+
64
+ ## Which builds are production
65
+
66
+ `UNBASE_DEPLOY_CONTEXT` (`production`, `preview`, `development`) when it is set; otherwise a dev
67
+ server is development, and the host decides (`VERCEL_ENV`, Netlify's `CONTEXT`). Anything else
68
+ counts as production, so a draft only shows where a host says it is a preview. `NODE_ENV` is never
69
+ read: previews are production-optimised builds too.
70
+
71
+ ## Fails closed
72
+
73
+ A production build stops, with the page and the reason, when a draft cannot be kept out: a
74
+ dynamic route, a page another file imports, content it cannot attribute to the page, an invalid
75
+ `unbase.pages.json`, or a draft's text still in the output. Mark the page as ready, or fix the
76
+ reason, and build again.
77
+
78
+ ## Page actions and redirects
79
+
80
+ Unbase renames, duplicates and deletes pages by one rule, the core's `planPage`: the same files
81
+ always give the same changes, in Unbase's editor and with `npx @unbase-app/cli page …` alike. A
82
+ page that was on the live site leaves a redirect when it is renamed or deleted, in the same file:
83
+
84
+ ```json
85
+ { "pages": { "/financiering": { "name": "Financiering" } }, "redirects": { "/funding": "/financiering" } }
86
+ ```
87
+
88
+ A source that ends in `/[...path]` sends everything under it on, the rest of the address kept
89
+ (`/over-ons/[...path]` → `/about/[...path]`): a renamed page's pages under it.
90
+
91
+ From 0.4.0 the build applies them, in the dev server and every build alike:
92
+
93
+ - **Astro**: as Astro redirects, permanent (308). In a prerendered site (Astro's default) a
94
+ redirect for everything under an address becomes one redirect per page under the new address,
95
+ because Astro only takes `[...path]` there when a dynamic route is at its destination.
96
+ - **Vite + React Router**: as routes in the router file's `<Routes>`, before the catch-all: an
97
+ address sent on renders `<Navigate to replace />`, everything under one a small component that
98
+ keeps the rest of the address, its query and its hash. A single-page app has no server status
99
+ to give, so this is a client redirect, and it works on any host.
100
+
101
+ The site's own redirects win: one Astro's config already has, to the same place, stays the
102
+ site's; the same address sent somewhere else stops the build. A redirect whose address is a page
103
+ again is not applied (the page wins), and the build says so. An invalid `unbase.pages.json` stops
104
+ a build; the dev server warns and goes on.
105
+
106
+ Unbase only renames or deletes a live page on a site whose package applies redirects
107
+ (`REDIRECTS_SINCE` in the core: this package 0.4.0, `@unbase-app/astro`, `/vite` and `/next`
108
+ 0.3.0), so an old address never breaks silently.
109
+
110
+ ## Removing it
111
+
112
+ Publish or delete the drafts first: without the package, a draft in `unbase.pages.json` is
113
+ simply built. Its redirects go with it too: move them into the site's own config first. Then
114
+ remove the package, its line in the config, and `unbase.pages.json`.
115
+
116
+ ## Exports
117
+
118
+ | | |
119
+ |---|---|
120
+ | `@unbase-app/pages/astro` | The Astro integration (default export, and `unbasePages`) |
121
+ | `@unbase-app/pages/vite` | The Vite plugin (`unbasePages`) |
122
+ | `@unbase-app/pages` | The core: discovering a site's pages, checking a draft, and planning a page action (`planPage`, `pageActions`, `redirectsFor`), as pure functions on the app's files |
123
+
124
+ Node 18.17 or newer. MIT licence.
125
+
126
+ ## Developing
127
+
128
+ Part of the kit (see its README; `npm test` there). `core.mjs` is the one implementation of page
129
+ discovery and the draft check; Unbase's backend and the Vite and Next.js packages run exact copies
130
+ (`supabase/functions/_shared/pages-core.mjs` in Unbase's repository, `vite/pages/core.mjs` and
131
+ `next/core.mjs` in the kit; tests fail when they differ): after changing it, `cp kit/pages/core.mjs
132
+ supabase/functions/_shared/pages-core.mjs`, `node vite/scripts/sync-pages.mjs` and `cp
133
+ pages/core.mjs next/core.mjs`.
134
+
135
+ - `node --test test/*.test.mjs`: the core (`core.test.mjs`), the page actions (`actions.test.mjs`) and the redirects in Astro and Vite (`redirects.test.mjs`).
136
+ - A11, the acceptance test, on lab sites only: `node test/a11.mjs vibe` (the Lovable-shaped
137
+ fixture in `test/fixtures/lab-vibe`) and `node test/a11.mjs astro --dir <lab copy>` (a git
138
+ repository without a remote). It needs `playwright-core` (`PLAYWRIGHT_CORE=<path>`) and Chrome
139
+ (`CHROME_PATH`).
package/astro.d.mts ADDED
@@ -0,0 +1,29 @@
1
+ import type { AstroIntegration } from "astro";
2
+
3
+ /**
4
+ * The Astro integration: in a production build every draft in unbase.pages.json is kept out, or
5
+ * the build stops; in every command the addresses its `redirects` send on become Astro redirects
6
+ * (308). Put it after sitemap() and comment-modus in `integrations`.
7
+ */
8
+ declare function unbasePages(): AstroIntegration;
9
+ export default unbasePages;
10
+ export { unbasePages };
11
+
12
+ /** Astro's content store without the entries the drafts own (used by the integration; exported for its tests). */
13
+ export declare function withoutDraftEntries(
14
+ code: string,
15
+ owned: Set<string>,
16
+ devalue: { unflatten(value: unknown): unknown; stringify(value: unknown): string },
17
+ ): { code: string; removed: string[] };
18
+
19
+ /**
20
+ * unbase.pages.json's redirects as Astro's `redirects` takes them, or null when it has none. Throws
21
+ * when one conflicts with the site's own (`own`) or the file is not valid (used by the integration;
22
+ * exported for its tests).
23
+ */
24
+ export declare function astroRedirects(input: {
25
+ root: string;
26
+ own?: Record<string, string | { destination: string }> | null;
27
+ prerender?: boolean;
28
+ warn?: (line: string) => void;
29
+ }): Record<string, { status: 308; destination: string }> | null;
package/astro.mjs ADDED
@@ -0,0 +1,202 @@
1
+ // @ts-check
2
+ // ============================================================================
3
+ // @unbase-app/pages/astro — the Astro integration. In a production build
4
+ // every draft in unbase.pages.json is kept out: its page file becomes an empty
5
+ // page before Astro compiles it (so nothing it imports is bundled), its HTML
6
+ // is removed afterwards, and its address and the content it owns leave every
7
+ // page list (sitemaps, comment-modus/pages.json and the content map). Then
8
+ // the output is checked for the page's text. Previews and the dev server show
9
+ // drafts as they are. Fails closed: a draft it cannot keep out stops the build.
10
+ //
11
+ // The addresses unbase.pages.json sends on (`redirects`: a page Unbase renamed
12
+ // or deleted while it was live) become Astro redirects, permanent (308), in
13
+ // the dev server and every build alike. One the site's own `redirects` sends
14
+ // somewhere else stops the build.
15
+ //
16
+ // It goes after @astrojs/sitemap and comment-modus in `integrations`, so the
17
+ // lists they write exist when it cleans them; the build stops otherwise.
18
+ //
19
+ // // astro.config.mjs
20
+ // import unbasePages from "@unbase-app/pages/astro";
21
+ // integrations: [..., sitemap(), unbasePages()]
22
+ // ============================================================================
23
+
24
+ import { existsSync } from "node:fs";
25
+ import { createRequire } from "node:module";
26
+ import { join } from "node:path";
27
+ import { fileURLToPath, pathToFileURL } from "node:url";
28
+ import * as core from "./core.mjs";
29
+ import { finishOutput, pageRedirects, planBuild, removePageHtml } from "./node.mjs";
30
+
31
+ const NAME = "@unbase-app/pages";
32
+ /** Integrations that write a page list in astro:build:done. */
33
+ const LISTS = ["@astrojs/sitemap", "comment-modus"];
34
+
35
+ const clean = (id) => id.replace(/\?.*$/, "");
36
+ /**
37
+ * Where a host's adapter copies the client output and serves it from. The Vercel adapter (11, with
38
+ * Astro 7) copies dist/client to .vercel/output/static in its own astro:build:done, which can run
39
+ * before this integration's: a draft removed from dist/client only would still be served (found
40
+ * on a copy of a real site, 10-11-2026). So the copy is cleaned and checked as well.
41
+ */
42
+ const HOST_COPIES = [".vercel/output/static"];
43
+ /** Astro's content store as one module: every collection's entries, also in the server's bundle. */
44
+ const DATA_STORE = "\0astro:data-layer-content";
45
+
46
+ /**
47
+ * The content store without the entries a draft owns (by their file), in the form Astro wrote it:
48
+ * `export default JSON.parse("<devalue>")`. Any other form, a store in chunks, stops the build:
49
+ * the kit cannot say the draft's content is out of it.
50
+ */
51
+ export function withoutDraftEntries(code, owned, devalue) {
52
+ if (code.trim() === "export default new Map()") return { code, removed: [] };
53
+ const m = code.match(/^\s*export default JSON\.parse\(("(?:[^"\\]|\\.)*")\)\s*;?\s*$/s);
54
+ if (!m) throw new Error("[unbase-pages] Astro's content store is not in a form the kit can read, so it cannot keep the drafts' content out of it, and the build stops.");
55
+ const store = devalue.unflatten(JSON.parse(JSON.parse(m[1])));
56
+ if (!(store instanceof Map)) throw new Error("[unbase-pages] Astro's content store is not a Map, so the build stops.");
57
+ const removed = [];
58
+ for (const [, entries] of store) {
59
+ if (!(entries instanceof Map)) throw new Error("[unbase-pages] A collection in Astro's content store is not a Map, so the build stops.");
60
+ for (const [key, entry] of entries) {
61
+ if (owned.has(entry?.filePath)) {
62
+ entries.delete(key);
63
+ removed.push(entry.filePath);
64
+ }
65
+ }
66
+ }
67
+ return { code: `export default JSON.parse(${JSON.stringify(devalue.stringify(store))})`, removed };
68
+ }
69
+
70
+ /** A redirect's address that carries what is under it: `/old/[...path]`. */
71
+ const REST = /\/\[\.\.\.[A-Za-z_]\w*\]$/;
72
+ /** An address as a redirect source is compared: no trailing slash, a rest parameter whatever its name. */
73
+ const sameAs = (p) => core.normalisePath(p).replace(/\[\.\.\.[A-Za-z_]\w*\]/g, "[...]");
74
+ const within = (p, at) => p === at || (at === "/" ? p !== "/" : p.startsWith(`${at}/`));
75
+
76
+ /**
77
+ * The page file's redirects in the form Astro's `redirects` takes, permanent (308), or null when
78
+ * there are none. `own` is the site's own `redirects`: a source it already sends to the same place
79
+ * stays the site's, and one it sends somewhere else stops the build (fail closed: which of the two
80
+ * a visitor gets would depend on Astro's merge).
81
+ *
82
+ * `prerender`: whether the site's pages are prerendered (Astro's default unless `output:
83
+ * "server"`). Astro only takes a redirect for everything under an address (`/old/[...path]`) in a
84
+ * prerendered site when a dynamic route is at its destination, and refuses the config otherwise.
85
+ * So there it becomes one redirect per page under the new address, and per address the page file
86
+ * sends there: the same addresses, each known at build.
87
+ * @param {{ root: string, own?: Record<string, string | { destination: string }> | null, prerender?: boolean, warn?: (line: string) => void }} input
88
+ * @returns {Record<string, { status: 308, destination: string }> | null}
89
+ */
90
+ export function astroRedirects({ root, own = {}, prerender = true, warn = () => {} }) {
91
+ const found = pageRedirects({ root, framework: "astro" });
92
+ if (!found) return null;
93
+ for (const s of found.skipped) warn(`${s} is a page now, so the redirect ${core.PAGE_FILE} has for it is not applied: the page wins.`);
94
+ const pages = new Set(found.found.pages.map((p) => p.path));
95
+ /** @type {Map<string, string>} source → destination, the page file's own first */
96
+ const list = new Map();
97
+ for (const r of found.list) if (!(prerender && REST.test(r.source))) list.set(r.source, r.destination);
98
+ if (prerender) {
99
+ const targets = [...new Set([...pages, ...Object.keys(found.redirects).filter((s) => !REST.test(s))])].sort();
100
+ for (const r of found.list) {
101
+ if (!REST.test(r.source)) continue;
102
+ const base = core.normalisePath(r.source.replace(REST, ""));
103
+ const to = core.normalisePath(r.destination.replace(REST, ""));
104
+ for (const t of targets) {
105
+ if (!within(t, to)) continue;
106
+ const source = t === to ? base : core.normalisePath(`${base}${t.slice(to === "/" ? 0 : to.length)}`);
107
+ // A page at the old address is a page again, and Astro would put the redirect in its place.
108
+ if (source !== t && !pages.has(source) && !list.has(source)) list.set(source, t);
109
+ }
110
+ }
111
+ }
112
+ const theirs = new Map(Object.entries(own ?? {}).map(([source, to]) => [sameAs(source), typeof to === "string" ? to : to?.destination]));
113
+ const conflicts = [];
114
+ /** @type {Record<string, { status: 308, destination: string }>} */
115
+ const out = {};
116
+ for (const [source, destination] of list) {
117
+ const have = theirs.get(sameAs(source));
118
+ if (have === undefined) out[source] = { status: 308, destination };
119
+ else if (typeof have !== "string" || sameAs(have) !== sameAs(destination)) conflicts.push(` ${source}: astro.config sends it to ${have}, ${core.PAGE_FILE} to ${destination}`);
120
+ }
121
+ if (conflicts.length) throw new Error(`[unbase-pages] astro.config's redirects and ${core.PAGE_FILE} send the same address to different places, so the build stops:\n${conflicts.join("\n")}\nKeep one of the two.`);
122
+ return Object.keys(out).length ? out : null;
123
+ }
124
+
125
+ /** @returns {import("astro").AstroIntegration} */
126
+ export default function unbasePages() {
127
+ /** @type {ReturnType<typeof planBuild>} */
128
+ let plan = null;
129
+ /** Where the build writes, client and server, for the leak check. */
130
+ let roots = [];
131
+ /** The project's folder, where a host adapter keeps its copy of the output. */
132
+ let root = "";
133
+ return {
134
+ name: NAME,
135
+ hooks: {
136
+ "astro:config:setup": async ({ command, config, updateConfig, logger }) => {
137
+ const root = fileURLToPath(config.root);
138
+ // Redirects in every command, so the dev server sends an old address on as Live does. A
139
+ // page file that cannot be read stops a build; the dev server says so and goes on.
140
+ let redirects = null;
141
+ try {
142
+ redirects = astroRedirects({ root, own: config.redirects, prerender: config.output !== "server", warn: (l) => logger.warn(l) });
143
+ } catch (e) {
144
+ if (command === "build") throw e;
145
+ logger.warn(/** @type {Error} */ (e).message);
146
+ }
147
+ if (redirects) {
148
+ updateConfig({ redirects });
149
+ logger.info(`redirects from ${core.PAGE_FILE}: ${Object.entries(redirects).map(([from, to]) => `${from} → ${to.destination}`).join(", ")}`);
150
+ }
151
+ if (command !== "build") return;
152
+ plan = planBuild({ root, framework: "astro", command: "build", log: (l) => logger.info(l) });
153
+ if (!plan) return;
154
+ const stubs = new Set(plan.drafts.map((d) => d.file));
155
+ const owned = new Set(plan.drafts.flatMap((d) => d.content));
156
+ // The site's own devalue, the one Astro wrote its content store with.
157
+ const devalue = await import(pathToFileURL(createRequire(join(root, "package.json")).resolve("devalue")).href);
158
+ updateConfig({
159
+ vite: {
160
+ plugins: [
161
+ {
162
+ name: "unbase-pages:drafts",
163
+ enforce: "pre",
164
+ load: (id) => (stubs.has(clean(id)) ? "---\n---\n" : null),
165
+ },
166
+ {
167
+ name: "unbase-pages:content-store",
168
+ transform(code, id) {
169
+ if (id !== DATA_STORE || !owned.size) return null;
170
+ const out = withoutDraftEntries(code, owned, devalue);
171
+ if (out.removed.length) logger.info(`content store without ${out.removed.join(", ")}`);
172
+ return { code: out.code, map: null };
173
+ },
174
+ },
175
+ ],
176
+ },
177
+ });
178
+ },
179
+ "astro:config:done": ({ config }) => {
180
+ if (!plan) return;
181
+ root = fileURLToPath(config.root);
182
+ const all = [config.outDir, config.build.client, config.build.server].map((u) => fileURLToPath(u));
183
+ roots = all.filter((r, i) => !all.some((o, j) => j !== i && r !== o && r.startsWith(o)) && all.indexOf(r) === i);
184
+ const names = config.integrations.map((i) => i.name);
185
+ const later = names.slice(names.indexOf(NAME) + 1).filter((n) => LISTS.includes(n));
186
+ if (later.length) throw new Error(`[unbase-pages] Put unbasePages() after ${later.join(" and ")} in integrations: they write page lists it has to clean, so the build stops.`);
187
+ },
188
+ "astro:build:done": ({ dir, logger }) => {
189
+ if (!plan) return;
190
+ const out = fileURLToPath(dir);
191
+ const copies = root ? HOST_COPIES.map((p) => join(root, p)).filter((p) => existsSync(p)) : [];
192
+ for (const at of [out, ...copies]) for (const d of plan.drafts) for (const f of removePageHtml(at, d.path)) logger.info(`removed ${f.slice((at === out ? out : root).length)}`);
193
+ // Lists are cleaned where the host serves them, its adapter's copy too; the leak check reads
194
+ // the server's bundle and that copy as well.
195
+ for (const copy of copies) finishOutput(copy, plan, (l) => logger.info(`${l} in ${copy.slice(root.length)}`), []);
196
+ finishOutput(out, plan, (l) => logger.info(l), [...(roots.length ? roots : [out]), ...copies]);
197
+ },
198
+ },
199
+ };
200
+ }
201
+
202
+ export { unbasePages };