uncial-cms 4.0.3 → 5.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.
Files changed (47) hide show
  1. package/README.md +1 -1
  2. package/dist/define-site.d.ts +13 -4
  3. package/dist/define-site.js +10 -0
  4. package/dist/editor-controller.d.ts +25 -0
  5. package/dist/editor-controller.js +174 -14
  6. package/dist/editor-session.d.ts +1 -1
  7. package/dist/editor-session.js +9 -1
  8. package/dist/image-source.d.ts +2 -1
  9. package/dist/image-source.js +19 -5
  10. package/dist/index-actions.js +3 -3
  11. package/dist/index-page.d.ts +2 -0
  12. package/dist/index-page.js +38 -20
  13. package/dist/index.d.ts +4 -3
  14. package/dist/index.js +1 -1
  15. package/dist/local/vite.d.ts +2 -0
  16. package/dist/local/vite.js +1 -1
  17. package/dist/served-url.js +2 -1
  18. package/dist/server/handlers.d.ts +45 -0
  19. package/dist/server/handlers.js +237 -0
  20. package/dist/server/index.d.ts +5 -0
  21. package/dist/server/index.js +4 -0
  22. package/dist/server/media.d.ts +69 -0
  23. package/dist/server/media.js +181 -0
  24. package/dist/server/migrations.d.ts +8 -0
  25. package/dist/server/migrations.js +47 -0
  26. package/dist/server/postgres-store.d.ts +72 -0
  27. package/dist/server/postgres-store.js +201 -0
  28. package/dist/server-forge/adapter.d.ts +17 -0
  29. package/dist/server-forge/adapter.js +95 -0
  30. package/dist/server-forge/media.d.ts +11 -0
  31. package/dist/server-forge/media.js +26 -0
  32. package/dist/server-forge/protocol.d.ts +65 -0
  33. package/dist/server-forge/protocol.js +27 -0
  34. package/dist/server-forge/session.d.ts +2 -0
  35. package/dist/server-forge/session.js +15 -0
  36. package/dist/svelte/EditorPage.svelte +217 -7
  37. package/dist/svelte/EditorPage.svelte.d.ts +6 -0
  38. package/dist/svelte/MediaLibrary.svelte +187 -0
  39. package/dist/svelte/MediaLibrary.svelte.d.ts +7 -0
  40. package/dist/svelte/index.d.ts +1 -0
  41. package/dist/svelte/index.js +1 -0
  42. package/dist/sveltekit/index.d.ts +7 -7
  43. package/dist/sveltekit/index.js +6 -6
  44. package/dist/types.d.ts +7 -1
  45. package/dist/upload-context.d.ts +2 -0
  46. package/dist/upload-context.js +4 -0
  47. package/package.json +18 -2
@@ -1,3 +1,4 @@
1
+ import { configMediaDir } from './upload-context.js';
1
2
  /**
2
3
  * Everything under the site's static directory is copied to the site root at
3
4
  * build time, so a committed asset path becomes a served URL by dropping that
@@ -11,7 +12,7 @@
11
12
  */
12
13
  export function servedUrl(site, repoPath, staticDir = 'static') {
13
14
  const prefix = `${staticDir.replace(/\/+$/, '')}/`;
14
- const mediaDir = site.config.mediaDir;
15
+ const mediaDir = configMediaDir(site.config);
15
16
  if (mediaDir?.startsWith(prefix) && repoPath.startsWith(prefix)) {
16
17
  return repoPath.slice(prefix.length - 1);
17
18
  }
@@ -0,0 +1,45 @@
1
+ import { type Action, type ServerUser } from '../server-forge/protocol.js';
2
+ import { type MediaLibrary } from './media.js';
3
+ import type { ContentRecord, ContentStore } from './postgres-store.js';
4
+ export type { Action, ServerUser };
5
+ export type Authorize = (user: ServerUser | null, action: Action, record: ContentRecord | null) => boolean | Promise<boolean>;
6
+ interface ContentRequestEvent {
7
+ request: Request;
8
+ url: URL;
9
+ }
10
+ export interface ServerContentHandlerOptions<Event extends ContentRequestEvent> {
11
+ store: ContentStore;
12
+ authorize: Authorize;
13
+ getUser: (event: Event) => ServerUser | null | Promise<ServerUser | null>;
14
+ /**
15
+ * The path a record of this kind belongs at, given its Draft, when the host
16
+ * derives paths from metadata. Saving a Draft that derives a new path moves
17
+ * the record there, which `authorize` must also grant as `move`.
18
+ */
19
+ derivePath?: (kind: string, draft: unknown) => string | null;
20
+ /** The host's form of a path an author asked to move a record to, or null to refuse it. */
21
+ normalizePath?: (path: string) => string | null;
22
+ }
23
+ type Handler<Event> = (event: Event) => Promise<Response>;
24
+ /**
25
+ * The SvelteKit `+server.ts` exports for a `server` forge's `apiBase`. The
26
+ * record path travels in the query (GET) or the JSON body, so one route serves
27
+ * every Content document, the site root included.
28
+ */
29
+ export declare function createServerContentHandlers<Event extends ContentRequestEvent>(opts: ServerContentHandlerOptions<Event>): {
30
+ GET: Handler<Event>;
31
+ POST: Handler<Event>;
32
+ PUT: Handler<Event>;
33
+ DELETE: Handler<Event>;
34
+ };
35
+ export interface ServerMediaHandlerOptions<Event extends ContentRequestEvent> {
36
+ library: MediaLibrary;
37
+ authorize: Authorize;
38
+ getUser: (event: Event) => ServerUser | null | Promise<ServerUser | null>;
39
+ }
40
+ /** The SvelteKit `+server.ts` exports for a `server` forge's `mediaApiBase`. */
41
+ export declare function createServerMediaHandlers<Event extends ContentRequestEvent>(opts: ServerMediaHandlerOptions<Event>): {
42
+ GET: Handler<Event>;
43
+ POST: Handler<Event>;
44
+ DELETE: Handler<Event>;
45
+ };
@@ -0,0 +1,237 @@
1
+ import { ConflictError, NotFoundError } from '../errors.js';
2
+ import { ACTIONS, contentStatus } from '../server-forge/protocol.js';
3
+ import { MediaInUseError } from './media.js';
4
+ class HttpError extends Error {
5
+ status;
6
+ constructor(status, message) {
7
+ super(message);
8
+ this.status = status;
9
+ }
10
+ }
11
+ function failure(error) {
12
+ if (error instanceof HttpError)
13
+ return Response.json({ error: error.message }, { status: error.status });
14
+ if (error instanceof MediaInUseError) {
15
+ return Response.json({ error: error.message, usage: error.usage }, { status: 409 });
16
+ }
17
+ if (error instanceof ConflictError)
18
+ return Response.json({ error: error.message }, { status: 409 });
19
+ if (error instanceof NotFoundError)
20
+ return Response.json({ error: error.message }, { status: 404 });
21
+ throw error;
22
+ }
23
+ async function body(request) {
24
+ const parsed = await request.json().catch(() => null);
25
+ if (parsed === null || typeof parsed !== 'object')
26
+ throw new HttpError(400, 'Expected a JSON body.');
27
+ return parsed;
28
+ }
29
+ function text(value, name) {
30
+ if (typeof value !== 'string')
31
+ throw new HttpError(400, `Expected a string "${name}".`);
32
+ return value;
33
+ }
34
+ function summary(record) {
35
+ return {
36
+ path: record.path,
37
+ kind: record.kind,
38
+ status: contentStatus(record.draft !== null, record.published !== null),
39
+ publishedAt: record.publishedAt?.toISOString() ?? null,
40
+ updatedAt: record.updatedAt.toISOString(),
41
+ updatedBy: record.updatedBy
42
+ };
43
+ }
44
+ /**
45
+ * The SvelteKit `+server.ts` exports for a `server` forge's `apiBase`. The
46
+ * record path travels in the query (GET) or the JSON body, so one route serves
47
+ * every Content document, the site root included.
48
+ */
49
+ export function createServerContentHandlers(opts) {
50
+ const { store, authorize } = opts;
51
+ const handle = (fn) => async (event) => {
52
+ try {
53
+ const user = await opts.getUser(event);
54
+ if (!user)
55
+ throw new HttpError(401, 'You are signed out. Sign in again to continue.');
56
+ return await fn(event, user);
57
+ }
58
+ catch (error) {
59
+ return failure(error);
60
+ }
61
+ };
62
+ async function guard(user, action, record) {
63
+ if (!(await authorize(user, action, record))) {
64
+ throw new HttpError(403, `You do not have permission to ${action.replace('-', ' ')}.`);
65
+ }
66
+ }
67
+ // Record-scoped decisions need the record, so this read precedes `guard`;
68
+ // no write reaches the store until `guard` passes.
69
+ async function existing(path) {
70
+ const record = await store.get(path);
71
+ if (!record)
72
+ throw new HttpError(404, `No content at ${path}.`);
73
+ return record;
74
+ }
75
+ async function view(user, record, status = 200) {
76
+ const allowed = [];
77
+ for (const action of ACTIONS) {
78
+ if (await authorize(user, action, record))
79
+ allowed.push(action);
80
+ }
81
+ return Response.json({ ...record, allowed }, { status });
82
+ }
83
+ return {
84
+ GET: handle(async ({ url }, user) => {
85
+ if (url.searchParams.has('session'))
86
+ return Response.json({ user });
87
+ const path = url.searchParams.get('path');
88
+ if (path === null) {
89
+ await guard(user, 'read-draft', null);
90
+ const kind = url.searchParams.get('kind') ?? undefined;
91
+ return Response.json({ records: (await store.list({ kind })).map(summary) });
92
+ }
93
+ const record = await store.get(path);
94
+ await guard(user, 'read-draft', record);
95
+ if (!record)
96
+ throw new HttpError(404, `No content at ${path}.`);
97
+ if (url.searchParams.has('history')) {
98
+ const versions = (await store.versions(path)).map((version) => ({
99
+ id: version.id,
100
+ createdAt: version.createdAt.toISOString(),
101
+ createdBy: version.createdBy
102
+ }));
103
+ return Response.json(versions);
104
+ }
105
+ const versionId = url.searchParams.get('version');
106
+ if (versionId !== null)
107
+ return Response.json(await store.getVersion(path, versionId));
108
+ return view(user, record);
109
+ }),
110
+ POST: handle(async ({ request }, user) => {
111
+ const input = await body(request);
112
+ const path = text(input.path, 'path');
113
+ if (input.action === 'create') {
114
+ await guard(user, 'create', null);
115
+ const kind = input.kind === undefined ? 'page' : text(input.kind, 'kind');
116
+ return view(user, await store.create(path, kind, input.draft, { author: user.email }), 201);
117
+ }
118
+ if (input.action === 'publish' || input.action === 'unpublish') {
119
+ const record = await existing(path);
120
+ await guard(user, input.action, record);
121
+ const write = { etag: text(input.etag, 'etag'), author: user.email };
122
+ if (input.action === 'unpublish')
123
+ return view(user, await store.unpublish(path, write));
124
+ if (record.draft === null)
125
+ throw new HttpError(400, `Nothing to publish: ${path} has no Draft.`);
126
+ return view(user, await store.publish(path, write));
127
+ }
128
+ if (input.action === 'restore') {
129
+ const record = await existing(path);
130
+ await guard(user, 'restore', record);
131
+ const versionId = text(input.versionId, 'versionId');
132
+ const write = { etag: text(input.etag, 'etag'), author: user.email };
133
+ return view(user, await store.restore(path, versionId, write));
134
+ }
135
+ if (input.action === 'move') {
136
+ const record = await existing(path);
137
+ await guard(user, 'move', record);
138
+ const requested = text(input.to, 'to');
139
+ const to = opts.normalizePath ? opts.normalizePath(requested) : requested;
140
+ if (to === null)
141
+ throw new HttpError(400, `${requested} is not a path content can live at.`);
142
+ if (opts.derivePath?.(record.kind, record.draft ?? record.published)) {
143
+ throw new HttpError(400, `The path of ${path} follows its metadata; edit that instead.`);
144
+ }
145
+ if (to === path)
146
+ throw new HttpError(400, `${path} is already there.`);
147
+ if (await store.get(to)) {
148
+ throw new HttpError(400, `Something else is already at ${to}. Choose another path.`);
149
+ }
150
+ const write = { etag: text(input.etag, 'etag'), author: user.email };
151
+ return view(user, await store.move(path, to, write));
152
+ }
153
+ throw new HttpError(400, 'Expected "action" to be create, publish, unpublish, restore or move.');
154
+ }),
155
+ PUT: handle(async ({ request }, user) => {
156
+ const input = await body(request);
157
+ const path = text(input.path, 'path');
158
+ const record = await existing(path);
159
+ await guard(user, 'save-draft', record);
160
+ const etag = text(input.etag, 'etag');
161
+ const target = opts.derivePath?.(record.kind, input.draft) ?? path;
162
+ if (target !== path) {
163
+ await guard(user, 'move', record);
164
+ if (await store.get(target)) {
165
+ throw new HttpError(400, `Something else is already at ${target}. Choose another path.`);
166
+ }
167
+ }
168
+ const saved = await store.saveDraft(path, input.draft, { etag, author: user.email });
169
+ if (target === path)
170
+ return view(user, saved);
171
+ return view(user, await store.move(path, target, { etag: saved.etag, author: user.email }));
172
+ }),
173
+ DELETE: handle(async ({ request }, user) => {
174
+ const input = await body(request);
175
+ const path = text(input.path, 'path');
176
+ await guard(user, 'delete', await existing(path));
177
+ await store.delete(path, { etag: text(input.etag, 'etag'), author: user.email });
178
+ return new Response(null, { status: 204 });
179
+ })
180
+ };
181
+ }
182
+ const MEDIA_ACTIONS = ['media-upload', 'media-delete'];
183
+ /** The SvelteKit `+server.ts` exports for a `server` forge's `mediaApiBase`. */
184
+ export function createServerMediaHandlers(opts) {
185
+ const { library, authorize } = opts;
186
+ const handle = (action, fn) => async (event) => {
187
+ try {
188
+ const user = await opts.getUser(event);
189
+ if (!user)
190
+ throw new HttpError(401, 'You are signed out. Sign in again to continue.');
191
+ if (!(await authorize(user, action, null))) {
192
+ throw new HttpError(403, `You do not have permission to ${action.replace('-', ' ')}.`);
193
+ }
194
+ return await fn(event, user);
195
+ }
196
+ catch (error) {
197
+ return failure(error);
198
+ }
199
+ };
200
+ return {
201
+ GET: handle('read-draft', async ({ url }, user) => {
202
+ const items = await library.list({
203
+ search: url.searchParams.get('search') || undefined,
204
+ contentType: url.searchParams.get('contentType') || undefined
205
+ });
206
+ const allowed = [];
207
+ for (const action of MEDIA_ACTIONS) {
208
+ if (await authorize(user, action, null))
209
+ allowed.push(action);
210
+ }
211
+ const view = {
212
+ items: items.map((item) => ({ ...item, uploadedAt: item.uploadedAt.toISOString() })),
213
+ allowed
214
+ };
215
+ return Response.json(view);
216
+ }),
217
+ POST: handle('media-upload', async ({ request }, user) => {
218
+ const form = await request.formData().catch(() => null);
219
+ const file = form?.get('file');
220
+ if (!(file instanceof File))
221
+ throw new HttpError(400, 'Expected a multipart "file".');
222
+ const title = form?.get('title');
223
+ const item = await library.upload(new Uint8Array(await file.arrayBuffer()), {
224
+ filename: file.name,
225
+ title: typeof title === 'string' ? title : undefined,
226
+ contentType: file.type || 'application/octet-stream',
227
+ uploadedBy: user.email
228
+ });
229
+ return Response.json(item, { status: 201 });
230
+ }),
231
+ DELETE: handle('media-delete', async ({ request }) => {
232
+ const id = text((await body(request)).id, 'id');
233
+ await library.delete(id);
234
+ return new Response(null, { status: 204 });
235
+ })
236
+ };
237
+ }
@@ -0,0 +1,5 @@
1
+ export { createPostgresContentStore } from './postgres-store.js';
2
+ export type { ContentRecord, ContentStore, OnMove, RetentionPolicy, VersionSummary } from './postgres-store.js';
3
+ export { contentStoreMigrations, mediaLibraryMigrations } from './migrations.js';
4
+ export { createMediaLibrary, MediaInUseError, type MediaItem, type MediaLibrary, type MediaLibraryOptions } from './media.js';
5
+ export { createServerContentHandlers, createServerMediaHandlers, type Action, type Authorize, type ServerContentHandlerOptions, type ServerMediaHandlerOptions, type ServerUser } from './handlers.js';
@@ -0,0 +1,4 @@
1
+ export { createPostgresContentStore } from './postgres-store.js';
2
+ export { contentStoreMigrations, mediaLibraryMigrations } from './migrations.js';
3
+ export { createMediaLibrary, MediaInUseError } from './media.js';
4
+ export { createServerContentHandlers, createServerMediaHandlers } from './handlers.js';
@@ -0,0 +1,69 @@
1
+ import type { Sql } from 'postgres';
2
+ import type { ContentStore } from './postgres-store.js';
3
+ export interface MediaItem {
4
+ id: string;
5
+ key: string;
6
+ url: string;
7
+ filename: string;
8
+ title: string;
9
+ contentType: string;
10
+ width: number | null;
11
+ height: number | null;
12
+ size: number;
13
+ uploadedBy: string;
14
+ uploadedAt: Date;
15
+ }
16
+ export interface MediaS3Options {
17
+ endpoint: string;
18
+ region: string;
19
+ bucket: string;
20
+ accessKeyId: string;
21
+ secretAccessKey: string;
22
+ forcePathStyle: boolean;
23
+ }
24
+ export interface MediaLibraryOptions {
25
+ sql: Sql;
26
+ s3: MediaS3Options;
27
+ publicBaseUrl: string;
28
+ store: ContentStore;
29
+ }
30
+ export interface MediaLibrary {
31
+ list(query?: {
32
+ search?: string;
33
+ contentType?: string;
34
+ }): Promise<Array<MediaItem & {
35
+ usage: number;
36
+ }>>;
37
+ upload(bytes: Uint8Array, meta: {
38
+ filename: string;
39
+ title?: string;
40
+ contentType: string;
41
+ uploadedBy: string;
42
+ }): Promise<MediaItem>;
43
+ usage(id: string): Promise<{
44
+ count: number;
45
+ paths: string[];
46
+ }>;
47
+ delete(id: string): Promise<void>;
48
+ }
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
+ /** Reads width and height from a PNG, GIF, WebP or JPEG header; null for anything else. */
60
+ export declare function imageSize(bytes: Uint8Array): {
61
+ width: number;
62
+ height: number;
63
+ } | null;
64
+ /**
65
+ * Content-addressed, immutable Media items in S3-compatible storage, with
66
+ * their metadata in Postgres. Usage counts references to an item's URL in
67
+ * Published copies and Drafts; Versions never count.
68
+ */
69
+ export declare function createMediaLibrary(opts: MediaLibraryOptions): MediaLibrary;
@@ -0,0 +1,181 @@
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
+ }
11
+ const EXTENSIONS = {
12
+ 'image/webp': 'webp',
13
+ 'image/png': 'png',
14
+ 'image/jpeg': 'jpg',
15
+ 'image/gif': 'gif',
16
+ 'image/avif': 'avif',
17
+ 'image/svg+xml': 'svg',
18
+ 'application/pdf': 'pdf',
19
+ 'video/mp4': 'mp4'
20
+ };
21
+ function extension(contentType, filename) {
22
+ return EXTENSIONS[contentType] ?? /\.([a-z0-9]+)$/i.exec(filename)?.[1]?.toLowerCase() ?? 'bin';
23
+ }
24
+ /** Reads width and height from a PNG, GIF, WebP or JPEG header; null for anything else. */
25
+ export function imageSize(bytes) {
26
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
27
+ const ascii = (start, end) => String.fromCharCode(...bytes.subarray(start, end));
28
+ if (bytes.length >= 24 && ascii(1, 4) === 'PNG') {
29
+ return { width: view.getUint32(16), height: view.getUint32(20) };
30
+ }
31
+ if (bytes.length >= 10 && ascii(0, 3) === 'GIF') {
32
+ return { width: view.getUint16(6, true), height: view.getUint16(8, true) };
33
+ }
34
+ if (bytes.length >= 30 && ascii(0, 4) === 'RIFF' && ascii(8, 12) === 'WEBP') {
35
+ const chunk = ascii(12, 16);
36
+ if (chunk === 'VP8X') {
37
+ const u24 = (at) => bytes[at] | (bytes[at + 1] << 8) | (bytes[at + 2] << 16);
38
+ return { width: u24(24) + 1, height: u24(27) + 1 };
39
+ }
40
+ if (chunk === 'VP8 ') {
41
+ return { width: view.getUint16(26, true) & 0x3fff, height: view.getUint16(28, true) & 0x3fff };
42
+ }
43
+ if (chunk === 'VP8L') {
44
+ const bits = view.getUint32(21, true);
45
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
46
+ }
47
+ }
48
+ if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
49
+ let at = 2;
50
+ while (at + 9 < bytes.length) {
51
+ if (bytes[at] !== 0xff)
52
+ return null;
53
+ const marker = bytes[at + 1];
54
+ const length = view.getUint16(at + 2);
55
+ // SOF0–SOF15, except DHT (C4), JPG (C8) and DAC (CC).
56
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
57
+ return { width: view.getUint16(at + 7), height: view.getUint16(at + 5) };
58
+ }
59
+ at += 2 + length;
60
+ }
61
+ }
62
+ return null;
63
+ }
64
+ function toItem(row, publicBaseUrl) {
65
+ return {
66
+ id: row.id,
67
+ key: row.key,
68
+ url: `${publicBaseUrl}/${row.key}`,
69
+ filename: row.filename,
70
+ title: row.title,
71
+ contentType: row.content_type,
72
+ width: row.width,
73
+ height: row.height,
74
+ size: row.size,
75
+ uploadedBy: row.uploaded_by,
76
+ uploadedAt: row.uploaded_at
77
+ };
78
+ }
79
+ /**
80
+ * Content-addressed, immutable Media items in S3-compatible storage, with
81
+ * their metadata in Postgres. Usage counts references to an item's URL in
82
+ * Published copies and Drafts; Versions never count.
83
+ */
84
+ export function createMediaLibrary(opts) {
85
+ const { sql, store } = opts;
86
+ const publicBaseUrl = opts.publicBaseUrl.replace(/\/+$/, '');
87
+ const { bucket } = opts.s3;
88
+ // Loaded on first use, so a host using only the ContentStore needs no S3 SDK.
89
+ let s3;
90
+ const connect = () => (s3 ??= import('@aws-sdk/client-s3').then((sdk) => ({
91
+ sdk,
92
+ client: new sdk.S3Client({
93
+ endpoint: opts.s3.endpoint,
94
+ region: opts.s3.region,
95
+ forcePathStyle: opts.s3.forcePathStyle,
96
+ credentials: {
97
+ accessKeyId: opts.s3.accessKeyId,
98
+ secretAccessKey: opts.s3.secretAccessKey
99
+ }
100
+ })
101
+ })));
102
+ async function referencing(urls) {
103
+ const records = await store.list();
104
+ const paths = new Map(urls.map((url) => [url, []]));
105
+ for (const record of records) {
106
+ const docs = [record.draft, record.published]
107
+ .filter((doc) => doc !== null)
108
+ .map((doc) => JSON.stringify(doc));
109
+ for (const url of urls) {
110
+ if (docs.some((doc) => doc.includes(url)))
111
+ paths.get(url).push(record.path);
112
+ }
113
+ }
114
+ return paths;
115
+ }
116
+ async function find(id) {
117
+ const [row] = await sql `select * from uncial_media where id = ${id}`;
118
+ if (!row)
119
+ throw new NotFoundError(`No Media item ${id}.`);
120
+ return toItem(row, publicBaseUrl);
121
+ }
122
+ async function usage(id) {
123
+ const item = await find(id);
124
+ const paths = (await referencing([item.url])).get(item.url);
125
+ return { count: paths.length, paths };
126
+ }
127
+ return {
128
+ async list({ search, contentType } = {}) {
129
+ const pattern = search ? `%${search.replace(/[\\%_]/g, '\\$&')}%` : undefined;
130
+ const rows = await sql `
131
+ select * from uncial_media
132
+ where true
133
+ ${pattern === undefined ? sql `` : sql `and (title ilike ${pattern} or filename ilike ${pattern})`}
134
+ ${contentType === undefined ? sql `` : sql `and content_type like ${contentType.replace('*', '%')}`}
135
+ order by uploaded_at desc, id
136
+ `;
137
+ const items = rows.map((row) => toItem(row, publicBaseUrl));
138
+ const paths = await referencing(items.map((item) => item.url));
139
+ return items.map((item) => ({ ...item, usage: paths.get(item.url).length }));
140
+ },
141
+ async upload(bytes, { filename, title, contentType, uploadedBy }) {
142
+ const id = createHash('sha256').update(bytes).digest('hex');
143
+ const [existing] = await sql `select * from uncial_media where id = ${id}`;
144
+ if (existing)
145
+ return toItem(existing, publicBaseUrl);
146
+ const key = `${id}.${extension(contentType, filename)}`;
147
+ const { client, sdk } = await connect();
148
+ await client.send(new sdk.PutObjectCommand({
149
+ Bucket: bucket,
150
+ Key: key,
151
+ Body: bytes,
152
+ ContentType: contentType,
153
+ CacheControl: 'public, max-age=31536000, immutable',
154
+ ACL: 'public-read'
155
+ }));
156
+ const size = imageSize(bytes);
157
+ const [row] = await sql `
158
+ insert into uncial_media
159
+ (id, key, filename, title, content_type, width, height, size, uploaded_by)
160
+ values (
161
+ ${id}, ${key}, ${filename}, ${title || filename.replace(/\.[^.]+$/, '')},
162
+ ${contentType}, ${size?.width ?? null}, ${size?.height ?? null},
163
+ ${bytes.byteLength}, ${uploadedBy}
164
+ )
165
+ on conflict (id) do update set id = excluded.id
166
+ returning *
167
+ `;
168
+ return toItem(row, publicBaseUrl);
169
+ },
170
+ usage,
171
+ async delete(id) {
172
+ const item = await find(id);
173
+ const current = await usage(id);
174
+ if (current.count > 0)
175
+ throw new MediaInUseError(current);
176
+ const { client, sdk } = await connect();
177
+ await client.send(new sdk.DeleteObjectCommand({ Bucket: bucket, Key: item.key }));
178
+ await sql `delete from uncial_media where id = ${id}`;
179
+ }
180
+ };
181
+ }
@@ -0,0 +1,8 @@
1
+ export declare const contentStoreMigrations: Array<{
2
+ id: string;
3
+ sql: string;
4
+ }>;
5
+ export declare const mediaLibraryMigrations: Array<{
6
+ id: string;
7
+ sql: string;
8
+ }>;
@@ -0,0 +1,47 @@
1
+ export const contentStoreMigrations = [
2
+ {
3
+ id: '0001_content_store.sql',
4
+ sql: `
5
+ create table uncial_content (
6
+ id uuid primary key default gen_random_uuid(),
7
+ kind text not null,
8
+ path text not null unique check (path ~ '^/(.+/)?$'),
9
+ draft jsonb,
10
+ published jsonb,
11
+ etag text not null default gen_random_uuid()::text,
12
+ published_at timestamptz,
13
+ updated_at timestamptz not null default now(),
14
+ updated_by text not null
15
+ );
16
+
17
+ create table uncial_content_versions (
18
+ id bigint generated always as identity primary key,
19
+ content_id uuid not null references uncial_content (id) on delete cascade,
20
+ doc jsonb not null,
21
+ created_at timestamptz not null default now(),
22
+ created_by text not null
23
+ );
24
+
25
+ create index uncial_content_versions_content_id on uncial_content_versions (content_id, id desc);
26
+ `
27
+ }
28
+ ];
29
+ export const mediaLibraryMigrations = [
30
+ {
31
+ id: '0001_media_library.sql',
32
+ sql: `
33
+ create table uncial_media (
34
+ id text primary key check (id ~ '^[0-9a-f]{64}$'),
35
+ key text not null unique,
36
+ filename text not null,
37
+ title text not null,
38
+ content_type text not null,
39
+ width integer,
40
+ height integer,
41
+ size integer not null,
42
+ uploaded_by text not null,
43
+ uploaded_at timestamptz not null default now()
44
+ );
45
+ `
46
+ }
47
+ ];