@backmatter/core 0.0.39 → 0.0.41
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 +1 -1
- package/src/api-loader.ts +24 -3
- package/src/fields.ts +28 -2
- package/src/index.ts +10 -3
- package/src/media-fields.ts +27 -14
- package/src/media-info.ts +114 -0
- package/src/media-url.ts +40 -7
- package/src/node/create-backmatter.ts +27 -1
- package/src/node/media-cli.ts +26 -3
- package/src/zod.ts +21 -9
package/package.json
CHANGED
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
|
+
}
|
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
|
-
) =>
|
|
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";
|
|
@@ -190,7 +195,9 @@ export {
|
|
|
190
195
|
PREVIEW_SESSION_TTL_MS,
|
|
191
196
|
} from "./preview-session";
|
|
192
197
|
export { signPayload, verifyPayload } from "./signed-token";
|
|
193
|
-
export { getDocFromApi, listDocsFromApi } from "./api-loader";
|
|
198
|
+
export { getDocFromApi, getMediaInfoFromApi, listDocsFromApi } from "./api-loader";
|
|
199
|
+
export { createMediaResolver, mediaIdsInContent } from "./media-info";
|
|
200
|
+
export type { MediaInfo, MediaInfoMap, MediaResolver } from "./media-info";
|
|
194
201
|
export type { PublicDocsQuery } from "./api-loader";
|
|
195
202
|
export { syncSchema, detectGitBranch } from "./sync-schema";
|
|
196
203
|
export type { SyncSchemaOptions } from "./sync-schema";
|
package/src/media-fields.ts
CHANGED
|
@@ -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
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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:
|
|
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
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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
|
|
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(/\/$/, "")}/
|
|
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(/\/$/, "")}/
|
|
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 (`/
|
|
60
|
-
* A transform URL and any other
|
|
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
|
|
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/node/media-cli.ts
CHANGED
|
@@ -12,12 +12,16 @@ export const MEDIA_USAGE = `Usage:
|
|
|
12
12
|
backmatter media url <id> [--width <px>] [--origin <url>]
|
|
13
13
|
|
|
14
14
|
login opens the browser, where you confirm the code and pick one workspace.
|
|
15
|
+
It calls --api, else BACKMATTER_API_URL, else the folder's linked api, else the
|
|
16
|
+
api of your saved logins when they share one, else https://api.backmatter.app.
|
|
15
17
|
It links this folder to that workspace in .backmatter/workspace.json and keeps
|
|
16
18
|
the token, which works only in that workspace, in ~/.backmatter/credentials.json.
|
|
17
19
|
media upload and list use --workspace, else BACKMATTER_WORKSPACE, else
|
|
18
20
|
BACKMATTER_WORKSPACE_ID, else the folder's linked workspace.
|
|
19
21
|
media url prints a CDN url. --width <px> appends width and format=auto.`;
|
|
20
22
|
|
|
23
|
+
const HOSTED_API = "https://api.backmatter.app";
|
|
24
|
+
|
|
21
25
|
type WorkspaceRef = { id: string; name: string; slug: string };
|
|
22
26
|
/** One workspace's token. The token works in that workspace only. */
|
|
23
27
|
type Login = { api: string; workspace: WorkspaceRef; token: string };
|
|
@@ -78,7 +82,13 @@ export async function runMediaCli(
|
|
|
78
82
|
async function login(argv: string[], io: Io): Promise<number> {
|
|
79
83
|
const flags = readFlags(argv);
|
|
80
84
|
const link = await findFolderLink(io.cwd);
|
|
81
|
-
const api = (
|
|
85
|
+
const api = (
|
|
86
|
+
flags.api ||
|
|
87
|
+
io.env.BACKMATTER_API_URL ||
|
|
88
|
+
link?.link.api ||
|
|
89
|
+
savedApi(await readCredentials(io.home)) ||
|
|
90
|
+
HOSTED_API
|
|
91
|
+
).replace(/\/$/, "");
|
|
82
92
|
const web = (flags.web || io.env.BACKMATTER_WEB_ORIGIN || "http://localhost:5173").replace(/\/$/, "");
|
|
83
93
|
const workspace =
|
|
84
94
|
flags.workspace ||
|
|
@@ -87,12 +97,15 @@ async function login(argv: string[], io: Io): Promise<number> {
|
|
|
87
97
|
(link && link.link.api === api ? link.link.workspaceId : undefined);
|
|
88
98
|
const pollSecret = crypto.randomUUID() + crypto.randomUUID();
|
|
89
99
|
const fetchImpl = io.fetch ?? fetch;
|
|
90
|
-
const
|
|
100
|
+
const startUrl = `${api}/cli/login`;
|
|
101
|
+
const started = await fetchImpl(startUrl, {
|
|
91
102
|
method: "POST",
|
|
92
103
|
headers: { "content-type": "application/json" },
|
|
93
104
|
body: JSON.stringify({ pollSecret, workspace, client: io.hostname }),
|
|
105
|
+
}).catch((err: unknown) => {
|
|
106
|
+
throw new Error(`login failed: could not reach ${startUrl} (${err instanceof Error ? err.message : String(err)})`);
|
|
94
107
|
});
|
|
95
|
-
if (!started.ok) throw new Error(`login failed: ${started.status}`);
|
|
108
|
+
if (!started.ok) throw new Error(`login failed: ${started.status} from ${startUrl}`);
|
|
96
109
|
const body = (await started.json()) as { id: string; userCode?: string; authorizeUrl: string };
|
|
97
110
|
const authorizeUrl = body.authorizeUrl || `${web}/cli/authorize?id=${encodeURIComponent(body.id)}`;
|
|
98
111
|
(io.open ?? openBrowser)(authorizeUrl);
|
|
@@ -245,6 +258,16 @@ async function readCredentials(home: string): Promise<Credentials | null> {
|
|
|
245
258
|
return readJson<Credentials>(credentialsPath(home));
|
|
246
259
|
}
|
|
247
260
|
|
|
261
|
+
/** The api every saved login uses, when they agree on one. */
|
|
262
|
+
function savedApi(creds: Credentials | null): string | undefined {
|
|
263
|
+
const apis = new Set(
|
|
264
|
+
[...(creds?.logins ?? []).map((entry) => entry.api), creds?.api]
|
|
265
|
+
.filter((api): api is string => !!api)
|
|
266
|
+
.map((api) => api.replace(/\/$/, "")),
|
|
267
|
+
);
|
|
268
|
+
return apis.size === 1 ? [...apis][0] : undefined;
|
|
269
|
+
}
|
|
270
|
+
|
|
248
271
|
/** Keeps one token per api and workspace, replacing an older one for the same pair. */
|
|
249
272
|
async function saveLogin(home: string, login: Login): Promise<void> {
|
|
250
273
|
const creds = (await readCredentials(home)) ?? {};
|
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/
|
|
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(
|
|
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
|
|
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
|
+
}
|