uncial-cms 3.0.1 → 3.1.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/README.md CHANGED
@@ -62,6 +62,11 @@ The package also ships a `uncial-cms` command; see
62
62
  - `uncial-cms/sveltekit` — build-time route factories for prerendered
63
63
  SvelteKit sites (`createContentHandlers`, `createEditorHandlers`,
64
64
  `createIndexHandlers`).
65
+ - `uncial-cms/astro` — the Astro integration (`uncialCms`) and build-time
66
+ route helpers for static Astro sites (`createContentRoutes`,
67
+ `createEditorRoutes`). See [Quick start: Astro](#quick-start-astro).
68
+ - `uncial-cms/astro/editor` — `EditorSurface`, the Svelte island for an Astro
69
+ site's editor routes.
65
70
  - `uncial-cms/vite` — `uncialCms(siteOptions)`, the Vite plugins a site
66
71
  installs: the development editing endpoint, and the build's forge literal.
67
72
  - `uncial-cms/paths` — the pure path↔source mapping and the page-path
@@ -313,6 +318,89 @@ const handlers = createContentHandlers({
313
318
  Pass the same resolver to `EditorPage` and to the Content page's renderer, and
314
319
  one page path means one schema everywhere.
315
320
 
321
+ ## Quick start: Astro
322
+
323
+ An Astro site renders content with `@astrojs/svelte` and Uncial's SSR renderer,
324
+ at build time and with no hydration. As with SvelteKit, the package registers
325
+ no routes: the site writes them and hands each its `getStaticPaths`.
326
+
327
+ ```js
328
+ // astro.config.mjs
329
+ import svelte from '@astrojs/svelte';
330
+ import { uncialCms } from 'uncial-cms/astro';
331
+ import { siteOptions } from './src/site-options.ts';
332
+
333
+ export default defineConfig({ integrations: [svelte(), uncialCms(siteOptions)] });
334
+ ```
335
+
336
+ The reader route is a rest route named `path`. The helpers take the plain site
337
+ options, not `defineSite`'s result: nothing a reader route imports may reach the
338
+ package root, whose editor stylesheet Astro would otherwise link into the page.
339
+
340
+ ```astro
341
+ ---
342
+ // src/pages/[...path].astro
343
+ import { Renderer } from 'uncial/render';
344
+ import { createContentRoutes, type ContentPage } from 'uncial-cms/astro';
345
+ import { blocks, schema } from '../site';
346
+ import { siteOptions } from '../site-options';
347
+
348
+ export function getStaticPaths() {
349
+ return createContentRoutes({ siteOptions, blocks, schema }).getStaticPaths();
350
+ }
351
+
352
+ const { document } = Astro.props as ContentPage;
353
+ ---
354
+
355
+ <Renderer content={document} {blocks} {schema} />
356
+ ```
357
+
358
+ `createContentRoutes` also returns `list()`, every normalized document (to
359
+ derive navigation from metadata, say), and `load(path)`, for a page that keeps a
360
+ fixed shell of its own and renders its document inside it. `exclude` and a
361
+ per-path `schema` work as they do for the SvelteKit handlers.
362
+
363
+ The editor route bakes only the source mapping. Blocks and schemas are not
364
+ serializable island props, so the site mounts `EditorSurface` from a small
365
+ component of its own:
366
+
367
+ ```astro
368
+ ---
369
+ // src/pages/[...path]/edit.astro
370
+ import { createEditorRoutes } from 'uncial-cms/astro';
371
+ import Editor from '../../Editor.svelte';
372
+
373
+ export function getStaticPaths() {
374
+ return createEditorRoutes({ siteOptions, blocks, schema }).getStaticPaths();
375
+ }
376
+ ---
377
+
378
+ <Editor client:only="svelte" {...Astro.props} />
379
+ ```
380
+
381
+ ```svelte
382
+ <!-- src/Editor.svelte -->
383
+ <script lang="ts">
384
+ import { defineSite } from 'uncial-cms';
385
+ import { EditorSurface } from 'uncial-cms/astro/editor';
386
+
387
+ let { sourcePath, pagePath } = $props();
388
+ </script>
389
+
390
+ <EditorSurface site={defineSite(siteOptions)} {blocks} {schema} {sourcePath} {pagePath} />
391
+ ```
392
+
393
+ `EditorSurface` forwards `extensions`, `toolbarFeatures` and
394
+ `toolbarExtensions` to `Editor`, for custom marks and their controls, and takes
395
+ a `sessionProvider`. Against the GitHub forge it shows a Sign in button first,
396
+ since a sign-in popup opened outside a click is blocked.
397
+
398
+ Astro bundles a `client:only` island for any page file that renders it, even
399
+ one whose `getStaticPaths` returns nothing. A site that wants no editor code in
400
+ its production build at all injects the editor route from an integration only
401
+ when `command === 'dev'` rather than writing it as a page file. Gate the build
402
+ with `uncial-cms assert-clean-pages dist --astro`.
403
+
316
404
  ## Local-only sites
317
405
 
318
406
  Omitting the `github` half is the whole of the configuration for a site edited
@@ -453,7 +541,7 @@ uses:
453
541
  The package ships a `bin` with two commands.
454
542
 
455
543
  ```sh
456
- pnpm exec uncial-cms assert-clean-pages [buildDir] [--local-only]
544
+ pnpm exec uncial-cms assert-clean-pages [buildDir] [--local-only | --astro]
457
545
  pnpm exec uncial-cms doctor --origin https://example.com [--repo owner/name]
458
546
  ```
459
547
 
@@ -462,7 +550,11 @@ pnpm exec uncial-cms doctor --origin https://example.com [--repo owner/name]
462
550
  of its scripts, and checks the runtime sentinel: absent from every Content page,
463
551
  present on every Editor variant, ignored on the Index page. With `--local-only`
464
552
  it asserts a local-only site's build instead — no Editor variant exists, and no
465
- page's closure carries the sentinel or the editor stack.
553
+ page's closure carries the sentinel or the editor stack. With `--astro` it reads
554
+ an Astro build (default `dist`): every `.html` file, the `_astro/` bundles and
555
+ island URLs, and dynamic imports as well as static ones, since an Astro page has
556
+ no router lazily importing other routes. A reader page there fails on the editor
557
+ stack as well as the sentinel.
466
558
 
467
559
  **`doctor`** is the provisioning check, run before the first sign-in rather than
468
560
  learned from it. Through the authenticated `gh` CLI it checks that the GitHub
@@ -0,0 +1,171 @@
1
+ <script lang="ts">
2
+ /**
3
+ * An Astro editor route's island: Uncial's `Editor` in the host's own tree
4
+ * and cascade, driven by the headless editor session, with the status line,
5
+ * conflict banner and Save or autosave around it.
6
+ *
7
+ * Blocks, schemas and Tiptap extensions are not serializable island props,
8
+ * so the host mounts this from a small component of its own that imports
9
+ * them, with `client:only="svelte"`.
10
+ */
11
+ import 'uncial/styles/chrome.css';
12
+ import { onMount, type ComponentProps } from 'svelte';
13
+ import type { BlockRegistry, ContentDocument, ContentSchema } from 'uncial/core';
14
+ import { Editor, type ToolbarFeature, type ToolbarFeatureSelection } from 'uncial/editor';
15
+ import type { Site } from '../define-site.js';
16
+ import type { EditorController, StatusView } from '../editor-controller.js';
17
+ import { createEditorSession } from '../editor-session.js';
18
+ import { UNCIAL_CMS_RUNTIME_SENTINEL } from '../sentinel.js';
19
+ import type { SessionProvider } from '../types.js';
20
+ import { clearActiveForge } from '../upload-context.js';
21
+
22
+ interface Props {
23
+ /** The site object from `defineSite`. */
24
+ site: Site;
25
+ /** Repo-root-relative JSON path, from the editor route's props. */
26
+ sourcePath: string;
27
+ /** Site-relative page path, from the editor route's props. */
28
+ pagePath: string;
29
+ blocks: BlockRegistry;
30
+ /** One schema for the site, or the schema this page path is written against. */
31
+ schema: ContentSchema | ((path: string) => ContentSchema);
32
+ /** Defaults to the provider the resolved forge implies. */
33
+ sessionProvider?: SessionProvider;
34
+ /** Forwarded to `Editor`: the Tiptap extensions behind custom marks. */
35
+ extensions?: ComponentProps<typeof Editor>['extensions'];
36
+ /** Forwarded to `Editor`. */
37
+ toolbarFeatures?: ToolbarFeatureSelection;
38
+ /** Forwarded to `Editor`. */
39
+ toolbarExtensions?: ToolbarFeature[];
40
+ /** Forwarded to `Editor`; `'overlay'` keeps the document at the host's width. */
41
+ attributesPanel?: 'docked' | 'overlay' | 'off';
42
+ /** Forwarded to `Editor`; `'bare'` draws no surface of the editor's own. */
43
+ presentation?: 'card' | 'bare';
44
+ }
45
+
46
+ let {
47
+ site,
48
+ sourcePath,
49
+ pagePath,
50
+ blocks,
51
+ schema,
52
+ sessionProvider,
53
+ extensions,
54
+ toolbarFeatures,
55
+ toolbarExtensions,
56
+ attributesPanel = 'overlay',
57
+ presentation = 'bare'
58
+ }: Props = $props();
59
+
60
+ const resolvedSchema = $derived(typeof schema === 'function' ? schema(pagePath) : schema);
61
+ const signIn = $derived(site.config.forge === 'github');
62
+ const branch = $derived(
63
+ site.config.forge === 'github' ? site.config.branch : 'the local checkout'
64
+ );
65
+
66
+ let doc = $state<ContentDocument | undefined>(undefined);
67
+ let meta = $state<Record<string, unknown>>({});
68
+ let status = $state<StatusView | undefined>(undefined);
69
+ let conflict = $state(false);
70
+ let saveEnabled = $state(false);
71
+ let started = $state(false);
72
+ let cancelled = false;
73
+ let controller: EditorController | undefined;
74
+
75
+ // A sign-in popup opens a window, which browsers block outside a click, so a
76
+ // forge that signs in waits for the button.
77
+ function start() {
78
+ started = true;
79
+ controller?.load().catch((error: unknown) => {
80
+ if (cancelled) return;
81
+ // Offer the sign-in again: most refusals are fixed outside this page.
82
+ if (signIn) started = false;
83
+ status = {
84
+ tone: 'error',
85
+ text: error instanceof Error ? error.message : 'Failed to load the document.'
86
+ };
87
+ });
88
+ }
89
+
90
+ onMount(() => {
91
+ controller = createEditorSession({
92
+ config: site.config,
93
+ sourcePath,
94
+ pagePath,
95
+ blocks,
96
+ schema: resolvedSchema,
97
+ sessionProvider,
98
+ autosaveMs: site.autosaveMs,
99
+ timings: site.deployStatusTimings,
100
+ isDestroyed: () => cancelled,
101
+ ui: {
102
+ status: (view) => (status = view),
103
+ setDocument: (next) => {
104
+ doc = next;
105
+ // Without this the metadata panel shows schema defaults, and
106
+ // committing metadata would clobber the document's own.
107
+ meta = next.meta ?? {};
108
+ },
109
+ saveEnabled: (enabled) => (saveEnabled = enabled),
110
+ conflictVisible: (visible) => (conflict = visible)
111
+ }
112
+ });
113
+ if (!signIn) start();
114
+ return () => {
115
+ cancelled = true;
116
+ controller?.stop();
117
+ clearActiveForge();
118
+ };
119
+ });
120
+ </script>
121
+
122
+ <div class="uncial-cms-editor-page" data-uncial-cms-runtime={UNCIAL_CMS_RUNTIME_SENTINEL}>
123
+ <div class="uncial-cms-chrome">
124
+ {#if !started}
125
+ <button type="button" onclick={start}>Sign in with GitHub</button>
126
+ {:else if site.autosaveMs === undefined && doc}
127
+ <button type="button" disabled={!saveEnabled} onclick={() => void controller?.save()}>
128
+ Save
129
+ </button>
130
+ {/if}
131
+ {#if status}
132
+ <p class="uncial-cms-status" role="status" data-tone={status.tone}>
133
+ {status.text}{#if status.href}&nbsp;<a href={status.href} target="_blank" rel="noopener"
134
+ >View commit</a
135
+ >{/if}
136
+ </p>
137
+ {/if}
138
+ </div>
139
+
140
+ {#if conflict}
141
+ <div class="uncial-cms-banner" role="alert">
142
+ <p class="uncial-cms-banner-message">
143
+ This page changed on {branch} since you loaded it. Your unsaved changes are safe — choose how
144
+ to proceed.
145
+ </p>
146
+ <div class="uncial-cms-banner-actions">
147
+ <button type="button" onclick={() => controller?.downloadMyVersion()}>
148
+ Download my version
149
+ </button>
150
+ <button type="button" onclick={() => void controller?.reloadLatest()}>Reload latest</button>
151
+ <button type="button" onclick={() => controller?.dismissConflict()}>Dismiss</button>
152
+ </div>
153
+ </div>
154
+ {/if}
155
+
156
+ {#if doc}
157
+ <Editor
158
+ {blocks}
159
+ schema={resolvedSchema}
160
+ metaFields={resolvedSchema.metaFields}
161
+ bind:json={doc}
162
+ bind:meta
163
+ {extensions}
164
+ {toolbarFeatures}
165
+ {toolbarExtensions}
166
+ {attributesPanel}
167
+ {presentation}
168
+ onChange={(next) => controller?.documentChanged(next as ContentDocument)}
169
+ />
170
+ {/if}
171
+ </div>
@@ -0,0 +1,41 @@
1
+ /**
2
+ * An Astro editor route's island: Uncial's `Editor` in the host's own tree
3
+ * and cascade, driven by the headless editor session, with the status line,
4
+ * conflict banner and Save or autosave around it.
5
+ *
6
+ * Blocks, schemas and Tiptap extensions are not serializable island props,
7
+ * so the host mounts this from a small component of its own that imports
8
+ * them, with `client:only="svelte"`.
9
+ */
10
+ import 'uncial/styles/chrome.css';
11
+ import { type ComponentProps } from 'svelte';
12
+ import type { BlockRegistry, ContentSchema } from 'uncial/core';
13
+ import { Editor, type ToolbarFeature, type ToolbarFeatureSelection } from 'uncial/editor';
14
+ import type { Site } from '../define-site.js';
15
+ import type { SessionProvider } from '../types.js';
16
+ interface Props {
17
+ /** The site object from `defineSite`. */
18
+ site: Site;
19
+ /** Repo-root-relative JSON path, from the editor route's props. */
20
+ sourcePath: string;
21
+ /** Site-relative page path, from the editor route's props. */
22
+ pagePath: string;
23
+ blocks: BlockRegistry;
24
+ /** One schema for the site, or the schema this page path is written against. */
25
+ schema: ContentSchema | ((path: string) => ContentSchema);
26
+ /** Defaults to the provider the resolved forge implies. */
27
+ sessionProvider?: SessionProvider;
28
+ /** Forwarded to `Editor`: the Tiptap extensions behind custom marks. */
29
+ extensions?: ComponentProps<typeof Editor>['extensions'];
30
+ /** Forwarded to `Editor`. */
31
+ toolbarFeatures?: ToolbarFeatureSelection;
32
+ /** Forwarded to `Editor`. */
33
+ toolbarExtensions?: ToolbarFeature[];
34
+ /** Forwarded to `Editor`; `'overlay'` keeps the document at the host's width. */
35
+ attributesPanel?: 'docked' | 'overlay' | 'off';
36
+ /** Forwarded to `Editor`; `'bare'` draws no surface of the editor's own. */
37
+ presentation?: 'card' | 'bare';
38
+ }
39
+ declare const EditorSurface: import("svelte").Component<Props, {}, "">;
40
+ type EditorSurface = ReturnType<typeof EditorSurface>;
41
+ export default EditorSurface;
@@ -0,0 +1,2 @@
1
+ /** `uncial-cms/astro/editor` — the editor island for an Astro site's editor routes. */
2
+ export { default as EditorSurface } from './EditorSurface.svelte';
@@ -0,0 +1,2 @@
1
+ /** `uncial-cms/astro/editor` — the editor island for an Astro site's editor routes. */
2
+ export { default as EditorSurface } from './EditorSurface.svelte';
@@ -0,0 +1,52 @@
1
+ import type { BlockRegistry, ContentDocument, ContentSchema } from 'uncial/core';
2
+ import type { SiteOptions } from '../define-site.js';
3
+ export { uncialCms } from './integration.js';
4
+ /** A content file as the helpers see it: site-relative path, repo-root-relative source. */
5
+ export interface ContentEntry {
6
+ path: string;
7
+ source: string;
8
+ }
9
+ /** A content document ready to render, with the paths an editor route needs. */
10
+ export interface ContentPage {
11
+ path: string;
12
+ /** Repo-root-relative, as the forge addresses it. */
13
+ sourcePath: string;
14
+ document: ContentDocument;
15
+ }
16
+ export interface ContentRouteOptions {
17
+ /** The options the site hands `defineSite`. */
18
+ siteOptions: SiteOptions;
19
+ blocks: BlockRegistry;
20
+ /** One schema for the whole site, or the schema this page path is written against. */
21
+ schema: ContentSchema | ((path: string) => ContentSchema);
22
+ /** Keep a non-page file — site settings, a manifest — out of the routes. */
23
+ exclude?: (entry: ContentEntry) => boolean;
24
+ }
25
+ /**
26
+ * A rest parameter's value: Astro spells the site root as `undefined`, which a
27
+ * `[...path]` route needs in order to emit `/`.
28
+ */
29
+ type RestParams = {
30
+ path: string | undefined;
31
+ };
32
+ export declare function createContentRoutes(opts: ContentRouteOptions): {
33
+ /** Every content document, normalized, in source order. */
34
+ list: () => ContentPage[];
35
+ /** One document by site path, for a route with a fixed shell of its own. */
36
+ load: (path: string) => ContentPage;
37
+ getStaticPaths: () => Array<{
38
+ params: RestParams;
39
+ props: ContentPage;
40
+ }>;
41
+ };
42
+ export declare function createEditorRoutes(opts: ContentRouteOptions & {
43
+ devOnly?: boolean;
44
+ }): {
45
+ getStaticPaths: () => Array<{
46
+ params: RestParams;
47
+ props: {
48
+ sourcePath: string;
49
+ pagePath: string;
50
+ };
51
+ }>;
52
+ };
@@ -0,0 +1,72 @@
1
+ /**
2
+ * `uncial-cms/astro` — the integration and route helpers for a static Astro
3
+ * site. Build time only: it reads the local content directory with node:fs, so
4
+ * import it from `astro.config` and route frontmatter, never from an island.
5
+ * The editor island lives at `uncial-cms/astro/editor`.
6
+ *
7
+ * Like `uncial-cms/sveltekit`, nothing here registers a route. The host writes
8
+ * its reader route as `[...path].astro` and injects or writes its editor route
9
+ * itself, and each hands its `getStaticPaths` to the helper.
10
+ *
11
+ * The helpers take the site's plain options rather than `defineSite`'s result
12
+ * so that no reader route has to import the package root: the root carries the
13
+ * editor's stylesheet, and Astro links a module's CSS into every page whose
14
+ * graph reaches it.
15
+ */
16
+ import { readFileSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ import { normalizeDocument } from 'uncial/core';
19
+ import { listContentSources } from '../content-sources.js';
20
+ import { defaultMapPathToSource, defaultMapSourceToPath } from '../paths/index.js';
21
+ export { uncialCms } from './integration.js';
22
+ function localContentDir({ siteOptions }) {
23
+ return siteOptions.localContentDir ?? siteOptions.contentDir;
24
+ }
25
+ function listEntries(opts) {
26
+ const { contentDir } = opts.siteOptions;
27
+ return listContentSources(localContentDir(opts))
28
+ .map((rel) => {
29
+ const source = `${contentDir}/${rel}`;
30
+ return { path: defaultMapSourceToPath(source, contentDir), source };
31
+ })
32
+ .filter((entry) => !opts.exclude?.(entry));
33
+ }
34
+ function readPage(opts, { path, source }) {
35
+ const rel = source.slice(opts.siteOptions.contentDir.length + 1);
36
+ const raw = JSON.parse(readFileSync(join(localContentDir(opts), rel), 'utf-8'));
37
+ const schema = typeof opts.schema === 'function' ? opts.schema(path) : opts.schema;
38
+ return {
39
+ path,
40
+ sourcePath: source,
41
+ document: normalizeDocument(raw, opts.blocks, schema)
42
+ };
43
+ }
44
+ function restParams(path) {
45
+ return { path: path === '' ? undefined : path };
46
+ }
47
+ export function createContentRoutes(opts) {
48
+ const list = () => listEntries(opts).map((entry) => readPage(opts, entry));
49
+ return {
50
+ list,
51
+ load: (path) => {
52
+ const source = defaultMapPathToSource(path, opts.siteOptions.contentDir);
53
+ if (opts.exclude?.({ path, source })) {
54
+ throw new Error(`Content path "${path}" is excluded from this site's routes.`);
55
+ }
56
+ return readPage(opts, { path, source });
57
+ },
58
+ getStaticPaths: () => list().map((page) => ({ params: restParams(page.path), props: page }))
59
+ };
60
+ }
61
+ export function createEditorRoutes(opts) {
62
+ // A local-only site has no forge to commit to outside development.
63
+ const devOnly = opts.devOnly ?? opts.siteOptions.github === undefined;
64
+ return {
65
+ getStaticPaths: () => devOnly && !import.meta.env.DEV
66
+ ? []
67
+ : listEntries(opts).map(({ path, source }) => ({
68
+ params: restParams(path),
69
+ props: { sourcePath: source, pagePath: path }
70
+ }))
71
+ };
72
+ }
@@ -0,0 +1,4 @@
1
+ import type { AstroIntegration } from 'astro';
2
+ import type { SiteOptions } from '../define-site.js';
3
+ /** Installs the dev server's local forge and the build's forge constant. */
4
+ export declare function uncialCms(options: SiteOptions): AstroIntegration;
@@ -0,0 +1,15 @@
1
+ import { uncialCms as uncialCmsVite } from '../vite/index.js';
2
+ /** Installs the dev server's local forge and the build's forge constant. */
3
+ export function uncialCms(options) {
4
+ return {
5
+ name: 'uncial-cms',
6
+ hooks: {
7
+ 'astro:config:setup': ({ updateConfig }) => {
8
+ // Typed against the Vite this package builds with, which need not be
9
+ // the one Astro bundles; the plugins use only hooks both versions share.
10
+ const plugins = uncialCmsVite(options);
11
+ updateConfig({ vite: { plugins } });
12
+ }
13
+ }
14
+ };
15
+ }
@@ -0,0 +1,2 @@
1
+ import { type CliOutput } from './assert-clean-pages.js';
2
+ export declare function assertCleanAstroPages(buildDir: string, io: CliOutput): number;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * The zero-CMS-JS build gate against Astro's asset layout: reader pages must
3
+ * ship none of the editor's JavaScript, and every editor page must ship it.
4
+ *
5
+ * It is stricter than the SvelteKit gate in two ways. Dynamic imports are
6
+ * followed, because an Astro page has no router lazily importing other routes:
7
+ * a dynamic import reachable from a page is code that page may run. And a
8
+ * reader page fails on the editor stack as well as the sentinel, which catches
9
+ * the editor imported directly, without the sentinel-bearing surface.
10
+ */
11
+ import { readFileSync } from 'node:fs';
12
+ import { dirname, join, relative } from 'node:path';
13
+ import { UNCIAL_CMS_RUNTIME_SENTINEL } from '../sentinel.js';
14
+ import { EDITOR_STACK_MARKERS, walk } from './assert-clean-pages.js';
15
+ const SENTINEL_NAME = 'uncial-cms runtime sentinel';
16
+ const MARKERS = [
17
+ [SENTINEL_NAME, new RegExp(UNCIAL_CMS_RUNTIME_SENTINEL)],
18
+ ...EDITOR_STACK_MARKERS
19
+ ];
20
+ function markersIn(source) {
21
+ return MARKERS.filter(([, pattern]) => pattern.test(source)).map(([name]) => name);
22
+ }
23
+ /**
24
+ * Map a URL from the page or a chunk to a file in the build directory. Astro
25
+ * emits its bundles under `_astro/`, so those resolve from that segment whatever
26
+ * base path prefixes them; other root-relative URLs are files from `public/`.
27
+ * Off-site URLs resolve to nothing.
28
+ */
29
+ function resolveAsset(buildDir, url) {
30
+ const marker = url.indexOf('_astro/');
31
+ if (marker !== -1)
32
+ return join(buildDir, url.slice(marker));
33
+ if (url.startsWith('/') && !url.startsWith('//'))
34
+ return join(buildDir, url);
35
+ return null;
36
+ }
37
+ function readSource(file, cache) {
38
+ if (!cache.has(file)) {
39
+ try {
40
+ cache.set(file, readFileSync(file, 'utf-8'));
41
+ }
42
+ catch {
43
+ cache.set(file, null); // external or non-emitted reference
44
+ }
45
+ }
46
+ return cache.get(file) ?? null;
47
+ }
48
+ /**
49
+ * Every JS file a page can load: script and preload tags, the component and
50
+ * renderer URLs of Astro islands, imports in inline module scripts, and then,
51
+ * transitively, each chunk's static and dynamic imports.
52
+ */
53
+ function scriptClosure(buildDir, html, cache) {
54
+ const queue = [];
55
+ const urls = [
56
+ ...html.matchAll(/(?:src|href|component-url|renderer-url|before-hydration-url)="([^"]+\.m?js)"/g),
57
+ ...html.matchAll(/import\s*\(?\s*["']([^"']+\.m?js)["']/g)
58
+ ];
59
+ for (const [, url] of urls) {
60
+ const resolved = resolveAsset(buildDir, url);
61
+ if (resolved)
62
+ queue.push(resolved);
63
+ }
64
+ const seen = new Set();
65
+ while (queue.length > 0) {
66
+ const file = queue.pop();
67
+ if (seen.has(file))
68
+ continue;
69
+ seen.add(file);
70
+ const source = readSource(file, cache);
71
+ if (source === null)
72
+ continue;
73
+ for (const [, spec] of source.matchAll(/(?:from|import)\s*\(?\s*["']([^"']+\.m?js)["']/g)) {
74
+ if (spec.startsWith('.'))
75
+ queue.push(join(dirname(file), spec));
76
+ else {
77
+ const resolved = resolveAsset(buildDir, spec);
78
+ if (resolved)
79
+ queue.push(resolved);
80
+ }
81
+ }
82
+ }
83
+ return seen;
84
+ }
85
+ /** Editor markers on a page, each named with the file that carries it. */
86
+ function pageFindings(buildDir, htmlPath, cache) {
87
+ const html = readFileSync(htmlPath, 'utf-8');
88
+ // The stack markers are looked for only in inline script bodies, since page
89
+ // prose may mention them; the sentinel counts anywhere, as an attribute too.
90
+ const inline = [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/g)]
91
+ .map(([, body]) => body)
92
+ .join('\n');
93
+ const findings = markersIn(inline).map((name) => `${name} in an inline script`);
94
+ if (html.includes(UNCIAL_CMS_RUNTIME_SENTINEL))
95
+ findings.push(`${SENTINEL_NAME} in the page`);
96
+ for (const file of scriptClosure(buildDir, html, cache)) {
97
+ const source = readSource(file, cache);
98
+ if (source === null)
99
+ continue;
100
+ for (const name of markersIn(source))
101
+ findings.push(`${name} in ${relative(buildDir, file)}`);
102
+ }
103
+ return findings;
104
+ }
105
+ /** Site-relative page path of an HTML file, as the failure messages name it. */
106
+ function pageOf(buildDir, htmlPath) {
107
+ const rel = relative(buildDir, htmlPath).split('\\').join('/');
108
+ if (rel === 'index.html')
109
+ return '/';
110
+ return rel.endsWith('/index.html') ? `/${rel.slice(0, -'index.html'.length)}` : `/${rel}`;
111
+ }
112
+ export function assertCleanAstroPages(buildDir, io) {
113
+ let htmlFiles;
114
+ try {
115
+ htmlFiles = walk(buildDir).filter((path) => path.endsWith('.html'));
116
+ }
117
+ catch {
118
+ htmlFiles = [];
119
+ }
120
+ if (htmlFiles.length === 0) {
121
+ io.err(`No pages found under "${buildDir}" — build the site first.`);
122
+ return 1;
123
+ }
124
+ const cache = new Map();
125
+ const failures = [];
126
+ for (const htmlPath of htmlFiles) {
127
+ const page = pageOf(buildDir, htmlPath);
128
+ const findings = pageFindings(buildDir, htmlPath, cache);
129
+ if (page.endsWith('/edit/')) {
130
+ if (!findings.some((finding) => finding.startsWith(SENTINEL_NAME))) {
131
+ failures.push(`${page} is an editor page but does not reference the CMS runtime.`);
132
+ }
133
+ }
134
+ else if (page !== '/uncial/' && findings.length > 0) {
135
+ failures.push(`${page} is a reader page but ships the editor runtime: ${findings.join('; ')}.`);
136
+ }
137
+ }
138
+ if (failures.length > 0) {
139
+ io.err('assert:clean-pages FAILED');
140
+ for (const failure of failures)
141
+ io.err(` - ${failure}`);
142
+ return 1;
143
+ }
144
+ io.out(`assert:clean-pages OK — ${htmlFiles.length} pages checked, reader pages ship no editor runtime.`);
145
+ return 0;
146
+ }
@@ -7,4 +7,14 @@ export interface AssertCleanPagesOptions {
7
7
  /** Assert a local-only site: no Editor variant, and no editor stack anywhere. */
8
8
  localOnly?: boolean;
9
9
  }
10
+ /**
11
+ * Names the editor stack cannot be bundled without, and that nothing else in a
12
+ * built site carries. The ProseMirror marker is its class-name prefix rather
13
+ * than the bare word: `ProseMirror-focused` and its siblings are string
14
+ * literals in prosemirror-view that survive minification, while the bare word
15
+ * also appears in a validation message uncial's renderer ships — prose about a
16
+ * document format, not a copy of the library.
17
+ */
18
+ export declare const EDITOR_STACK_MARKERS: ReadonlyArray<readonly [string, RegExp]>;
19
+ export declare function walk(dir: string): string[];
10
20
  export declare function assertCleanPages(buildDir: string, options: AssertCleanPagesOptions, io: CliOutput): number;
@@ -18,12 +18,12 @@ import { UNCIAL_CMS_RUNTIME_SENTINEL } from '../sentinel.js';
18
18
  * also appears in a validation message uncial's renderer ships — prose about a
19
19
  * document format, not a copy of the library.
20
20
  */
21
- const EDITOR_STACK_MARKERS = [
21
+ export const EDITOR_STACK_MARKERS = [
22
22
  ['tiptap', /tiptap/i],
23
23
  ['ProseMirror-', /ProseMirror-/],
24
24
  ['uncial-editor', /uncial-editor/]
25
25
  ];
26
- function walk(dir) {
26
+ export function walk(dir) {
27
27
  return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
28
28
  const path = join(dir, entry.name);
29
29
  return entry.isDirectory() ? walk(path) : [path];
package/dist/cli/run.js CHANGED
@@ -1,18 +1,22 @@
1
1
  /** Argument parsing and dispatch for the `uncial-cms` command. */
2
+ import { assertCleanAstroPages } from './assert-clean-astro-pages.js';
2
3
  import { assertCleanPages } from './assert-clean-pages.js';
3
4
  import { DEFAULT_APP_SLUG } from '../define-site.js';
4
5
  import { doctor } from './doctor.js';
5
6
  const USAGE = `uncial-cms — build gates and provisioning checks for a site that edits itself
6
7
 
7
8
  Usage:
8
- uncial-cms assert-clean-pages [buildDir] [--local-only]
9
+ uncial-cms assert-clean-pages [buildDir] [--local-only | --astro]
9
10
 
10
11
  Assert that Content pages ship no uncial-cms JavaScript and that every
11
- Editor variant does. buildDir defaults to "build".
12
+ Editor variant does. buildDir defaults to "build", or "dist" with --astro.
12
13
 
13
14
  --local-only Assert a local-only site's production build instead: no
14
15
  Editor variant exists, and no file in the build carries the
15
16
  CMS runtime sentinel or the editor stack.
17
+ --astro Read an Astro build's asset layout, following dynamic
18
+ imports and island URLs, and fail a reader page on the
19
+ editor stack as well as the sentinel.
16
20
 
17
21
  uncial-cms doctor --origin <https://host> [--repo owner/name]
18
22
  [--app-slug <slug>] [--branch <ref>] [--no-pages]
@@ -95,12 +99,20 @@ export async function run(argv, io = consoleOutput, gh) {
95
99
  }, io, gh);
96
100
  }
97
101
  const localOnly = rest.includes('--local-only');
102
+ const astro = rest.includes('--astro');
98
103
  const positional = rest.filter((arg) => !arg.startsWith('-'));
99
- const unknownFlag = rest.find((arg) => arg.startsWith('-') && arg !== '--local-only');
104
+ const unknownFlag = rest.find((arg) => arg.startsWith('-') && arg !== '--local-only' && arg !== '--astro');
100
105
  if (unknownFlag !== undefined) {
101
106
  io.err(`Unknown option "${unknownFlag}".`);
102
107
  io.err(USAGE);
103
108
  return 2;
104
109
  }
110
+ if (localOnly && astro) {
111
+ io.err('--local-only and --astro cannot be combined.');
112
+ io.err(USAGE);
113
+ return 2;
114
+ }
115
+ if (astro)
116
+ return assertCleanAstroPages(positional[0] ?? 'dist', io);
105
117
  return assertCleanPages(positional[0] ?? 'build', { localOnly }, io);
106
118
  }
@@ -0,0 +1,2 @@
1
+ /** Every `.json` file under the local content dir, content-dir-relative and sorted. */
2
+ export declare function listContentSources(localContentDir: string, prefix?: string): string[];
@@ -0,0 +1,15 @@
1
+ /** Build-time enumeration of a content directory, shared by the framework route factories. Node only. */
2
+ import { readdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ /** Every `.json` file under the local content dir, content-dir-relative and sorted. */
5
+ export function listContentSources(localContentDir, prefix = '') {
6
+ const sources = [];
7
+ for (const entry of readdirSync(join(localContentDir, prefix), { withFileTypes: true })) {
8
+ const rel = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
9
+ if (entry.isDirectory())
10
+ sources.push(...listContentSources(localContentDir, rel));
11
+ else if (entry.isFile() && entry.name.endsWith('.json'))
12
+ sources.push(rel);
13
+ }
14
+ return sources.sort();
15
+ }
@@ -5,9 +5,10 @@
5
5
  * reads the local content directory with node:fs — do not import it from
6
6
  * client-side code (the pure mapping lives in `./mapping.js` for that).
7
7
  */
8
- import { readdirSync, readFileSync } from 'node:fs';
8
+ import { readFileSync } from 'node:fs';
9
9
  import { join } from 'node:path';
10
10
  import { normalizeDocument } from 'uncial/core';
11
+ import { listContentSources } from '../content-sources.js';
11
12
  import { defaultMapPathToSource, defaultMapSourceToPath } from '../paths/index.js';
12
13
  export { defaultMapPathToSource, defaultMapSourceToPath } from '../paths/index.js';
13
14
  function resolveSite(opts) {
@@ -20,17 +21,6 @@ function resolveSite(opts) {
20
21
  }
21
22
  return { config: opts.config, localContentDir: opts.localContentDir, localOnly: false };
22
23
  }
23
- function listContentSources(localContentDir, prefix = '') {
24
- const sources = [];
25
- for (const entry of readdirSync(join(localContentDir, prefix), { withFileTypes: true })) {
26
- const rel = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
27
- if (entry.isDirectory())
28
- sources.push(...listContentSources(localContentDir, rel));
29
- else if (entry.isFile() && entry.name.endsWith('.json'))
30
- sources.push(rel);
31
- }
32
- return sources.sort();
33
- }
34
24
  function createEntries(opts, site) {
35
25
  return () => listContentSources(site.localContentDir)
36
26
  .map((rel) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uncial-cms",
3
- "version": "3.0.1",
3
+ "version": "3.1.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -59,6 +59,15 @@
59
59
  "./sveltekit": {
60
60
  "types": "./dist/sveltekit/index.d.ts",
61
61
  "default": "./dist/sveltekit/index.js"
62
+ },
63
+ "./astro": {
64
+ "types": "./dist/astro/index.d.ts",
65
+ "default": "./dist/astro/index.js"
66
+ },
67
+ "./astro/editor": {
68
+ "types": "./dist/astro/editor.d.ts",
69
+ "svelte": "./dist/astro/editor.js",
70
+ "default": "./dist/astro/editor.js"
62
71
  }
63
72
  },
64
73
  "peerDependencies": {
@@ -66,12 +75,14 @@
66
75
  "uncial": "^3.0.0"
67
76
  },
68
77
  "devDependencies": {
78
+ "@astrojs/svelte": "^7.2.5",
69
79
  "@playwright/test": "^1.58.2",
70
80
  "@sveltejs/adapter-static": "^3.0.10",
71
81
  "@sveltejs/kit": "^2.50.2",
72
82
  "@sveltejs/package": "^2.5.7",
73
83
  "@sveltejs/vite-plugin-svelte": "^6.2.4",
74
84
  "@vitest/browser-playwright": "^4.0.18",
85
+ "astro": "^5.18.2",
75
86
  "playwright": "^1.58.2",
76
87
  "publint": "^0.3.17",
77
88
  "svelte": "^5.56.10",