uncial-cms 5.1.0 → 5.3.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.
Files changed (86) hide show
  1. package/README.md +216 -23
  2. package/dist/astro/EditorSurface.svelte +6 -2
  3. package/dist/astro/EditorSurface.svelte.d.ts +3 -1
  4. package/dist/astro/index.d.ts +2 -1
  5. package/dist/astro/index.js +7 -2
  6. package/dist/content-sources.d.ts +10 -0
  7. package/dist/content-sources.js +25 -1
  8. package/dist/dashboard/ConfirmDialog.svelte +76 -0
  9. package/dist/dashboard/ConfirmDialog.svelte.d.ts +10 -0
  10. package/dist/dashboard/Dashboard.svelte +650 -0
  11. package/dist/dashboard/Dashboard.svelte.d.ts +4 -0
  12. package/dist/dashboard/FallbackEditor.svelte +42 -0
  13. package/dist/dashboard/FallbackEditor.svelte.d.ts +14 -0
  14. package/dist/dashboard/GlobalForm.svelte +405 -0
  15. package/dist/dashboard/GlobalForm.svelte.d.ts +17 -0
  16. package/dist/dashboard/GlobalsList.svelte +62 -0
  17. package/dist/dashboard/GlobalsList.svelte.d.ts +7 -0
  18. package/dist/dashboard/MediaSection.svelte +221 -0
  19. package/dist/dashboard/MediaSection.svelte.d.ts +16 -0
  20. package/dist/dashboard/PagesSection.svelte +477 -0
  21. package/dist/dashboard/PagesSection.svelte.d.ts +23 -0
  22. package/dist/dashboard/element.d.ts +41 -0
  23. package/dist/dashboard/element.js +113 -0
  24. package/dist/dashboard/pages-list.d.ts +18 -0
  25. package/dist/dashboard/pages-list.js +29 -0
  26. package/dist/dashboard/routes.d.ts +25 -0
  27. package/dist/dashboard/routes.js +81 -0
  28. package/dist/dashboard/types.d.ts +34 -0
  29. package/dist/dashboard/types.js +1 -0
  30. package/dist/define-site.d.ts +15 -6
  31. package/dist/define-site.js +12 -9
  32. package/dist/editor-controller.d.ts +1 -0
  33. package/dist/editor-controller.js +1 -0
  34. package/dist/editor-session.d.ts +5 -0
  35. package/dist/editor-session.js +1 -1
  36. package/dist/errors.d.ts +13 -0
  37. package/dist/errors.js +14 -0
  38. package/dist/github/broker.d.ts +26 -0
  39. package/dist/github/broker.js +196 -0
  40. package/dist/github/index.d.ts +1 -0
  41. package/dist/github/index.js +1 -0
  42. package/dist/globals.d.ts +12 -0
  43. package/dist/globals.js +29 -0
  44. package/dist/image-source.d.ts +0 -10
  45. package/dist/image-source.js +15 -44
  46. package/dist/index-actions.d.ts +29 -2
  47. package/dist/index-actions.js +36 -4
  48. package/dist/index-page.d.ts +2 -0
  49. package/dist/index-page.js +6 -256
  50. package/dist/index.d.ts +6 -3
  51. package/dist/index.js +4 -3
  52. package/dist/local/vite.d.ts +8 -2
  53. package/dist/local/vite.js +32 -15
  54. package/dist/media-source.d.ts +45 -0
  55. package/dist/media-source.js +113 -0
  56. package/dist/mount.d.ts +3 -0
  57. package/dist/mount.js +3 -0
  58. package/dist/nav/index.d.ts +39 -0
  59. package/dist/nav/index.js +52 -0
  60. package/dist/served-url.d.ts +6 -4
  61. package/dist/served-url.js +18 -7
  62. package/dist/server/handlers.d.ts +1 -1
  63. package/dist/server/handlers.js +32 -5
  64. package/dist/server/index.d.ts +2 -1
  65. package/dist/server/index.js +2 -1
  66. package/dist/server/media.d.ts +1 -10
  67. package/dist/server/media.js +7 -11
  68. package/dist/server/postgres-store.d.ts +5 -0
  69. package/dist/server/postgres-store.js +50 -5
  70. package/dist/server-forge/adapter.d.ts +1 -0
  71. package/dist/server-forge/adapter.js +7 -4
  72. package/dist/server-forge/protocol.d.ts +3 -1
  73. package/dist/server-forge/protocol.js +2 -1
  74. package/dist/svelte/EditorPage.svelte +5 -1
  75. package/dist/svelte/EditorPage.svelte.d.ts +3 -1
  76. package/dist/svelte/MediaLibrary.svelte +109 -53
  77. package/dist/svelte/MediaLibrary.svelte.d.ts +10 -2
  78. package/dist/svelte/index.d.ts +1 -4
  79. package/dist/svelte/index.js +1 -4
  80. package/dist/sveltekit/index.d.ts +11 -1
  81. package/dist/sveltekit/index.js +23 -9
  82. package/dist/types.d.ts +2 -0
  83. package/dist/upload-context.d.ts +1 -0
  84. package/dist/upload-context.js +3 -0
  85. package/dist/vite/index.js +18 -4
  86. package/package.json +16 -3
@@ -1,52 +1,23 @@
1
1
  import { resolveImageSrc } from 'uncial/render';
2
- import { resolveMediaDir, uploadImageAsset } from './index-actions.js';
3
- import { servedUrl } from './served-url.js';
4
- import { listMedia, uploadMedia } from './server-forge/media.js';
5
- import { configMediaDir, getActiveForge } from './upload-context.js';
6
- const IMAGE_EXTENSION = /\.(png|jpe?g|gif|webp|avif|svg)$/i;
7
- /**
8
- * The editor's image source for a CMS site: an upload is fitted under the
9
- * forge limit, committed under the media dir through the active editor
10
- * session, and stored as its base-less served URL; browse lists the media
11
- * dir's images the same way. `base` and `staticDir` are the site's build-time
12
- * values, which the config does not carry. A site with a rendition pipeline
13
- * replaces the listing with `list` (served paths) and the tile URL with
14
- * `thumbnail`. On a `server` forge, upload and browse go to the Media
15
- * library at `mediaApiBase` instead.
16
- */
2
+ import { mediaSourceFor } from './media-source.js';
3
+ import { getActiveForge } from './upload-context.js';
17
4
  export function cmsImageSource(config, options = {}) {
18
5
  const { base = '', staticDir = 'static', list } = options;
19
6
  const thumbnail = options.thumbnail ?? ((src) => resolveImageSrc(src, base));
20
- if (config.forge === 'server') {
21
- const { mediaApiBase } = config;
22
- if (!mediaApiBase)
23
- return { thumbnail };
24
- return {
25
- upload: async (file) => (await uploadMedia(mediaApiBase, file)).url,
26
- browse: list ??
27
- (async () => (await listMedia(mediaApiBase, { contentType: 'image/*' })).items.map((item) => item.url)),
28
- thumbnail
29
- };
30
- }
7
+ if (config.forge === 'server' && !config.mediaApiBase)
8
+ return { thumbnail };
9
+ const source = () => {
10
+ if (config.forge === 'server')
11
+ return mediaSourceFor(config);
12
+ const forge = getActiveForge();
13
+ if (!forge) {
14
+ throw new Error('No active editor session — open a page in the editor and sign in before choosing or uploading an image.');
15
+ }
16
+ return mediaSourceFor(config, forge, { staticDir });
17
+ };
31
18
  return {
32
- upload: async (file) => {
33
- const result = await uploadImageAsset(file, { fit: true, mediaDir: configMediaDir(config) });
34
- return servedUrl({ config }, result.path, staticDir);
35
- },
36
- browse: list ?? (async () => {
37
- const forge = getActiveForge();
38
- if (!forge) {
39
- throw new Error('No active editor session — open a page in the editor and sign in before choosing an image.');
40
- }
41
- // The same resolution `uploadImageAsset` commits under, so browse lists what upload wrote.
42
- const mediaDir = resolveMediaDir(configMediaDir(config), configMediaDir(forge.config));
43
- const entries = await forge.adapter.listDir(mediaDir);
44
- return entries
45
- .filter((entry) => entry.type === 'file' && IMAGE_EXTENSION.test(entry.path))
46
- .map((entry) => entry.path)
47
- .sort()
48
- .map((path) => servedUrl({ config }, path, staticDir));
49
- }),
19
+ upload: async (file) => (await source().upload(file)).url,
20
+ browse: list ?? (async () => (await source().list({ contentType: 'image/*' })).map((item) => item.url)),
50
21
  thumbnail
51
22
  };
52
23
  }
@@ -1,6 +1,7 @@
1
+ import type { ContentSchema } from 'uncial/core';
1
2
  import type { Site } from './define-site.js';
2
3
  import { type FitOptions, type ImageEncoder } from './fit-image.js';
3
- import type { ForgeAdapter } from './types.js';
4
+ import type { ForgeAdapter, UncialCmsSiteConfig } from './types.js';
4
5
  export interface CreatePageDeps {
5
6
  adapter: ForgeAdapter;
6
7
  blocks: unknown;
@@ -21,6 +22,33 @@ export declare function createPage(deps: CreatePageDeps, { pagePath, sourcePath
21
22
  }>;
22
23
  /** Delete `sourcePath` at its current sha. */
23
24
  export declare function deletePage(adapter: ForgeAdapter, { pagePath, sourcePath }: PageRef): Promise<void>;
25
+ export declare function readStoredGlobal(deps: {
26
+ adapter: ForgeAdapter;
27
+ config: UncialCmsSiteConfig;
28
+ }, global: {
29
+ name: string;
30
+ schema: ContentSchema;
31
+ }): Promise<{
32
+ value: Record<string, unknown>;
33
+ sha?: string;
34
+ }>;
35
+ export interface SaveGlobalDeps {
36
+ adapter: ForgeAdapter;
37
+ config: UncialCmsSiteConfig;
38
+ author: {
39
+ name: string;
40
+ email: string;
41
+ };
42
+ }
43
+ export declare function saveGlobal(deps: SaveGlobalDeps, global: {
44
+ name: string;
45
+ schema: ContentSchema;
46
+ value: Record<string, unknown>;
47
+ sha?: string;
48
+ }): Promise<{
49
+ sha: string;
50
+ commitSha: string;
51
+ }>;
24
52
  export interface UploadAssetFile {
25
53
  bytes: Uint8Array;
26
54
  filename: string;
@@ -72,5 +100,4 @@ export interface UploadImageAssetOptions {
72
100
  * dynamically from a block so the reader bundle stays free of CMS runtime.
73
101
  */
74
102
  export declare function uploadImageAsset(file: UploadAssetFile | File, opts?: UploadImageAssetOptions): Promise<UploadAssetResult>;
75
- /** Recursively list the content dir's JSON sources, sorted by page path. */
76
103
  export declare function listPages(adapter: ForgeAdapter, contentDir: string, mapSourceToPath?: (source: string) => string): Promise<PageRef[]>;
@@ -5,9 +5,10 @@
5
5
  */
6
6
  import { normalizeDocument } from 'uncial/core';
7
7
  import { MAX_CONTENT_BYTES } from './constants.js';
8
- import { serializeDocument } from './document.js';
8
+ import { parseDocument, serializeDocument } from './document.js';
9
9
  import { NotFoundError } from './errors.js';
10
10
  import { fitImage } from './fit-image.js';
11
+ import { globalDocument, globalRecordPath, globalSourcePath, GLOBALS_DIR } from './globals.js';
11
12
  import { defaultMapSourceToPath } from './paths/index.js';
12
13
  import { configMediaDir, getActiveForge } from './upload-context.js';
13
14
  /** Seed `sourcePath` with a normalized empty document (create-mode commit). */
@@ -37,6 +38,35 @@ export async function deletePage(adapter, { pagePath, sourcePath }) {
37
38
  const { sha } = await adapter.readFile(sourcePath);
38
39
  await adapter.deleteFile(sourcePath, { message: `uncial-cms: delete ${pagePath}`, sha });
39
40
  }
41
+ export async function readStoredGlobal(deps, global) {
42
+ const { config } = deps;
43
+ const path = config.forge === 'server'
44
+ ? globalRecordPath(global.name)
45
+ : globalSourcePath(config.contentDir, global.name);
46
+ try {
47
+ const file = await deps.adapter.readFile(path);
48
+ return { value: parseDocument(file.content, [], global.schema).meta ?? {}, sha: file.sha };
49
+ }
50
+ catch (error) {
51
+ if (!(error instanceof NotFoundError))
52
+ throw error;
53
+ return { value: normalizeDocument(null, [], global.schema).meta ?? {} };
54
+ }
55
+ }
56
+ export async function saveGlobal(deps, global) {
57
+ const { name, schema, value, sha } = global;
58
+ const content = serializeDocument(globalDocument(value), [], schema);
59
+ if (deps.config.forge === 'server') {
60
+ const adapter = deps.adapter;
61
+ const record = await adapter.saveGlobal(name, JSON.parse(content), sha);
62
+ return { sha: record.etag, commitSha: '' };
63
+ }
64
+ return deps.adapter.writeFile(globalSourcePath(deps.config.contentDir, name), content, {
65
+ message: `uncial-cms: save global ${name}`,
66
+ sha,
67
+ author: deps.author
68
+ });
69
+ }
40
70
  const EXTENSION_FROM_CONTENT_TYPE = {
41
71
  'image/jpeg': 'jpg',
42
72
  'image/svg+xml': 'svg'
@@ -129,13 +159,15 @@ export async function uploadImageAsset(file, opts = {}) {
129
159
  : file;
130
160
  return uploadAsset({ adapter: forge.adapter }, asset, { mediaDir, author: forge.author });
131
161
  }
132
- /** Recursively list the content dir's JSON sources, sorted by page path. */
133
162
  export async function listPages(adapter, contentDir, mapSourceToPath = (source) => defaultMapSourceToPath(source, contentDir)) {
134
163
  const sources = [];
164
+ const globalsDir = `${contentDir}/${GLOBALS_DIR}`;
135
165
  const walk = async (dir) => {
136
166
  for (const entry of await adapter.listDir(dir)) {
137
- if (entry.type === 'dir')
138
- await walk(entry.path);
167
+ if (entry.type === 'dir') {
168
+ if (entry.path !== globalsDir)
169
+ await walk(entry.path);
170
+ }
139
171
  else if (entry.path.endsWith('.json'))
140
172
  sources.push(entry.path);
141
173
  }
@@ -1,4 +1,5 @@
1
1
  import type { SessionProvider, UncialCmsSiteConfig } from './types.js';
2
+ /** @deprecated Render `<uncial-dashboard>`, which takes these options as properties. */
2
3
  export interface MountIndexPageOptions {
3
4
  config: UncialCmsSiteConfig;
4
5
  blocks: unknown;
@@ -16,6 +17,7 @@ export interface MountIndexPageOptions {
16
17
  /** Open pages in the host's own editing view instead of the Fallback editor. */
17
18
  editorHref?: (pagePath: string) => string;
18
19
  }
20
+ /** @deprecated Render `<uncial-dashboard>`; this mounts it showing only Pages. */
19
21
  export declare function mountIndexPage(target: HTMLElement, opts: MountIndexPageOptions): {
20
22
  destroy(): void;
21
23
  };
@@ -1,258 +1,8 @@
1
- /**
2
- * `/uncial/` site-index runtime (PRD §6.6, D2): list/create/delete pages and
3
- * the hash-routed fallback editor (`#/<path>/`). Framework-agnostic plain DOM,
4
- * same style as mountEditorPage — the SvelteKit index route is just a shell
5
- * that calls this.
6
- */
7
- import { createPage, deletePage, listPages } from './index-actions.js';
8
- import { mountEditorPage } from './mount.js';
9
- import { defaultMapPathToSource, hashForPagePath, pagePathFromHash, validatePagePath } from './paths/index.js';
10
- import { defaultSessionProvider, forgeAdapter } from './editor-session.js';
11
- import { describeContentStatus } from './server-forge/protocol.js';
12
- import { UNCIAL_CMS_RUNTIME_SENTINEL } from './sentinel.js';
1
+ import { UncialDashboardElement } from './dashboard/element.js';
2
+ /** @deprecated Render `<uncial-dashboard>`; this mounts it showing only Pages. */
13
3
  export function mountIndexPage(target, opts) {
14
- const { config, basePath = '' } = opts;
15
- const sessionProvider = opts.sessionProvider ?? defaultSessionProvider(config);
16
- const branchLabel = config.forge === 'github'
17
- ? config.branch
18
- : config.forge === 'server'
19
- ? 'the server'
20
- : 'the local checkout';
21
- const locationLabel = config.forge === 'github' ? `${config.repo}@${config.branch}` : branchLabel;
22
- // A server record's path is the site path with its surrounding slashes ('/' = site root).
23
- const mapPathToSource = opts.mapPathToSource ??
24
- (config.forge === 'server'
25
- ? (path) => (path === '' ? '/' : `/${path}/`)
26
- : (path) => defaultMapPathToSource(path, config.contentDir));
27
- const editHref = opts.editorHref ?? hashForPagePath;
28
- const root = document.createElement('div');
29
- root.className = 'uncial-cms-index';
30
- root.dataset.uncialCmsRuntime = UNCIAL_CMS_RUNTIME_SENTINEL;
31
- const status = document.createElement('p');
32
- status.className = 'uncial-cms-status';
33
- status.setAttribute('role', 'status');
34
- const listView = document.createElement('section');
35
- listView.className = 'uncial-cms-index-list';
36
- const editorView = document.createElement('section');
37
- editorView.className = 'uncial-cms-fallback-editor';
38
- editorView.hidden = true;
39
- const signInButton = document.createElement('button');
40
- signInButton.type = 'button';
41
- signInButton.className = 'uncial-cms-sign-in';
42
- signInButton.textContent = 'Sign in';
43
- signInButton.hidden = true;
44
- root.append(status, signInButton, listView, editorView);
45
- target.append(root);
46
- let destroyed = false;
47
- let adapter = null;
48
- let session = null;
49
- let editorHandle = null;
50
- let currentHash = location.hash;
51
- let revertingHash = false;
52
- const setStatus = (text) => {
53
- status.textContent = text;
54
- };
55
- const livePageUrl = (pagePath) => `${basePath}/${pagePath === '' ? '' : `${pagePath}/`}`;
56
- const renderList = (pages) => {
57
- listView.replaceChildren();
58
- const heading = document.createElement('h2');
59
- heading.textContent = 'Pages';
60
- const list = document.createElement('ul');
61
- for (const page of pages) {
62
- const item = document.createElement('li');
63
- const live = document.createElement('a');
64
- live.href = livePageUrl(page.pagePath);
65
- live.textContent = page.pagePath === '' ? '(site root)' : `/${page.pagePath}/`;
66
- // Always link the fallback editor — it works whether or not the page's
67
- // static variant has deployed yet.
68
- const edit = document.createElement('a');
69
- edit.href = editHref(page.pagePath);
70
- edit.textContent = 'Edit';
71
- const del = document.createElement('button');
72
- del.type = 'button';
73
- del.textContent = 'Delete';
74
- del.addEventListener('click', () => void onDelete(page));
75
- item.append(live, ' ');
76
- if (page.status) {
77
- const status = document.createElement('span');
78
- status.className = 'uncial-cms-index-status';
79
- status.textContent = page.status;
80
- item.append(status, ' ');
81
- }
82
- item.append(edit, ' ', del);
83
- list.append(item);
84
- }
85
- const form = document.createElement('form');
86
- form.className = 'uncial-cms-create';
87
- const label = document.createElement('label');
88
- label.textContent = 'New page path ';
89
- const input = document.createElement('input');
90
- input.name = 'path';
91
- input.placeholder = 'team/new-page';
92
- label.append(input);
93
- const submit = document.createElement('button');
94
- submit.type = 'submit';
95
- submit.textContent = 'Create page';
96
- const message = document.createElement('p');
97
- message.className = 'uncial-cms-create-message';
98
- message.setAttribute('role', 'alert');
99
- message.hidden = true;
100
- form.append(label, ' ', submit, message);
101
- form.addEventListener('submit', (event) => {
102
- event.preventDefault();
103
- void onCreate(input.value, message, submit);
104
- });
105
- listView.append(heading, list, form);
106
- };
107
- const refreshList = async () => {
108
- if (!adapter)
109
- return;
110
- setStatus('Loading pages…');
111
- const pages = config.forge === 'server'
112
- ? (await adapter.list()).map((record) => ({
113
- pagePath: opts.mapSourceToPath?.(record.path) ?? record.path.replace(/^\/+|\/+$/g, ''),
114
- sourcePath: record.path,
115
- status: describeContentStatus(record.status)
116
- }))
117
- : await listPages(adapter, config.contentDir, opts.mapSourceToPath);
118
- if (destroyed)
119
- return;
120
- renderList(pages);
121
- setStatus(`Editing ${locationLabel} as ${session.user.login}`);
122
- };
123
- const onCreate = async (raw, message, submit) => {
124
- const result = validatePagePath(raw);
125
- if (!result.ok) {
126
- message.hidden = false;
127
- message.textContent = result.message;
128
- return;
129
- }
130
- if (!adapter || !session)
131
- return;
132
- message.hidden = true;
133
- submit.disabled = true;
134
- try {
135
- await createPage({ adapter, blocks: opts.blocks, schema: opts.schema, author: session.user }, { pagePath: result.path, sourcePath: mapPathToSource(result.path) });
136
- // Open the fallback editor immediately — the static variant only
137
- // appears after the next deploy.
138
- if (opts.editorHref)
139
- location.assign(opts.editorHref(result.path));
140
- else
141
- location.hash = hashForPagePath(result.path);
142
- }
143
- catch (error) {
144
- message.hidden = false;
145
- message.textContent = error instanceof Error ? error.message : 'Create failed.';
146
- }
147
- finally {
148
- submit.disabled = false;
149
- }
150
- };
151
- const onDelete = async (page) => {
152
- if (!adapter)
153
- return;
154
- const confirmed = window.confirm(`Delete ${page.sourcePath} from ${branchLabel}? ` +
155
- (config.forge === 'server' ? 'This cannot be undone.' : 'This commits the deletion immediately.'));
156
- if (!confirmed)
157
- return;
158
- try {
159
- await deletePage(adapter, page);
160
- await refreshList();
161
- }
162
- catch (error) {
163
- setStatus(error instanceof Error ? error.message : 'Delete failed.');
164
- }
165
- };
166
- const closeEditor = () => {
167
- editorHandle?.destroy();
168
- editorHandle = null;
169
- editorView.replaceChildren();
170
- editorView.hidden = true;
171
- listView.hidden = false;
172
- };
173
- const openEditor = (pagePath) => {
174
- closeEditor();
175
- listView.hidden = true;
176
- editorView.hidden = false;
177
- const back = document.createElement('a');
178
- back.href = '#';
179
- back.textContent = '← Back to index';
180
- const heading = document.createElement('h2');
181
- heading.textContent = pagePath === '' ? 'Editing site root' : `Editing /${pagePath}/`;
182
- const mountTarget = document.createElement('div');
183
- editorView.append(back, heading, mountTarget);
184
- editorHandle = mountEditorPage(mountTarget, {
185
- config,
186
- sourcePath: mapPathToSource(pagePath),
187
- pagePath,
188
- blocks: opts.blocks,
189
- schema: opts.schema,
190
- sessionProvider,
191
- editorStylesheets: opts.editorStylesheets
192
- });
193
- };
194
- const applyHash = () => {
195
- const pagePath = pagePathFromHash(location.hash);
196
- if (pagePath === null) {
197
- closeEditor();
198
- void refreshList().catch((error) => {
199
- setStatus(error instanceof Error ? error.message : 'Failed to list pages.');
200
- });
201
- }
202
- else {
203
- openEditor(pagePath);
204
- }
205
- currentHash = location.hash;
206
- };
207
- const onHashChange = () => {
208
- if (revertingHash) {
209
- revertingHash = false;
210
- return;
211
- }
212
- if (editorHandle?.isDirty() && !window.confirm('Discard unsaved changes?')) {
213
- revertingHash = true;
214
- location.hash = currentHash;
215
- return;
216
- }
217
- applyHash();
218
- };
219
- const onBeforeUnload = (event) => {
220
- if (editorHandle?.isDirty())
221
- event.preventDefault();
222
- };
223
- window.addEventListener('hashchange', onHashChange);
224
- window.addEventListener('beforeunload', onBeforeUnload);
225
- const load = async () => {
226
- setStatus('Signing in…');
227
- adapter = forgeAdapter(config);
228
- session = await adapter.authenticate(config, sessionProvider);
229
- if (destroyed)
230
- return;
231
- applyHash();
232
- };
233
- // The first attempt runs outside a click, where browsers block the sign-in
234
- // popup, so a failed sign-in is retried from a button.
235
- const signIn = async () => {
236
- signInButton.hidden = true;
237
- try {
238
- await load();
239
- }
240
- catch (error) {
241
- if (destroyed)
242
- return;
243
- setStatus(error instanceof Error ? error.message : 'Failed to load the site index.');
244
- signInButton.hidden = false;
245
- }
246
- };
247
- signInButton.addEventListener('click', () => void signIn());
248
- void signIn();
249
- return {
250
- destroy() {
251
- destroyed = true;
252
- window.removeEventListener('hashchange', onHashChange);
253
- window.removeEventListener('beforeunload', onBeforeUnload);
254
- editorHandle?.destroy();
255
- root.remove();
256
- }
257
- };
4
+ const element = new UncialDashboardElement();
5
+ Object.assign(element, opts, { sections: ['pages'] });
6
+ target.append(element);
7
+ return { destroy: () => element.remove() };
258
8
  }
package/dist/index.d.ts CHANGED
@@ -1,17 +1,20 @@
1
1
  export type { ForgeAdapter, ForgeSession, GitHubSiteConfig, ServerSiteConfig, SessionProvider, UncialCmsSiteConfig } from './types.js';
2
2
  export { defineServerSite, defineSite, DEFAULT_APP_SLUG, DEFAULT_AUTH_WORKER_URL, type ServerSiteOptions, type Site, type SiteOptions } from './define-site.js';
3
- export { ConflictError, NotFoundError } from './errors.js';
3
+ export { ConflictError, MediaInUseError, NotFoundError } from './errors.js';
4
4
  export { UNCIAL_CMS_RUNTIME_SENTINEL } from './sentinel.js';
5
5
  export { mountEditorPage, type MountEditorPageOptions } from './mount.js';
6
6
  export { createEditorSession, defaultSessionProvider, forgeAdapter, type CreateEditorSessionOptions } from './editor-session.js';
7
7
  export { createEditorController, conflictDownloadFilename, type DownloadPayload, type EditorController, type EditorControllerOptions, type EditorPageUi, type RecordState, type StatusView } from './editor-controller.js';
8
8
  export { mountIndexPage, type MountIndexPageOptions } from './index-page.js';
9
- export { createPage, deletePage, listPages, uploadAsset, uploadImageAsset, type PageRef, type UploadAssetFile, type UploadAssetOptions, type UploadAssetResult, type UploadImageAssetOptions } from './index-actions.js';
9
+ export type { UncialDashboardElement } from './dashboard/element.js';
10
+ export type { DashboardAction, DashboardOptions } from './dashboard/types.js';
11
+ export { createPage, deletePage, listPages, saveGlobal, uploadAsset, uploadImageAsset, type PageRef, type SaveGlobalDeps, type UploadAssetFile, type UploadAssetOptions, type UploadAssetResult, type UploadImageAssetOptions } from './index-actions.js';
10
12
  export { fitImage, type FitOptions, type FittedImage, type ImageEncoder, type EncodableImage } from './fit-image.js';
11
13
  export { servedUrl } from './served-url.js';
12
14
  export { cmsImageSource } from './image-source.js';
15
+ export { mediaSourceFor, type MediaItem, type MediaSource } from './media-source.js';
13
16
  export { MAX_CONTENT_BYTES } from './constants.js';
14
17
  export { hashForPagePath, pagePathFromHash, validatePagePath } from './paths/index.js';
15
18
  export { parseDocument, serializeDocument, type Blocks } from './document.js';
16
- export { patSessionProvider, popupSessionProvider } from './github/index.js';
19
+ export { brokerSessionProvider, patSessionProvider, popupSessionProvider, type BrokerSessionOptions } from './github/index.js';
17
20
  export type { Action, MediaItemView, MediaListView, VersionView } from './server-forge/protocol.js';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { defineServerSite, defineSite, DEFAULT_APP_SLUG, DEFAULT_AUTH_WORKER_URL } from './define-site.js';
2
- export { ConflictError, NotFoundError } from './errors.js';
2
+ export { ConflictError, MediaInUseError, NotFoundError } from './errors.js';
3
3
  export { UNCIAL_CMS_RUNTIME_SENTINEL } from './sentinel.js';
4
4
  export { mountEditorPage } from './mount.js';
5
5
  /*
@@ -12,11 +12,12 @@ export { mountEditorPage } from './mount.js';
12
12
  export { createEditorSession, defaultSessionProvider, forgeAdapter } from './editor-session.js';
13
13
  export { createEditorController, conflictDownloadFilename } from './editor-controller.js';
14
14
  export { mountIndexPage } from './index-page.js';
15
- export { createPage, deletePage, listPages, uploadAsset, uploadImageAsset } from './index-actions.js';
15
+ export { createPage, deletePage, listPages, saveGlobal, uploadAsset, uploadImageAsset } from './index-actions.js';
16
16
  export { fitImage } from './fit-image.js';
17
17
  export { servedUrl } from './served-url.js';
18
18
  export { cmsImageSource } from './image-source.js';
19
+ export { mediaSourceFor } from './media-source.js';
19
20
  export { MAX_CONTENT_BYTES } from './constants.js';
20
21
  export { hashForPagePath, pagePathFromHash, validatePagePath } from './paths/index.js';
21
22
  export { parseDocument, serializeDocument } from './document.js';
22
- export { patSessionProvider, popupSessionProvider } from './github/index.js';
23
+ export { brokerSessionProvider, patSessionProvider, popupSessionProvider } from './github/index.js';
@@ -2,8 +2,14 @@ import type { Plugin } from 'vite';
2
2
  export interface LocalVitePluginOptions {
3
3
  /** Repository root: every path the endpoint receives resolves against it. */
4
4
  root: string;
5
- /** Repo-root-relative directories a request may address, as the site declares them. */
6
- permittedRoots: string[];
5
+ /**
6
+ * Repo-root-relative directories a request may address, as the site declares
7
+ * them. An entry with `local` sits at that FS path instead of under `root`.
8
+ */
9
+ permittedRoots: Array<string | {
10
+ path: string;
11
+ local: string;
12
+ }>;
7
13
  /** Vite `server.host`; defaults to loopback because the endpoint has no auth. */
8
14
  host?: string | boolean;
9
15
  }
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { mkdir, readFile, readdir, rename, rm, unlink, writeFile } from 'node:fs/promises';
3
- import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
3
+ import { dirname, isAbsolute, posix, relative, resolve, sep } from 'node:path';
4
4
  import { MAX_CONTENT_BYTES } from '../constants.js';
5
5
  import { LOCAL_API_PATH } from './constants.js';
6
6
  /**
@@ -42,14 +42,21 @@ async function readJson(request) {
42
42
  throw new HttpError(400, 'Request body must be valid JSON.');
43
43
  }
44
44
  }
45
+ function normalizePath(path) {
46
+ const normalized = posix.normalize(path).replace(/\/+$/, '');
47
+ return normalized === '.' ? '' : normalized;
48
+ }
45
49
  function resolveRoots({ root, permittedRoots }) {
46
50
  const repositoryRoot = resolve(root);
47
51
  return {
48
52
  root: repositoryRoot,
49
- permitted: permittedRoots.map((declared) => ({
50
- declared,
51
- absolute: resolve(repositoryRoot, declared)
52
- }))
53
+ permitted: permittedRoots.map((entry) => {
54
+ const declared = typeof entry === 'string' ? entry : entry.path;
55
+ return {
56
+ declared: normalizePath(declared).replace(/^\/+/, ''),
57
+ absolute: typeof entry === 'string' ? resolve(repositoryRoot, entry) : resolve(entry.local)
58
+ };
59
+ })
53
60
  };
54
61
  }
55
62
  function contains(directory, target) {
@@ -64,16 +71,26 @@ function repositoryPath(roots, encodedPath) {
64
71
  catch {
65
72
  throw new HttpError(400, 'Path is not valid URL encoding.');
66
73
  }
67
- const target = resolve(roots.root, path);
68
- if (!roots.permitted.some((permitted) => contains(permitted.absolute, target))) {
69
- const names = roots.permitted.map((permitted) => permitted.declared).join(', ');
70
- throw new HttpError(403, `Path must stay within ${names}.`);
74
+ const normalized = normalizePath(path);
75
+ for (const permitted of roots.permitted) {
76
+ const { declared } = permitted;
77
+ const rest = declared === '' || normalized === declared
78
+ ? normalized.slice(declared.length)
79
+ : normalized.startsWith(`${declared}/`)
80
+ ? normalized.slice(declared.length + 1)
81
+ : undefined;
82
+ if (rest === undefined)
83
+ continue;
84
+ const target = resolve(permitted.absolute, rest);
85
+ if (contains(permitted.absolute, target))
86
+ return { target, permitted };
71
87
  }
72
- return target;
88
+ const names = roots.permitted.map((permitted) => permitted.declared).join(', ');
89
+ throw new HttpError(403, `Path must stay within ${names}.`);
73
90
  }
74
91
  async function handleRead(request, response, roots, encodedPath) {
75
92
  await readJson(request);
76
- const target = repositoryPath(roots, encodedPath);
93
+ const { target } = repositoryPath(roots, encodedPath);
77
94
  let content;
78
95
  try {
79
96
  content = await readFile(target);
@@ -103,7 +120,7 @@ async function handleWrite(request, response, roots, encodedPath) {
103
120
  if (body.sha !== undefined && typeof body.sha !== 'string') {
104
121
  throw new HttpError(400, 'Write sha must be a string when provided.');
105
122
  }
106
- const target = repositoryPath(roots, encodedPath);
123
+ const { target } = repositoryPath(roots, encodedPath);
107
124
  const content = Buffer.from(body.content, body.encoding === 'base64' ? 'base64' : 'utf8');
108
125
  if (content.byteLength > MAX_CONTENT_BYTES) {
109
126
  throw new HttpError(413, `Content exceeds ${MAX_CONTENT_BYTES} bytes.`);
@@ -141,7 +158,7 @@ async function handleWrite(request, response, roots, encodedPath) {
141
158
  }
142
159
  async function handleDelete(request, response, roots, encodedPath) {
143
160
  await readJson(request);
144
- const target = repositoryPath(roots, encodedPath);
161
+ const { target } = repositoryPath(roots, encodedPath);
145
162
  try {
146
163
  await unlink(target);
147
164
  }
@@ -155,7 +172,7 @@ async function handleDelete(request, response, roots, encodedPath) {
155
172
  }
156
173
  async function handleList(request, response, roots, encodedPath) {
157
174
  await readJson(request);
158
- const target = repositoryPath(roots, encodedPath);
175
+ const { target, permitted } = repositoryPath(roots, encodedPath);
159
176
  let entries;
160
177
  try {
161
178
  entries = await readdir(target, { encoding: 'utf8', withFileTypes: true });
@@ -170,7 +187,7 @@ async function handleList(request, response, roots, encodedPath) {
170
187
  entries: entries
171
188
  .filter((entry) => entry.isFile() || entry.isDirectory())
172
189
  .map((entry) => ({
173
- path: relative(roots.root, resolve(target, entry.name)).split(sep).join('/'),
190
+ path: posix.join(permitted.declared, relative(permitted.absolute, resolve(target, entry.name)).split(sep).join('/')),
174
191
  type: entry.isDirectory() ? 'dir' : 'file'
175
192
  }))
176
193
  });