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
@@ -0,0 +1,45 @@
1
+ import type { Action } from './server-forge/protocol.js';
2
+ import type { ForgeAdapter, UncialCmsSiteConfig } from './types.js';
3
+ export interface MediaSource {
4
+ capabilities: {
5
+ metadata: boolean;
6
+ usage: boolean;
7
+ delete: boolean;
8
+ search: boolean;
9
+ };
10
+ list(query?: {
11
+ search?: string;
12
+ contentType?: string;
13
+ }): Promise<MediaItem[]>;
14
+ upload(file: File, opts?: {
15
+ title?: string;
16
+ }): Promise<MediaItem>;
17
+ delete(item: MediaItem): Promise<void>;
18
+ }
19
+ export interface MediaItem {
20
+ id: string;
21
+ /** What a Content document stores as `src`: base-less on git forges. */
22
+ url: string;
23
+ filename: string;
24
+ contentType: string;
25
+ size?: number;
26
+ width?: number;
27
+ height?: number;
28
+ title?: string;
29
+ uploadedAt?: string;
30
+ uploadedBy?: string;
31
+ usage?: Array<{
32
+ path: string;
33
+ title?: string;
34
+ }>;
35
+ }
36
+ export declare function serverMediaSource(apiBase: string, onAllowed?: (allowed: Action[]) => void): MediaSource;
37
+ export declare function mediaSourceFor(config: UncialCmsSiteConfig, session?: {
38
+ adapter: ForgeAdapter;
39
+ author: {
40
+ name: string;
41
+ email: string;
42
+ };
43
+ }, opts?: {
44
+ staticDir?: string;
45
+ }): MediaSource;
@@ -0,0 +1,113 @@
1
+ import { fitImage } from './fit-image.js';
2
+ import { uploadAsset } from './index-actions.js';
3
+ import { servedUrl } from './served-url.js';
4
+ import { deleteMedia, listMedia, uploadMedia } from './server-forge/media.js';
5
+ import { configMediaDir } from './upload-context.js';
6
+ const CONTENT_TYPES = {
7
+ png: 'image/png',
8
+ jpg: 'image/jpeg',
9
+ jpeg: 'image/jpeg',
10
+ gif: 'image/gif',
11
+ webp: 'image/webp',
12
+ avif: 'image/avif',
13
+ svg: 'image/svg+xml'
14
+ };
15
+ function matchesType(contentType, pattern) {
16
+ if (!pattern)
17
+ return true;
18
+ return pattern.endsWith('/*')
19
+ ? contentType.startsWith(pattern.slice(0, -1))
20
+ : contentType === pattern;
21
+ }
22
+ function gitMediaSource(opts) {
23
+ const { adapter, author, config, mediaDir, staticDir } = opts;
24
+ const item = (path) => {
25
+ const filename = path.slice(path.lastIndexOf('/') + 1);
26
+ const extension = filename.slice(filename.lastIndexOf('.') + 1).toLowerCase();
27
+ return {
28
+ id: path,
29
+ url: servedUrl({ config }, path, staticDir),
30
+ filename,
31
+ contentType: CONTENT_TYPES[extension] ?? 'application/octet-stream'
32
+ };
33
+ };
34
+ return {
35
+ capabilities: { metadata: false, usage: false, delete: true, search: false },
36
+ async list({ contentType } = {}) {
37
+ const entries = await adapter.listDir(mediaDir);
38
+ return entries
39
+ .filter((entry) => entry.type === 'file')
40
+ .map((entry) => entry.path)
41
+ .sort()
42
+ .map(item)
43
+ .filter((media) => matchesType(media.contentType, contentType));
44
+ },
45
+ async upload(file) {
46
+ const raster = file.type.startsWith('image/') && file.type !== 'image/svg+xml';
47
+ const asset = raster
48
+ ? await fitImage(file)
49
+ : {
50
+ bytes: new Uint8Array(await file.arrayBuffer()),
51
+ filename: file.name,
52
+ contentType: file.type || 'application/octet-stream'
53
+ };
54
+ const { path } = await uploadAsset({ adapter }, asset, { mediaDir, author });
55
+ return item(path);
56
+ },
57
+ async delete(media) {
58
+ // The forge deletes at a blob sha, which a listing does not carry.
59
+ const { sha } = await adapter.readFile(media.id);
60
+ await adapter.deleteFile(media.id, { message: `uncial-cms: delete ${media.id}`, sha });
61
+ }
62
+ };
63
+ }
64
+ function fromView(item) {
65
+ return {
66
+ id: item.id,
67
+ url: item.url,
68
+ filename: item.filename,
69
+ contentType: item.contentType,
70
+ size: item.size,
71
+ width: item.width ?? undefined,
72
+ height: item.height ?? undefined,
73
+ title: item.title,
74
+ uploadedAt: item.uploadedAt,
75
+ uploadedBy: item.uploadedBy
76
+ };
77
+ }
78
+ export function serverMediaSource(apiBase, onAllowed) {
79
+ return {
80
+ capabilities: { metadata: true, usage: true, delete: true, search: true },
81
+ async list(query) {
82
+ const view = await listMedia(apiBase, query);
83
+ onAllowed?.(view.allowed);
84
+ return view.items.map((item) => ({
85
+ ...fromView(item),
86
+ usage: item.usagePaths.map((path) => ({ path }))
87
+ }));
88
+ },
89
+ upload: async (file, opts) => fromView(await uploadMedia(apiBase, file, opts)),
90
+ delete: (item) => deleteMedia(apiBase, item.id)
91
+ };
92
+ }
93
+ export function mediaSourceFor(config, session, opts = {}) {
94
+ if (config.forge === 'server') {
95
+ if (!config.mediaApiBase) {
96
+ throw new Error('This server site sets no `mediaApiBase`, so it has no Media library.');
97
+ }
98
+ return serverMediaSource(config.mediaApiBase);
99
+ }
100
+ if (!session) {
101
+ throw new Error('A git forge reaches its media through a signed-in editing session.');
102
+ }
103
+ const mediaDir = configMediaDir(config);
104
+ if (!mediaDir)
105
+ throw new Error('No media directory: set `mediaDir` in the site config.');
106
+ return gitMediaSource({
107
+ adapter: session.adapter,
108
+ author: session.author,
109
+ config,
110
+ mediaDir,
111
+ staticDir: opts.staticDir ?? 'static'
112
+ });
113
+ }
package/dist/mount.d.ts CHANGED
@@ -38,6 +38,9 @@ export interface MountEditorPageOptions {
38
38
  editorStylesheets?: string[];
39
39
  /** Where `input: 'image'` fields get images; defaults to `cmsImageSource(config)`. */
40
40
  imageSource?: UncialEditorElement['imageSource'];
41
+ /** Svelte components for host-defined attribute `input` kinds. */
42
+ attributeInputs?: UncialEditorElement['attributeInputs'];
43
+ onerror?: (error: unknown) => void;
41
44
  }
42
45
  export declare function mountEditorPage(target: HTMLElement, opts: MountEditorPageOptions): {
43
46
  destroy(): void;
package/dist/mount.js CHANGED
@@ -73,6 +73,7 @@ export function mountEditorPage(target, opts) {
73
73
  if (opts.presentation !== undefined)
74
74
  editor.presentation = opts.presentation;
75
75
  editor.imageSource = opts.imageSource ?? cmsImageSource(config);
76
+ editor.attributeInputs = opts.attributeInputs;
76
77
  editor.blocks = blocks;
77
78
  editor.schema = schema;
78
79
  // Forward the schema's declared meta fields so the editor renders (and edits)
@@ -86,6 +87,7 @@ export function mountEditorPage(target, opts) {
86
87
  target.append(root);
87
88
  let destroyed = false;
88
89
  const ui = {
90
+ failed: opts.onerror,
89
91
  status(view) {
90
92
  status.replaceChildren(document.createTextNode(view.text));
91
93
  status.dataset.tone = view.tone;
@@ -136,6 +138,7 @@ export function mountEditorPage(target, opts) {
136
138
  void controller.load().catch((error) => {
137
139
  if (destroyed)
138
140
  return;
141
+ opts.onerror?.(error);
139
142
  ui.status({
140
143
  tone: 'error',
141
144
  text: error instanceof Error ? error.message : 'Failed to load the document.'
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `uncial-cms/nav` — grouped, ordered site navigation from Content documents'
3
+ * `navGroup`, `navOrder` and `navLabel` meta. Pure: safe in any bundle.
4
+ */
5
+ export interface NavLink {
6
+ href: string;
7
+ label: string;
8
+ }
9
+ export type NavEntry = ({
10
+ kind: 'link';
11
+ } & NavLink) | {
12
+ kind: 'group';
13
+ id: string;
14
+ label: string;
15
+ links: NavLink[];
16
+ };
17
+ /** A page as the route helpers' `list()` returns it. */
18
+ export interface NavPage {
19
+ path: string;
20
+ document: {
21
+ meta?: Record<string, unknown>;
22
+ };
23
+ }
24
+ /** A link that is not a Content document, placed like one. */
25
+ export interface NavExtraLink extends NavLink {
26
+ /** Blank or absent for a top-level link. */
27
+ group?: string;
28
+ order?: number;
29
+ }
30
+ export interface BuildNavOptions {
31
+ /** Prepended to every site-root-relative href, e.g. SvelteKit's `base`. */
32
+ base?: string;
33
+ links?: NavExtraLink[];
34
+ }
35
+ /**
36
+ * Links sort by `navOrder` (absent last), then label. A group sits where its
37
+ * first member sorts and is labelled by its `navGroup`.
38
+ */
39
+ export declare function buildNav(pages: NavPage[], options?: BuildNavOptions): NavEntry[];
@@ -0,0 +1,52 @@
1
+ /**
2
+ * `uncial-cms/nav` — grouped, ordered site navigation from Content documents'
3
+ * `navGroup`, `navOrder` and `navLabel` meta. Pure: safe in any bundle.
4
+ */
5
+ const text = (value) => (typeof value === 'string' ? value.trim() : '');
6
+ const finite = (value) => typeof value === 'number' && Number.isFinite(value) ? value : Infinity;
7
+ /**
8
+ * Links sort by `navOrder` (absent last), then label. A group sits where its
9
+ * first member sorts and is labelled by its `navGroup`.
10
+ */
11
+ export function buildNav(pages, options = {}) {
12
+ const base = (options.base ?? '').replace(/\/+$/, '');
13
+ const withBase = (href) => (href.startsWith('/') ? base + href : href);
14
+ const placed = [
15
+ ...(options.links ?? []).map((link) => ({
16
+ href: withBase(link.href),
17
+ label: link.label,
18
+ group: text(link.group),
19
+ order: finite(link.order)
20
+ })),
21
+ ...pages.map(({ path, document }) => {
22
+ const meta = document.meta ?? {};
23
+ return {
24
+ href: withBase(path === '' ? '/' : `/${path}/`),
25
+ label: text(meta.navLabel) || text(meta.title) || path,
26
+ group: text(meta.navGroup),
27
+ order: finite(meta.navOrder)
28
+ };
29
+ })
30
+ ];
31
+ placed.sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));
32
+ const entries = [];
33
+ const groups = new Map();
34
+ for (const { href, label, group } of placed) {
35
+ if (group === '') {
36
+ entries.push({ kind: 'link', href, label });
37
+ continue;
38
+ }
39
+ let links = groups.get(group);
40
+ if (!links) {
41
+ links = [];
42
+ groups.set(group, links);
43
+ const id = group
44
+ .toLowerCase()
45
+ .replace(/[^a-z0-9]+/g, '-')
46
+ .replace(/^-|-$/g, '');
47
+ entries.push({ kind: 'group', id, label: group, links });
48
+ }
49
+ links.push({ href, label });
50
+ }
51
+ return entries;
52
+ }
@@ -3,10 +3,12 @@
3
3
  */
4
4
  import type { Site } from './define-site.js';
5
5
  /**
6
- * Everything under the site's static directory is copied to the site root at
7
- * build time, so a committed asset path becomes a served URL by dropping that
8
- * prefix. `staticDir` is repo-root-relative, like `mediaDir`; a `mediaDir` that
9
- * does not sit under it is not served by the copy, so the path is returned
6
+ * A site with a `mediaUrlPrefix` serves `mediaDir` under that prefix wherever
7
+ * the directory lives, e.g. on a content branch. Otherwise everything under the
8
+ * site's static directory is copied to the site root at build time, so a
9
+ * committed asset path becomes a served URL by dropping that prefix.
10
+ * `staticDir` is repo-root-relative, like `mediaDir`; a `mediaDir` that does not
11
+ * sit under it is not served by the copy, so the path is returned
10
12
  * site-root-absolute unchanged.
11
13
  *
12
14
  * The result carries no base path: a stored `src` must stay correct at every
@@ -1,9 +1,12 @@
1
- import { configMediaDir } from './upload-context.js';
1
+ import { configMediaDir, configMediaUrlPrefix } from './upload-context.js';
2
+ const trimSlashes = (path) => path.replace(/^\/+|\/+$/g, '');
2
3
  /**
3
- * Everything under the site's static directory is copied to the site root at
4
- * build time, so a committed asset path becomes a served URL by dropping that
5
- * prefix. `staticDir` is repo-root-relative, like `mediaDir`; a `mediaDir` that
6
- * does not sit under it is not served by the copy, so the path is returned
4
+ * A site with a `mediaUrlPrefix` serves `mediaDir` under that prefix wherever
5
+ * the directory lives, e.g. on a content branch. Otherwise everything under the
6
+ * site's static directory is copied to the site root at build time, so a
7
+ * committed asset path becomes a served URL by dropping that prefix.
8
+ * `staticDir` is repo-root-relative, like `mediaDir`; a `mediaDir` that does not
9
+ * sit under it is not served by the copy, so the path is returned
7
10
  * site-root-absolute unchanged.
8
11
  *
9
12
  * The result carries no base path: a stored `src` must stay correct at every
@@ -11,10 +14,18 @@ import { configMediaDir } from './upload-context.js';
11
14
  * render time.
12
15
  */
13
16
  export function servedUrl(site, repoPath, staticDir = 'static') {
14
- const prefix = `${staticDir.replace(/\/+$/, '')}/`;
15
17
  const mediaDir = configMediaDir(site.config);
18
+ const urlPrefix = configMediaUrlPrefix(site.config);
19
+ const path = repoPath.replace(/^\/+/, '');
20
+ if (mediaDir !== undefined && urlPrefix !== undefined) {
21
+ const dir = `${trimSlashes(mediaDir)}/`;
22
+ if (path.startsWith(dir)) {
23
+ return `/${[trimSlashes(urlPrefix), path.slice(dir.length)].filter(Boolean).join('/')}`;
24
+ }
25
+ }
26
+ const prefix = `${staticDir.replace(/\/+$/, '')}/`;
16
27
  if (mediaDir?.startsWith(prefix) && repoPath.startsWith(prefix)) {
17
28
  return repoPath.slice(prefix.length - 1);
18
29
  }
19
- return `/${repoPath.replace(/^\/+/, '')}`;
30
+ return `/${path}`;
20
31
  }
@@ -1,5 +1,5 @@
1
1
  import { type Action, type ServerUser } from '../server-forge/protocol.js';
2
- import { type MediaLibrary } from './media.js';
2
+ import type { MediaLibrary } from './media.js';
3
3
  import type { ContentRecord, ContentStore } from './postgres-store.js';
4
4
  export type { Action, ServerUser };
5
5
  export type Authorize = (user: ServerUser | null, action: Action, record: ContentRecord | null) => boolean | Promise<boolean>;
@@ -1,6 +1,6 @@
1
- import { ConflictError, NotFoundError } from '../errors.js';
1
+ import { ConflictError, MediaInUseError, NotFoundError } from '../errors.js';
2
+ import { assertPagePath, GLOBAL_KIND, GLOBAL_NAME, globalRecordPath } from '../globals.js';
2
3
  import { ACTIONS, contentStatus } from '../server-forge/protocol.js';
3
- import { MediaInUseError } from './media.js';
4
4
  class HttpError extends Error {
5
5
  status;
6
6
  constructor(status, message) {
@@ -31,9 +31,20 @@ function text(value, name) {
31
31
  throw new HttpError(400, `Expected a string "${name}".`);
32
32
  return value;
33
33
  }
34
+ function pagePath(path) {
35
+ try {
36
+ assertPagePath(path);
37
+ return path;
38
+ }
39
+ catch (error) {
40
+ throw new HttpError(400, error.message);
41
+ }
42
+ }
34
43
  function summary(record) {
44
+ const { meta } = (record.draft ?? record.published ?? {});
35
45
  return {
36
46
  path: record.path,
47
+ title: typeof meta?.title === 'string' ? meta.title : undefined,
37
48
  kind: record.kind,
38
49
  status: contentStatus(record.draft !== null, record.published !== null),
39
50
  publishedAt: record.publishedAt?.toISOString() ?? null,
@@ -109,10 +120,24 @@ export function createServerContentHandlers(opts) {
109
120
  }),
110
121
  POST: handle(async ({ request }, user) => {
111
122
  const input = await body(request);
112
- const path = text(input.path, 'path');
123
+ if (input.action === 'global-edit') {
124
+ const name = text(input.name, 'name');
125
+ if (!GLOBAL_NAME.test(name))
126
+ throw new HttpError(400, `"${name}" is not a Global name.`);
127
+ await guard(user, 'global-edit', await store.get(globalRecordPath(name)));
128
+ const etag = input.etag === undefined ? undefined : text(input.etag, 'etag');
129
+ const record = await store.publishGlobal(name, input.document, {
130
+ etag,
131
+ author: user.email
132
+ });
133
+ return view(user, record, etag === undefined ? 201 : 200);
134
+ }
135
+ const path = pagePath(text(input.path, 'path'));
113
136
  if (input.action === 'create') {
114
137
  await guard(user, 'create', null);
115
138
  const kind = input.kind === undefined ? 'page' : text(input.kind, 'kind');
139
+ if (kind === GLOBAL_KIND)
140
+ throw new HttpError(400, 'Globals are saved with global-edit.');
116
141
  return view(user, await store.create(path, kind, input.draft, { author: user.email }), 201);
117
142
  }
118
143
  if (input.action === 'publish' || input.action === 'unpublish') {
@@ -139,6 +164,7 @@ export function createServerContentHandlers(opts) {
139
164
  const to = opts.normalizePath ? opts.normalizePath(requested) : requested;
140
165
  if (to === null)
141
166
  throw new HttpError(400, `${requested} is not a path content can live at.`);
167
+ pagePath(to);
142
168
  if (opts.derivePath?.(record.kind, record.draft ?? record.published)) {
143
169
  throw new HttpError(400, `The path of ${path} follows its metadata; edit that instead.`);
144
170
  }
@@ -150,15 +176,16 @@ export function createServerContentHandlers(opts) {
150
176
  const write = { etag: text(input.etag, 'etag'), author: user.email };
151
177
  return view(user, await store.move(path, to, write));
152
178
  }
153
- throw new HttpError(400, 'Expected "action" to be create, publish, unpublish, restore or move.');
179
+ throw new HttpError(400, 'Expected "action" to be create, publish, unpublish, restore, move or global-edit.');
154
180
  }),
155
181
  PUT: handle(async ({ request }, user) => {
156
182
  const input = await body(request);
157
- const path = text(input.path, 'path');
183
+ const path = pagePath(text(input.path, 'path'));
158
184
  const record = await existing(path);
159
185
  await guard(user, 'save-draft', record);
160
186
  const etag = text(input.etag, 'etag');
161
187
  const target = opts.derivePath?.(record.kind, input.draft) ?? path;
188
+ pagePath(target);
162
189
  if (target !== path) {
163
190
  await guard(user, 'move', record);
164
191
  if (await store.get(target)) {
@@ -1,5 +1,6 @@
1
1
  export { createPostgresContentStore } from './postgres-store.js';
2
2
  export type { ContentRecord, ContentStore, OnMove, RetentionPolicy, VersionSummary } from './postgres-store.js';
3
3
  export { contentStoreMigrations, mediaLibraryMigrations } from './migrations.js';
4
- export { createMediaLibrary, MediaInUseError, type MediaItem, type MediaLibrary, type MediaLibraryOptions } from './media.js';
4
+ export { MediaInUseError } from '../errors.js';
5
+ export { createMediaLibrary, type MediaItem, type MediaLibrary, type MediaLibraryOptions } from './media.js';
5
6
  export { createServerContentHandlers, createServerMediaHandlers, type Action, type Authorize, type ServerContentHandlerOptions, type ServerMediaHandlerOptions, type ServerUser } from './handlers.js';
@@ -1,4 +1,5 @@
1
1
  export { createPostgresContentStore } from './postgres-store.js';
2
2
  export { contentStoreMigrations, mediaLibraryMigrations } from './migrations.js';
3
- export { createMediaLibrary, MediaInUseError } from './media.js';
3
+ export { MediaInUseError } from '../errors.js';
4
+ export { createMediaLibrary } from './media.js';
4
5
  export { createServerContentHandlers, createServerMediaHandlers } from './handlers.js';
@@ -33,6 +33,7 @@ export interface MediaLibrary {
33
33
  contentType?: string;
34
34
  }): Promise<Array<MediaItem & {
35
35
  usage: number;
36
+ usagePaths: string[];
36
37
  }>>;
37
38
  upload(bytes: Uint8Array, meta: {
38
39
  filename: string;
@@ -46,16 +47,6 @@ export interface MediaLibrary {
46
47
  }>;
47
48
  delete(id: string): Promise<void>;
48
49
  }
49
- export declare class MediaInUseError extends Error {
50
- readonly usage: {
51
- count: number;
52
- paths: string[];
53
- };
54
- constructor(usage: {
55
- count: number;
56
- paths: string[];
57
- });
58
- }
59
50
  /** Reads width and height from a PNG, GIF, WebP or JPEG header; null for anything else. */
60
51
  export declare function imageSize(bytes: Uint8Array): {
61
52
  width: number;
@@ -1,13 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { NotFoundError } from '../errors.js';
3
- export class MediaInUseError extends Error {
4
- usage;
5
- constructor(usage) {
6
- super(`This Media item is used by ${usage.count} Content document${usage.count === 1 ? '' : 's'}: ${usage.paths.join(', ')}.`);
7
- this.usage = usage;
8
- this.name = 'MediaInUseError';
9
- }
10
- }
2
+ import { MediaInUseError, NotFoundError } from '../errors.js';
3
+ import { GLOBAL_KIND } from '../globals.js';
11
4
  const EXTENSIONS = {
12
5
  'image/webp': 'webp',
13
6
  'image/png': 'png',
@@ -100,7 +93,7 @@ export function createMediaLibrary(opts) {
100
93
  })
101
94
  })));
102
95
  async function referencing(urls) {
103
- const records = await store.list();
96
+ const records = (await Promise.all([store.list(), store.list({ kind: GLOBAL_KIND })])).flat();
104
97
  const paths = new Map(urls.map((url) => [url, []]));
105
98
  for (const record of records) {
106
99
  const docs = [record.draft, record.published]
@@ -136,7 +129,10 @@ export function createMediaLibrary(opts) {
136
129
  `;
137
130
  const items = rows.map((row) => toItem(row, publicBaseUrl));
138
131
  const paths = await referencing(items.map((item) => item.url));
139
- return items.map((item) => ({ ...item, usage: paths.get(item.url).length }));
132
+ return items.map((item) => {
133
+ const usagePaths = paths.get(item.url);
134
+ return { ...item, usage: usagePaths.length, usagePaths };
135
+ });
140
136
  },
141
137
  async upload(bytes, { filename, title, contentType, uploadedBy }) {
142
138
  const id = createHash('sha256').update(bytes).digest('hex');
@@ -22,6 +22,7 @@ export interface VersionSummary {
22
22
  }
23
23
  export interface ContentStore {
24
24
  get(path: string): Promise<ContentRecord | null>;
25
+ /** Globals are listed only when asked for by their kind, `global`. */
25
26
  list(query?: {
26
27
  kind?: string;
27
28
  status?: 'draft' | 'published' | 'any';
@@ -55,6 +56,10 @@ export interface ContentStore {
55
56
  etag: string;
56
57
  author: string;
57
58
  }): Promise<ContentRecord>;
59
+ publishGlobal(name: string, doc: unknown, opts: {
60
+ etag?: string;
61
+ author: string;
62
+ }): Promise<ContentRecord>;
58
63
  }
59
64
  /**
60
65
  * Runs inside a move's transaction, after the record has moved, so a host can
@@ -1,4 +1,5 @@
1
1
  import { ConflictError, NotFoundError } from '../errors.js';
2
+ import { assertPagePath, GLOBAL_KIND, globalRecordPath, GLOBALS_DIR } from '../globals.js';
2
3
  const UNIQUE_VIOLATION = '23505';
3
4
  function toRecord(row) {
4
5
  return {
@@ -26,6 +27,14 @@ export function createPostgresContentStore(sql, opts) {
26
27
  throw new ConflictError();
27
28
  return row;
28
29
  }
30
+ async function keepPublished(tx, current, author) {
31
+ if (current.published === null)
32
+ return;
33
+ await tx `
34
+ insert into uncial_content_versions (content_id, doc, created_by)
35
+ values (${current.id}, ${json(current.published)}, ${author})
36
+ `;
37
+ }
29
38
  async function prune(tx, contentId) {
30
39
  const { retention } = opts;
31
40
  if ('keep' in retention) {
@@ -60,11 +69,15 @@ export function createPostgresContentStore(sql, opts) {
60
69
  ${kind === undefined ? sql `` : sql `and kind = ${kind}`}
61
70
  ${status === 'draft' ? sql `and draft is not null` : sql ``}
62
71
  ${status === 'published' ? sql `and published is not null` : sql ``}
72
+ ${kind === GLOBAL_KIND ? sql `` : sql `and not starts_with(path, ${`/${GLOBALS_DIR}/`})`}
63
73
  order by path
64
74
  `;
65
75
  return rows.map(toRecord);
66
76
  },
67
77
  async create(path, kind, draft, { author }) {
78
+ assertPagePath(path);
79
+ if (kind === GLOBAL_KIND)
80
+ throw new Error('Globals are saved with publishGlobal.');
68
81
  try {
69
82
  const [row] = await sql `
70
83
  insert into uncial_content (kind, path, draft, updated_by)
@@ -80,6 +93,7 @@ export function createPostgresContentStore(sql, opts) {
80
93
  }
81
94
  },
82
95
  async saveDraft(path, draft, { etag, author }) {
96
+ assertPagePath(path);
83
97
  return sql.begin(async (tx) => {
84
98
  await lock(tx, path, etag);
85
99
  const [row] = await tx `
@@ -93,19 +107,46 @@ export function createPostgresContentStore(sql, opts) {
93
107
  });
94
108
  },
95
109
  async publish(path, { etag, author }) {
110
+ assertPagePath(path);
96
111
  return sql.begin(async (tx) => {
97
112
  const current = await lock(tx, path, etag);
98
113
  if (current.draft === null)
99
114
  throw new Error(`Nothing to publish: ${path} has no Draft.`);
100
- if (current.published !== null) {
101
- await tx `
102
- insert into uncial_content_versions (content_id, doc, created_by)
103
- values (${current.id}, ${json(current.published)}, ${author})
115
+ await keepPublished(tx, current, author);
116
+ const [row] = await tx `
117
+ update uncial_content
118
+ set published = draft, draft = null, published_at = now(),
119
+ etag = gen_random_uuid()::text, updated_at = now(), updated_by = ${author}
120
+ where id = ${current.id}
121
+ returning *
122
+ `;
123
+ await prune(tx, current.id);
124
+ return toRecord(row);
125
+ });
126
+ },
127
+ async publishGlobal(name, doc, { etag, author }) {
128
+ const path = globalRecordPath(name);
129
+ if (etag === undefined) {
130
+ try {
131
+ const [row] = await sql `
132
+ insert into uncial_content (kind, path, published, published_at, updated_by)
133
+ values (${GLOBAL_KIND}, ${path}, ${json(doc)}, now(), ${author})
134
+ returning *
104
135
  `;
136
+ return toRecord(row);
137
+ }
138
+ catch (error) {
139
+ if (isUniqueViolation(error))
140
+ throw new ConflictError();
141
+ throw error;
105
142
  }
143
+ }
144
+ return sql.begin(async (tx) => {
145
+ const current = await lock(tx, path, etag);
146
+ await keepPublished(tx, current, author);
106
147
  const [row] = await tx `
107
148
  update uncial_content
108
- set published = draft, draft = null, published_at = now(),
149
+ set published = ${json(doc)}, draft = null, published_at = now(),
109
150
  etag = gen_random_uuid()::text, updated_at = now(), updated_by = ${author}
110
151
  where id = ${current.id}
111
152
  returning *
@@ -115,6 +156,7 @@ export function createPostgresContentStore(sql, opts) {
115
156
  });
116
157
  },
117
158
  async unpublish(path, { etag, author }) {
159
+ assertPagePath(path);
118
160
  return sql.begin(async (tx) => {
119
161
  await lock(tx, path, etag);
120
162
  const [row] = await tx `
@@ -134,6 +176,8 @@ export function createPostgresContentStore(sql, opts) {
134
176
  });
135
177
  },
136
178
  async move(from, to, { etag, author }) {
179
+ assertPagePath(from);
180
+ assertPagePath(to);
137
181
  try {
138
182
  return await sql.begin(async (tx) => {
139
183
  await lock(tx, from, etag);
@@ -179,6 +223,7 @@ export function createPostgresContentStore(sql, opts) {
179
223
  return version.doc;
180
224
  },
181
225
  async restore(path, versionId, { etag, author }) {
226
+ assertPagePath(path);
182
227
  return sql.begin(async (tx) => {
183
228
  const current = await lock(tx, path, etag);
184
229
  const [version] = await tx `
@@ -9,6 +9,7 @@ export interface ServerForgeAdapter extends ForgeAdapter {
9
9
  getVersion(path: string, versionId: string): Promise<unknown>;
10
10
  restore(path: string, versionId: string, etag: string): Promise<ContentView>;
11
11
  move(path: string, to: string, etag: string): Promise<ContentView>;
12
+ saveGlobal(name: string, document: unknown, etag?: string): Promise<ContentView>;
12
13
  }
13
14
  export declare function serverRequest<T>(apiBase: string, method: string, opts?: {
14
15
  query?: Record<string, string>;