@backmatter/core 0.0.33 → 0.0.35

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.
@@ -2,7 +2,8 @@
2
2
  // Sandbox-eval convention model and object files (GitHub import). The allowed
3
3
  // surface is the same one `discoverModels` / `discoverObjects` run: `defineModel`,
4
4
  // `defineObject`, and `field` from @backmatter/core or @backmatter/next, plus
5
- // `import name from "../objects/<name>"`. Never import() the customer checkout.
5
+ // `import name from "../objects/<name>"` and `import name from "./<model>"`.
6
+ // Never import() the customer checkout.
6
7
  import { runInNewContext } from "node:vm";
7
8
  import { defineModel, type ModelDef } from "../model";
8
9
  import { defineObject, type ObjectDef } from "../object";
@@ -73,14 +74,26 @@ function stripAllowedImports(
73
74
  return stripped;
74
75
  }
75
76
 
76
- /** `import name from "../objects/<file>"` — the only local import a model may use. */
77
- function takeObjectImports(source: string): {
78
- source: string;
79
- bindings: Array<{ local: string; stem: string }>;
80
- } {
81
- const bindings: Array<{ local: string; stem: string }> = [];
82
- const re =
83
- /^\s*import\s+([A-Za-z_$][\w$]*)\s+from\s+["']\.\.\/objects\/([A-Za-z][A-Za-z0-9]*)(?:\.(?:ts|tsx|js|jsx|mjs))?["']\s*;?\s*$/gm;
77
+ type LocalImport = { local: string; stem: string };
78
+
79
+ /** `import name from "../objects/<file>"`. */
80
+ function takeObjectImports(source: string): { source: string; bindings: LocalImport[] } {
81
+ return takeLocalImports(
82
+ source,
83
+ /^\s*import\s+([A-Za-z_$][\w$]*)\s+from\s+["']\.\.\/objects\/([A-Za-z][A-Za-z0-9]*)(?:\.(?:ts|tsx|js|jsx|mjs))?["']\s*;?\s*$/gm,
84
+ );
85
+ }
86
+
87
+ /** `import name from "./<model>"` — another file in `models/`. */
88
+ function takeModelImports(source: string): { source: string; bindings: LocalImport[] } {
89
+ return takeLocalImports(
90
+ source,
91
+ /^\s*import\s+([A-Za-z_$][\w$]*)\s+from\s+["']\.\/([A-Za-z][A-Za-z0-9-]*)(?:\.(?:ts|tsx|js|jsx|mjs))?["']\s*;?\s*$/gm,
92
+ );
93
+ }
94
+
95
+ function takeLocalImports(source: string, re: RegExp): { source: string; bindings: LocalImport[] } {
96
+ const bindings: LocalImport[] = [];
84
97
  const next = source.replace(re, (_full, local: string, stem: string) => {
85
98
  bindings.push({ local, stem });
86
99
  return "";
@@ -88,6 +101,12 @@ function takeObjectImports(source: string): {
88
101
  return { source: next, bindings };
89
102
  }
90
103
 
104
+ function missingSiblingImport(err: unknown): string | null {
105
+ const message = err instanceof Error ? err.message : String(err);
106
+ const match = message.match(/import "\.\/([^"]+)" was not found/);
107
+ return match?.[1] ?? null;
108
+ }
109
+
91
110
  function assertNoForbidden(source: string, kind = "model"): void {
92
111
  for (const { re, name } of FORBIDDEN) {
93
112
  re.lastIndex = 0;
@@ -161,25 +180,33 @@ export function evalObjectSource(source: string, stem: string): ObjectDef {
161
180
  /**
162
181
  * Evaluate one convention model file. `stem` is the file name without extension
163
182
  * and must equal `model.type`. `objects` supplies `import x from "../objects/<file>"`.
183
+ * `models` supplies `import x from "./<file>"`.
164
184
  */
165
185
  export function evalModelSource(
166
186
  source: string,
167
187
  stem: string,
168
188
  objects: Readonly<Record<string, ObjectDef>> = {},
189
+ models: Readonly<Record<string, ModelDef>> = {},
169
190
  ): ModelDef {
170
- const taken = takeObjectImports(source);
171
- const body = rewriteDefaultExport(stripAllowedImports(taken.source));
191
+ const takenObjects = takeObjectImports(source);
192
+ const takenModels = takeModelImports(takenObjects.source);
193
+ const body = rewriteDefaultExport(stripAllowedImports(takenModels.source));
172
194
  assertNoForbidden(body);
173
195
  const wrapped = `(function () {\n${body}\n})()`;
174
196
  const js = transpile(wrapped);
175
197
  const sandbox = Object.create(null) as Record<string, unknown>;
176
198
  sandbox.defineModel = defineModel;
177
199
  sandbox.field = field;
178
- for (const binding of taken.bindings) {
200
+ for (const binding of takenObjects.bindings) {
179
201
  const object = objects[binding.stem];
180
202
  if (!object) throw new Error(`import "../objects/${binding.stem}" was not found`);
181
203
  sandbox[binding.local] = object;
182
204
  }
205
+ for (const binding of takenModels.bindings) {
206
+ const model = models[binding.stem];
207
+ if (!model) throw new Error(`import "./${binding.stem}" was not found`);
208
+ sandbox[binding.local] = model;
209
+ }
183
210
  Object.freeze(sandbox);
184
211
 
185
212
  let result: unknown;
@@ -204,6 +231,70 @@ export function evalModelSource(
204
231
  return result;
205
232
  }
206
233
 
234
+ /**
235
+ * Evaluate every flat model file. A file may import another model in the same
236
+ * folder; that dependency is evaluated first. One failure is returned, not thrown,
237
+ * so the caller can keep the files that did load.
238
+ */
239
+ export function evalModelFiles(
240
+ files: Array<{ path: string; source: string }>,
241
+ objects: Readonly<Record<string, ObjectDef>> = {},
242
+ modelsDir = "models",
243
+ ): {
244
+ models: ModelDef[];
245
+ failures: Array<{ path: string; stem: string; message: string; duplicate?: boolean }>;
246
+ } {
247
+ const models: ModelDef[] = [];
248
+ const failures: Array<{ path: string; stem: string; message: string; duplicate?: boolean }> = [];
249
+ const byStem = new Map<string, ModelDef>();
250
+ const types = new Set<string>();
251
+ const waiting = new Map(
252
+ files
253
+ .filter((file) => isModelSourcePath(file.path, modelsDir))
254
+ .sort((a, b) => a.path.localeCompare(b.path))
255
+ .map((file) => [stemOf(file.path), file] as const),
256
+ );
257
+
258
+ let progressed = true;
259
+ while (waiting.size > 0 && progressed) {
260
+ progressed = false;
261
+ for (const [stem, file] of [...waiting]) {
262
+ try {
263
+ const model = evalModelSource(file.source, stem, objects, Object.fromEntries(byStem));
264
+ if (types.has(model.type)) {
265
+ failures.push({
266
+ path: file.path,
267
+ stem,
268
+ message: `duplicate model type "${model.type}"`,
269
+ duplicate: true,
270
+ });
271
+ } else {
272
+ types.add(model.type);
273
+ byStem.set(stem, model);
274
+ models.push(model);
275
+ }
276
+ waiting.delete(stem);
277
+ progressed = true;
278
+ } catch (err) {
279
+ const missing = missingSiblingImport(err);
280
+ if (missing && waiting.has(missing)) continue;
281
+ const message = err instanceof Error ? err.message : String(err);
282
+ failures.push({ path: file.path, stem, message });
283
+ waiting.delete(stem);
284
+ progressed = true;
285
+ }
286
+ }
287
+ }
288
+ for (const [stem, file] of waiting) {
289
+ failures.push({
290
+ path: file.path,
291
+ stem,
292
+ message: `import "./${stem}" is part of a cycle`,
293
+ });
294
+ }
295
+ return { models, failures };
296
+ }
297
+
207
298
  export function evalModelsFromTree(
208
299
  files: Array<{ path: string; source: string }>,
209
300
  modelsDir = "models",
@@ -213,19 +304,12 @@ export function evalModelsFromTree(
213
304
  const stem = stemOf(file.path);
214
305
  objects[stem] = evalObjectSource(file.source, stem);
215
306
  }
216
- const models: ModelDef[] = [];
217
- const types = new Set<string>();
218
- const sorted = files
219
- .filter((f) => isModelSourcePath(f.path, modelsDir))
220
- .sort((a, b) => a.path.localeCompare(b.path));
221
- for (const file of sorted) {
222
- const stem = stemOf(file.path);
223
- const model = evalModelSource(file.source, stem, objects);
224
- if (types.has(model.type)) {
225
- throw new Error(`duplicate model type "${model.type}" (${file.path})`);
226
- }
227
- types.add(model.type);
228
- models.push(model);
307
+ const { models, failures } = evalModelFiles(files, objects, modelsDir);
308
+ const first = failures[0];
309
+ if (first) {
310
+ throw new Error(
311
+ first.duplicate ? `${first.message} (${first.path})` : first.message,
312
+ );
229
313
  }
230
314
  return models;
231
315
  }
@@ -101,7 +101,7 @@ export function detectSdk(root: string): string {
101
101
  return "@backmatter/core/node";
102
102
  }
103
103
 
104
- function renderCachedCmsClient(): string[] {
104
+ function renderCachedCmsClient(typeArgs: string): string[] {
105
105
  return [
106
106
  "const raw = createBackmatter({ ...config, models, sync: false });",
107
107
  "",
@@ -136,7 +136,7 @@ function renderCachedCmsClient(): string[] {
136
136
  " ...raw,",
137
137
  " getDoc,",
138
138
  " listDocs,",
139
- ` query: createQuery(models, { getDoc, listDocs }),`,
139
+ ` query: createQuery${typeArgs}(models, { getDoc, listDocs }),`,
140
140
  "};",
141
141
  ];
142
142
  }
@@ -144,10 +144,13 @@ function renderCachedCmsClient(): string[] {
144
144
  export function renderModelsBarrel(input: {
145
145
  outDir: string;
146
146
  models: ModelFile[];
147
+ blocks?: BlockFile[];
147
148
  configFile: string | null;
148
149
  sdk: string;
149
150
  }): string {
150
151
  const nextHost = input.sdk === "@backmatter/next";
152
+ const blocks = input.blocks ?? [];
153
+ const typeArgs = blocks.length > 0 ? "<typeof models, Blocks>" : "";
151
154
  const lines = [GENERATED_HEADER, `import { createBackmatter } from "${input.sdk}";`];
152
155
  if (nextHost) {
153
156
  lines.push('import { contentCacheTags, createQuery, listCacheTags } from "@backmatter/core";');
@@ -162,15 +165,21 @@ export function renderModelsBarrel(input: {
162
165
  for (const m of input.models) {
163
166
  lines.push(`import ${m.importName} from "${importSpecifier(input.outDir, m.file)}";`);
164
167
  }
168
+ for (const block of blocks) {
169
+ lines.push(`import type ${block.name} from "${importSpecifier(input.outDir, block.file)}";`);
170
+ }
165
171
  lines.push("");
166
172
  lines.push(`export const models = [${input.models.map((m) => m.importName).join(", ")}] as const;`);
167
173
  lines.push("export type Models = typeof models;");
174
+ if (blocks.length > 0) {
175
+ lines.push(`type Blocks = readonly [${blocks.map((block) => `typeof ${block.name}`).join(", ")}];`);
176
+ }
168
177
  lines.push("");
169
178
  if (nextHost) {
170
- lines.push(...renderCachedCmsClient());
179
+ lines.push(...renderCachedCmsClient(typeArgs));
171
180
  } else {
172
181
  lines.push("/** Typed content client: cms.query.{type}, cms.getDoc, cms.listDocs. */");
173
- lines.push("export const cms = createBackmatter({ ...config, models });");
182
+ lines.push(`export const cms = createBackmatter${typeArgs}({ ...config, models });`);
174
183
  }
175
184
  return `${lines.join("\n")}\n`;
176
185
  }
@@ -373,7 +382,7 @@ export function generate(options: GenerateOptions): GenerateResult {
373
382
  const write = options.write ?? true;
374
383
 
375
384
  const rendered: Record<(typeof REGISTRY_FILES)[number], string> = {
376
- "index.ts": renderModelsBarrel({ outDir, models, configFile, sdk }),
385
+ "index.ts": renderModelsBarrel({ outDir, models, blocks, configFile, sdk }),
377
386
  "blocks.ts": renderBlocksBarrel({ outDir, blocks }),
378
387
  "block-fallbacks.ts": renderBlockFallbacksBarrel({ outDir, fallbacks }),
379
388
  "mdx.ts": renderMdxBarrel({ outDir, mdx }),
package/src/node/index.ts CHANGED
@@ -18,7 +18,13 @@ export {
18
18
  toIdentifier,
19
19
  } from "./discover";
20
20
  export type { BlockFile, ModelFile } from "./discover";
21
- export { evalModelSource, evalModelsFromTree, evalObjectSource, isModelSourcePath } from "./eval-model";
21
+ export {
22
+ evalModelFiles,
23
+ evalModelSource,
24
+ evalModelsFromTree,
25
+ evalObjectSource,
26
+ isModelSourcePath,
27
+ } from "./eval-model";
22
28
  export {
23
29
  evalBlockSource,
24
30
  evalBlocksFromTree,