@triflare/fx 2.2.0-alpha.1 → 2.2.0-alpha.3

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.
@@ -15,6 +15,7 @@ import { tokenizeWithComments } from "../lexer.js";
15
15
  import { mergePrograms } from "../merge.js";
16
16
  import { parse } from "../parser.js";
17
17
  import { DEFAULT_TEST_PATTERN, isTestPath } from "../test/pattern.js";
18
+ import { DEFAULT_RUN_PATTERN } from "../run/pattern.js";
18
19
  import { DEFAULT_LINT, resolveRuleSeverities } from "./config.js";
19
20
  import { RULES, ruleById } from "./rules.js";
20
21
 
@@ -1195,6 +1196,7 @@ export function sortDiagnostics(diagnostics) {
1195
1196
  * configDir?: string|null,
1196
1197
  * rootDir?: string|null,
1197
1198
  * testPattern?: string|null,
1199
+ * runPattern?: string|null,
1198
1200
  * extensionCatalog?: Record<string, object>,
1199
1201
  * declaredExtensions?: string[],
1200
1202
  * lintConfig?: object,
@@ -1216,6 +1218,7 @@ export function lintSources({
1216
1218
  configDir = null,
1217
1219
  rootDir = null,
1218
1220
  testPattern = DEFAULT_TEST_PATTERN,
1221
+ runPattern = DEFAULT_RUN_PATTERN,
1219
1222
  extensionCatalog = {},
1220
1223
  declaredExtensions = [],
1221
1224
  lintConfig = DEFAULT_LINT,
@@ -1258,18 +1261,22 @@ export function lintSources({
1258
1261
  }
1259
1262
 
1260
1263
  // A source that declares tests, or whose path matches the configured
1261
- // test-file pattern, is a test file. Test files are never part of the
1262
- // project program — `mergePrograms` rejects them by design — so they are
1263
- // left out of the cross-file merge and the project rules. Editors lint every
1264
- // `.tfx` file in a project, test files included, and must not report the
1265
- // merge error on each test declaration. Pattern matching also keeps a
1266
- // helper-only test file (no `test` declarations) from leaking its top-level
1267
- // variables into project scope.
1264
+ // test-file or run-file pattern, is not project code. Test files are never
1265
+ // part of the project program — `mergePrograms` rejects them by design — and
1266
+ // run files are entry points that `fx run` merges only in memory. Leaving
1267
+ // both out of the cross-file merge keeps a helper-only test or run file from
1268
+ // leaking its top-level variables into project scope.
1268
1269
  const testRoot = rootDir ?? configDir ?? null;
1270
+ const isRunSource = ({ file, ast }) =>
1271
+ (ast.tests ?? []).length === 0 &&
1272
+ !isTestPath(file, testRoot, testPattern) &&
1273
+ isTestPath(file, testRoot, runPattern);
1274
+ const runParsed = parsed.filter(isRunSource);
1269
1275
  const projectParsed = parsed.filter(
1270
- ({ file, ast }) =>
1271
- (ast.tests ?? []).length === 0 &&
1272
- !isTestPath(file, testRoot, testPattern),
1276
+ (entry) =>
1277
+ (entry.ast.tests ?? []).length === 0 &&
1278
+ !isTestPath(entry.file, testRoot, testPattern) &&
1279
+ !isTestPath(entry.file, testRoot, runPattern),
1273
1280
  );
1274
1281
 
1275
1282
  // Partial sprites are resolved by the project merge, which throws when the
@@ -1327,6 +1334,29 @@ export function lintSources({
1327
1334
  if (program) analyzer.analyzeProgram(program);
1328
1335
  else for (const { ast } of projectParsed) analyzer.analyzeProgram(ast);
1329
1336
 
1337
+ // Run files are entry points, so they stay out of the project merge but
1338
+ // still need the project's declarations in scope. Analyze them beside a
1339
+ // merged project program, then keep only diagnostics in the run files.
1340
+ if (runParsed.length > 0) {
1341
+ const runProgram = {
1342
+ type: "Program",
1343
+ stage: program?.stage ?? null,
1344
+ sprites: program?.sprites ?? [],
1345
+ topItems: [
1346
+ ...(program?.topItems ?? []),
1347
+ ...runParsed.flatMap(({ ast }) => ast.topItems),
1348
+ ],
1349
+ };
1350
+ const runFiles = new Set(runParsed.map(({ file }) => file));
1351
+ const first = analyzer.diagnostics.length;
1352
+ analyzer.analyzeProgram(runProgram);
1353
+ analyzer.diagnostics.push(
1354
+ ...analyzer.diagnostics
1355
+ .splice(first)
1356
+ .filter((diagnostic) => runFiles.has(diagnostic.file)),
1357
+ );
1358
+ }
1359
+
1330
1360
  // Diagnostics from filesystem-backed project checks (assets, fx.lock).
1331
1361
  for (const diagnostic of extraDiagnostics) {
1332
1362
  const rule = RULES[diagnostic.ruleId];
@@ -9,6 +9,8 @@
9
9
 
10
10
  import * as yaml from "js-yaml";
11
11
  import { normalizeLintConfig } from "./config.js";
12
+ import { DEFAULT_TEST_PATTERN } from "../test/pattern.js";
13
+ import { DEFAULT_RUN_PATTERN } from "../run/pattern.js";
12
14
 
13
15
  /** Extension name from a vendor path such as `extensions/signals.js`. */
14
16
  function extensionName(source) {
@@ -23,6 +25,7 @@ function extensionName(source) {
23
25
  * lintConfig: object,
24
26
  * declaredExtensions: string[],
25
27
  * testPattern: string|null,
28
+ * runPattern: string|null,
26
29
  * projectName: string|null,
27
30
  * error?: string,
28
31
  * }}
@@ -37,6 +40,7 @@ export function parseProjectConfigText(text) {
37
40
  lintConfig: null,
38
41
  declaredExtensions: [],
39
42
  testPattern: null,
43
+ runPattern: null,
40
44
  projectName: null,
41
45
  error: error instanceof Error ? error.message : String(error),
42
46
  };
@@ -47,6 +51,7 @@ export function parseProjectConfigText(text) {
47
51
  lintConfig: null,
48
52
  declaredExtensions: [],
49
53
  testPattern: null,
54
+ runPattern: null,
50
55
  projectName: null,
51
56
  error: "fx.yml must contain a mapping at the top level",
52
57
  };
@@ -72,6 +77,7 @@ export function parseProjectConfigText(text) {
72
77
  lintConfig: null,
73
78
  declaredExtensions: [],
74
79
  testPattern: null,
80
+ runPattern: null,
75
81
  projectName: typeof project.name === "string" ? project.name : null,
76
82
  error: error instanceof Error ? error.message : String(error),
77
83
  };
@@ -92,20 +98,24 @@ export function parseProjectConfigText(text) {
92
98
  }
93
99
  }
94
100
 
95
- const testPattern =
96
- fx.tests &&
97
- typeof fx.tests === "object" &&
98
- !Array.isArray(fx.tests) &&
99
- typeof fx.tests.pattern === "string" &&
100
- fx.tests.pattern.trim()
101
- ? fx.tests.pattern.trim()
102
- : null;
101
+ const patternOf = (value, fallback) => {
102
+ if (value === true) return fallback;
103
+ if (value && typeof value === "object" && !Array.isArray(value)) {
104
+ if (value.pattern === undefined) return fallback;
105
+ if (typeof value.pattern === "string" && value.pattern.trim())
106
+ return value.pattern.trim();
107
+ }
108
+ return null;
109
+ };
110
+ const testPattern = patternOf(fx.tests, DEFAULT_TEST_PATTERN);
111
+ const runPattern = patternOf(fx.run, DEFAULT_RUN_PATTERN);
103
112
 
104
113
  return {
105
114
  config: { fx: { partialSprites: Boolean(fx.partialSprites) } },
106
115
  lintConfig,
107
116
  declaredExtensions: [...declaredExtensions],
108
117
  testPattern,
118
+ runPattern,
109
119
  projectName: typeof project.name === "string" ? project.name : null,
110
120
  };
111
121
  }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Extension catalog assembly shared by `fx test` and `fx run`.
3
+ *
4
+ * Build-like commands already resolve this through `loadProjectState`; the
5
+ * headless runners load it themselves so they can also be called as a Node API.
6
+ */
7
+ import { loadExtensions } from "./extensions.js";
8
+ import { loadFeatureExtensions } from "./features.js";
9
+ import { loadVendorExtensions } from "./vendor.js";
10
+
11
+ /**
12
+ * Load vendored, feature and legacy extensions into one catalog.
13
+ *
14
+ * @param {{configDir: string, loaded: object}} options
15
+ * @returns {Promise<{catalog: Record<string, object>, extensionUrls: Record<string, string>, warnings: string[]}>}
16
+ */
17
+ export async function loadProjectCatalog({ configDir, loaded }) {
18
+ const catalog = {};
19
+ const extensionUrls = {};
20
+ const warnings = [];
21
+ if (loaded.vendor?.length) {
22
+ const vendored = await loadVendorExtensions({ configDir, config: loaded });
23
+ Object.assign(catalog, vendored.catalog);
24
+ Object.assign(extensionUrls, vendored.extensionUrls);
25
+ warnings.push(...vendored.warnings);
26
+ }
27
+ const features = await loadFeatureExtensions({ configDir, config: loaded });
28
+ Object.assign(catalog, features.catalog);
29
+ Object.assign(extensionUrls, features.extensionUrls);
30
+ warnings.push(...features.warnings);
31
+ if (loaded.project?.extensions?.length) {
32
+ const legacy = await loadExtensions(loaded.project.extensions, {
33
+ baseDir: configDir,
34
+ expectUnsandboxed: loaded.project.unsandboxed,
35
+ reportUnmatchedUnsandboxed: false,
36
+ });
37
+ Object.assign(catalog, legacy.catalog);
38
+ Object.assign(extensionUrls, legacy.extensionUrls);
39
+ warnings.push(...legacy.warnings);
40
+ }
41
+ return { catalog, extensionUrls, warnings };
42
+ }
package/src/project.js CHANGED
@@ -10,6 +10,7 @@ import path from "node:path";
10
10
  import { configFilename, sourceExtension } from "./brand.js";
11
11
  import { mergePrograms as mergeParsed } from "./merge.js";
12
12
  import { DEFAULT_TEST_PATTERN, matchesTestPattern } from "./test/discover.js";
13
+ import { DEFAULT_RUN_PATTERN } from "./run/pattern.js";
13
14
 
14
15
  /** Directories never scanned for `.tfx` sources. */
15
16
  const IGNORED_DIRS = new Set([
@@ -22,17 +23,18 @@ const IGNORED_DIRS = new Set([
22
23
 
23
24
  /**
24
25
  * Recursively find every `.tfx` file under `dir`, skipping hidden entries and
25
- * well-known build/dependency directories. Test files are skipped so they
26
- * never become part of the project target.
26
+ * well-known build/dependency directories. Test and run files are skipped so
27
+ * they never become part of the project target.
27
28
  *
28
29
  * Results are deterministic (sorted by path) so builds are reproducible.
29
30
  * @param {string} dir
30
- * @param {{testPattern?: string|null}} [options] `null` keeps test files
31
+ * @param {{testPattern?: string|null, runPattern?: string|null}} [options]
32
+ * `null` keeps test or run files
31
33
  * @returns {string[]} absolute file paths
32
34
  */
33
35
  export function discoverSources(
34
36
  dir,
35
- { testPattern = DEFAULT_TEST_PATTERN } = {},
37
+ { testPattern = DEFAULT_TEST_PATTERN, runPattern = DEFAULT_RUN_PATTERN } = {},
36
38
  ) {
37
39
  const root = path.resolve(dir);
38
40
  const found = [];
@@ -56,10 +58,9 @@ export function discoverSources(
56
58
  entry.isFile() &&
57
59
  entry.name.toLowerCase().endsWith(extension)
58
60
  ) {
59
- if (testPattern) {
60
- const relative = path.relative(root, full).split(path.sep).join("/");
61
- if (matchesTestPattern(relative, testPattern)) continue;
62
- }
61
+ const relative = path.relative(root, full).split(path.sep).join("/");
62
+ if (testPattern && matchesTestPattern(relative, testPattern)) continue;
63
+ if (runPattern && matchesTestPattern(relative, runPattern)) continue;
63
64
  found.push(full);
64
65
  }
65
66
  }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Run-file discovery.
3
+ *
4
+ * Run files use the same glob rules as test files, so both share the matcher
5
+ * and walker. They are never part of the project target.
6
+ */
7
+ import { discoverTests } from "../test/discover.js";
8
+ import { DEFAULT_RUN_PATTERN } from "./pattern.js";
9
+
10
+ export { DEFAULT_RUN_PATTERN };
11
+
12
+ /**
13
+ * Find every run file under a directory.
14
+ *
15
+ * @param {{dir: string, pattern?: string, extension?: string}} options
16
+ * @returns {Array<{file: string, relative: string}>} sorted by path
17
+ */
18
+ export function discoverRuns({
19
+ dir,
20
+ pattern = DEFAULT_RUN_PATTERN,
21
+ extension = ".tfx",
22
+ } = {}) {
23
+ return discoverTests({ dir, pattern, extension });
24
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Run-file parsing.
3
+ *
4
+ * A run file is a normal `.tfx` source with function and variable declarations
5
+ * only. It is never part of the project target: `fx run` merges it into an
6
+ * in-memory build so the compiler can type-check the entry point and every
7
+ * block it calls, then invokes `main` in the headless VM.
8
+ */
9
+ import { parse } from "../parser.js";
10
+ import { ParseError } from "../errors.js";
11
+
12
+ const ALLOWED_TOP_LEVEL = new Set(["VarDecl", "FunctionDecl"]);
13
+
14
+ /** Source location of an AST node, defaulting unknown fields to null. */
15
+ function locationOf(node) {
16
+ const loc = node?.loc ?? {};
17
+ return { file: loc.file, line: loc.line, column: loc.column };
18
+ }
19
+
20
+ /**
21
+ * Parse one run file.
22
+ *
23
+ * A helper-only file is allowed, so a project can split shared functions from
24
+ * the entry point. `parseRuns` requires exactly one `main` across all files.
25
+ *
26
+ * @param {string} source
27
+ * @param {string} file
28
+ * @returns {{file: string, ast: object, main: object|null, helpers: object[]}}
29
+ */
30
+ export function parseRunFile(source, file = "<run>") {
31
+ const ast = parse(source, file);
32
+
33
+ if (ast.stage)
34
+ throw new ParseError(
35
+ "Run files cannot declare a stage; runs execute against the project build",
36
+ locationOf(ast.stage),
37
+ );
38
+ if (ast.sprites.length > 0)
39
+ throw new ParseError(
40
+ `Run files cannot declare sprites (found ${JSON.stringify(ast.sprites[0].name)})`,
41
+ locationOf(ast.sprites[0]),
42
+ );
43
+ if ((ast.tests ?? []).length > 0)
44
+ throw new ParseError(
45
+ "Run files cannot declare tests; move them to a test file",
46
+ locationOf(ast.tests[0]),
47
+ );
48
+
49
+ for (const item of ast.topItems) {
50
+ if (!ALLOWED_TOP_LEVEL.has(item.type))
51
+ throw new ParseError(
52
+ "Run files may only declare shared variables and functions",
53
+ locationOf(item),
54
+ );
55
+ }
56
+
57
+ const mains = ast.topItems.filter(
58
+ (item) => item.type === "FunctionDecl" && item.name === "main",
59
+ );
60
+ if (mains.length > 1)
61
+ throw new ParseError(
62
+ "A run file can only declare one `main` function",
63
+ locationOf(mains[1]),
64
+ );
65
+ const main = mains[0] ?? null;
66
+ if (main && main.params.length > 0)
67
+ throw new ParseError(
68
+ "The run entry point `main` must not take parameters",
69
+ locationOf(main),
70
+ );
71
+
72
+ return { file, ast, main, helpers: ast.topItems };
73
+ }
74
+
75
+ /**
76
+ * Parse several run files and require one entry point.
77
+ *
78
+ * @param {Array<{file: string, source: string}>} entries
79
+ * @returns {Array<{file: string, ast: object, main: object|null, helpers: object[]}>}
80
+ */
81
+ export function parseRuns(entries) {
82
+ const files = entries.map((entry) => parseRunFile(entry.source, entry.file));
83
+ const mains = files.filter((file) => file.main);
84
+ if (files.length === 0) return files;
85
+ if (mains.length === 0)
86
+ throw new ParseError(
87
+ "Run files must declare an entry point: `function main() { ... }`.",
88
+ { file: files[0].file, line: 1, column: 1 },
89
+ );
90
+ if (mains.length > 1) {
91
+ const first = mains[0].file;
92
+ const second = mains[1].file;
93
+ throw new ParseError(
94
+ `Only one run file may declare \`main\` (found in ${first} and ${second})`,
95
+ locationOf(mains[1].main),
96
+ );
97
+ }
98
+ return files;
99
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Run-file globs.
3
+ *
4
+ * Kept separate from the matcher so the build, the CLI and editor tooling can
5
+ * agree on which sources are entry points rather than project code.
6
+ */
7
+
8
+ /** Default run-entry glob, relative to the project directory. */
9
+ export const DEFAULT_RUN_PATTERN = "run/**/*.run.tfx";