@backmatter/core 0.0.17 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backmatter/core",
3
- "version": "0.0.17",
3
+ "version": "0.0.18",
4
4
  "description": "Experimental Backmatter SDK. APIs will break. Not ready for production.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -1,15 +1,18 @@
1
1
  // packages/core/src/node/eval-model.ts
2
- // Sandbox-eval a convention `models/{type}.ts` blob (GitHub import). Only
3
- // `defineModel` / `field` from @backmatter/core or @backmatter/next are in scope —
4
- // never import() the customer checkout.
2
+ // Sandbox-eval convention model and object files (GitHub import). The allowed
3
+ // surface is the same one `discoverModels` / `discoverObjects` run: `defineModel`,
4
+ // `defineObject`, and `field` from @backmatter/core or @backmatter/next, plus
5
+ // `import name from "../objects/<name>"`. Never import() the customer checkout.
5
6
  import { runInNewContext } from "node:vm";
6
7
  import { defineModel, type ModelDef } from "../model";
8
+ import { defineObject, type ObjectDef } from "../object";
7
9
  import { field } from "../fields";
8
10
 
9
11
  const SOURCE_EXT = /\.(ts|tsx|js|jsx|mjs)$/;
10
12
  const IGNORED = /(\.test\.|\.spec\.|\.d\.ts$|\.stories\.)/;
11
13
  const ALLOWED_IMPORT = /^\s*import\s+\{([^}]+)\}\s+from\s+["'](@backmatter\/core|@backmatter\/next)["']\s*;?\s*$/gm;
12
14
  const ALLOWED_NAMES = new Set(["defineModel", "field"]);
15
+ const OBJECT_NAMES = new Set(["defineObject", "field"]);
13
16
  const FORBIDDEN = [
14
17
  { re: /\brequire\s*\(/, name: "require" },
15
18
  { re: /\bimport\s*\(/, name: "import" },
@@ -44,38 +47,61 @@ function stemOf(repoPath: string): string {
44
47
  return name.replace(SOURCE_EXT, "");
45
48
  }
46
49
 
47
- function stripAllowedImports(source: string): string {
50
+ function stripAllowedImports(
51
+ source: string,
52
+ allowed: Set<string> = ALLOWED_NAMES,
53
+ label = "defineModel and field",
54
+ ): string {
55
+ ALLOWED_IMPORT.lastIndex = 0;
48
56
  const names = new Set<string>();
49
57
  const stripped = source.replace(ALLOWED_IMPORT, (_full, specifiers: string) => {
50
58
  for (const part of specifiers.split(",")) {
51
59
  const name = part.trim();
52
60
  if (!name) continue;
53
- if (/\bas\b/.test(name) || !ALLOWED_NAMES.has(name)) {
54
- throw new Error(`import "${name}" is not allowed; only defineModel and field`);
61
+ if (/\bas\b/.test(name) || !allowed.has(name)) {
62
+ throw new Error(`import "${name}" is not allowed; only ${label}`);
55
63
  }
56
64
  names.add(name);
57
65
  }
58
66
  return "";
59
67
  });
60
68
  if (/^\s*import\b/m.test(stripped)) {
61
- throw new Error("import is not allowed except defineModel/field from @backmatter/core or @backmatter/next");
69
+ throw new Error(
70
+ `import is not allowed except ${label} from @backmatter/core or @backmatter/next`,
71
+ );
62
72
  }
63
73
  return stripped;
64
74
  }
65
75
 
66
- function assertNoForbidden(source: string): void {
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;
84
+ const next = source.replace(re, (_full, local: string, stem: string) => {
85
+ bindings.push({ local, stem });
86
+ return "";
87
+ });
88
+ return { source: next, bindings };
89
+ }
90
+
91
+ function assertNoForbidden(source: string, kind = "model"): void {
67
92
  for (const { re, name } of FORBIDDEN) {
68
- if (re.test(source)) throw new Error(`${name} is not allowed in model files`);
93
+ re.lastIndex = 0;
94
+ if (re.test(source)) throw new Error(`${name} is not allowed in ${kind} files`);
69
95
  }
70
96
  }
71
97
 
72
- function rewriteDefaultExport(source: string): string {
98
+ function rewriteDefaultExport(source: string, what = "defineModel({ ... })"): string {
73
99
  if (!/\bexport\s+default\b/.test(source)) {
74
- throw new Error("must export default defineModel({ ... })");
100
+ throw new Error(`must export default ${what}`);
75
101
  }
76
102
  const rewritten = source.replace(/\bexport\s+default\s+/, "return ");
77
103
  if (/\bexport\b/.test(rewritten)) {
78
- throw new Error("must export default defineModel({ ... })");
104
+ throw new Error(`must export default ${what}`);
79
105
  }
80
106
  return rewritten;
81
107
  }
@@ -85,18 +111,75 @@ function transpile(source: string): string {
85
111
  return transpiler.transformSync(source);
86
112
  }
87
113
 
114
+ function isObjectDef(value: unknown): value is ObjectDef {
115
+ if (!value || typeof value !== "object") return false;
116
+ const object = value as Record<string, unknown>;
117
+ return typeof object.name === "string" && typeof object.fields === "object" && !("type" in object);
118
+ }
119
+
120
+ /**
121
+ * Evaluate one `objects/{name}.ts` blob. Same rule as `discoverObjects`:
122
+ * the file stem must equal `object.name`.
123
+ */
124
+ export function evalObjectSource(source: string, stem: string): ObjectDef {
125
+ const body = rewriteDefaultExport(
126
+ stripAllowedImports(source, OBJECT_NAMES, "defineObject and field"),
127
+ "defineObject({ ... })",
128
+ );
129
+ assertNoForbidden(body, "object");
130
+ const wrapped = `(function () {\n${body}\n})()`;
131
+ const js = transpile(wrapped);
132
+ const sandbox = Object.create(null) as {
133
+ defineObject: typeof defineObject;
134
+ field: typeof field;
135
+ };
136
+ sandbox.defineObject = defineObject;
137
+ sandbox.field = field;
138
+ Object.freeze(sandbox);
139
+
140
+ let result: unknown;
141
+ try {
142
+ result = runInNewContext(js, sandbox, {
143
+ timeout: EVAL_TIMEOUT_MS,
144
+ filename: `${stem}.js`,
145
+ });
146
+ } catch (err) {
147
+ const message = err instanceof Error ? err.message : String(err);
148
+ throw new Error(`object "${stem}" failed to evaluate: ${message}`);
149
+ }
150
+ if (!isObjectDef(result)) {
151
+ throw new Error("must export default defineObject({ ... })");
152
+ }
153
+ if (result.name !== stem) {
154
+ throw new Error(
155
+ `defines name "${result.name}" but the file is named "${stem}"; rename one so they match`,
156
+ );
157
+ }
158
+ return result;
159
+ }
160
+
88
161
  /**
89
162
  * Evaluate one convention model file. `stem` is the file name without extension
90
- * and must equal `model.type`.
163
+ * and must equal `model.type`. `objects` supplies `import x from "../objects/<file>"`.
91
164
  */
92
- export function evalModelSource(source: string, stem: string): ModelDef {
93
- const body = rewriteDefaultExport(stripAllowedImports(source));
165
+ export function evalModelSource(
166
+ source: string,
167
+ stem: string,
168
+ objects: Readonly<Record<string, ObjectDef>> = {},
169
+ ): ModelDef {
170
+ const taken = takeObjectImports(source);
171
+ const body = rewriteDefaultExport(stripAllowedImports(taken.source));
94
172
  assertNoForbidden(body);
95
173
  const wrapped = `(function () {\n${body}\n})()`;
96
174
  const js = transpile(wrapped);
97
- const sandbox = Object.create(null) as { defineModel: typeof defineModel; field: typeof field };
175
+ const sandbox = Object.create(null) as Record<string, unknown>;
98
176
  sandbox.defineModel = defineModel;
99
177
  sandbox.field = field;
178
+ for (const binding of taken.bindings) {
179
+ const object = objects[binding.stem];
180
+ if (!object) throw new Error(`import "../objects/${binding.stem}" was not found`);
181
+ sandbox[binding.local] = object;
182
+ }
100
183
  Object.freeze(sandbox);
101
184
 
102
185
  let result: unknown;
@@ -125,6 +208,11 @@ export function evalModelsFromTree(
125
208
  files: Array<{ path: string; source: string }>,
126
209
  modelsDir = "models",
127
210
  ): ModelDef[] {
211
+ const objects: Record<string, ObjectDef> = {};
212
+ for (const file of files.filter((f) => isModelSourcePath(f.path, "objects"))) {
213
+ const stem = stemOf(file.path);
214
+ objects[stem] = evalObjectSource(file.source, stem);
215
+ }
128
216
  const models: ModelDef[] = [];
129
217
  const types = new Set<string>();
130
218
  const sorted = files
@@ -132,7 +220,7 @@ export function evalModelsFromTree(
132
220
  .sort((a, b) => a.path.localeCompare(b.path));
133
221
  for (const file of sorted) {
134
222
  const stem = stemOf(file.path);
135
- const model = evalModelSource(file.source, stem);
223
+ const model = evalModelSource(file.source, stem, objects);
136
224
  if (types.has(model.type)) {
137
225
  throw new Error(`duplicate model type "${model.type}" (${file.path})`);
138
226
  }
package/src/node/index.ts CHANGED
@@ -18,7 +18,7 @@ export {
18
18
  toIdentifier,
19
19
  } from "./discover";
20
20
  export type { BlockFile, ModelFile } from "./discover";
21
- export { evalModelSource, evalModelsFromTree, isModelSourcePath } from "./eval-model";
21
+ export { evalModelSource, evalModelsFromTree, evalObjectSource, isModelSourcePath } from "./eval-model";
22
22
  export {
23
23
  evalBlockSource,
24
24
  evalBlocksFromTree,