@backmatter/core 0.0.40 → 0.0.42

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backmatter/core",
3
- "version": "0.0.40",
3
+ "version": "0.0.42",
4
4
  "description": "Experimental Backmatter SDK. APIs will break. Not ready for production.",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/src/api-loader.ts CHANGED
@@ -1,11 +1,14 @@
1
1
  // packages/core/src/api-loader.ts
2
2
  import type { BackmatterDoc, BackmatterDocSummary } from "./doc";
3
+ import type { MediaInfoMap } from "./media-info";
3
4
 
4
5
  export type PublicDocsQuery = {
5
6
  branch?: string;
6
7
  type?: string;
7
8
  /** When set, Next Data Cache uses these tags instead of `cache: "no-store"`. */
8
9
  tags?: string[];
10
+ /** Receives the kind and file facts of the media the response names. */
11
+ onMedia?: (media: MediaInfoMap) => void;
9
12
  };
10
13
 
11
14
  function fetchInit(
@@ -44,7 +47,8 @@ export async function listDocsFromApi(
44
47
  if (!res.ok) {
45
48
  throw new Error(`backmatter listDocs failed: ${res.status}`);
46
49
  }
47
- const data = (await res.json()) as { docs: BackmatterDocSummary[] };
50
+ const data = (await res.json()) as { docs: BackmatterDocSummary[]; media?: MediaInfoMap };
51
+ if (data.media) query.onMedia?.(data.media);
48
52
  return data.docs;
49
53
  }
50
54
 
@@ -54,7 +58,7 @@ export async function getDocFromApi(
54
58
  contentToken: string | undefined,
55
59
  type: string,
56
60
  slug: string,
57
- query: Pick<PublicDocsQuery, "branch" | "tags"> = {},
61
+ query: Pick<PublicDocsQuery, "branch" | "tags" | "onMedia"> = {},
58
62
  ): Promise<BackmatterDoc | null> {
59
63
  const res = await fetch(
60
64
  publicDocsUrl(apiUrl, workspaceId, `/${type}/${slug}`, query),
@@ -64,6 +68,23 @@ export async function getDocFromApi(
64
68
  if (!res.ok) {
65
69
  throw new Error(`backmatter getDoc failed: ${res.status}`);
66
70
  }
67
- const data = (await res.json()) as { doc: BackmatterDoc };
71
+ const data = (await res.json()) as { doc: BackmatterDoc; media?: MediaInfoMap };
72
+ if (data.media) query.onMedia?.(data.media);
68
73
  return data.doc;
69
74
  }
75
+
76
+ /** Kind and file facts for media ids in the workspace. Ids it does not hold are absent. */
77
+ export async function getMediaInfoFromApi(
78
+ apiUrl: string,
79
+ workspaceId: string,
80
+ contentToken: string | undefined,
81
+ ids: string[],
82
+ tags?: string[],
83
+ ): Promise<MediaInfoMap> {
84
+ const url = new URL(`${apiUrl.replace(/\/$/, "")}/public/workspaces/${workspaceId}/media`);
85
+ url.searchParams.set("ids", ids.join(","));
86
+ const res = await fetch(url.toString(), fetchInit(contentToken, tags));
87
+ if (!res.ok) throw new Error(`backmatter media failed: ${res.status}`);
88
+ const data = (await res.json()) as { media: MediaInfoMap };
89
+ return data.media;
90
+ }
@@ -0,0 +1,124 @@
1
+ // packages/core/src/block-gallery.ts
2
+ // The block gallery: a page on the host, reachable only in draft mode, that
3
+ // renders blocks with their examples so Studio's block library can show the
4
+ // real components. Studio builds the URL and posts messages; the host reads
5
+ // both. This file is the contract between them.
6
+
7
+ /** Path the host's catch-all serves the gallery on. */
8
+ export const BLOCK_GALLERY_PATH = "/_backmatter/blocks";
9
+
10
+ /** Studio → gallery: render the single block with these props. */
11
+ export const BLOCK_GALLERY_PROPS_MESSAGE = "backmatter:block-gallery-props";
12
+
13
+ /** Gallery → Studio: the editor asked to open one block example. */
14
+ export const BLOCK_GALLERY_OPEN_MESSAGE = "backmatter:block-gallery-open";
15
+
16
+ const MAX_BLOCKS = 100;
17
+ const BLOCK_NAME = /^[A-Z][A-Za-z0-9]*$/;
18
+
19
+ export type BlockGalleryQuery = {
20
+ /** Block names in display order. One name with `example` set is the single view. */
21
+ blocks: string[];
22
+ /** Index into the block's examples. Set only in the single view. */
23
+ example?: number;
24
+ /** Props that replace the example's, from Studio's editor. Single view only. */
25
+ props?: Record<string, unknown>;
26
+ };
27
+
28
+ export type BlockGalleryPropsMessage = {
29
+ type: typeof BLOCK_GALLERY_PROPS_MESSAGE;
30
+ props: Record<string, unknown>;
31
+ };
32
+
33
+ export type BlockGalleryOpenMessage = {
34
+ type: typeof BLOCK_GALLERY_OPEN_MESSAGE;
35
+ block: string;
36
+ example: number;
37
+ };
38
+
39
+ /** True for the gallery path, with or without a trailing slash. */
40
+ export function isBlockGalleryPath(pathname: string): boolean {
41
+ return pathname.replace(/\/+$/, "") === BLOCK_GALLERY_PATH;
42
+ }
43
+
44
+ export function isBlockGallerySegments(segments: readonly string[] | undefined): boolean {
45
+ return isBlockGalleryPath(`/${(segments ?? []).join("/")}`);
46
+ }
47
+
48
+ function toBase64Url(text: string): string {
49
+ const bytes = new TextEncoder().encode(text);
50
+ let binary = "";
51
+ for (const byte of bytes) binary += String.fromCharCode(byte);
52
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
53
+ }
54
+
55
+ function fromBase64Url(value: string): string {
56
+ const base64 = value.replace(/-/g, "+").replace(/_/g, "/");
57
+ const binary = atob(base64 + "=".repeat((4 - (base64.length % 4)) % 4));
58
+ return new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
59
+ }
60
+
61
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
62
+ return !!value && typeof value === "object" && !Array.isArray(value);
63
+ }
64
+
65
+ /** Gallery path and query for these blocks. */
66
+ export function blockGalleryPath(query: BlockGalleryQuery): string {
67
+ const params = new URLSearchParams();
68
+ params.set("blocks", query.blocks.join(","));
69
+ if (query.example !== undefined) params.set("example", String(query.example));
70
+ if (query.props) params.set("props", toBase64Url(JSON.stringify(query.props)));
71
+ return `${BLOCK_GALLERY_PATH}?${params}`;
72
+ }
73
+
74
+ type SearchInput = URLSearchParams | Record<string, string | string[] | undefined>;
75
+
76
+ function first(search: SearchInput, key: string): string | undefined {
77
+ if (search instanceof URLSearchParams) return search.get(key) ?? undefined;
78
+ const raw = search[key];
79
+ return Array.isArray(raw) ? raw[0] : raw;
80
+ }
81
+
82
+ /** The query a gallery request asks for. Unknown or malformed parts are dropped. */
83
+ export function readBlockGalleryQuery(search: SearchInput): BlockGalleryQuery {
84
+ const blocks = [
85
+ ...new Set(
86
+ (first(search, "blocks") ?? "")
87
+ .split(",")
88
+ .map((name) => name.trim())
89
+ .filter((name) => BLOCK_NAME.test(name)),
90
+ ),
91
+ ].slice(0, MAX_BLOCKS);
92
+ const query: BlockGalleryQuery = { blocks };
93
+ if (blocks.length !== 1) return query;
94
+ const example = Number(first(search, "example"));
95
+ if (Number.isInteger(example) && example >= 0) query.example = example;
96
+ const raw = first(search, "props");
97
+ if (raw && query.example !== undefined) {
98
+ try {
99
+ const props = JSON.parse(fromBase64Url(raw)) as unknown;
100
+ if (isPlainObject(props)) query.props = props;
101
+ } catch {
102
+ // A broken props value shows the example as declared.
103
+ }
104
+ }
105
+ return query;
106
+ }
107
+
108
+ export function isBlockGalleryPropsMessage(value: unknown): value is BlockGalleryPropsMessage {
109
+ return (
110
+ isPlainObject(value) && value.type === BLOCK_GALLERY_PROPS_MESSAGE && isPlainObject(value.props)
111
+ );
112
+ }
113
+
114
+ export function isBlockGalleryOpenMessage(value: unknown): value is BlockGalleryOpenMessage {
115
+ return (
116
+ isPlainObject(value) &&
117
+ value.type === BLOCK_GALLERY_OPEN_MESSAGE &&
118
+ typeof value.block === "string" &&
119
+ BLOCK_NAME.test(value.block) &&
120
+ typeof value.example === "number" &&
121
+ Number.isInteger(value.example) &&
122
+ value.example >= 0
123
+ );
124
+ }
package/src/block.ts CHANGED
@@ -33,6 +33,17 @@ export type BlockMeta = {
33
33
  * without one get a wireframe drawn from their fields.
34
34
  */
35
35
  preview?: string;
36
+ /**
37
+ * Named props that show the block in Studio's block library, one render per
38
+ * example. Never content: nothing reads them on a published page.
39
+ */
40
+ examples?: readonly BlockExample[];
41
+ };
42
+
43
+ /** One named set of props a block shows itself with in the block library. */
44
+ export type BlockExample = {
45
+ name: string;
46
+ props: Record<string, unknown>;
36
47
  };
37
48
 
38
49
  export type BlockDef<C = unknown> = BlockMeta & {
@@ -83,9 +94,58 @@ function readBlockMeta(value: Record<string, unknown>, strict: boolean): BlockMe
83
94
  bad('block.preview must be an https:// URL or a site path like "/block-previews/hero.png"');
84
95
  } else meta.preview = value.preview.trim();
85
96
  }
97
+ if (value.examples !== undefined) {
98
+ const examples = readBlockExamples(value.examples, strict);
99
+ if (examples === null) bad("block.examples must be a list of { name, props } with a name and an object of props");
100
+ else if (examples.length > 0) meta.examples = examples;
101
+ }
86
102
  return meta;
87
103
  }
88
104
 
105
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
106
+ return !!value && typeof value === "object" && !Array.isArray(value);
107
+ }
108
+
109
+ /** Valid examples; null when `strict` and any entry is bad (otherwise bad ones are dropped). */
110
+ function readBlockExamples(value: unknown, strict: boolean): BlockExample[] | null {
111
+ if (!Array.isArray(value)) return strict ? null : [];
112
+ const out: BlockExample[] = [];
113
+ for (const entry of value) {
114
+ const name = isPlainObject(entry) && typeof entry.name === "string" ? entry.name.trim() : "";
115
+ if (!name || !isPlainObject(entry) || !isPlainObject(entry.props)) {
116
+ if (strict) return null;
117
+ continue;
118
+ }
119
+ out.push({ name, props: { ...entry.props } });
120
+ }
121
+ return out;
122
+ }
123
+
124
+ function humanize(name: string): string {
125
+ const words = name
126
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
127
+ .replace(/[_-]+/g, " ")
128
+ .trim()
129
+ .toLowerCase();
130
+ return words ? words[0]!.toUpperCase() + words.slice(1) : name;
131
+ }
132
+
133
+ /**
134
+ * Stand-in props for a block without examples: a label for text, the first
135
+ * option, the minimum, false. Richer fields stay unset.
136
+ */
137
+ export function placeholderBlockProps(
138
+ fields: Record<string, { kind: string; options?: readonly string[]; min?: number }>,
139
+ ): Record<string, unknown> {
140
+ const props: Record<string, unknown> = {};
141
+ for (const [name, field] of Object.entries(fields)) {
142
+ if (field.kind === "text") props[name] = field.options?.[0] ?? humanize(name);
143
+ else if (field.kind === "number") props[name] = field.min ?? 0;
144
+ else if (field.kind === "boolean") props[name] = false;
145
+ }
146
+ return props;
147
+ }
148
+
89
149
  /** An http(s) URL or a root-relative path (not protocol-relative). */
90
150
  export function isBlockPreviewSrc(value: string): boolean {
91
151
  if (value.startsWith("/")) return !value.startsWith("//") && !/\s/.test(value);
package/src/fields.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  // packages/core/src/fields.ts
2
+ import { MEDIA_KINDS, isMediaKind, type MediaKind } from "./media-url";
2
3
 
3
4
  export type FieldKind =
4
5
  | "text"
@@ -49,6 +50,8 @@ export type FieldDef<
49
50
  step?: number;
50
51
  where?: RelationWhere;
51
52
  multiple?: true;
53
+ /** For media fields: the kinds of file it may hold. Absent means images only. */
54
+ accept?: readonly MediaKind[];
52
55
  /** For blocks fields: how Studio's "Add block" picker lays out the blocks. */
53
56
  picker?: BlockPickerView;
54
57
  /** Guidance for editors and the AI: what goes here, length, tone. Never rendered. */
@@ -82,6 +85,7 @@ export type FieldSnapshot = {
82
85
  step?: number;
83
86
  where?: RelationWhere;
84
87
  multiple?: true;
88
+ accept?: MediaKind[];
85
89
  picker?: BlockPickerView;
86
90
  description?: string;
87
91
  };
@@ -494,8 +498,14 @@ const constructors = {
494
498
  },
495
499
  image: <const R extends boolean = false>(opts?: Opts<R>) => base("image", opts),
496
500
  media: <const R extends boolean = false, const M extends boolean = false>(
497
- opts?: Opts<R> & { multiple?: M },
498
- ) => base("media", opts) as MediaFieldDef<R, M>,
501
+ opts?: Opts<R> & { multiple?: M; accept?: readonly MediaKind[] },
502
+ ) => {
503
+ const def = base("media", opts) as MediaFieldDef<R, M>;
504
+ if (opts?.accept === undefined) return def;
505
+ const accept = normalizeAccept(opts.accept);
506
+ if (!accept) throw new Error(`field.media accept must list "image" and/or "pdf"`);
507
+ return (accept.length === 1 && accept[0] === "image" ? def : { ...def, accept }) as MediaFieldDef<R, M>;
508
+ },
499
509
  number: <const R extends boolean = false>(opts?: NumberOpts<R>) => {
500
510
  const bounds = opts ? assertNumberConstraints(opts) : undefined;
501
511
  if (bounds) {
@@ -545,6 +555,7 @@ export function serializeField(def: FieldDef): FieldSnapshot {
545
555
  ...(def.models ? { models: [...def.models] } : {}),
546
556
  ...(def.where ? { where: def.where } : {}),
547
557
  ...(def.multiple ? { multiple: true as const } : {}),
558
+ ...(def.accept ? { accept: [...def.accept] } : {}),
548
559
  ...(def.picker ? { picker: def.picker } : {}),
549
560
  ...(def.description?.trim() ? { description: def.description.trim() } : {}),
550
561
  };
@@ -587,6 +598,11 @@ export function parseFieldSnapshot(input: unknown): FieldSnapshot {
587
598
  }
588
599
  if (value.multiple === true) snap.multiple = true;
589
600
  }
601
+ if (value.accept !== undefined) {
602
+ const accept = normalizeAccept(value.accept);
603
+ if (!accept) throw new Error("invalid field.accept");
604
+ if (!(accept.length === 1 && accept[0] === "image")) snap.accept = accept;
605
+ }
590
606
  if (typeof value.relationTo === "string" && value.relationTo.length > 0) {
591
607
  snap.relationTo = value.relationTo;
592
608
  }
@@ -642,3 +658,13 @@ export function parseFieldSnapshot(input: unknown): FieldSnapshot {
642
658
  }
643
659
  return snap;
644
660
  }
661
+
662
+ /**
663
+ * Accepted media kinds in catalog order, without repeats; null when the list
664
+ * is empty or names a kind that does not exist.
665
+ */
666
+ function normalizeAccept(value: unknown): MediaKind[] | null {
667
+ if (!Array.isArray(value) || value.length === 0) return null;
668
+ if (!value.every(isMediaKind)) return null;
669
+ return MEDIA_KINDS.filter((kind) => value.includes(kind));
670
+ }
package/src/index.ts CHANGED
@@ -14,16 +14,21 @@ export {
14
14
  MAX_MEDIA_TEXT,
15
15
  MAX_VARIANT_WIDTH,
16
16
  MEDIA_CONTENT_TYPES,
17
+ MEDIA_KINDS,
17
18
  MEDIA_WIDTHS,
18
19
  isMediaContentType,
19
20
  isMediaId,
21
+ isLegacyImageUrl,
22
+ isMediaKind,
20
23
  isMediaWidth,
21
24
  mediaIdFromUrl,
25
+ mediaKindOf,
22
26
  mediaOriginalUrl,
23
27
  mediaVariantUrl,
24
28
  } from "./media-url";
25
- export type { MediaContentType, MediaWidth } from "./media-url";
26
- export { mediaIdsInDocument } from "./media-fields";
29
+ export type { MediaContentType, MediaKind, MediaWidth } from "./media-url";
30
+ export { mediaIdsInDocument, mediaRefsInDocument } from "./media-fields";
31
+ export type { MediaRef } from "./media-fields";
27
32
 
28
33
  export type { ObjectDef, ObjectSnapshot } from "./object";
29
34
  export { defineObject, serializeObject, parseObjectSnapshot } from "./object";
@@ -57,6 +62,7 @@ export type {
57
62
  BlockSnapshot,
58
63
  InferBlockProps,
59
64
  BlockMeta,
65
+ BlockExample,
60
66
  } from "./block";
61
67
  export type { BlockGroupInfo, BlockPlacement, BuiltinBlockGroup } from "./block-groups";
62
68
  export { BLOCK_GROUPS, blockGroupInfo, blockLayoutWarnings, blockRules } from "./block-groups";
@@ -65,6 +71,7 @@ export {
65
71
  serializeBlock,
66
72
  parseBlockSnapshot,
67
73
  isBlockPreviewSrc,
74
+ placeholderBlockProps,
68
75
  RESERVED_BLOCK_PROP,
69
76
  } from "./block";
70
77
 
@@ -190,7 +197,9 @@ export {
190
197
  PREVIEW_SESSION_TTL_MS,
191
198
  } from "./preview-session";
192
199
  export { signPayload, verifyPayload } from "./signed-token";
193
- export { getDocFromApi, listDocsFromApi } from "./api-loader";
200
+ export { getDocFromApi, getMediaInfoFromApi, listDocsFromApi } from "./api-loader";
201
+ export { createMediaResolver, mediaIdsInContent } from "./media-info";
202
+ export type { MediaInfo, MediaInfoMap, MediaResolver } from "./media-info";
194
203
  export type { PublicDocsQuery } from "./api-loader";
195
204
  export { syncSchema, detectGitBranch } from "./sync-schema";
196
205
  export type { SyncSchemaOptions } from "./sync-schema";
@@ -226,3 +235,17 @@ export {
226
235
  linkSide,
227
236
  splitInternalLink,
228
237
  } from "./link-address";
238
+ export {
239
+ BLOCK_GALLERY_PATH,
240
+ BLOCK_GALLERY_PROPS_MESSAGE,
241
+ BLOCK_GALLERY_OPEN_MESSAGE,
242
+ blockGalleryPath,
243
+ readBlockGalleryQuery,
244
+ isBlockGalleryPath,
245
+ isBlockGallerySegments,
246
+ isBlockGalleryPropsMessage,
247
+ isBlockGalleryOpenMessage,
248
+ type BlockGalleryQuery,
249
+ type BlockGalleryPropsMessage,
250
+ type BlockGalleryOpenMessage,
251
+ } from "./block-gallery";
@@ -1,39 +1,52 @@
1
1
  // packages/core/src/media-fields.ts
2
2
  import type { FieldSnapshot } from "./fields";
3
- import { mediaIdFromUrl } from "./media-url";
3
+ import { mediaIdFromUrl, type MediaKind } from "./media-url";
4
4
 
5
5
  type BlockCatalog = Array<{ name: string; fields: Record<string, FieldSnapshot> }>;
6
6
 
7
+ /** One media URL in a document, and the kinds the field holding it accepts. */
8
+ export type MediaRef = { id: string; accept: MediaKind[] };
9
+
7
10
  /** Media ids referenced by media fields in a document or block props. */
8
11
  export function mediaIdsInDocument(
9
12
  fields: Record<string, FieldSnapshot>,
10
13
  data: Record<string, unknown>,
11
14
  blocks: BlockCatalog = [],
12
15
  ): string[] {
13
- const ids: string[] = [];
14
- collect(fields, data, blocks, ids);
15
- return ids;
16
+ return mediaRefsInDocument(fields, data, blocks).map((ref) => ref.id);
17
+ }
18
+
19
+ /**
20
+ * Media referenced in a document or block props, with each field's accepted
21
+ * kinds. A /media/ URL does not say whether it is an image or a PDF, so the
22
+ * server checks these against the catalog.
23
+ */
24
+ export function mediaRefsInDocument(
25
+ fields: Record<string, FieldSnapshot>,
26
+ data: Record<string, unknown>,
27
+ blocks: BlockCatalog = [],
28
+ ): MediaRef[] {
29
+ const refs: MediaRef[] = [];
30
+ collect(fields, data, blocks, refs);
31
+ return refs;
16
32
  }
17
33
 
18
34
  function collect(
19
35
  fields: Record<string, FieldSnapshot>,
20
36
  data: Record<string, unknown>,
21
37
  blocks: BlockCatalog,
22
- ids: string[],
38
+ ids: MediaRef[],
23
39
  ) {
24
40
  for (const [name, field] of Object.entries(fields)) {
25
41
  const value = data[name];
26
42
  if (value == null) continue;
27
43
  if (field.kind === "media") {
28
- if (typeof value === "string") {
29
- const id = mediaIdFromUrl(value);
30
- if (id) ids.push(id);
31
- } else if (Array.isArray(value)) {
32
- for (const entry of value) {
33
- if (typeof entry !== "string") continue;
34
- const id = mediaIdFromUrl(entry);
35
- if (id) ids.push(id);
36
- }
44
+ const accept: MediaKind[] = field.accept?.length ? [...field.accept] : ["image"];
45
+ const entries = typeof value === "string" ? [value] : Array.isArray(value) ? value : [];
46
+ for (const entry of entries) {
47
+ if (typeof entry !== "string") continue;
48
+ const id = mediaIdFromUrl(entry);
49
+ if (id) ids.push({ id, accept });
37
50
  }
38
51
  continue;
39
52
  }
@@ -0,0 +1,114 @@
1
+ // packages/core/src/media-info.ts
2
+ // What a site may know about a media file it renders: its kind and the facts
3
+ // of the file. A media URL does not say whether it is an image or a PDF, so
4
+ // content responses carry this beside the documents, and `cms.media(url)`
5
+ // answers from them. Alt text and captions are not here: the document keeps
6
+ // the words it publishes (ADR 0003).
7
+ import { isMediaId, mediaKindOf, type MediaKind } from "./media-url";
8
+
9
+ export type MediaInfo = {
10
+ id: string;
11
+ kind: MediaKind;
12
+ /** Null when only the kind is known, as for an /img/ URL read offline. */
13
+ contentType: string | null;
14
+ byteSize: number | null;
15
+ /** Null for a PDF, and when unknown. */
16
+ width: number | null;
17
+ height: number | null;
18
+ };
19
+
20
+ /** Media info keyed by media id, as content responses carry it. */
21
+ export type MediaInfoMap = Record<string, MediaInfo>;
22
+
23
+ const MEDIA_URL = /https?:\/\/[^\s"'()<>]+?\/(media|img)\/(med_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gi;
24
+
25
+ /**
26
+ * Media ids named anywhere in a document: any frontmatter string (fields,
27
+ * blocks, objects, lists) and the body. Width variants count; they name the
28
+ * same media.
29
+ */
30
+ export function mediaIdsInContent(frontmatter: unknown, body = ""): string[] {
31
+ const ids = new Set<string>();
32
+ const scan = (text: string) => {
33
+ for (const match of text.matchAll(MEDIA_URL)) ids.add(match[2]!);
34
+ };
35
+ const walk = (value: unknown) => {
36
+ if (typeof value === "string") scan(value);
37
+ else if (Array.isArray(value)) value.forEach(walk);
38
+ else if (value && typeof value === "object") Object.values(value).forEach(walk);
39
+ };
40
+ walk(frontmatter);
41
+ scan(body);
42
+ return [...ids];
43
+ }
44
+
45
+ /** The media id and path form in an original or variant CDN URL. */
46
+ function parseUrl(value: string): { id: string; legacyImage: boolean } | null {
47
+ let url: URL;
48
+ try {
49
+ url = new URL(value);
50
+ } catch {
51
+ return null;
52
+ }
53
+ const parts = url.pathname.split("/").filter(Boolean);
54
+ if (parts.length < 2 || parts.length > 3) return null;
55
+ if (parts[0] !== "media" && parts[0] !== "img") return null;
56
+ const id = parts[1]!;
57
+ return isMediaId(id) ? { id, legacyImage: parts[0] === "img" } : null;
58
+ }
59
+
60
+ export type MediaResolver = {
61
+ /** Kind and file facts for a media URL; null when it is not media or cannot be found. */
62
+ get(url: string): Promise<(MediaInfo & { url: string }) | null>;
63
+ /** Record what a content response carried. Media is immutable, so it never goes stale. */
64
+ remember(map: MediaInfoMap | undefined): void;
65
+ };
66
+
67
+ /**
68
+ * `fetchInfo` asks the content API by id. Without it (a site reading files
69
+ * from disk), `fetchHead` asks the CDN for the file's content type.
70
+ */
71
+ export function createMediaResolver(input: {
72
+ fetchInfo?: (ids: string[]) => Promise<MediaInfoMap>;
73
+ fetchHead?: (url: string) => Promise<string | null>;
74
+ }): MediaResolver {
75
+ const known = new Map<string, MediaInfo>();
76
+ const pending = new Map<string, Promise<MediaInfo | null>>();
77
+
78
+ async function lookUp(url: string, id: string, legacyImage: boolean): Promise<MediaInfo | null> {
79
+ if (input.fetchInfo) {
80
+ const map = await input.fetchInfo([id]);
81
+ return map[id] ?? null;
82
+ }
83
+ if (legacyImage) {
84
+ return { id, kind: "image", contentType: null, byteSize: null, width: null, height: null };
85
+ }
86
+ const contentType = input.fetchHead ? await input.fetchHead(url) : null;
87
+ if (!contentType) return null;
88
+ const base = contentType.split(";")[0]!.trim().toLowerCase();
89
+ return { id, kind: mediaKindOf(base), contentType: base, byteSize: null, width: null, height: null };
90
+ }
91
+
92
+ return {
93
+ remember(map) {
94
+ if (!map) return;
95
+ for (const [id, info] of Object.entries(map)) known.set(id, info);
96
+ },
97
+ async get(url) {
98
+ const parsed = parseUrl(url);
99
+ if (!parsed) return null;
100
+ let info = known.get(parsed.id) ?? null;
101
+ if (!info) {
102
+ let wait = pending.get(parsed.id);
103
+ if (!wait) {
104
+ wait = lookUp(url, parsed.id, parsed.legacyImage).catch(() => null);
105
+ pending.set(parsed.id, wait);
106
+ }
107
+ info = await wait;
108
+ pending.delete(parsed.id);
109
+ if (info) known.set(parsed.id, info);
110
+ }
111
+ return info ? { ...info, url } : null;
112
+ },
113
+ };
114
+ }
package/src/media-url.ts CHANGED
@@ -11,7 +11,7 @@ export type MediaWidth = (typeof MEDIA_WIDTHS)[number];
11
11
  /** Bytes the catalog accepts for one file. */
12
12
  export const MAX_MEDIA_BYTES = 20 * 1024 * 1024;
13
13
 
14
- /** Characters of alt text or caption the catalog stores on one image. */
14
+ /** Characters of alt text or caption the catalog stores on one file. */
15
15
  export const MAX_MEDIA_TEXT = 500;
16
16
 
17
17
  export const MEDIA_CONTENT_TYPES = [
@@ -20,10 +20,28 @@ export const MEDIA_CONTENT_TYPES = [
20
20
  "image/webp",
21
21
  "image/gif",
22
22
  "image/avif",
23
+ "application/pdf",
23
24
  ] as const;
24
25
 
25
26
  export type MediaContentType = (typeof MEDIA_CONTENT_TYPES)[number];
26
27
 
28
+ /**
29
+ * What a media file is. Both are served from /media/{id}; only an image takes
30
+ * transform options. The URL does not say which: the catalog does.
31
+ */
32
+ export const MEDIA_KINDS = ["image", "pdf"] as const;
33
+
34
+ export type MediaKind = (typeof MEDIA_KINDS)[number];
35
+
36
+ export function isMediaKind(value: unknown): value is MediaKind {
37
+ return (MEDIA_KINDS as readonly unknown[]).includes(value);
38
+ }
39
+
40
+ /** The kind of a stored content type. Anything that is not a PDF is an image. */
41
+ export function mediaKindOf(contentType: string): MediaKind {
42
+ return contentType === "application/pdf" ? "pdf" : "image";
43
+ }
44
+
27
45
  const MEDIA_ID =
28
46
  /^med_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
29
47
 
@@ -35,8 +53,9 @@ export function isMediaContentType(value: string): value is MediaContentType {
35
53
  return (MEDIA_CONTENT_TYPES as readonly string[]).includes(value);
36
54
  }
37
55
 
56
+ /** The URL a document stores for a media file, image or PDF. */
38
57
  export function mediaOriginalUrl(origin: string, id: string): string {
39
- return `${origin.replace(/\/$/, "")}/img/${id}`;
58
+ return `${origin.replace(/\/$/, "")}/media/${id}`;
40
59
  }
41
60
 
42
61
  /** A width variant, or null when the id or width cannot be requested. */
@@ -48,7 +67,7 @@ export function mediaVariantUrl(
48
67
  if (!isMediaId(id) || !Number.isInteger(width) || width < 1 || width > MAX_VARIANT_WIDTH) {
49
68
  return null;
50
69
  }
51
- return `${origin.replace(/\/$/, "")}/img/${id}/width=${width},format=auto`;
70
+ return `${origin.replace(/\/$/, "")}/media/${id}/width=${width},format=auto`;
52
71
  }
53
72
 
54
73
  export function isMediaWidth(width: number): width is MediaWidth {
@@ -56,10 +75,23 @@ export function isMediaWidth(width: number): width is MediaWidth {
56
75
  }
57
76
 
58
77
  /**
59
- * The id inside an original media URL (`/img/med_…`, no options segment).
60
- * A transform URL and any other URL return null.
78
+ * The id inside an original media URL (`/media/med_…`, or `/img/med_…` from
79
+ * before media held PDFs; no options segment). A transform URL and any other
80
+ * URL return null.
61
81
  */
62
82
  export function mediaIdFromUrl(value: string): string | null {
83
+ return parseMediaUrl(value)?.id ?? null;
84
+ }
85
+
86
+ /**
87
+ * An original `/img/` URL. Only images were ever stored under /img/, so this
88
+ * one URL form is known to be an image without asking the catalog.
89
+ */
90
+ export function isLegacyImageUrl(value: string): boolean {
91
+ return parseMediaUrl(value)?.legacyImage === true;
92
+ }
93
+
94
+ function parseMediaUrl(value: string): { id: string; legacyImage: boolean } | null {
63
95
  let url: URL;
64
96
  try {
65
97
  url = new URL(value);
@@ -69,7 +101,8 @@ export function mediaIdFromUrl(value: string): string | null {
69
101
  if (url.protocol !== "https:" && url.protocol !== "http:") return null;
70
102
  if (url.search || url.hash) return null;
71
103
  const parts = url.pathname.split("/").filter(Boolean);
72
- if (parts.length !== 2 || parts[0] !== "img") return null;
104
+ if (parts.length !== 2) return null;
105
+ if (parts[0] !== "media" && parts[0] !== "img") return null;
73
106
  const id = parts[1]!;
74
- return isMediaId(id) ? id : null;
107
+ return isMediaId(id) ? { id, legacyImage: parts[0] === "img" } : null;
75
108
  }
@@ -2,7 +2,8 @@
2
2
  import type { ModelDef, ModelSnapshot } from "../model";
3
3
  import type { BlockDef } from "../block";
4
4
  import type { ObjectDef } from "../object";
5
- import { getDocFromApi, listDocsFromApi } from "../api-loader";
5
+ import { getDocFromApi, getMediaInfoFromApi, listDocsFromApi } from "../api-loader";
6
+ import { createMediaResolver, type MediaInfo } from "../media-info";
6
7
  import { getDocFromFs, listDocsFromFs } from "./fs-loader";
7
8
  import { createQuery, type DocLoader, type Query } from "../query";
8
9
  import { syncSchema } from "../sync-schema";
@@ -45,6 +46,12 @@ export type BackmatterClient<
45
46
  getDoc: (type: string, slug: string) => Promise<BackmatterDoc | null>;
46
47
  /** Typed access keyed by model.type: cms.query.blog.get / findMany */
47
48
  query: Query<Models, Blocks>;
49
+ /**
50
+ * Whether a media URL is an image or a PDF, and the file's facts. A media
51
+ * field stores only the URL, which does not say. Answers from what content
52
+ * responses carried; null when the URL is not media or cannot be found.
53
+ */
54
+ media: (url: string) => Promise<(MediaInfo & { url: string }) | null>;
48
55
  /** The registered models, e.g. for route matching. */
49
56
  models: Models;
50
57
  /** Effective config after env fallbacks. */
@@ -104,6 +111,22 @@ export function createBackmatter<
104
111
  }
105
112
  }
106
113
 
114
+ const mediaInfo = createMediaResolver(
115
+ useApi
116
+ ? {
117
+ fetchInfo: (ids) =>
118
+ getMediaInfoFromApi(apiUrl!, workspaceId!, contentToken, ids, taggedApiFetch ? listCacheTags() : undefined),
119
+ }
120
+ : {
121
+ // Files read from disk carry no catalog. The CDN's response names the kind.
122
+ fetchHead: async (url) => {
123
+ const res = await fetch(url, { method: "HEAD" });
124
+ return res.ok ? res.headers.get("content-type") : null;
125
+ },
126
+ },
127
+ );
128
+ const onMedia = mediaInfo.remember;
129
+
107
130
  const loader: DocLoader = {
108
131
  async listDocs(filter) {
109
132
  const docs = useApi
@@ -111,6 +134,7 @@ export function createBackmatter<
111
134
  branch,
112
135
  type: filter?.type,
113
136
  tags: taggedApiFetch ? listCacheTags(filter?.type) : undefined,
137
+ onMedia,
114
138
  })
115
139
  : await listDocsFromFs(siteRoot, models);
116
140
 
@@ -125,6 +149,7 @@ export function createBackmatter<
125
149
  return getDocFromApi(apiUrl!, workspaceId!, contentToken, type, slug, {
126
150
  branch,
127
151
  tags: taggedApiFetch ? contentCacheTags(type, slug) : undefined,
152
+ onMedia,
128
153
  });
129
154
  }
130
155
  return getDocFromFs(siteRoot, models, type, slug);
@@ -135,6 +160,7 @@ export function createBackmatter<
135
160
  listDocs: loader.listDocs,
136
161
  getDoc: loader.getDoc,
137
162
  query: createQuery<Models, Blocks>(modelDefs, loader, blockDefs),
163
+ media: mediaInfo.get,
138
164
  models: modelDefs,
139
165
  config,
140
166
  };
package/src/zod.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  import { z } from "zod";
3
3
  import { isColorString } from "./color";
4
4
  import type { FieldKind, FieldSnapshot } from "./fields";
5
- import { mediaIdFromUrl } from "./media-url";
5
+ import { isLegacyImageUrl, mediaIdFromUrl, type MediaKind } from "./media-url";
6
6
  import type { Frontmatter } from "./mdx";
7
7
  import type { ModelSnapshot } from "./model";
8
8
  import type { ObjectSnapshot } from "./object";
@@ -51,7 +51,7 @@ export function exampleValueFor(kind: FieldKind): unknown {
51
51
  case "image":
52
52
  return "https://example.com/image.jpg";
53
53
  case "media":
54
- return "https://cdn.backmatter.app/img/med_018f6b3e-7c2a-7b1d-8e4f-9a0b1c2d3e4f";
54
+ return "https://cdn.backmatter.app/media/med_018f6b3e-7c2a-7b1d-8e4f-9a0b1c2d3e4f";
55
55
  case "relation":
56
56
  return "related-slug";
57
57
  case "link":
@@ -173,12 +173,19 @@ function fieldZod(field: FieldSnapshot, ctx: ZodBuildContext): z.ZodType {
173
173
  return value;
174
174
  };
175
175
  const asAbsent = <T extends z.ZodType>(schema: T) => z.preprocess(absentMedia, schema);
176
+ const accept: readonly MediaKind[] = field.accept ?? ["image"];
177
+ const wrongKind = { message: `must be ${acceptPhrase(accept)}` };
178
+ const isMediaUrl = (value: string) => mediaIdFromUrl(value) !== null;
179
+ // A /media/ URL does not name its kind; Commit checks it against the catalog.
180
+ // Only a legacy /img/ URL is known here, and it is an image.
181
+ const isAccepted = (value: string) => !isLegacyImageUrl(value) || accept.includes("image");
176
182
  if (field.multiple) {
177
183
  const entry = z
178
184
  .string()
179
185
  .trim()
180
186
  .min(1)
181
- .refine((value) => mediaIdFromUrl(value) !== null);
187
+ .refine(isMediaUrl)
188
+ .refine(isAccepted, wrongKind);
182
189
  const arr = z.array(entry).superRefine((values, ctx) => {
183
190
  const seen = new Set<string>();
184
191
  for (const value of values) {
@@ -192,14 +199,13 @@ function fieldZod(field: FieldSnapshot, ctx: ZodBuildContext): z.ZodType {
192
199
  });
193
200
  return asAbsent(field.required ? arr.min(1) : arr.optional());
194
201
  }
195
- const url = z.string().refine((value) => value.trim() === "" || mediaIdFromUrl(value) !== null);
202
+ const url = z
203
+ .string()
204
+ .refine((value) => value.trim() === "" || isMediaUrl(value))
205
+ .refine(isAccepted, wrongKind);
196
206
  if (!field.required) return asAbsent(url.optional());
197
207
  return asAbsent(
198
- z
199
- .string()
200
- .trim()
201
- .min(1)
202
- .refine((value) => mediaIdFromUrl(value) !== null),
208
+ z.string().trim().min(1).refine(isMediaUrl).refine(isAccepted, wrongKind),
203
209
  );
204
210
  }
205
211
  let base: z.ZodType;
@@ -289,3 +295,9 @@ export function fieldAtPath(
289
295
  }
290
296
  return current;
291
297
  }
298
+
299
+ function acceptPhrase(accept: readonly MediaKind[]): string {
300
+ const names = accept.map((kind) => (kind === "pdf" ? "PDF" : "image"));
301
+ const phrase = names.join(" or ");
302
+ return /^[aeiou]/i.test(phrase) ? `an ${phrase}` : `a ${phrase}`;
303
+ }