@backmatter/core 0.0.36 → 0.0.38
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/block-groups.ts +112 -0
- package/src/block.ts +82 -4
- package/src/fields.ts +42 -2
- package/src/index.ts +6 -0
- package/src/link-address.ts +6 -1
- package/src/link-problems.ts +23 -1
- package/src/model.ts +17 -0
- package/src/node/eval-block.ts +29 -7
- package/src/node/eval-model.ts +25 -3
- package/src/node/index.ts +2 -0
- package/src/node/local-modules.ts +268 -0
- package/src/node/media-cli.ts +134 -55
- package/src/preview-channel.ts +5 -0
package/package.json
CHANGED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// packages/core/src/block-groups.ts
|
|
2
|
+
//
|
|
3
|
+
// Built-in block groups. A block opts in with `group: "header"` etc. The
|
|
4
|
+
// description tells editors and the AI what blocks in the group are for and
|
|
5
|
+
// where they belong on a page; `placement`/`maxPerPage` are defaults a block
|
|
6
|
+
// can override. Custom group names are allowed and simply have no built-in text.
|
|
7
|
+
|
|
8
|
+
export type BlockPlacement = "first" | "last" | "any";
|
|
9
|
+
|
|
10
|
+
export type BlockGroupInfo = {
|
|
11
|
+
label: string;
|
|
12
|
+
description: string;
|
|
13
|
+
placement?: BlockPlacement;
|
|
14
|
+
maxPerPage?: number;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export const BLOCK_GROUPS = {
|
|
18
|
+
header: {
|
|
19
|
+
label: "Page header",
|
|
20
|
+
description:
|
|
21
|
+
"Opens the page: hero, page title, intro banner. Says what the page is about in one glance. Exactly one, always the first block.",
|
|
22
|
+
placement: "first",
|
|
23
|
+
maxPerPage: 1,
|
|
24
|
+
},
|
|
25
|
+
content: {
|
|
26
|
+
label: "Content",
|
|
27
|
+
description:
|
|
28
|
+
"The body of the page: text sections, text with image, features, steps, FAQ. Alternate different content blocks instead of repeating one.",
|
|
29
|
+
},
|
|
30
|
+
media: {
|
|
31
|
+
label: "Media",
|
|
32
|
+
description:
|
|
33
|
+
"Visual sections: full-width images, galleries, video. Use them to break up runs of text; never two in a row.",
|
|
34
|
+
},
|
|
35
|
+
people: {
|
|
36
|
+
label: "People",
|
|
37
|
+
description: "Team members, board, contact persons, profiles. Group all people of one kind together.",
|
|
38
|
+
},
|
|
39
|
+
proof: {
|
|
40
|
+
label: "Social proof",
|
|
41
|
+
description:
|
|
42
|
+
"Testimonials, quotes, partner logos, numbers. Builds trust: place after the offer is explained and before the call to action.",
|
|
43
|
+
},
|
|
44
|
+
cta: {
|
|
45
|
+
label: "Call to action",
|
|
46
|
+
description:
|
|
47
|
+
"Asks the visitor to act: contact, apply, sign up, read more. Usually near the end of the page; at most two per page.",
|
|
48
|
+
maxPerPage: 2,
|
|
49
|
+
},
|
|
50
|
+
footer: {
|
|
51
|
+
label: "Footer",
|
|
52
|
+
description: "Closes the page. At most one, always the last block.",
|
|
53
|
+
placement: "last",
|
|
54
|
+
maxPerPage: 1,
|
|
55
|
+
},
|
|
56
|
+
} as const satisfies Record<string, BlockGroupInfo>;
|
|
57
|
+
|
|
58
|
+
export type BuiltinBlockGroup = keyof typeof BLOCK_GROUPS;
|
|
59
|
+
|
|
60
|
+
export function blockGroupInfo(group: string | undefined): BlockGroupInfo | null {
|
|
61
|
+
if (!group) return null;
|
|
62
|
+
return (BLOCK_GROUPS as Record<string, BlockGroupInfo>)[group] ?? null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Placement and per-page limit for a block: its own values, else its group's defaults. */
|
|
66
|
+
export function blockRules(block: {
|
|
67
|
+
group?: string;
|
|
68
|
+
placement?: BlockPlacement;
|
|
69
|
+
maxPerPage?: number;
|
|
70
|
+
}): { placement: BlockPlacement; maxPerPage?: number } {
|
|
71
|
+
const group = blockGroupInfo(block.group);
|
|
72
|
+
const maxPerPage = block.maxPerPage ?? group?.maxPerPage;
|
|
73
|
+
return {
|
|
74
|
+
placement: block.placement ?? group?.placement ?? "any",
|
|
75
|
+
...(maxPerPage !== undefined ? { maxPerPage } : {}),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Placement and per-page-limit problems in a page's block list, as short
|
|
81
|
+
* sentences. Advisory: commits do not enforce these rules.
|
|
82
|
+
*/
|
|
83
|
+
export function blockLayoutWarnings(
|
|
84
|
+
blocks: unknown,
|
|
85
|
+
catalog: ReadonlyArray<{ name: string; group?: string; placement?: BlockPlacement; maxPerPage?: number }>,
|
|
86
|
+
prefix = "blocks",
|
|
87
|
+
): string[] {
|
|
88
|
+
if (!Array.isArray(blocks)) return [];
|
|
89
|
+
const byName = new Map(catalog.map((b) => [b.name, b]));
|
|
90
|
+
const warnings: string[] = [];
|
|
91
|
+
const counts = new Map<string, number>();
|
|
92
|
+
blocks.forEach((item, i) => {
|
|
93
|
+
const type = item && typeof item === "object" ? (item as { type?: unknown }).type : undefined;
|
|
94
|
+
const def = typeof type === "string" ? byName.get(type) : undefined;
|
|
95
|
+
if (!def) return;
|
|
96
|
+
counts.set(def.name, (counts.get(def.name) ?? 0) + 1);
|
|
97
|
+
const { placement } = blockRules(def);
|
|
98
|
+
if (placement === "first" && i !== 0) {
|
|
99
|
+
warnings.push(`${prefix}[${i}]: ${def.name} should be the first block on the page`);
|
|
100
|
+
}
|
|
101
|
+
if (placement === "last" && i !== blocks.length - 1) {
|
|
102
|
+
warnings.push(`${prefix}[${i}]: ${def.name} should be the last block on the page`);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
for (const [name, count] of counts) {
|
|
106
|
+
const { maxPerPage } = blockRules(byName.get(name)!);
|
|
107
|
+
if (maxPerPage !== undefined && count > maxPerPage) {
|
|
108
|
+
warnings.push(`${prefix}: ${count} ${name} blocks, but at most ${maxPerPage} per page`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return warnings;
|
|
112
|
+
}
|
package/src/block.ts
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
parseFieldSnapshot,
|
|
7
7
|
serializeField,
|
|
8
8
|
} from "./fields";
|
|
9
|
+
import type { BlockPlacement } from "./block-groups";
|
|
9
10
|
|
|
10
11
|
export type BlockInstance = {
|
|
11
12
|
id: string;
|
|
@@ -13,17 +14,89 @@ export type BlockInstance = {
|
|
|
13
14
|
props: Record<string, unknown>;
|
|
14
15
|
};
|
|
15
16
|
|
|
16
|
-
|
|
17
|
+
/**
|
|
18
|
+
* Guidance for editors and the AI. Never rendered on the site. Shared by
|
|
19
|
+
* block definitions and snapshots.
|
|
20
|
+
*/
|
|
21
|
+
export type BlockMeta = {
|
|
22
|
+
/** What the block is for and when to use it. */
|
|
23
|
+
description?: string;
|
|
24
|
+
/** A built-in group from `BLOCK_GROUPS` ("header", "content", …) or a custom kebab-case name. */
|
|
25
|
+
group?: string;
|
|
26
|
+
/** "first" / "last" pin the block to the start or end of a page. Defaults from the group. */
|
|
27
|
+
placement?: BlockPlacement;
|
|
28
|
+
/** Most instances one page may hold. Defaults from the group. */
|
|
29
|
+
maxPerPage?: number;
|
|
30
|
+
/**
|
|
31
|
+
* Thumbnail for the Studio block picker: an `https://` URL, or a site path
|
|
32
|
+
* like "/block-previews/hero.png" (a file in the site's `public/`). Blocks
|
|
33
|
+
* without one get a wireframe drawn from their fields.
|
|
34
|
+
*/
|
|
35
|
+
preview?: string;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export type BlockDef<C = unknown> = BlockMeta & {
|
|
17
39
|
name: string;
|
|
18
40
|
fields: Record<string, FieldDef>;
|
|
19
41
|
component: C;
|
|
20
42
|
};
|
|
21
43
|
|
|
22
|
-
export type BlockSnapshot = {
|
|
44
|
+
export type BlockSnapshot = BlockMeta & {
|
|
23
45
|
name: string;
|
|
24
46
|
fields: Record<string, FieldSnapshot>;
|
|
25
47
|
};
|
|
26
48
|
|
|
49
|
+
const PLACEMENTS: readonly BlockPlacement[] = ["first", "last", "any"];
|
|
50
|
+
const GROUP_NAME = /^[a-z][a-z0-9-]*$/;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Read guidance keys. `strict` throws on a bad value (defineBlock); otherwise a
|
|
54
|
+
* bad value is dropped so a stored snapshot still loads.
|
|
55
|
+
*/
|
|
56
|
+
function readBlockMeta(value: Record<string, unknown>, strict: boolean): BlockMeta {
|
|
57
|
+
const meta: BlockMeta = {};
|
|
58
|
+
const bad = (message: string) => {
|
|
59
|
+
if (strict) throw new Error(message);
|
|
60
|
+
};
|
|
61
|
+
if (value.description !== undefined) {
|
|
62
|
+
if (typeof value.description !== "string") bad("block.description must be a string");
|
|
63
|
+
else if (value.description.trim()) meta.description = value.description.trim();
|
|
64
|
+
}
|
|
65
|
+
if (value.group !== undefined) {
|
|
66
|
+
if (typeof value.group !== "string" || !GROUP_NAME.test(value.group)) {
|
|
67
|
+
bad('block.group must be a lowercase name like "header" or "content"');
|
|
68
|
+
} else meta.group = value.group;
|
|
69
|
+
}
|
|
70
|
+
if (value.placement !== undefined) {
|
|
71
|
+
if (!PLACEMENTS.includes(value.placement as BlockPlacement)) {
|
|
72
|
+
bad('block.placement must be "first", "last" or "any"');
|
|
73
|
+
} else meta.placement = value.placement as BlockPlacement;
|
|
74
|
+
}
|
|
75
|
+
if (value.maxPerPage !== undefined) {
|
|
76
|
+
const n = value.maxPerPage;
|
|
77
|
+
if (typeof n !== "number" || !Number.isInteger(n) || n < 1) {
|
|
78
|
+
bad("block.maxPerPage must be a positive integer");
|
|
79
|
+
} else meta.maxPerPage = n;
|
|
80
|
+
}
|
|
81
|
+
if (value.preview !== undefined) {
|
|
82
|
+
if (typeof value.preview !== "string" || !isBlockPreviewSrc(value.preview.trim())) {
|
|
83
|
+
bad('block.preview must be an https:// URL or a site path like "/block-previews/hero.png"');
|
|
84
|
+
} else meta.preview = value.preview.trim();
|
|
85
|
+
}
|
|
86
|
+
return meta;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** An http(s) URL or a root-relative path (not protocol-relative). */
|
|
90
|
+
export function isBlockPreviewSrc(value: string): boolean {
|
|
91
|
+
if (value.startsWith("/")) return !value.startsWith("//") && !/\s/.test(value);
|
|
92
|
+
try {
|
|
93
|
+
const url = new URL(value);
|
|
94
|
+
return url.protocol === "https:" || url.protocol === "http:";
|
|
95
|
+
} catch {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
27
100
|
const PASCAL = /^[A-Z][A-Za-z0-9]*$/;
|
|
28
101
|
|
|
29
102
|
export function defineBlock<const D extends BlockDef>(def: D): D {
|
|
@@ -44,6 +117,7 @@ export function defineBlock<const D extends BlockDef>(def: D): D {
|
|
|
44
117
|
`block.fields.${RESERVED_BLOCK_PROP} is reserved: it carries the external source record`,
|
|
45
118
|
);
|
|
46
119
|
}
|
|
120
|
+
readBlockMeta(def as unknown as Record<string, unknown>, true);
|
|
47
121
|
return def;
|
|
48
122
|
}
|
|
49
123
|
|
|
@@ -89,7 +163,11 @@ export function serializeBlock(block: BlockDef): BlockSnapshot {
|
|
|
89
163
|
for (const [name, def] of Object.entries(block.fields)) {
|
|
90
164
|
fields[name] = serializeField(def);
|
|
91
165
|
}
|
|
92
|
-
return {
|
|
166
|
+
return {
|
|
167
|
+
name: block.name,
|
|
168
|
+
...readBlockMeta(block as unknown as Record<string, unknown>, true),
|
|
169
|
+
fields,
|
|
170
|
+
};
|
|
93
171
|
}
|
|
94
172
|
|
|
95
173
|
export function parseBlockSnapshot(input: unknown): BlockSnapshot {
|
|
@@ -111,5 +189,5 @@ export function parseBlockSnapshot(input: unknown): BlockSnapshot {
|
|
|
111
189
|
// Drop unknown kinds so a stored snapshot still loads.
|
|
112
190
|
}
|
|
113
191
|
}
|
|
114
|
-
return { name: value.name, fields };
|
|
192
|
+
return { name: value.name, ...readBlockMeta(value, false), fields };
|
|
115
193
|
}
|
package/src/fields.ts
CHANGED
|
@@ -49,6 +49,8 @@ export type FieldDef<
|
|
|
49
49
|
step?: number;
|
|
50
50
|
where?: RelationWhere;
|
|
51
51
|
multiple?: true;
|
|
52
|
+
/** Guidance for editors and the AI: what goes here, length, tone. Never rendered. */
|
|
53
|
+
description?: string;
|
|
52
54
|
};
|
|
53
55
|
|
|
54
56
|
export type FieldSnapshot = {
|
|
@@ -66,11 +68,17 @@ export type FieldSnapshot = {
|
|
|
66
68
|
step?: number;
|
|
67
69
|
where?: RelationWhere;
|
|
68
70
|
multiple?: true;
|
|
71
|
+
description?: string;
|
|
69
72
|
};
|
|
70
73
|
|
|
71
74
|
type ObjectLike = { name: string; fields: Record<string, FieldDef> };
|
|
72
75
|
|
|
73
|
-
type Opts<R extends boolean> = {
|
|
76
|
+
type Opts<R extends boolean> = {
|
|
77
|
+
required?: R;
|
|
78
|
+
input?: string;
|
|
79
|
+
/** Guidance for editors and the AI: what goes here, length, tone. Never rendered. */
|
|
80
|
+
description?: string;
|
|
81
|
+
};
|
|
74
82
|
|
|
75
83
|
type TextOpts<R extends boolean> = Opts<R> & { options?: string[] };
|
|
76
84
|
|
|
@@ -435,7 +443,22 @@ type TextFieldDef<R extends boolean, O extends readonly string[] | undefined = u
|
|
|
435
443
|
type MediaFieldDef<R extends boolean, M extends boolean = false> = FieldDef<"media", R> &
|
|
436
444
|
(M extends true ? { readonly multiple: true } : {});
|
|
437
445
|
|
|
438
|
-
|
|
446
|
+
/** Copy `opts.description` (trimmed, non-blank) onto the definition a constructor built. */
|
|
447
|
+
function described<A extends unknown[], D extends FieldDef>(
|
|
448
|
+
make: (...args: A) => D,
|
|
449
|
+
optsIndex: number,
|
|
450
|
+
): (...args: A) => D {
|
|
451
|
+
return (...args: A) => {
|
|
452
|
+
const def = make(...args);
|
|
453
|
+
const opts = args[optsIndex] as { description?: unknown } | undefined;
|
|
454
|
+
const raw = opts && typeof opts === "object" ? opts.description : undefined;
|
|
455
|
+
if (raw === undefined) return def;
|
|
456
|
+
if (typeof raw !== "string") throw new Error("field description must be a string");
|
|
457
|
+
return raw.trim() ? { ...def, description: raw.trim() } : def;
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const constructors = {
|
|
439
462
|
text: <
|
|
440
463
|
const R extends boolean = false,
|
|
441
464
|
const O extends readonly string[] | undefined = undefined,
|
|
@@ -473,6 +496,19 @@ export const field = {
|
|
|
473
496
|
array: arrayField,
|
|
474
497
|
};
|
|
475
498
|
|
|
499
|
+
export const field = {
|
|
500
|
+
text: described(constructors.text, 0),
|
|
501
|
+
image: described(constructors.image, 0),
|
|
502
|
+
media: described(constructors.media, 0),
|
|
503
|
+
number: described(constructors.number, 0),
|
|
504
|
+
boolean: described(constructors.boolean, 0),
|
|
505
|
+
relation: described(constructors.relation, 1) as typeof relation,
|
|
506
|
+
link: described(constructors.link, 0) as typeof link,
|
|
507
|
+
blocks: described(constructors.blocks, 0),
|
|
508
|
+
object: described(constructors.object, 1) as typeof objectField,
|
|
509
|
+
array: described(constructors.array, 1) as typeof arrayField,
|
|
510
|
+
};
|
|
511
|
+
|
|
476
512
|
export function serializeField(def: FieldDef): FieldSnapshot {
|
|
477
513
|
const snap: FieldSnapshot = {
|
|
478
514
|
kind: def.kind,
|
|
@@ -488,6 +524,7 @@ export function serializeField(def: FieldDef): FieldSnapshot {
|
|
|
488
524
|
...(def.models ? { models: [...def.models] } : {}),
|
|
489
525
|
...(def.where ? { where: def.where } : {}),
|
|
490
526
|
...(def.multiple ? { multiple: true as const } : {}),
|
|
527
|
+
...(def.description?.trim() ? { description: def.description.trim() } : {}),
|
|
491
528
|
};
|
|
492
529
|
if (def.fields) {
|
|
493
530
|
const fields: Record<string, FieldSnapshot> = {};
|
|
@@ -570,6 +607,9 @@ export function parseFieldSnapshot(input: unknown): FieldSnapshot {
|
|
|
570
607
|
if (where) {
|
|
571
608
|
snap.where = where;
|
|
572
609
|
}
|
|
610
|
+
if (typeof value.description === "string" && value.description.trim()) {
|
|
611
|
+
snap.description = value.description.trim();
|
|
612
|
+
}
|
|
573
613
|
if (value.fields && typeof value.fields === "object" && !Array.isArray(value.fields)) {
|
|
574
614
|
const fields: Record<string, FieldSnapshot> = {};
|
|
575
615
|
for (const [name, nested] of Object.entries(value.fields as Record<string, unknown>)) {
|
package/src/index.ts
CHANGED
|
@@ -32,6 +32,7 @@ export type {
|
|
|
32
32
|
ModelInput,
|
|
33
33
|
ModelSnapshot,
|
|
34
34
|
SchemaSnapshot,
|
|
35
|
+
SchemaFailure,
|
|
35
36
|
InferFrontmatter,
|
|
36
37
|
} from "./model";
|
|
37
38
|
export {
|
|
@@ -54,11 +55,15 @@ export type {
|
|
|
54
55
|
BlockDef,
|
|
55
56
|
BlockSnapshot,
|
|
56
57
|
InferBlockProps,
|
|
58
|
+
BlockMeta,
|
|
57
59
|
} from "./block";
|
|
60
|
+
export type { BlockGroupInfo, BlockPlacement, BuiltinBlockGroup } from "./block-groups";
|
|
61
|
+
export { BLOCK_GROUPS, blockGroupInfo, blockLayoutWarnings, blockRules } from "./block-groups";
|
|
58
62
|
export {
|
|
59
63
|
defineBlock,
|
|
60
64
|
serializeBlock,
|
|
61
65
|
parseBlockSnapshot,
|
|
66
|
+
isBlockPreviewSrc,
|
|
62
67
|
RESERVED_BLOCK_PROP,
|
|
63
68
|
} from "./block";
|
|
64
69
|
|
|
@@ -215,6 +220,7 @@ export type { LinkSide } from "./link-address";
|
|
|
215
220
|
export {
|
|
216
221
|
externalLinkOk,
|
|
217
222
|
internalSuffixError,
|
|
223
|
+
isBareAnchor,
|
|
218
224
|
joinInternalLink,
|
|
219
225
|
linkSide,
|
|
220
226
|
splitInternalLink,
|
package/src/link-address.ts
CHANGED
|
@@ -13,12 +13,17 @@ export function linkSide(value: string): LinkSide {
|
|
|
13
13
|
return "external";
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
|
-
if (trimmed.startsWith("/")) {
|
|
16
|
+
if (trimmed.startsWith("/") || isBareAnchor(trimmed)) {
|
|
17
17
|
return "internal";
|
|
18
18
|
}
|
|
19
19
|
return "neither";
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
/** A link to a section of the page the link sits on: `#forloeb`. */
|
|
23
|
+
export function isBareAnchor(value: string): boolean {
|
|
24
|
+
return value.trim().startsWith("#");
|
|
25
|
+
}
|
|
26
|
+
|
|
22
27
|
export function splitInternalLink(value: string): {
|
|
23
28
|
path: string;
|
|
24
29
|
query: string;
|
package/src/link-problems.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type { FieldSnapshot } from "./fields";
|
|
|
4
4
|
import {
|
|
5
5
|
externalLinkOk,
|
|
6
6
|
internalSuffixError,
|
|
7
|
+
isBareAnchor,
|
|
7
8
|
linkSide,
|
|
8
9
|
splitInternalLink,
|
|
9
10
|
} from "./link-address";
|
|
@@ -87,8 +88,20 @@ function validateInternalLink(
|
|
|
87
88
|
errors: string[],
|
|
88
89
|
): void {
|
|
89
90
|
const parts = splitInternalLink(value);
|
|
90
|
-
const atPath = routeIndex.get(parts.path) ?? [];
|
|
91
91
|
const models = field.models;
|
|
92
|
+
|
|
93
|
+
if (isBareAnchor(value)) {
|
|
94
|
+
// The page a bare anchor points at is whichever page renders the link,
|
|
95
|
+
// so it cannot be held to a model or a filter.
|
|
96
|
+
if ((models && models.length > 0) || field.where) {
|
|
97
|
+
errors.push(documentRouteMessage(path, models));
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
pushSuffixError(path, value, parts, errors);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const atPath = routeIndex.get(parts.path) ?? [];
|
|
92
105
|
let candidates = atPath;
|
|
93
106
|
if (models && models.length > 0) {
|
|
94
107
|
candidates = atPath.filter((d) => models.includes(d.type));
|
|
@@ -107,6 +120,15 @@ function validateInternalLink(
|
|
|
107
120
|
return;
|
|
108
121
|
}
|
|
109
122
|
|
|
123
|
+
pushSuffixError(path, value, parts, errors);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function pushSuffixError(
|
|
127
|
+
path: string,
|
|
128
|
+
value: string,
|
|
129
|
+
parts: { query: string; anchor: string },
|
|
130
|
+
errors: string[],
|
|
131
|
+
): void {
|
|
110
132
|
const hashIndex = value.indexOf("#");
|
|
111
133
|
const preHash = hashIndex === -1 ? value : value.slice(0, hashIndex);
|
|
112
134
|
const suffixErr = internalSuffixError(
|
package/src/model.ts
CHANGED
|
@@ -134,8 +134,13 @@ export type SchemaSnapshot = {
|
|
|
134
134
|
/** In-content blocks from `richtext/`. Separate from page-builder `blocks`. */
|
|
135
135
|
richtext?: BlockSnapshot[];
|
|
136
136
|
objects?: ObjectSnapshot[];
|
|
137
|
+
/** Model, object, and block files the last import could not evaluate. */
|
|
138
|
+
failures?: SchemaFailure[];
|
|
137
139
|
};
|
|
138
140
|
|
|
141
|
+
/** A source file that failed to evaluate. Its definition is missing or stale in the snapshot. */
|
|
142
|
+
export type SchemaFailure = { path: string; message: string };
|
|
143
|
+
|
|
139
144
|
type WithPath<D extends ModelInput> = D extends { path: string } ? D : D & { path: string };
|
|
140
145
|
type WithTemplate<D extends ModelInput> = D extends { external: true }
|
|
141
146
|
? D extends { template: string }
|
|
@@ -433,11 +438,23 @@ export function parseSchemaSnapshot(input: unknown): SchemaSnapshot {
|
|
|
433
438
|
}
|
|
434
439
|
}
|
|
435
440
|
|
|
441
|
+
const failures = parseSchemaFailures(value.failures);
|
|
436
442
|
return {
|
|
437
443
|
version,
|
|
438
444
|
models,
|
|
439
445
|
blocks,
|
|
440
446
|
...(richtext.length > 0 ? { richtext } : {}),
|
|
441
447
|
objects,
|
|
448
|
+
...(failures.length > 0 ? { failures } : {}),
|
|
442
449
|
};
|
|
443
450
|
}
|
|
451
|
+
|
|
452
|
+
function parseSchemaFailures(raw: unknown): SchemaFailure[] {
|
|
453
|
+
if (!Array.isArray(raw)) return [];
|
|
454
|
+
return raw.flatMap((item) => {
|
|
455
|
+
if (!item || typeof item !== "object") return [];
|
|
456
|
+
const { path, message } = item as Record<string, unknown>;
|
|
457
|
+
if (typeof path !== "string" || typeof message !== "string") return [];
|
|
458
|
+
return [{ path, message }];
|
|
459
|
+
});
|
|
460
|
+
}
|
package/src/node/eval-block.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { runInNewContext } from "node:vm";
|
|
6
6
|
import { field } from "../fields";
|
|
7
7
|
import { defineBlock, type BlockDef } from "../block";
|
|
8
|
+
import { compileLocalModules, pickBindings, withLocalModules, type LocalModules } from "./local-modules";
|
|
8
9
|
|
|
9
10
|
const SOURCE_EXT = /\.(ts|tsx|js|jsx|mjs)$/;
|
|
10
11
|
const IGNORED = /(\.test\.|\.spec\.|\.d\.ts$|\.stories\.)/;
|
|
@@ -81,7 +82,7 @@ function stubImportSpec(spec: string): string {
|
|
|
81
82
|
return stubs.join("\n");
|
|
82
83
|
}
|
|
83
84
|
|
|
84
|
-
function rewriteSource(source: string): string {
|
|
85
|
+
function rewriteSource(source: string, modules: LocalModules | null): string {
|
|
85
86
|
let body = source.replace(USE_CLIENT, "");
|
|
86
87
|
body = body.replace(TYPE_IMPORT, "");
|
|
87
88
|
body = body.replace(CORE_IMPORT, (_full, specifiers: string) => {
|
|
@@ -97,9 +98,10 @@ function rewriteSource(source: string): string {
|
|
|
97
98
|
return "";
|
|
98
99
|
});
|
|
99
100
|
body = body.replace(VALUE_IMPORT, (line) => {
|
|
100
|
-
const m = line.match(/^\s*import\s+([\s\S]*?)\s+from\s+["'][^"']+["']\s*;?\s*$/);
|
|
101
|
+
const m = line.match(/^\s*import\s+([\s\S]*?)\s+from\s+["']([^"']+)["']\s*;?\s*$/);
|
|
101
102
|
if (!m) throw new Error("import is not allowed");
|
|
102
|
-
|
|
103
|
+
const index = modules?.indexFor(m[2]) ?? null;
|
|
104
|
+
return index === null ? stubImportSpec(m[1]) : pickBindings(m[1], index);
|
|
103
105
|
});
|
|
104
106
|
if (/^\s*import\b/m.test(body)) {
|
|
105
107
|
throw new Error("import is not allowed except defineBlock/field from @backmatter/core");
|
|
@@ -130,17 +132,36 @@ function assertNoForbidden(source: string): void {
|
|
|
130
132
|
}
|
|
131
133
|
}
|
|
132
134
|
|
|
135
|
+
function hasForbidden(source: string): boolean {
|
|
136
|
+
return FORBIDDEN.some(({ re }) => re.test(source));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export type BlockSourceOptions = {
|
|
140
|
+
/** Repo path of the block file, so its relative imports resolve. */
|
|
141
|
+
path?: string;
|
|
142
|
+
/** Site files by repo path. Relative imports that land here run in the sandbox. */
|
|
143
|
+
files?: ReadonlyMap<string, string>;
|
|
144
|
+
};
|
|
145
|
+
|
|
133
146
|
function transpile(source: string): string {
|
|
134
147
|
const transpiler = new Bun.Transpiler({ loader: "tsx", target: "node" });
|
|
135
148
|
return transpiler.transformSync(source);
|
|
136
149
|
}
|
|
137
150
|
|
|
138
151
|
/** Evaluate one convention block file. `stem` must equal `block.name`. */
|
|
139
|
-
export function evalBlockSource(
|
|
140
|
-
|
|
152
|
+
export function evalBlockSource(
|
|
153
|
+
source: string,
|
|
154
|
+
stem: string,
|
|
155
|
+
options: BlockSourceOptions = {},
|
|
156
|
+
): BlockDef {
|
|
157
|
+
const modules =
|
|
158
|
+
options.path && options.files
|
|
159
|
+
? compileLocalModules(source, options.path, options.files, hasForbidden)
|
|
160
|
+
: null;
|
|
161
|
+
const body = rewriteSource(source, modules);
|
|
141
162
|
assertNoForbidden(body);
|
|
142
163
|
const wrapped = `(function () {\n${body}\n})()`;
|
|
143
|
-
const js = transpile(wrapped);
|
|
164
|
+
const js = withLocalModules(transpile(wrapped), modules);
|
|
144
165
|
const sandbox = Object.create(null) as {
|
|
145
166
|
defineBlock: typeof defineBlock;
|
|
146
167
|
field: typeof field;
|
|
@@ -189,9 +210,10 @@ export function evalBlocksFromTree(
|
|
|
189
210
|
const sorted = files
|
|
190
211
|
.filter((f) => isBlockSourcePath(f.path, blocksDir))
|
|
191
212
|
.sort((a, b) => a.path.localeCompare(b.path));
|
|
213
|
+
const sources = new Map(files.map((f) => [f.path, f.source]));
|
|
192
214
|
for (const file of sorted) {
|
|
193
215
|
const stem = stemOf(file.path);
|
|
194
|
-
const block = evalBlockSource(file.source, stem);
|
|
216
|
+
const block = evalBlockSource(file.source, stem, { path: file.path, files: sources });
|
|
195
217
|
if (names.has(block.name)) {
|
|
196
218
|
throw new Error(`duplicate block name "${block.name}" (${file.path})`);
|
|
197
219
|
}
|
package/src/node/eval-model.ts
CHANGED
|
@@ -3,11 +3,14 @@
|
|
|
3
3
|
// surface is the same one `discoverModels` / `discoverObjects` run: `defineModel`,
|
|
4
4
|
// `defineObject`, and `field` from @backmatter/core or @backmatter/next, plus
|
|
5
5
|
// `import name from "../objects/<name>"` and `import name from "./<model>"`.
|
|
6
|
+
// Other relative imports (`../lib/posts`) run the site file in the same sandbox
|
|
7
|
+
// when the caller passes the site's files; see local-modules.ts.
|
|
6
8
|
// Never import() the customer checkout.
|
|
7
9
|
import { runInNewContext } from "node:vm";
|
|
8
10
|
import { defineModel, type ModelDef } from "../model";
|
|
9
11
|
import { defineObject, type ObjectDef } from "../object";
|
|
10
12
|
import { field } from "../fields";
|
|
13
|
+
import { bindLocalImports, compileLocalModules, withLocalModules } from "./local-modules";
|
|
11
14
|
|
|
12
15
|
const SOURCE_EXT = /\.(ts|tsx|js|jsx|mjs)$/;
|
|
13
16
|
const IGNORED = /(\.test\.|\.spec\.|\.d\.ts$|\.stories\.)/;
|
|
@@ -107,6 +110,13 @@ function missingSiblingImport(err: unknown): string | null {
|
|
|
107
110
|
return match?.[1] ?? null;
|
|
108
111
|
}
|
|
109
112
|
|
|
113
|
+
function hasForbidden(source: string): boolean {
|
|
114
|
+
return FORBIDDEN.some(({ re }) => {
|
|
115
|
+
re.lastIndex = 0;
|
|
116
|
+
return re.test(source);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
110
120
|
function assertNoForbidden(source: string, kind = "model"): void {
|
|
111
121
|
for (const { re, name } of FORBIDDEN) {
|
|
112
122
|
re.lastIndex = 0;
|
|
@@ -182,18 +192,26 @@ export function evalObjectSource(source: string, stem: string): ObjectDef {
|
|
|
182
192
|
* and must equal `model.type`. `objects` supplies `import x from "../objects/<file>"`.
|
|
183
193
|
* `models` supplies `import x from "./<file>"`.
|
|
184
194
|
*/
|
|
195
|
+
/** The site's files, so a model's relative imports (e.g. `../lib/posts`) resolve. */
|
|
196
|
+
export type ModelSiteFiles = { path: string; files: ReadonlyMap<string, string> };
|
|
197
|
+
|
|
185
198
|
export function evalModelSource(
|
|
186
199
|
source: string,
|
|
187
200
|
stem: string,
|
|
188
201
|
objects: Readonly<Record<string, ObjectDef>> = {},
|
|
189
202
|
models: Readonly<Record<string, ModelDef>> = {},
|
|
203
|
+
site?: ModelSiteFiles,
|
|
190
204
|
): ModelDef {
|
|
191
205
|
const takenObjects = takeObjectImports(source);
|
|
192
206
|
const takenModels = takeModelImports(takenObjects.source);
|
|
193
|
-
const
|
|
207
|
+
const modules = site
|
|
208
|
+
? compileLocalModules(takenModels.source, site.path, site.files, hasForbidden)
|
|
209
|
+
: null;
|
|
210
|
+
const bound = modules ? bindLocalImports(takenModels.source, modules) : takenModels.source;
|
|
211
|
+
const body = rewriteDefaultExport(stripAllowedImports(bound));
|
|
194
212
|
assertNoForbidden(body);
|
|
195
213
|
const wrapped = `(function () {\n${body}\n})()`;
|
|
196
|
-
const js = transpile(wrapped);
|
|
214
|
+
const js = withLocalModules(transpile(wrapped), modules);
|
|
197
215
|
const sandbox = Object.create(null) as Record<string, unknown>;
|
|
198
216
|
sandbox.defineModel = defineModel;
|
|
199
217
|
sandbox.field = field;
|
|
@@ -248,6 +266,7 @@ export function evalModelFiles(
|
|
|
248
266
|
const failures: Array<{ path: string; stem: string; message: string; duplicate?: boolean }> = [];
|
|
249
267
|
const byStem = new Map<string, ModelDef>();
|
|
250
268
|
const types = new Set<string>();
|
|
269
|
+
const sources = new Map(files.map((file) => [file.path, file.source]));
|
|
251
270
|
const waiting = new Map(
|
|
252
271
|
files
|
|
253
272
|
.filter((file) => isModelSourcePath(file.path, modelsDir))
|
|
@@ -260,7 +279,10 @@ export function evalModelFiles(
|
|
|
260
279
|
progressed = false;
|
|
261
280
|
for (const [stem, file] of [...waiting]) {
|
|
262
281
|
try {
|
|
263
|
-
const model = evalModelSource(file.source, stem, objects, Object.fromEntries(byStem)
|
|
282
|
+
const model = evalModelSource(file.source, stem, objects, Object.fromEntries(byStem), {
|
|
283
|
+
path: file.path,
|
|
284
|
+
files: sources,
|
|
285
|
+
});
|
|
264
286
|
if (types.has(model.type)) {
|
|
265
287
|
failures.push({
|
|
266
288
|
path: file.path,
|
package/src/node/index.ts
CHANGED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// packages/core/src/node/local-modules.ts
|
|
2
|
+
// A block file often imports option lists and field kits from the site's own
|
|
3
|
+
// files (`../lib/block-fields`). The block sandbox runs those files too, under
|
|
4
|
+
// the same rules, so their exports carry real values instead of stubs. A file
|
|
5
|
+
// that is missing, breaks a rule, or throws falls back to stubs for its names.
|
|
6
|
+
|
|
7
|
+
const SOURCE_EXTS = [".ts", ".tsx", ".js", ".jsx", ".mjs"];
|
|
8
|
+
const INDEX_FILES = ["/index.ts", "/index.tsx", "/index.js"];
|
|
9
|
+
const MAX_MODULES = 32;
|
|
10
|
+
const CORE_SPECIFIERS = new Set(["@backmatter/core", "@backmatter/next"]);
|
|
11
|
+
/** Names a site file may take from core; the sandbox provides them as globals. */
|
|
12
|
+
const CORE_GLOBALS = new Set(["defineBlock", "field"]);
|
|
13
|
+
const IMPORT_LINE = /^\s*import\s+(?:([\s\S]*?)\s+from\s+)?["']([^"']+)["']\s*;?\s*$/gm;
|
|
14
|
+
|
|
15
|
+
/** Repo path a relative import from `fromPath` points at, if that file exists. */
|
|
16
|
+
export function resolveLocalImport(
|
|
17
|
+
fromPath: string,
|
|
18
|
+
specifier: string,
|
|
19
|
+
has: (repoPath: string) => boolean,
|
|
20
|
+
): string | null {
|
|
21
|
+
if (!specifier.startsWith("./") && !specifier.startsWith("../")) return null;
|
|
22
|
+
const parts = fromPath.split("/").slice(0, -1);
|
|
23
|
+
for (const segment of specifier.split("/")) {
|
|
24
|
+
if (segment === "" || segment === ".") continue;
|
|
25
|
+
if (segment === "..") {
|
|
26
|
+
if (parts.length === 0) return null;
|
|
27
|
+
parts.pop();
|
|
28
|
+
} else {
|
|
29
|
+
parts.push(segment);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const base = parts.join("/");
|
|
33
|
+
if (!base) return null;
|
|
34
|
+
const candidates = [base, ...SOURCE_EXTS.map((ext) => base + ext), ...INDEX_FILES.map((f) => base + f)];
|
|
35
|
+
return candidates.find((candidate) => has(candidate)) ?? null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Specifiers a source file imports from. */
|
|
39
|
+
function importSpecifiers(source: string): string[] {
|
|
40
|
+
try {
|
|
41
|
+
return transpiler("tsx")
|
|
42
|
+
.scan(source)
|
|
43
|
+
.imports.map((entry) => entry.path);
|
|
44
|
+
} catch {
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Repo paths of the site files `source` imports, directly, that exist per `has`.
|
|
51
|
+
* The GitHub import calls this to know which extra files to read.
|
|
52
|
+
*/
|
|
53
|
+
export function localImportPaths(
|
|
54
|
+
source: string,
|
|
55
|
+
fromPath: string,
|
|
56
|
+
has: (repoPath: string) => boolean,
|
|
57
|
+
): string[] {
|
|
58
|
+
const out: string[] = [];
|
|
59
|
+
for (const specifier of importSpecifiers(source)) {
|
|
60
|
+
const resolved = resolveLocalImport(fromPath, specifier, has);
|
|
61
|
+
if (resolved && !out.includes(resolved)) out.push(resolved);
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export type LocalModules = {
|
|
67
|
+
/** JS that declares `__mods` and `__pick`, then fills `__mods` in dependency order. */
|
|
68
|
+
prelude: string;
|
|
69
|
+
/** Index into `__mods` for a relative specifier imported by the entry file, if it compiled. */
|
|
70
|
+
indexFor: (specifier: string) => number | null;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
type CompileContext = {
|
|
74
|
+
files: ReadonlyMap<string, string>;
|
|
75
|
+
isForbidden: (source: string) => boolean;
|
|
76
|
+
indexes: Map<string, number>;
|
|
77
|
+
inProgress: Set<string>;
|
|
78
|
+
chunks: string[];
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/** Compile the site files reachable from `entryPath`'s relative imports. */
|
|
82
|
+
export function compileLocalModules(
|
|
83
|
+
entrySource: string,
|
|
84
|
+
entryPath: string,
|
|
85
|
+
files: ReadonlyMap<string, string>,
|
|
86
|
+
isForbidden: (source: string) => boolean,
|
|
87
|
+
): LocalModules {
|
|
88
|
+
const ctx: CompileContext = {
|
|
89
|
+
files,
|
|
90
|
+
isForbidden,
|
|
91
|
+
indexes: new Map(),
|
|
92
|
+
inProgress: new Set([entryPath]),
|
|
93
|
+
chunks: [],
|
|
94
|
+
};
|
|
95
|
+
const has = (p: string) => files.has(p);
|
|
96
|
+
const direct = new Map<string, number>();
|
|
97
|
+
for (const specifier of importSpecifiers(entrySource)) {
|
|
98
|
+
const resolved = resolveLocalImport(entryPath, specifier, has);
|
|
99
|
+
if (!resolved) continue;
|
|
100
|
+
const index = compileModule(resolved, ctx);
|
|
101
|
+
if (index !== null) direct.set(specifier, index);
|
|
102
|
+
}
|
|
103
|
+
const prelude = [
|
|
104
|
+
"var __mods = [];",
|
|
105
|
+
"function __stub() { return null; }",
|
|
106
|
+
"function __pick(k, name) { var m = __mods[k]; var v = m ? m[name] : undefined; return v === undefined ? __stub : v; }",
|
|
107
|
+
...ctx.chunks,
|
|
108
|
+
].join("\n");
|
|
109
|
+
return { prelude, indexFor: (specifier) => direct.get(specifier) ?? null };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function compileModule(repoPath: string, ctx: CompileContext): number | null {
|
|
113
|
+
const known = ctx.indexes.get(repoPath);
|
|
114
|
+
if (known !== undefined) return known;
|
|
115
|
+
// A cycle, or too many files: the importer gets stubs for this one.
|
|
116
|
+
if (ctx.inProgress.has(repoPath) || ctx.indexes.size >= MAX_MODULES) return null;
|
|
117
|
+
const source = ctx.files.get(repoPath);
|
|
118
|
+
if (source === undefined || ctx.isForbidden(source)) return null;
|
|
119
|
+
|
|
120
|
+
let js: string;
|
|
121
|
+
try {
|
|
122
|
+
js = transpiler(loaderFor(repoPath)).transformSync(source);
|
|
123
|
+
} catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
ctx.inProgress.add(repoPath);
|
|
128
|
+
const has = (p: string) => ctx.files.has(p);
|
|
129
|
+
let body = js.replace(IMPORT_LINE, (_line, spec: string | undefined, from: string) => {
|
|
130
|
+
if (!spec) return "";
|
|
131
|
+
if (CORE_SPECIFIERS.has(from)) return bindCore(spec);
|
|
132
|
+
const resolved = resolveLocalImport(repoPath, from, has);
|
|
133
|
+
const index = resolved ? compileModule(resolved, ctx) : null;
|
|
134
|
+
return index === null ? stubBindings(spec) : pickBindings(spec, index);
|
|
135
|
+
});
|
|
136
|
+
ctx.inProgress.delete(repoPath);
|
|
137
|
+
|
|
138
|
+
if (/^\s*import\b/m.test(body)) return null;
|
|
139
|
+
const exported = collectExports(body);
|
|
140
|
+
body = exported.body;
|
|
141
|
+
if (/\bexport\b/.test(body)) return null;
|
|
142
|
+
|
|
143
|
+
const index = ctx.indexes.size;
|
|
144
|
+
ctx.indexes.set(repoPath, index);
|
|
145
|
+
const entries = exported.names
|
|
146
|
+
.map(([name, local]) => `${JSON.stringify(name)}: ${local}`)
|
|
147
|
+
.join(", ");
|
|
148
|
+
ctx.chunks.push(
|
|
149
|
+
`try { __mods[${index}] = (function () {\n${body}\nreturn { ${entries} };\n})(); } catch (e) { __mods[${index}] = undefined; }`,
|
|
150
|
+
);
|
|
151
|
+
return index;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Strip `export` keywords and list [exported name, local expression] pairs. */
|
|
155
|
+
function collectExports(js: string): { body: string; names: Array<[string, string]> } {
|
|
156
|
+
const names: Array<[string, string]> = [];
|
|
157
|
+
let body = js.replace(/^\s*export\s*\{([^}]*)\}\s*(?:from\s*["'][^"']+["'])?\s*;?\s*$/gm, (line, list: string) => {
|
|
158
|
+
if (/\bfrom\b/.test(line)) return "";
|
|
159
|
+
for (const part of list.split(",")) {
|
|
160
|
+
const [local, exportedAs] = part.trim().split(/\s+as\s+/).map((s) => s.trim());
|
|
161
|
+
if (local) names.push([exportedAs ?? local, local]);
|
|
162
|
+
}
|
|
163
|
+
return "";
|
|
164
|
+
});
|
|
165
|
+
body = body.replace(/^\s*export\s+\*.*$/gm, "");
|
|
166
|
+
body = body.replace(
|
|
167
|
+
/\bexport\s+((?:async\s+)?function\*?|class|const|let|var)\s+([A-Za-z_$][\w$]*)/g,
|
|
168
|
+
(_m, kind: string, name: string) => {
|
|
169
|
+
names.push([name, name]);
|
|
170
|
+
return `${kind} ${name}`;
|
|
171
|
+
},
|
|
172
|
+
);
|
|
173
|
+
if (/\bexport\s+default\s+/.test(body)) {
|
|
174
|
+
body = body.replace(/\bexport\s+default\s+/, "var __default = ");
|
|
175
|
+
names.push(["default", "__default"]);
|
|
176
|
+
}
|
|
177
|
+
return { body, names };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function parseSpec(spec: string): {
|
|
181
|
+
defaultName: string | null;
|
|
182
|
+
namespace: string | null;
|
|
183
|
+
named: Array<[imported: string, local: string]>;
|
|
184
|
+
} {
|
|
185
|
+
const named: Array<[string, string]> = [];
|
|
186
|
+
const braces = spec.match(/\{([^}]*)\}/);
|
|
187
|
+
if (braces) {
|
|
188
|
+
for (const part of braces[1].split(",")) {
|
|
189
|
+
const trimmed = part.trim();
|
|
190
|
+
if (!trimmed || trimmed.startsWith("type ")) continue;
|
|
191
|
+
const [imported, local] = trimmed.split(/\s+as\s+/).map((s) => s.trim());
|
|
192
|
+
if (imported) named.push([imported, local ?? imported]);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const head = (spec.split("{")[0] ?? "").replace(/,\s*$/, "").trim();
|
|
196
|
+
const ns = head.match(/\*\s+as\s+([A-Za-z_$][\w$]*)/);
|
|
197
|
+
const defaultName = !ns && head ? head.split(",")[0]?.trim() || null : null;
|
|
198
|
+
return { defaultName, namespace: ns ? ns[1] : null, named };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function bindCore(spec: string): string {
|
|
202
|
+
const { named, defaultName, namespace } = parseSpec(spec);
|
|
203
|
+
const lines: string[] = [];
|
|
204
|
+
for (const [imported, local] of named) {
|
|
205
|
+
if (CORE_GLOBALS.has(imported)) {
|
|
206
|
+
if (local !== imported) lines.push(`var ${local} = ${imported};`);
|
|
207
|
+
} else {
|
|
208
|
+
lines.push(`var ${local} = __stub;`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (defaultName) lines.push(`var ${defaultName} = __stub;`);
|
|
212
|
+
if (namespace) lines.push(`var ${namespace} = { defineBlock: defineBlock, field: field };`);
|
|
213
|
+
return lines.join("\n");
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Bindings for an import whose file compiled to `__mods[index]`. */
|
|
217
|
+
export function pickBindings(spec: string, index: number): string {
|
|
218
|
+
const { named, defaultName, namespace } = parseSpec(spec);
|
|
219
|
+
const lines = named.map(([imported, local]) => `var ${local} = __pick(${index}, ${JSON.stringify(imported)});`);
|
|
220
|
+
if (defaultName) lines.push(`var ${defaultName} = __pick(${index}, "default");`);
|
|
221
|
+
if (namespace) lines.push(`var ${namespace} = __mods[${index}] || {};`);
|
|
222
|
+
return lines.join("\n");
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const VALUE_IMPORT_LINE = /^\s*import\s+([\s\S]*?)\s+from\s+["']([^"']+)["']\s*;?\s*$/gm;
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Replace each `import … from "<relative>"` line whose file compiled into `modules`
|
|
229
|
+
* with bindings to its exports. Other import lines are left for the caller.
|
|
230
|
+
*/
|
|
231
|
+
export function bindLocalImports(source: string, modules: LocalModules): string {
|
|
232
|
+
return source.replace(VALUE_IMPORT_LINE, (line, spec: string, from: string) => {
|
|
233
|
+
if (/^type\s/.test(spec.trim())) return line;
|
|
234
|
+
const index = modules.indexFor(from);
|
|
235
|
+
return index === null ? line : pickBindings(spec, index);
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Wrap a transpiled `(function () { … })()` so it runs after the site files. */
|
|
240
|
+
export function withLocalModules(js: string, modules: LocalModules | null): string {
|
|
241
|
+
if (!modules) return js;
|
|
242
|
+
return `(function () {\n${modules.prelude}\nreturn ${js.trim().replace(/;\s*$/, "")};\n})()`;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function stubBindings(spec: string): string {
|
|
246
|
+
const { named, defaultName, namespace } = parseSpec(spec);
|
|
247
|
+
const lines = named.map(([, local]) => `var ${local} = __stub;`);
|
|
248
|
+
if (defaultName) lines.push(`var ${defaultName} = __stub;`);
|
|
249
|
+
if (namespace) lines.push(`var ${namespace} = {};`);
|
|
250
|
+
return lines.join("\n");
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function loaderFor(repoPath: string): "ts" | "tsx" | "js" | "jsx" {
|
|
254
|
+
if (repoPath.endsWith(".tsx")) return "tsx";
|
|
255
|
+
if (repoPath.endsWith(".ts")) return "ts";
|
|
256
|
+
if (repoPath.endsWith(".jsx")) return "jsx";
|
|
257
|
+
return "js";
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const transpilers = new Map<string, InstanceType<typeof Bun.Transpiler>>();
|
|
261
|
+
function transpiler(loader: "ts" | "tsx" | "js" | "jsx"): InstanceType<typeof Bun.Transpiler> {
|
|
262
|
+
let t = transpilers.get(loader);
|
|
263
|
+
if (!t) {
|
|
264
|
+
t = new Bun.Transpiler({ loader, target: "node" });
|
|
265
|
+
transpilers.set(loader, t);
|
|
266
|
+
}
|
|
267
|
+
return t;
|
|
268
|
+
}
|
package/src/node/media-cli.ts
CHANGED
|
@@ -1,21 +1,42 @@
|
|
|
1
1
|
// packages/core/src/node/media-cli.ts
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
|
-
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
4
4
|
import os from "node:os";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { mediaOriginalUrl, mediaVariantUrl } from "../media-url";
|
|
7
7
|
|
|
8
8
|
export const MEDIA_USAGE = `Usage:
|
|
9
|
-
backmatter login [--api <url>] [--web <url>]
|
|
10
|
-
backmatter media upload <file...> --workspace <id> [--api <url>]
|
|
11
|
-
backmatter media list [--q <text>] --workspace <id> [--api <url>]
|
|
9
|
+
backmatter login [--workspace <id-or-slug>] [--api <url>] [--web <url>]
|
|
10
|
+
backmatter media upload <file...> [--workspace <id>] [--api <url>]
|
|
11
|
+
backmatter media list [--q <text>] [--workspace <id>] [--api <url>]
|
|
12
12
|
backmatter media url <id> [--width <px>] [--origin <url>]
|
|
13
13
|
|
|
14
|
-
login opens the browser
|
|
15
|
-
|
|
14
|
+
login opens the browser, where you confirm the code and pick one workspace.
|
|
15
|
+
It links this folder to that workspace in .backmatter/workspace.json and keeps
|
|
16
|
+
the token, which works only in that workspace, in ~/.backmatter/credentials.json.
|
|
17
|
+
media upload and list use --workspace, else BACKMATTER_WORKSPACE, else
|
|
18
|
+
BACKMATTER_WORKSPACE_ID, else the folder's linked workspace.
|
|
16
19
|
media url prints a CDN url. --width <px> appends width and format=auto.`;
|
|
17
20
|
|
|
18
|
-
type
|
|
21
|
+
type WorkspaceRef = { id: string; name: string; slug: string };
|
|
22
|
+
/** One workspace's token. The token works in that workspace only. */
|
|
23
|
+
type Login = { api: string; workspace: WorkspaceRef; token: string };
|
|
24
|
+
/** `api` and `token` are the shape written before logins named a workspace. */
|
|
25
|
+
type Credentials = { logins?: Login[]; api?: string; token?: string };
|
|
26
|
+
/** Which workspace a folder works in. It holds no secret. */
|
|
27
|
+
type FolderLink = { api: string; workspaceId: string; slug?: string; name?: string };
|
|
28
|
+
|
|
29
|
+
type Io = {
|
|
30
|
+
log: (line: string) => void;
|
|
31
|
+
error: (line: string) => void;
|
|
32
|
+
open?: (url: string) => void;
|
|
33
|
+
fetch?: typeof fetch;
|
|
34
|
+
home: string;
|
|
35
|
+
cwd: string;
|
|
36
|
+
hostname: string;
|
|
37
|
+
env: Record<string, string | undefined>;
|
|
38
|
+
sleep: (ms: number) => Promise<void>;
|
|
39
|
+
};
|
|
19
40
|
|
|
20
41
|
export async function runMediaCli(
|
|
21
42
|
argv: string[],
|
|
@@ -25,78 +46,84 @@ export async function runMediaCli(
|
|
|
25
46
|
open?: (url: string) => void;
|
|
26
47
|
fetch?: typeof fetch;
|
|
27
48
|
home?: string;
|
|
49
|
+
cwd?: string;
|
|
50
|
+
hostname?: string;
|
|
28
51
|
env?: Record<string, string | undefined>;
|
|
52
|
+
sleep?: (ms: number) => Promise<void>;
|
|
29
53
|
} = {},
|
|
30
54
|
): Promise<number> {
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
55
|
+
const ctx: Io = {
|
|
56
|
+
log: io.log ?? ((line) => console.log(line)),
|
|
57
|
+
error: io.error ?? ((line) => console.error(line)),
|
|
58
|
+
open: io.open,
|
|
59
|
+
fetch: io.fetch,
|
|
60
|
+
home: io.home ?? os.homedir(),
|
|
61
|
+
cwd: io.cwd ?? process.cwd(),
|
|
62
|
+
hostname: io.hostname ?? os.hostname(),
|
|
63
|
+
env: io.env ?? process.env,
|
|
64
|
+
sleep: io.sleep ?? delay,
|
|
65
|
+
};
|
|
35
66
|
try {
|
|
36
67
|
const command = argv[0];
|
|
37
|
-
if (command === "login") return await login(argv.slice(1),
|
|
38
|
-
if (command === "media") return await media(argv.slice(1),
|
|
39
|
-
error(MEDIA_USAGE);
|
|
68
|
+
if (command === "login") return await login(argv.slice(1), ctx);
|
|
69
|
+
if (command === "media") return await media(argv.slice(1), ctx);
|
|
70
|
+
ctx.error(MEDIA_USAGE);
|
|
40
71
|
return 2;
|
|
41
72
|
} catch (err) {
|
|
42
|
-
error(`backmatter: ${err instanceof Error ? err.message : String(err)}`);
|
|
73
|
+
ctx.error(`backmatter: ${err instanceof Error ? err.message : String(err)}`);
|
|
43
74
|
return 2;
|
|
44
75
|
}
|
|
45
76
|
}
|
|
46
77
|
|
|
47
|
-
async function login(
|
|
48
|
-
argv: string[],
|
|
49
|
-
io: {
|
|
50
|
-
log: (line: string) => void;
|
|
51
|
-
error: (line: string) => void;
|
|
52
|
-
open?: (url: string) => void;
|
|
53
|
-
fetch?: typeof fetch;
|
|
54
|
-
home: string;
|
|
55
|
-
env: Record<string, string | undefined>;
|
|
56
|
-
},
|
|
57
|
-
): Promise<number> {
|
|
78
|
+
async function login(argv: string[], io: Io): Promise<number> {
|
|
58
79
|
const flags = readFlags(argv);
|
|
59
|
-
const
|
|
80
|
+
const link = await findFolderLink(io.cwd);
|
|
81
|
+
const api = (flags.api || io.env.BACKMATTER_API_URL || link?.link.api || "http://localhost:3001").replace(/\/$/, "");
|
|
60
82
|
const web = (flags.web || io.env.BACKMATTER_WEB_ORIGIN || "http://localhost:5173").replace(/\/$/, "");
|
|
83
|
+
const workspace =
|
|
84
|
+
flags.workspace ||
|
|
85
|
+
io.env.BACKMATTER_WORKSPACE ||
|
|
86
|
+
io.env.BACKMATTER_WORKSPACE_ID ||
|
|
87
|
+
(link && link.link.api === api ? link.link.workspaceId : undefined);
|
|
61
88
|
const pollSecret = crypto.randomUUID() + crypto.randomUUID();
|
|
62
89
|
const fetchImpl = io.fetch ?? fetch;
|
|
63
90
|
const started = await fetchImpl(`${api}/cli/login`, {
|
|
64
91
|
method: "POST",
|
|
65
92
|
headers: { "content-type": "application/json" },
|
|
66
|
-
body: JSON.stringify({ pollSecret }),
|
|
93
|
+
body: JSON.stringify({ pollSecret, workspace, client: io.hostname }),
|
|
67
94
|
});
|
|
68
95
|
if (!started.ok) throw new Error(`login failed: ${started.status}`);
|
|
69
|
-
const body = (await started.json()) as { id: string; authorizeUrl: string };
|
|
96
|
+
const body = (await started.json()) as { id: string; userCode?: string; authorizeUrl: string };
|
|
70
97
|
const authorizeUrl = body.authorizeUrl || `${web}/cli/authorize?id=${encodeURIComponent(body.id)}`;
|
|
71
98
|
(io.open ?? openBrowser)(authorizeUrl);
|
|
72
|
-
io.error(`Open ${authorizeUrl}
|
|
99
|
+
io.error(`Open ${authorizeUrl}`);
|
|
100
|
+
if (body.userCode) io.error(`Check that the browser shows ${body.userCode}, then allow the CLI.`);
|
|
73
101
|
const deadline = Date.now() + 10 * 60 * 1000;
|
|
74
102
|
while (Date.now() < deadline) {
|
|
75
|
-
await
|
|
103
|
+
await io.sleep(1000);
|
|
76
104
|
const polled = await fetchImpl(`${api}/cli/login/${body.id}`, {
|
|
77
105
|
headers: { "x-backmatter-poll": pollSecret },
|
|
78
106
|
});
|
|
79
107
|
if (!polled.ok) continue;
|
|
80
|
-
const status = (await polled.json()) as { status: string; token?: string };
|
|
81
|
-
if (status.status === "ready" && status.token) {
|
|
82
|
-
await
|
|
83
|
-
|
|
108
|
+
const status = (await polled.json()) as { status: string; token?: string; workspace?: WorkspaceRef };
|
|
109
|
+
if (status.status === "ready" && status.token && status.workspace) {
|
|
110
|
+
await saveLogin(io.home, { api, workspace: status.workspace, token: status.token });
|
|
111
|
+
const dir = link?.dir ?? (await projectRoot(io.cwd));
|
|
112
|
+
await writeJson(folderLinkPath(dir), {
|
|
113
|
+
api,
|
|
114
|
+
workspaceId: status.workspace.id,
|
|
115
|
+
slug: status.workspace.slug,
|
|
116
|
+
name: status.workspace.name,
|
|
117
|
+
} satisfies FolderLink);
|
|
118
|
+
io.log(`Logged in to ${status.workspace.name} (${status.workspace.slug}).`);
|
|
119
|
+
io.log(`Linked ${dir} to ${status.workspace.name}.`);
|
|
84
120
|
return 0;
|
|
85
121
|
}
|
|
86
122
|
}
|
|
87
123
|
throw new Error("login timed out");
|
|
88
124
|
}
|
|
89
125
|
|
|
90
|
-
async function media(
|
|
91
|
-
argv: string[],
|
|
92
|
-
io: {
|
|
93
|
-
log: (line: string) => void;
|
|
94
|
-
error: (line: string) => void;
|
|
95
|
-
fetch?: typeof fetch;
|
|
96
|
-
home: string;
|
|
97
|
-
env: Record<string, string | undefined>;
|
|
98
|
-
},
|
|
99
|
-
): Promise<number> {
|
|
126
|
+
async function media(argv: string[], io: Io): Promise<number> {
|
|
100
127
|
const sub = argv[0];
|
|
101
128
|
const rest = argv.slice(1);
|
|
102
129
|
const flags = readFlags(rest);
|
|
@@ -120,12 +147,17 @@ async function media(
|
|
|
120
147
|
return 0;
|
|
121
148
|
}
|
|
122
149
|
const creds = await readCredentials(io.home);
|
|
123
|
-
const
|
|
124
|
-
const token = creds?.token;
|
|
150
|
+
const link = (await findFolderLink(io.cwd))?.link;
|
|
125
151
|
const workspace =
|
|
126
|
-
flags.workspace || io.env.BACKMATTER_WORKSPACE || io.env.BACKMATTER_WORKSPACE_ID;
|
|
127
|
-
if (!
|
|
128
|
-
|
|
152
|
+
flags.workspace || io.env.BACKMATTER_WORKSPACE || io.env.BACKMATTER_WORKSPACE_ID || link?.workspaceId;
|
|
153
|
+
if (!workspace) throw new Error("run backmatter login in this folder, or pass --workspace <id>");
|
|
154
|
+
const saved = creds?.logins?.find(
|
|
155
|
+
(entry) => (entry.workspace.id === workspace || entry.workspace.slug === workspace) &&
|
|
156
|
+
(!flags.api || sameOrigin(entry.api, flags.api)),
|
|
157
|
+
);
|
|
158
|
+
const api = (flags.api || saved?.api || link?.api || creds?.api || io.env.BACKMATTER_API_URL || "").replace(/\/$/, "");
|
|
159
|
+
const token = saved?.token ?? creds?.token;
|
|
160
|
+
if (!api || !token) throw new Error(`run backmatter login --workspace ${workspace} first`);
|
|
129
161
|
const fetchImpl = io.fetch ?? fetch;
|
|
130
162
|
if (sub === "list") {
|
|
131
163
|
const params = new URLSearchParams();
|
|
@@ -188,18 +220,65 @@ function credentialsPath(home: string): string {
|
|
|
188
220
|
return path.join(home, ".backmatter", "credentials.json");
|
|
189
221
|
}
|
|
190
222
|
|
|
191
|
-
|
|
223
|
+
function folderLinkPath(dir: string): string {
|
|
224
|
+
return path.join(dir, ".backmatter", "workspace.json");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function sameOrigin(a: string, b: string): boolean {
|
|
228
|
+
return a.replace(/\/$/, "") === b.replace(/\/$/, "");
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function readJson<T>(file: string): Promise<T | null> {
|
|
192
232
|
try {
|
|
193
|
-
return JSON.parse(await readFile(
|
|
233
|
+
return JSON.parse(await readFile(file, "utf8")) as T;
|
|
194
234
|
} catch {
|
|
195
235
|
return null;
|
|
196
236
|
}
|
|
197
237
|
}
|
|
198
238
|
|
|
199
|
-
async function
|
|
200
|
-
const file = credentialsPath(home);
|
|
239
|
+
async function writeJson(file: string, value: unknown, mode?: number): Promise<void> {
|
|
201
240
|
await mkdir(path.dirname(file), { recursive: true });
|
|
202
|
-
await writeFile(file, JSON.stringify(
|
|
241
|
+
await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, mode === undefined ? undefined : { mode });
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function readCredentials(home: string): Promise<Credentials | null> {
|
|
245
|
+
return readJson<Credentials>(credentialsPath(home));
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Keeps one token per api and workspace, replacing an older one for the same pair. */
|
|
249
|
+
async function saveLogin(home: string, login: Login): Promise<void> {
|
|
250
|
+
const creds = (await readCredentials(home)) ?? {};
|
|
251
|
+
const logins = (creds.logins ?? []).filter(
|
|
252
|
+
(entry) => !(sameOrigin(entry.api, login.api) && entry.workspace.id === login.workspace.id),
|
|
253
|
+
);
|
|
254
|
+
await writeJson(credentialsPath(home), { logins: [...logins, login] } satisfies Credentials, 0o600);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The nearest `.backmatter/workspace.json` at or above `cwd`. */
|
|
258
|
+
async function findFolderLink(cwd: string): Promise<{ dir: string; link: FolderLink } | null> {
|
|
259
|
+
let dir = path.resolve(cwd);
|
|
260
|
+
while (true) {
|
|
261
|
+
const link = await readJson<FolderLink>(folderLinkPath(dir));
|
|
262
|
+
if (link?.workspaceId && link.api) return { dir, link };
|
|
263
|
+
const parent = path.dirname(dir);
|
|
264
|
+
if (parent === dir) return null;
|
|
265
|
+
dir = parent;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** The nearest folder at or above `cwd` with a package.json, else `cwd`. */
|
|
270
|
+
async function projectRoot(cwd: string): Promise<string> {
|
|
271
|
+
let dir = path.resolve(cwd);
|
|
272
|
+
while (true) {
|
|
273
|
+
try {
|
|
274
|
+
await stat(path.join(dir, "package.json"));
|
|
275
|
+
return dir;
|
|
276
|
+
} catch {
|
|
277
|
+
const parent = path.dirname(dir);
|
|
278
|
+
if (parent === dir) return path.resolve(cwd);
|
|
279
|
+
dir = parent;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
203
282
|
}
|
|
204
283
|
|
|
205
284
|
function openBrowser(url: string) {
|
package/src/preview-channel.ts
CHANGED
|
@@ -70,6 +70,8 @@ export type PreviewGrabMessage = Envelope & {
|
|
|
70
70
|
line?: number;
|
|
71
71
|
column?: number;
|
|
72
72
|
stack?: string[];
|
|
73
|
+
/** Block prop the clicked text came from (`data-backmatter-field`). */
|
|
74
|
+
field?: string;
|
|
73
75
|
};
|
|
74
76
|
|
|
75
77
|
export type PreviewHighlightMessage = Envelope & {
|
|
@@ -125,6 +127,8 @@ function readEnvelope(value: Record<string, unknown>): Envelope | null {
|
|
|
125
127
|
return { v: PREVIEW_CHANNEL_VERSION, ref };
|
|
126
128
|
}
|
|
127
129
|
|
|
130
|
+
const GRAB_FIELD = /^[\w.$-]{1,80}$/;
|
|
131
|
+
|
|
128
132
|
const GRAB_FILE = /^[\w./@+-]+\.(?:tsx|ts|jsx|js|mdx)$/;
|
|
129
133
|
|
|
130
134
|
function readGrabPlace(data: Record<string, unknown>): Pick<
|
|
@@ -225,6 +229,7 @@ export function parsePreviewMessage(data: unknown): PreviewChannelMessage | null
|
|
|
225
229
|
quote: normalizePointerQuote(data.quote),
|
|
226
230
|
shift: data.shift,
|
|
227
231
|
...place,
|
|
232
|
+
...(typeof data.field === "string" && GRAB_FIELD.test(data.field) ? { field: data.field } : {}),
|
|
228
233
|
};
|
|
229
234
|
}
|
|
230
235
|
case "backmatter:highlight": {
|