@prunellejs/cms 0.0.0-stage → 0.7.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 Kaynooo
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/llms.txt ADDED
@@ -0,0 +1,74 @@
1
+ # @prunellejs/cms Reference
2
+
3
+ > Schema-driven, dev-only CMS plugin for `@prunellejs/content` Markdown collections. Zero client JS on public pages, zero duplicate field declarations, and full no-JS HTML form support.
4
+
5
+ ## Imports
6
+
7
+ - `@prunellejs/cms`: `cms`; types `CmsOptions`, `CmsGuard`, `CmsField`, `CmsFieldKind`, `CmsSchemaIssue`.
8
+
9
+ ## Setup (`cms(options?)`)
10
+
11
+ Register `cms()` in `prunelle.config.ts` alongside `content()` from `@prunellejs/content`. Collections are discovered automatically via the shared `CONTENT_COLLECTIONS_SERVICE` — never declare fields twice.
12
+
13
+ - `guard?: (ctx: RequestContext) => boolean | Response | Promise<boolean | Response>`: runs on every CMS route and gates in-page overlay injection. Return `false` for `403 Forbidden`, or return a `Response` (e.g. a login redirect). Optional on a loopback `prunelle dev`; with `prunelle dev --host` on an address other machines reach, the CMS throws at start without one.
14
+ - `basePath?: string`: URL prefix where the dev CMS is mounted (default `'/_pru/cms'`).
15
+ - `inline?: boolean`: inject the dev-only Shadow DOM in-page editing overlay on pages that read file-backed collections (default `true`; set `false` for `/_pru/cms`-only editing).
16
+
17
+ ## Mounted Routes (dev-only — never mounted when `dev: false` or on `--static`, and their code is not even loaded then)
18
+
19
+ - `GET /_pru/cms` — list all collections with entry counts and links to create entries.
20
+ - `GET /_pru/cms/:collection` — list entries with optional `?locale=...` switching and `?q=...` filtering.
21
+ - `GET /_pru/cms/:collection/new` & `POST /_pru/cms/:collection/new` — create a new Markdown entry.
22
+ - `GET /_pru/cms/:collection/*slug` & `POST /_pru/cms/:collection/*slug` — edit an existing entry (supports nested slugs and `?locale=...`).
23
+ - `GET /_pru/cms/_entry?collection=...&slug=...&locale=...` — JSON metadata, schema fields, frontmatter, and Markdown body for the in-page overlay.
24
+ - `PATCH /_pru/cms/_inline` — CSRF-protected, Standard Schema-validated JSON patch/save endpoint used by the in-page overlay (`422` returns `{ ok: false, errors }`).
25
+ - `POST /_pru/cms/_preview` — renders Markdown preview HTML via `Bun.markdown.html()`, sanitized with the allowlist `@prunellejs/content` applies to the published page.
26
+ - `GET /_pru/cms/_assets/cms.css`, `cms.js`, `inline.css`, `inline.js` — self-contained RGAA-accessible stylesheets and scripts (0 B in production/`--static`).
27
+
28
+ ## Saving and slugs
29
+
30
+ - Slugs follow `@prunellejs/content`: `_index`, `café`, `my post`, nested `a/b c`. Refused: empty, `.`, `..` and `__proto__` segments, backslash, control characters, lone surrogates. A segment over 252 bytes or a path over 4000 bytes is a `422` field error on the slug ("too long").
31
+ - Create is exclusive (`wx`): a concurrent second create of one slug gets `422` "An entry with this slug already exists.". Update writes a temp file in the entry's folder and renames it (a symlinked entry keeps its link).
32
+ - Frontmatter is edited in place: comments, order and keys the form has no field for are kept, only changed keys are rewritten (a trailing `# note` on a plain one-line value stays), new keys are appended. Comments inside a changed nested value or list are dropped.
33
+ - `PATCH /_pru/cms/_inline` answers `422` with `errors` naming the field when a value or key holds a lone UTF-16 surrogate.
34
+
35
+ ## In-Page Editing (dev-only, zero app markup)
36
+
37
+ When `inline` is enabled (the default), `@prunellejs/content` tracks file-backed entries read during each dev request and wraps rendered `entry.html` in zero-impact HTML comment anchors (`<!--pru-cms:...-->`). Pages that render a collection entry automatically receive a Shadow DOM floating toolbar (`Alt+Shift+E` toggles Edit-on-Page mode, `Cmd/Ctrl+S` saves, `Escape` cancels):
38
+
39
+ - **Edit on page**: highlights matched frontmatter string fields (click to edit inline via `contenteditable`, validated against the collection's Standard Schema on save) and the Markdown body region.
40
+ - **Docked slide-over panel**: full schema-driven Frontmatter form and a Markdown body editor that live-updates the actual page prose between the comment anchors as you type.
41
+ - **Zero app code & zero prod bytes**: routes never import `@prunellejs/cms`; non-content pages, unauthorized requests (`guard`), production servers (`dev: false`), and `--static` builds emit nothing.
42
+
43
+ ## JSON Schema Field Mapping & `prunelle check`
44
+
45
+ Extracts JSON Schema from each collection's Standard Schema (`~standard.jsonSchema.input`, `toJSONSchema()`, or `.jsonSchema`):
46
+
47
+ - `string` (`text`, `date`, `date-time`, `email`, `uri`/`url`, `contentMediaType: 'text/markdown'` textarea)
48
+ - `enum` (`<select>` for string or number enums)
49
+ - `boolean` (accessible `<input type="checkbox" role="switch">`)
50
+ - `number` / `integer` (`<input type="number">` with `min`, `max`, `step`)
51
+ - `array` of `string` (tags input)
52
+ - nested `object` (`<fieldset>` with dotted field names like `author.name`)
53
+ - `array` of `object` (repeatable rows like `items[0].title` with no-JS Add/Remove/Move buttons)
54
+ - Markdown body (`<textarea name="__body">` with progressive live preview)
55
+
56
+ `prunelle check` reports an error if a file-backed collection has a schema without JSON Schema output or uses an unsupported field construct (naming both collection and field path).
57
+
58
+ ## Snippet
59
+
60
+ ```ts
61
+ // prunelle.config.ts
62
+ import { cms } from '@prunellejs/cms'
63
+ import { content } from '@prunellejs/content'
64
+ import { defineConfig } from 'prunelle/config'
65
+
66
+ export default defineConfig({
67
+ plugins: [
68
+ content(),
69
+ cms({
70
+ guard: ctx => Boolean(ctx.locals.user),
71
+ }),
72
+ ],
73
+ })
74
+ ```
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@prunellejs/cms",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.0",
4
+ "description": "Schema-driven dev-only CMS plugin for Prunelle Markdown content collections",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "src",
10
+ "llms.txt"
11
+ ],
12
+ "exports": {
13
+ ".": "./src/index.ts"
14
+ },
15
+ "engines": {
16
+ "bun": ">=1.4.0"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/Kayno0o/prunelle",
21
+ "directory": "packages/plugin-cms"
22
+ },
23
+ "peerDependencies": {
24
+ "prunelle": "^0.7.0"
25
+ }
26
+ }
@@ -0,0 +1,101 @@
1
+ // Progressive enhancement script for full-page @prunellejs/cms admin routes (live Markdown preview + row reordering).
2
+
3
+ export const CMS_JS = `(() => {
4
+ const editors = document.querySelectorAll('[data-cms-md-editor]');
5
+ for (const editor of editors) {
6
+ const previewUrl = editor.getAttribute('data-preview-url');
7
+ const toggle = editor.querySelector('[data-cms-md-toggle]');
8
+ const textarea = editor.querySelector('textarea[name="__body"]');
9
+ const split = editor.querySelector('.cms-md-split');
10
+ const pane = editor.querySelector('[data-cms-md-preview]');
11
+ if (!previewUrl || !toggle || !textarea || !split || !pane) continue;
12
+
13
+ toggle.hidden = false;
14
+ let timer = null;
15
+ let seq = 0;
16
+
17
+ const refresh = async () => {
18
+ if (pane.hidden) return;
19
+ const ticket = ++seq;
20
+ try {
21
+ const res = await fetch(previewUrl, {
22
+ method: 'POST',
23
+ headers: { 'content-type': 'application/json', 'accept': 'text/html' },
24
+ body: JSON.stringify({ markdown: textarea.value }),
25
+ });
26
+ if (!res.ok || ticket !== seq) return;
27
+ const html = await res.text();
28
+ pane.innerHTML = html || '<p class="cms-muted">Nothing to preview yet.</p>';
29
+ } catch (_err) {
30
+ if (ticket === seq) pane.textContent = 'Preview unavailable.';
31
+ }
32
+ };
33
+
34
+ toggle.addEventListener('click', () => {
35
+ const nextOpen = pane.hidden;
36
+ pane.hidden = !nextOpen;
37
+ split.setAttribute('data-preview-open', nextOpen ? 'true' : 'false');
38
+ toggle.setAttribute('aria-pressed', nextOpen ? 'true' : 'false');
39
+ toggle.textContent = nextOpen ? 'Hide preview' : 'Live preview';
40
+ if (nextOpen) void refresh();
41
+ });
42
+
43
+ textarea.addEventListener('input', () => {
44
+ if (pane.hidden) return;
45
+ if (timer !== null) clearTimeout(timer);
46
+ timer = setTimeout(() => void refresh(), 180);
47
+ });
48
+ }
49
+
50
+ const reindexGroup = (group) => {
51
+ const path = group.getAttribute('data-cms-rows');
52
+ if (!path) return;
53
+ const rows = Array.from(group.querySelectorAll(':scope > [data-cms-row]'));
54
+ const countInput = group.querySelector('input[type="hidden"][name="__rows:' + path + '"]');
55
+ if (countInput) countInput.value = String(rows.length);
56
+ const escPath = path.replace(/[.*+?^\${}()|[\\]\\\\]/g, '\\\\$&');
57
+ const nameRe = new RegExp('^' + escPath + '\\\\[\\\\d+\\\\]');
58
+ rows.forEach((row, idx) => {
59
+ const title = row.querySelector('[data-cms-row-title]');
60
+ if (title) title.textContent = 'Row ' + (idx + 1);
61
+ for (const el of row.querySelectorAll('[name]')) {
62
+ const name = el.getAttribute('name');
63
+ if (name && nameRe.test(name)) {
64
+ el.setAttribute('name', name.replace(nameRe, path + '[' + idx + ']'));
65
+ }
66
+ }
67
+ for (const btn of row.querySelectorAll('button[name="__cms_action"]')) {
68
+ const val = btn.getAttribute('value') || '';
69
+ const parts = val.split(':');
70
+ if (parts.length === 3 && parts[1] === path) {
71
+ btn.setAttribute('value', parts[0] + ':' + path + ':' + idx);
72
+ }
73
+ }
74
+ const upBtn = row.querySelector('[data-cms-row-move="up"]');
75
+ const downBtn = row.querySelector('[data-cms-row-move="down"]');
76
+ if (upBtn) upBtn.disabled = idx === 0;
77
+ if (downBtn) downBtn.disabled = idx === rows.length - 1;
78
+ });
79
+ };
80
+
81
+ document.addEventListener('click', (event) => {
82
+ const target = event.target;
83
+ if (!(target instanceof Element)) return;
84
+ const btn = target.closest('[data-cms-row-move]');
85
+ if (!btn) return;
86
+ const row = btn.closest('[data-cms-row]');
87
+ const group = row && row.parentElement && row.parentElement.closest('[data-cms-rows]');
88
+ if (!row || !group) return;
89
+ const dir = btn.getAttribute('data-cms-row-move');
90
+ if (dir === 'up' && row.previousElementSibling && row.previousElementSibling.hasAttribute('data-cms-row')) {
91
+ event.preventDefault();
92
+ group.insertBefore(row, row.previousElementSibling);
93
+ reindexGroup(group);
94
+ } else if (dir === 'down' && row.nextElementSibling && row.nextElementSibling.hasAttribute('data-cms-row')) {
95
+ event.preventDefault();
96
+ group.insertBefore(row.nextElementSibling, row);
97
+ reindexGroup(group);
98
+ }
99
+ });
100
+ })();
101
+ `