uncial-cms 3.1.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -632,9 +632,17 @@ Residual risks accepted for v1 (see the spec's §6.5 for the full treatment):
632
632
 
633
633
  ## Media
634
634
 
635
- Single-image upload commits an image straight into the repo and hands the block
636
- back its served path. It is exposed as pure, adapter-injected functions in the
637
- same family as `createPage`/`deletePage`:
635
+ A Block gets image upload by declaring an attribute with `input: 'image'`:
636
+ `EditorPage` and `mountEditorPage` back its attributes-panel field with
637
+ `cmsImageSource(config, { base, staticDir })`, which fits an upload under the
638
+ forge limit, commits it under `mediaDir`, stores its served URL and lists the
639
+ media dir for Choose existing. Pass `list` and `thumbnail` to override the
640
+ listing and tile URLs for a rendition pipeline, or `imageSource` to replace the
641
+ source outright.
642
+
643
+ Underneath, single-image upload commits an image straight into the repo and
644
+ answers its served path. It is exposed as pure, adapter-injected functions in
645
+ the same family as `createPage`/`deletePage`:
638
646
 
639
647
  ```ts
640
648
  import { uploadAsset, uploadImageAsset, servedUrl, MAX_CONTENT_BYTES } from 'uncial-cms';
@@ -647,10 +655,10 @@ const { path, sha, commitSha } = await uploadAsset(
647
655
  );
648
656
  ```
649
657
 
650
- From a block, use the editor convenience: it resolves the adapter and author
651
- from the active editor session, and reads `mediaDir` off the site object, so no
652
- block hardcodes a directory. Import it **dynamically**, inside the handler, so
653
- `uncial-cms` never enters a reader page's static import graph:
658
+ For a custom flow (e.g. uploading a fetched video poster), use the editor
659
+ convenience: it resolves the adapter and author from the active editor session,
660
+ and reads `mediaDir` off the site object. Import it **dynamically**, inside the
661
+ handler, so `uncial-cms` never enters a reader page's static import graph:
654
662
 
655
663
  ```ts
656
664
  const { servedUrl, uploadImageAsset } = await import('uncial-cms');
@@ -676,8 +684,8 @@ updateAttributes?.({ src: servedUrl(site, result.path, STATIC_DIR) });
676
684
  no git-blobs-API fallback in v1. With `fit`, the re-encode happens first.
677
685
  - **`mediaDir`** is repo-root-relative and comes from the site options; the
678
686
  returned `path` is repo-root-relative too. Until the next redeploy the
679
- committed copy is not served, so the editor should bridge the gap with a local
680
- `objectURL` preview.
687
+ committed copy is not served; an `input: 'image'` field bridges the gap with a
688
+ local `blob:` preview, and a custom flow has to do the same.
681
689
 
682
690
  The `ForgeAdapter`'s `writeFile` accepts `string | Uint8Array`; binary content is
683
691
  base64-encoded and PUT to the Contents API with the same message/branch/sha
@@ -65,15 +65,26 @@ class GitHubAdapter {
65
65
  await this.#assertOk(response, `delete ${path}`);
66
66
  }
67
67
  async listDir(path) {
68
- const response = await this.#request(`${this.#contentsUrl(path)}?ref=${this.#config.branch}`);
68
+ // The Trees API, unlike the Contents API, has no 1,000-entry directory cap.
69
+ const dir = path.replace(/^\/+|\/+$/g, '');
70
+ const ref = `${this.#config.branch}:${encodeRepoPath(dir)}`;
71
+ // GitHub marks this `private, max-age=60`, so the browser would otherwise
72
+ // answer from its cache and omit a file committed within the last minute.
73
+ const response = await this.#request(`${GITHUB_API_URL}/repos/${this.#config.repo}/git/trees/${ref}`, { cache: 'no-cache' });
69
74
  await this.#assertOk(response, `list ${path}`);
70
- const entries = (await response.json());
71
- if (!Array.isArray(entries)) {
75
+ const body = (await response.json());
76
+ if (!Array.isArray(body.tree)) {
72
77
  throw new Error(`Expected a directory but found a file: ${path}`);
73
78
  }
74
- return entries
75
- .filter((entry) => entry.type === 'file' || entry.type === 'dir')
76
- .map((entry) => ({ path: entry.path, type: entry.type }));
79
+ if (body.truncated) {
80
+ throw new Error(`Directory is too large to list: ${path}`);
81
+ }
82
+ // Tree entry paths are relative to the listed directory; callers expect repo-root-relative.
83
+ const prefix = dir ? `${dir}/` : '';
84
+ const kinds = { blob: 'file', tree: 'dir' };
85
+ return body.tree
86
+ .filter((entry) => entry.type in kinds)
87
+ .map((entry) => ({ path: prefix + entry.path, type: kinds[entry.type] }));
77
88
  }
78
89
  /**
79
90
  * Both of GitHub's two answers to "how did this commit fare", because a repo
@@ -0,0 +1,17 @@
1
+ import type { ImageSource } from 'uncial/editor';
2
+ import type { UncialCmsSiteConfig } from './types.js';
3
+ /**
4
+ * The editor's image source for a CMS site: an upload is fitted under the
5
+ * forge limit, committed under the media dir through the active editor
6
+ * session, and stored as its base-less served URL; browse lists the media
7
+ * dir's images the same way. `base` and `staticDir` are the site's build-time
8
+ * values, which the config does not carry. A site with a rendition pipeline
9
+ * replaces the listing with `list` (served paths) and the tile URL with
10
+ * `thumbnail`.
11
+ */
12
+ export declare function cmsImageSource(config: UncialCmsSiteConfig, options?: {
13
+ base?: string;
14
+ staticDir?: string;
15
+ list?: () => Promise<string[]>;
16
+ thumbnail?: (src: string) => string;
17
+ }): ImageSource;
@@ -0,0 +1,38 @@
1
+ import { resolveImageSrc } from 'uncial/render';
2
+ import { resolveMediaDir, uploadImageAsset } from './index-actions.js';
3
+ import { servedUrl } from './served-url.js';
4
+ import { getActiveForge } from './upload-context.js';
5
+ const IMAGE_EXTENSION = /\.(png|jpe?g|gif|webp|avif|svg)$/i;
6
+ /**
7
+ * The editor's image source for a CMS site: an upload is fitted under the
8
+ * forge limit, committed under the media dir through the active editor
9
+ * session, and stored as its base-less served URL; browse lists the media
10
+ * dir's images the same way. `base` and `staticDir` are the site's build-time
11
+ * values, which the config does not carry. A site with a rendition pipeline
12
+ * replaces the listing with `list` (served paths) and the tile URL with
13
+ * `thumbnail`.
14
+ */
15
+ export function cmsImageSource(config, options = {}) {
16
+ const { base = '', staticDir = 'static', list } = options;
17
+ return {
18
+ upload: async (file) => {
19
+ const result = await uploadImageAsset(file, { fit: true, mediaDir: config.mediaDir });
20
+ return servedUrl({ config }, result.path, staticDir);
21
+ },
22
+ browse: list ?? (async () => {
23
+ const forge = getActiveForge();
24
+ if (!forge) {
25
+ throw new Error('No active editor session — open a page in the editor and sign in before choosing an image.');
26
+ }
27
+ // The same resolution `uploadImageAsset` commits under, so browse lists what upload wrote.
28
+ const mediaDir = resolveMediaDir(config.mediaDir, forge.config.mediaDir);
29
+ const entries = await forge.adapter.listDir(mediaDir);
30
+ return entries
31
+ .filter((entry) => entry.type === 'file' && IMAGE_EXTENSION.test(entry.path))
32
+ .map((entry) => entry.path)
33
+ .sort()
34
+ .map((path) => servedUrl({ config }, path, staticDir));
35
+ }),
36
+ thumbnail: options.thumbnail ?? ((src) => resolveImageSrc(src, base))
37
+ };
38
+ }
@@ -50,6 +50,8 @@ export interface UploadAssetResult {
50
50
  export declare function uploadAsset(deps: {
51
51
  adapter: ForgeAdapter;
52
52
  }, file: UploadAssetFile, opts: UploadAssetOptions): Promise<UploadAssetResult>;
53
+ /** `mediaDir` from the most specific source that supplies one. */
54
+ export declare function resolveMediaDir(...candidates: Array<string | undefined>): string;
53
55
  export interface UploadImageAssetOptions {
54
56
  mediaDir?: string;
55
57
  site?: Site;
@@ -86,7 +86,7 @@ export async function uploadAsset(deps, file, opts) {
86
86
  return { path, sha, commitSha };
87
87
  }
88
88
  /** `mediaDir` from the most specific source that supplies one. */
89
- function resolveMediaDir(...candidates) {
89
+ export function resolveMediaDir(...candidates) {
90
90
  const dir = candidates.find((candidate) => candidate);
91
91
  if (!dir) {
92
92
  throw new Error('No media directory for the upload: pass `mediaDir`, or give a `site` whose config sets it.');
@@ -35,7 +35,12 @@ export function mountIndexPage(target, opts) {
35
35
  const editorView = document.createElement('section');
36
36
  editorView.className = 'uncial-cms-fallback-editor';
37
37
  editorView.hidden = true;
38
- root.append(status, listView, editorView);
38
+ const signInButton = document.createElement('button');
39
+ signInButton.type = 'button';
40
+ signInButton.className = 'uncial-cms-sign-in';
41
+ signInButton.textContent = 'Sign in';
42
+ signInButton.hidden = true;
43
+ root.append(status, signInButton, listView, editorView);
39
44
  target.append(root);
40
45
  let destroyed = false;
41
46
  let adapter = null;
@@ -207,11 +212,22 @@ export function mountIndexPage(target, opts) {
207
212
  return;
208
213
  applyHash();
209
214
  };
210
- void load().catch((error) => {
211
- if (destroyed)
212
- return;
213
- setStatus(error instanceof Error ? error.message : 'Failed to load the site index.');
214
- });
215
+ // The first attempt runs outside a click, where browsers block the sign-in
216
+ // popup, so a failed sign-in is retried from a button.
217
+ const signIn = async () => {
218
+ signInButton.hidden = true;
219
+ try {
220
+ await load();
221
+ }
222
+ catch (error) {
223
+ if (destroyed)
224
+ return;
225
+ setStatus(error instanceof Error ? error.message : 'Failed to load the site index.');
226
+ signInButton.hidden = false;
227
+ }
228
+ };
229
+ signInButton.addEventListener('click', () => void signIn());
230
+ void signIn();
215
231
  return {
216
232
  destroy() {
217
233
  destroyed = true;
package/dist/index.d.ts CHANGED
@@ -9,6 +9,7 @@ export { mountIndexPage, type MountIndexPageOptions } from './index-page.js';
9
9
  export { createPage, deletePage, listPages, uploadAsset, uploadImageAsset, type PageRef, type UploadAssetFile, type UploadAssetOptions, type UploadAssetResult, type UploadImageAssetOptions } from './index-actions.js';
10
10
  export { fitImage, type FitOptions, type FittedImage, type ImageEncoder, type EncodableImage } from './fit-image.js';
11
11
  export { servedUrl } from './served-url.js';
12
+ export { cmsImageSource } from './image-source.js';
12
13
  export { MAX_CONTENT_BYTES } from './constants.js';
13
14
  export { hashForPagePath, pagePathFromHash, validatePagePath } from './paths/index.js';
14
15
  export { parseDocument, serializeDocument, type Blocks } from './document.js';
package/dist/index.js CHANGED
@@ -15,6 +15,7 @@ export { mountIndexPage } from './index-page.js';
15
15
  export { createPage, deletePage, listPages, uploadAsset, uploadImageAsset } from './index-actions.js';
16
16
  export { fitImage } from './fit-image.js';
17
17
  export { servedUrl } from './served-url.js';
18
+ export { cmsImageSource } from './image-source.js';
18
19
  export { MAX_CONTENT_BYTES } from './constants.js';
19
20
  export { hashForPagePath, pagePathFromHash, validatePagePath } from './paths/index.js';
20
21
  export { parseDocument, serializeDocument } from './document.js';
package/dist/mount.d.ts CHANGED
@@ -36,6 +36,8 @@ export interface MountEditorPageOptions {
36
36
  * renders behind a shadow boundary, which page styles do not cross).
37
37
  */
38
38
  editorStylesheets?: string[];
39
+ /** Where `input: 'image'` fields get images; defaults to `cmsImageSource(config)`. */
40
+ imageSource?: UncialEditorElement['imageSource'];
39
41
  }
40
42
  export declare function mountEditorPage(target: HTMLElement, opts: MountEditorPageOptions): {
41
43
  destroy(): void;
package/dist/mount.js CHANGED
@@ -8,6 +8,7 @@ import 'uncial/web-components';
8
8
  import 'uncial/styles/chrome.css';
9
9
  import {} from './editor-controller.js';
10
10
  import { createEditorSession, defaultSessionProvider } from './editor-session.js';
11
+ import { cmsImageSource } from './image-source.js';
11
12
  import { UNCIAL_CMS_RUNTIME_SENTINEL } from './sentinel.js';
12
13
  import { clearActiveForge } from './upload-context.js';
13
14
  function mirrorPageStylesIntoEditor(editor, explicit) {
@@ -71,6 +72,7 @@ export function mountEditorPage(target, opts) {
71
72
  editor.attributesPanel = opts.attributesPanel;
72
73
  if (opts.presentation !== undefined)
73
74
  editor.presentation = opts.presentation;
75
+ editor.imageSource = opts.imageSource ?? cmsImageSource(config);
74
76
  editor.blocks = blocks;
75
77
  editor.schema = schema;
76
78
  // Forward the schema's declared meta fields so the editor renders (and edits)
@@ -13,4 +13,4 @@ import type { Site } from './define-site.js';
13
13
  * `paths.base` the same content is built at, so the site prepends its base at
14
14
  * render time.
15
15
  */
16
- export declare function servedUrl(site: Site, repoPath: string, staticDir?: string): string;
16
+ export declare function servedUrl(site: Pick<Site, 'config'>, repoPath: string, staticDir?: string): string;
@@ -13,8 +13,10 @@
13
13
  */
14
14
  import { onMount } from 'svelte';
15
15
  import type { BlockRegistry, ContentDocument, ContentSchema } from 'uncial/core';
16
+ import type { ImageSource } from 'uncial/editor';
16
17
  import type { Site } from '../define-site.js';
17
18
  import type { EditorController, StatusView } from '../editor-controller.js';
19
+ import { cmsImageSource } from '../image-source.js';
18
20
  import { UNCIAL_CMS_RUNTIME_SENTINEL } from '../sentinel.js';
19
21
  import type { SessionProvider } from '../types.js';
20
22
  import { clearActiveForge } from '../upload-context.js';
@@ -35,6 +37,8 @@
35
37
  attributesPanel?: 'docked' | 'overlay' | 'off';
36
38
  /** Forwarded to `Editor`; `'bare'` draws no surface of the editor's own. */
37
39
  presentation?: 'card' | 'bare';
40
+ /** Forwarded to `Editor`; defaults to `cmsImageSource(site.config)`. */
41
+ imageSource?: ImageSource;
38
42
  }
39
43
 
40
44
  let {
@@ -45,13 +49,15 @@
45
49
  schema,
46
50
  sessionProvider,
47
51
  attributesPanel = 'overlay',
48
- presentation = 'bare'
52
+ presentation = 'bare',
53
+ imageSource
49
54
  }: Props = $props();
50
55
 
51
56
  const resolvedSchema = $derived(typeof schema === 'function' ? schema(pagePath) : schema);
52
57
  // Autosave leaves nothing to press; a forge commit is never autosaved, so a
53
58
  // Save button and autosave are exactly the two modes.
54
59
  const manualSave = $derived(site.autosaveMs === undefined);
60
+ const resolvedImageSource = $derived(imageSource ?? cmsImageSource(site.config));
55
61
  const branch = $derived(
56
62
  site.config.forge === 'github' ? site.config.branch : 'the local checkout'
57
63
  );
@@ -174,6 +180,7 @@
174
180
  bind:meta
175
181
  {attributesPanel}
176
182
  {presentation}
183
+ imageSource={resolvedImageSource}
177
184
  onChange={(next) => controller?.documentChanged(next as ContentDocument)}
178
185
  />
179
186
  {/if}
@@ -1,4 +1,5 @@
1
1
  import type { BlockRegistry, ContentSchema } from 'uncial/core';
2
+ import type { ImageSource } from 'uncial/editor';
2
3
  import type { Site } from '../define-site.js';
3
4
  import type { SessionProvider } from '../types.js';
4
5
  interface Props {
@@ -17,6 +18,8 @@ interface Props {
17
18
  attributesPanel?: 'docked' | 'overlay' | 'off';
18
19
  /** Forwarded to `Editor`; `'bare'` draws no surface of the editor's own. */
19
20
  presentation?: 'card' | 'bare';
21
+ /** Forwarded to `Editor`; defaults to `cmsImageSource(site.config)`. */
22
+ imageSource?: ImageSource;
20
23
  }
21
24
  declare const EditorPage: import("svelte").Component<Props, {}, "">;
22
25
  type EditorPage = ReturnType<typeof EditorPage>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uncial-cms",
3
- "version": "3.1.0",
3
+ "version": "4.0.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -72,7 +72,7 @@
72
72
  },
73
73
  "peerDependencies": {
74
74
  "svelte": "^5.0.0",
75
- "uncial": "^3.0.0"
75
+ "uncial": "^4.0.0"
76
76
  },
77
77
  "devDependencies": {
78
78
  "@astrojs/svelte": "^7.2.5",