@triflare/fx 2.3.0-alpha.5 → 2.3.0-alpha.7

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": "@triflare/fx",
3
- "version": "2.3.0-alpha.5",
3
+ "version": "2.3.0-alpha.7",
4
4
  "description": "Code PenguinMod projects with text.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
package/product.yml CHANGED
@@ -1,7 +1,7 @@
1
1
  # Identity
2
2
  name: "Triflare Fx"
3
3
  command: "fx"
4
- version: "2.3.0-alpha.5"
4
+ version: "2.3.0-alpha.7"
5
5
  tagline: "Code PenguinMod projects with text."
6
6
  author: "Triflare"
7
7
  homepage: "https://github.com/triflare/fx"
@@ -94,6 +94,11 @@ it with "fx feature tests enable".`,
94
94
  flags: "--allow-external-io",
95
95
  description: "Allow network access (fetch and WebSocket) during tests",
96
96
  },
97
+ {
98
+ flags: "--slow",
99
+ description:
100
+ "Run tests asynchronously so async extension blocks can finish",
101
+ },
97
102
  ],
98
103
  examples: [
99
104
  "fx test",
@@ -141,6 +146,7 @@ it with "fx feature tests enable".`,
141
146
  timeout: validateNumber(options.timeout, "--timeout"),
142
147
  allowProjectExtensions: Boolean(options.allowProjectExtensions),
143
148
  allowExternalIO: Boolean(options.allowExternalIO),
149
+ slow: options.slow ? true : undefined,
144
150
  onEvent: testReporter.onEvent,
145
151
  });
146
152
  };
package/src/config.js CHANGED
@@ -38,6 +38,7 @@ export const DEFAULT_TESTS = {
38
38
  ticksPerSecond: 30,
39
39
  failOnRuntimeError: true,
40
40
  parallel: false,
41
+ slow: false,
41
42
  };
42
43
 
43
44
  /**
@@ -129,6 +130,7 @@ export function normalizeTestConfig(value) {
129
130
  if (value.failOnRuntimeError != null)
130
131
  tests.failOnRuntimeError = Boolean(value.failOnRuntimeError);
131
132
  if (value.parallel != null) tests.parallel = Boolean(value.parallel);
133
+ if (value.slow != null) tests.slow = Boolean(value.slow);
132
134
  return tests;
133
135
  }
134
136
 
@@ -10,6 +10,7 @@
10
10
  import fs from "node:fs";
11
11
  import path from "node:path";
12
12
  import { build } from "../build.js";
13
+ import { CATALOG } from "../catalog.js";
13
14
  import { loadProject } from "../vm.js";
14
15
  import { loadConfigFrom, DEFAULT_TESTS } from "../config.js";
15
16
  import { loadProjectCatalog } from "../project-catalog.js";
@@ -118,6 +119,26 @@ function compareValues(left, right) {
118
119
  return a < b ? -1 : a > b ? 1 : 0;
119
120
  }
120
121
 
122
+ /** Apply an ordered comparison operator to two already-evaluated values. */
123
+ function compareOperands(op, left, right) {
124
+ switch (op) {
125
+ case "==":
126
+ return compareValues(left, right) === 0;
127
+ case "!=":
128
+ return compareValues(left, right) !== 0;
129
+ case "<":
130
+ return compareValues(left, right) < 0;
131
+ case "<=":
132
+ return compareValues(left, right) <= 0;
133
+ case ">":
134
+ return compareValues(left, right) > 0;
135
+ case ">=":
136
+ return compareValues(left, right) >= 0;
137
+ default:
138
+ throw new TestError(`Unsupported operator ${op} in a test`);
139
+ }
140
+ }
141
+
121
142
  /** Render a value for an assertion message. */
122
143
  function formatValue(value) {
123
144
  if (typeof value === "string") return JSON.stringify(value);
@@ -182,7 +203,15 @@ function restoreVm(vm, snapshot) {
182
203
  // ------------------------------------------------------------------ interpreter
183
204
 
184
205
  /** Execution state for one test: bindings, VM, clocks and captures. */
185
- function createScope({ vm, config, seed, capture, deadline, warnings }) {
206
+ function createScope({
207
+ vm,
208
+ config,
209
+ seed,
210
+ capture,
211
+ deadline,
212
+ warnings,
213
+ catalog,
214
+ }) {
186
215
  return {
187
216
  vm,
188
217
  config,
@@ -190,6 +219,7 @@ function createScope({ vm, config, seed, capture, deadline, warnings }) {
190
219
  capture,
191
220
  deadline,
192
221
  warnings,
222
+ catalog: catalog ?? {},
193
223
  progress: { ticks: 0 },
194
224
  vars: new Map(),
195
225
  functions: new Map(),
@@ -208,6 +238,34 @@ function checkDeadline(scope) {
208
238
  throw new TimeoutFailure(scope.config.timeout);
209
239
  }
210
240
 
241
+ /** Largest delay Node's timers accept; longer values fire immediately. */
242
+ const MAX_TIMER_DELAY = 2_147_483_647;
243
+
244
+ /** Await a promise without letting it outlive the test's timeout. */
245
+ async function waitForPromise(scope, promise) {
246
+ let timer;
247
+ try {
248
+ return await Promise.race([
249
+ promise,
250
+ new Promise((_, reject) => {
251
+ const armDeadline = () => {
252
+ const remaining = scope.deadline - performance.now();
253
+ if (remaining <= 0) {
254
+ reject(new TimeoutFailure(scope.config.timeout));
255
+ return;
256
+ }
257
+ // A timeout can exceed Node's timer range, so wake up early and
258
+ // check the real deadline again instead of overflowing the delay.
259
+ timer = setTimeout(armDeadline, Math.min(remaining, MAX_TIMER_DELAY));
260
+ };
261
+ armDeadline();
262
+ }),
263
+ ]);
264
+ } finally {
265
+ clearTimeout(timer);
266
+ }
267
+ }
268
+
211
269
  /** Scope for a function call or block: new cells, shared outer bindings. */
212
270
  function childScope(scope) {
213
271
  // Copy bindings while sharing their cells; declarations and parameters get
@@ -216,14 +274,17 @@ function childScope(scope) {
216
274
  }
217
275
 
218
276
  /** Evaluate a test-language expression. */
219
- function evaluate(node, scope) {
277
+ async function evaluate(node, scope) {
220
278
  switch (node.type) {
221
279
  case "Number":
222
280
  case "String":
223
281
  case "Boolean":
224
282
  return node.value;
225
- case "ArrayLiteral":
226
- return node.items.map((item) => evaluate(item, scope));
283
+ case "ArrayLiteral": {
284
+ const items = [];
285
+ for (const item of node.items) items.push(await evaluate(item, scope));
286
+ return items;
287
+ }
227
288
  case "Identifier": {
228
289
  if (scope.vars.has(node.name)) return scope.vars.get(node.name).value;
229
290
  throw new TestError(
@@ -232,7 +293,7 @@ function evaluate(node, scope) {
232
293
  );
233
294
  }
234
295
  case "Member": {
235
- const object = evaluate(node.object, scope);
296
+ const object = await evaluate(node.object, scope);
236
297
  if (object == null || !(node.property in Object(object)))
237
298
  throw new TestError(
238
299
  `Value has no property ${JSON.stringify(node.property)}`,
@@ -241,7 +302,7 @@ function evaluate(node, scope) {
241
302
  return object[node.property];
242
303
  }
243
304
  case "Unary": {
244
- const value = evaluate(node.operand, scope);
305
+ const value = await evaluate(node.operand, scope);
245
306
  return node.op === "not" ? !truthy(value) : -Number(value);
246
307
  }
247
308
  case "Binary":
@@ -256,31 +317,28 @@ function evaluate(node, scope) {
256
317
  }
257
318
 
258
319
  /** Evaluate a binary operator with short-circuiting for `and`/`or`. */
259
- function evaluateBinary(node, scope) {
320
+ async function evaluateBinary(node, scope) {
260
321
  if (node.op === "and")
261
322
  return (
262
- truthy(evaluate(node.left, scope)) && truthy(evaluate(node.right, scope))
323
+ truthy(await evaluate(node.left, scope)) &&
324
+ truthy(await evaluate(node.right, scope))
263
325
  );
264
326
  if (node.op === "or")
265
327
  return (
266
- truthy(evaluate(node.left, scope)) || truthy(evaluate(node.right, scope))
328
+ truthy(await evaluate(node.left, scope)) ||
329
+ truthy(await evaluate(node.right, scope))
267
330
  );
268
331
 
269
- const left = evaluate(node.left, scope);
270
- const right = evaluate(node.right, scope);
332
+ const left = await evaluate(node.left, scope);
333
+ const right = await evaluate(node.right, scope);
271
334
  switch (node.op) {
272
335
  case "==":
273
- return compareValues(left, right) === 0;
274
336
  case "!=":
275
- return compareValues(left, right) !== 0;
276
337
  case "<":
277
- return compareValues(left, right) < 0;
278
338
  case "<=":
279
- return compareValues(left, right) <= 0;
280
339
  case ">":
281
- return compareValues(left, right) > 0;
282
340
  case ">=":
283
- return compareValues(left, right) >= 0;
341
+ return compareOperands(node.op, left, right);
284
342
  case "+":
285
343
  return isNumeric(left) && isNumeric(right)
286
344
  ? Number(left) + Number(right)
@@ -314,22 +372,16 @@ function argument(node, index) {
314
372
  return value;
315
373
  }
316
374
 
317
- /** Evaluate a test helper call, `state.*` query or project block call. */
318
- function evaluateCall(node, scope) {
319
- const segments = node.segments ?? String(node.name).split(".");
320
- if (segments[0] === "state")
321
- return stateQuery(segments.slice(1), node, scope);
322
-
375
+ /** Call a shared test function, returning its value or 0. */
376
+ async function callTestFunction(node, scope) {
323
377
  const fn = scope.functions.get(node.name);
324
- if (!fn) return callProjectProcedure(node, scope);
325
378
  const local = childScope(scope);
326
- fn.params.forEach((param, index) => {
379
+ for (const [index, param] of fn.params.entries())
327
380
  local.vars.set(param.name, {
328
- value: node.args[index] ? evaluate(node.args[index], scope) : 0,
381
+ value: node.args[index] ? await evaluate(node.args[index], scope) : 0,
329
382
  });
330
- });
331
383
  try {
332
- executeStatements(fn.body, local);
384
+ await executeStatements(fn.body, local);
333
385
  } catch (signal) {
334
386
  if (signal instanceof ReturnSignal) return signal.value;
335
387
  throw signal;
@@ -337,6 +389,18 @@ function evaluateCall(node, scope) {
337
389
  return 0;
338
390
  }
339
391
 
392
+ /** Evaluate a test helper call, `state.*` query or project block call. */
393
+ async function evaluateCall(node, scope) {
394
+ const segments = node.segments ?? String(node.name).split(".");
395
+ if (segments[0] === "state")
396
+ return stateQuery(segments.slice(1), node, scope);
397
+
398
+ if (scope.functions.has(node.name)) return callTestFunction(node, scope);
399
+ const catalog = await callCatalogBlock(node, scope);
400
+ if (catalog) return catalog.value;
401
+ return callProjectProcedure(node, scope);
402
+ }
403
+
340
404
  /** Stage first, then sprites: where a project block can be declared. */
341
405
  function procedureTargets(vm) {
342
406
  const stage = vm.runtime.getTargetForStage?.();
@@ -492,7 +556,7 @@ function resolveProcedure(node, scope) {
492
556
  * value can be read from the VM, then the synthetic blocks and variable are
493
557
  * removed again.
494
558
  */
495
- function callProjectProcedure(node, scope) {
559
+ async function callProjectProcedure(node, scope) {
496
560
  const { target, procedure } = resolveProcedure(node, scope);
497
561
  const { vm } = scope;
498
562
  const blocks = target.blocks;
@@ -507,7 +571,8 @@ function callProjectProcedure(node, scope) {
507
571
  { diagnostics: [locOf(node)] },
508
572
  );
509
573
 
510
- const values = node.args.map((arg) => evaluate(arg, scope));
574
+ const values = [];
575
+ for (const arg of node.args) values.push(await evaluate(arg, scope));
511
576
  scope.progress.procedureCalls = (scope.progress.procedureCalls ?? 0) + 1;
512
577
  const stamp = `${String(target.id ?? "target").replace(/[^A-Za-z0-9_]/g, "_")}_fxtest${scope.progress.procedureCalls}_${scope.progress.ticks}`;
513
578
  const callId = `${stamp}_call`;
@@ -587,7 +652,7 @@ function callProjectProcedure(node, scope) {
587
652
  `Could not start ${JSON.stringify(node.name)} in the VM`,
588
653
  { diagnostics: [locOf(node)] },
589
654
  );
590
- while (vm.runtime.threads.includes(thread)) stepTicks(scope, 1);
655
+ while (vm.runtime.threads.includes(thread)) await stepTicks(scope, 1);
591
656
  if (!procedure.returns) return 0;
592
657
  return target.variables[varId]?.value ?? 0;
593
658
  } finally {
@@ -596,10 +661,439 @@ function callProjectProcedure(node, scope) {
596
661
  }
597
662
  }
598
663
 
664
+ /** Find a target by the name used in front of an extension block. */
665
+ function findCallTarget(vm, name) {
666
+ if (/^stage$/i.test(name)) return vm.runtime.getTargetForStage?.() ?? null;
667
+ return (
668
+ vm.runtime.targets.find(
669
+ (target) => !target.isStage && target.getName?.() === name,
670
+ ) ?? null
671
+ );
672
+ }
673
+
674
+ /**
675
+ * Find an exact `Sprite.procedure(...)` match, if the sprite declares one.
676
+ * A qualified call prefers the project's block over a catalog entry with the
677
+ * same name, so the catalog is only a fallback.
678
+ */
679
+ function findQualifiedProcedure(node, scope) {
680
+ const segments = node.segments ?? String(node.name).split(".");
681
+ if (segments.length < 2) return null;
682
+ const target = findCallTarget(scope.vm, segments[0]);
683
+ if (!target) return null;
684
+ const name = segments.slice(1).join(".");
685
+ return findProcedure(target, name, node.args.length)
686
+ ? { target, name }
687
+ : null;
688
+ }
689
+
690
+ /**
691
+ * Resolve `extension.block(...)` or `Sprite.extension.block(...)` to its
692
+ * catalog entry and target. Returns null when the name is not an extension
693
+ * block, leaving project-block resolution untouched.
694
+ */
695
+ function resolveCatalogCall(node, scope, defaultTarget = null) {
696
+ const segments = node.segments ?? String(node.name).split(".");
697
+ if (findQualifiedProcedure(node, scope)) return null;
698
+ let name;
699
+ let targetName = null;
700
+ if (segments.length === 2) {
701
+ name = node.name;
702
+ } else if (segments.length === 3) {
703
+ name = `${segments[1]}.${segments[2]}`;
704
+ targetName = segments[0];
705
+ } else {
706
+ return null;
707
+ }
708
+ const entry = scope.catalog?.[name] ?? CATALOG[name];
709
+ if (!entry || entry.runOnly || !entry.opcode) return null;
710
+
711
+ if (targetName == null)
712
+ return {
713
+ entry,
714
+ target: defaultTarget ?? scope.vm.runtime.getTargetForStage?.(),
715
+ };
716
+ const target = findCallTarget(scope.vm, targetName);
717
+ if (!target)
718
+ throw new TestError(
719
+ `No sprite named ${JSON.stringify(targetName)} in the project`,
720
+ { diagnostics: [locOf(node)] },
721
+ );
722
+ return { entry, target };
723
+ }
724
+
725
+ /** Write one catalog call into a target. */
726
+ async function buildCatalogCallBlock(node, entry, { target, scope, nextId }) {
727
+ const blocks = target.blocks._blocks;
728
+ const evaluated = new Map();
729
+ const valueAt = async (index) => {
730
+ if (index >= node.args.length) return undefined;
731
+ if (!evaluated.has(index))
732
+ evaluated.set(index, await evaluate(node.args[index], scope));
733
+ return evaluated.get(index);
734
+ };
735
+ const fieldNames = Object.keys(entry.fields || {});
736
+ const inputNames = Object.keys(entry.inputs || {}).filter(
737
+ (name) => entry.inputs[name].type !== "substack",
738
+ );
739
+ const substackNames = Object.keys(entry.inputs || {}).filter(
740
+ (name) => entry.inputs[name].type === "substack",
741
+ );
742
+ if (node.args.length > fieldNames.length + inputNames.length)
743
+ throw new TestError(
744
+ `${node.name} expects at most ${fieldNames.length + inputNames.length} argument(s)`,
745
+ { diagnostics: [locOf(node)] },
746
+ );
747
+ if (node.body && substackNames.length === 0)
748
+ throw new TestError(`${node.name} cannot take a block body`, {
749
+ diagnostics: [locOf(node)],
750
+ });
751
+ if (node.else && substackNames.length < 2)
752
+ throw new TestError(`${node.name} does not support an else branch`, {
753
+ diagnostics: [locOf(node)],
754
+ });
755
+
756
+ const callId = nextId("call");
757
+ const fields = {};
758
+ let argIndex = 0;
759
+ for (const name of fieldNames) {
760
+ const declared = entry.fields[name];
761
+ const fallback = Array.isArray(declared) ? declared[0] : declared;
762
+ const value =
763
+ argIndex < node.args.length ? await valueAt(argIndex) : fallback;
764
+ fields[name] = { name, value: String(value ?? "") };
765
+ argIndex += 1;
766
+ }
767
+
768
+ const inputs = {};
769
+ for (const name of inputNames) {
770
+ const spec = entry.inputs[name];
771
+ const hasArg = argIndex < node.args.length;
772
+ const value = hasArg ? await valueAt(argIndex) : (spec.default ?? "");
773
+ if (spec.type === "variable" || spec.type === "list") {
774
+ const refName = String(value ?? "");
775
+ const variable = findVariable(
776
+ scope.vm,
777
+ refName,
778
+ spec.type === "list" ? "list" : "",
779
+ );
780
+ if (!variable)
781
+ throw new TestError(
782
+ `No ${spec.type} named ${JSON.stringify(refName)} in the project`,
783
+ { diagnostics: [locOf(node)] },
784
+ );
785
+ fields[name] = {
786
+ name,
787
+ value: variable.name,
788
+ id: variable.id,
789
+ variableType: variable.type ?? "",
790
+ };
791
+ argIndex += 1;
792
+ continue;
793
+ }
794
+
795
+ const inputId = nextId("arg");
796
+ if (spec.type === "menu") {
797
+ blocks[inputId] = {
798
+ id: inputId,
799
+ opcode: spec.menu,
800
+ next: null,
801
+ parent: callId,
802
+ inputs: {},
803
+ fields: {
804
+ [spec.field]: {
805
+ name: spec.field,
806
+ value: String(value ?? spec.default ?? ""),
807
+ },
808
+ },
809
+ shadow: true,
810
+ topLevel: false,
811
+ };
812
+ } else {
813
+ blocks[inputId] = textBlock(inputId, value, callId);
814
+ }
815
+ inputs[name] = { name, block: inputId, shadow: inputId };
816
+ argIndex += 1;
817
+ }
818
+
819
+ blocks[callId] = {
820
+ id: callId,
821
+ opcode: entry.opcode,
822
+ next: null,
823
+ parent: null,
824
+ inputs,
825
+ fields,
826
+ shadow: false,
827
+ topLevel: false,
828
+ x: 0,
829
+ y: 0,
830
+ };
831
+ return callId;
832
+ }
833
+
834
+ /** Evaluate a catalog block's positional arguments for a host call. */
835
+ async function catalogArguments(node, entry, scope) {
836
+ const values = [];
837
+ for (const arg of node.args) values.push(await evaluate(arg, scope));
838
+ const fieldNames = Object.keys(entry.fields || {});
839
+ const inputNames = Object.keys(entry.inputs || {}).filter(
840
+ (name) => entry.inputs[name].type !== "substack",
841
+ );
842
+ const args = {};
843
+ let argIndex = 0;
844
+ for (const name of fieldNames) {
845
+ const declared = entry.fields[name];
846
+ const fallback = Array.isArray(declared) ? declared[0] : declared;
847
+ args[name] = argIndex < values.length ? values[argIndex] : fallback;
848
+ argIndex += 1;
849
+ }
850
+ for (const name of inputNames) {
851
+ const spec = entry.inputs[name];
852
+ args[name] =
853
+ argIndex < values.length ? values[argIndex] : (spec.default ?? "");
854
+ argIndex += 1;
855
+ }
856
+ return args;
857
+ }
858
+
859
+ /**
860
+ * Run a catalog block with a test body by driving its branches directly.
861
+ *
862
+ * The VM normally executes a substack as blocks. A test body can contain test
863
+ * statements (assertions, variable updates, stepping), so instead the test
864
+ * interpreter runs the selected branch while the block keeps its loop state in
865
+ * `util.stackFrame`. This keeps the whole test language available inside the
866
+ * body.
867
+ */
868
+ async function runCatalogSubstack(node, entry, target, scope) {
869
+ const substackCount = Object.keys(entry.inputs || {}).filter(
870
+ (name) => entry.inputs[name].type === "substack",
871
+ ).length;
872
+ if (node.else && substackCount < 2)
873
+ throw new TestError(`${node.name} does not support an else branch`, {
874
+ diagnostics: [locOf(node)],
875
+ });
876
+
877
+ const { vm } = scope;
878
+ const primitive = vm.runtime.getOpcodeFunction(entry.opcode);
879
+ if (typeof primitive !== "function")
880
+ throw new TestError(
881
+ `Block ${JSON.stringify(node.name)} is not available in this VM`,
882
+ { diagnostics: [locOf(node)] },
883
+ );
884
+
885
+ const stackFrame = {};
886
+ let requested;
887
+ let isLoop;
888
+ const util = {
889
+ target,
890
+ runtime: vm.runtime,
891
+ stackFrame,
892
+ thread: { target, peekStackFrame: () => stackFrame },
893
+ startBranch(branch, loop) {
894
+ requested = Number(branch);
895
+ isLoop = Boolean(loop);
896
+ },
897
+ yield() {},
898
+ };
899
+ const branches = [node.body, node.else];
900
+ const previousTarget = scope.callTarget;
901
+ scope.callTarget = target;
902
+
903
+ try {
904
+ for (;;) {
905
+ checkDeadline(scope);
906
+ requested = null;
907
+ isLoop = false;
908
+ const result = primitive(
909
+ await catalogArguments(node, entry, scope),
910
+ util,
911
+ );
912
+ if (result && typeof result.then === "function") {
913
+ if (!scope.config.slow) {
914
+ // The block already returned a promise; discard a later rejection so
915
+ // it does not surface as an unhandled rejection after this error.
916
+ result.catch(() => {});
917
+ throw new TestError(
918
+ `${node.name} is asynchronous and cannot use a test substack outside slow mode`,
919
+ { diagnostics: [locOf(node)] },
920
+ );
921
+ }
922
+ await waitForPromise(scope, result);
923
+ }
924
+ if (requested == null) break;
925
+ const body = branches[requested - 1];
926
+ if (body) await executeStatements(body, scope);
927
+ if (!isLoop) break;
928
+ }
929
+ } finally {
930
+ scope.callTarget = previousTarget;
931
+ }
932
+ return { value: 0, kind: entry.kind ?? "command" };
933
+ }
934
+
935
+ /**
936
+ * Run a catalog block called from a test, or return null when the name is not
937
+ * a catalog block.
938
+ *
939
+ * Test scripts are not compiled, so the block is written into the target's
940
+ * block container as a temporary Scratch block and started as a thread, the
941
+ * same way the VM runs a block from the editor. Reporter results are captured
942
+ * through a temporary variable so they can be used in assertions.
943
+ */
944
+ async function callCatalogBlock(node, scope, { asStatement = false } = {}) {
945
+ const resolved = resolveCatalogCall(node, scope, scope.callTarget ?? null);
946
+ if (!resolved) return null;
947
+ const { entry, target } = resolved;
948
+
949
+ const kind = entry.kind ?? "command";
950
+ if (kind === "hat")
951
+ throw new TestError(`${node.name} is an event and cannot be called`, {
952
+ diagnostics: [locOf(node)],
953
+ });
954
+ if (asStatement && (kind === "reporter" || kind === "boolean"))
955
+ throw new TestError(
956
+ `${node.name} returns a value and cannot be used as a statement`,
957
+ { diagnostics: [locOf(node)] },
958
+ );
959
+
960
+ const { vm } = scope;
961
+ const blocks = target?.blocks;
962
+ if (!blocks?._blocks)
963
+ throw new TestError(
964
+ "The project target has no blocks to call; rebuild the project",
965
+ { diagnostics: [locOf(node)] },
966
+ );
967
+ if (
968
+ typeof vm.runtime.getOpcodeFunction === "function" &&
969
+ !vm.runtime.getOpcodeFunction(entry.opcode)
970
+ )
971
+ throw new TestError(
972
+ entry.extension
973
+ ? `Extension block ${JSON.stringify(node.name)} is not loaded; ` +
974
+ `the project does not include extension ${JSON.stringify(entry.extension)}`
975
+ : `Block ${JSON.stringify(node.name)} is not available in this VM`,
976
+ {
977
+ diagnostics: [locOf(node)],
978
+ },
979
+ );
980
+
981
+ const fieldNames = Object.keys(entry.fields || {});
982
+ const inputNames = Object.keys(entry.inputs || {}).filter(
983
+ (name) => entry.inputs[name].type !== "substack",
984
+ );
985
+ const substackNames = Object.keys(entry.inputs || {}).filter(
986
+ (name) => entry.inputs[name].type === "substack",
987
+ );
988
+ // Validate the call before either path evaluates an argument.
989
+ if (node.args.length > fieldNames.length + inputNames.length)
990
+ throw new TestError(
991
+ `${node.name} expects at most ${fieldNames.length + inputNames.length} argument(s)`,
992
+ { diagnostics: [locOf(node)] },
993
+ );
994
+ if (node.body && substackNames.length === 0)
995
+ throw new TestError(`${node.name} cannot take a block body`, {
996
+ diagnostics: [locOf(node)],
997
+ });
998
+ if (node.else && substackNames.length < 2)
999
+ throw new TestError(`${node.name} does not support an else branch`, {
1000
+ diagnostics: [locOf(node)],
1001
+ });
1002
+ if (substackNames.length > 0 && (node.body || node.else))
1003
+ return runCatalogSubstack(node, entry, target, scope);
1004
+
1005
+ scope.progress.extensionCalls = (scope.progress.extensionCalls ?? 0) + 1;
1006
+ const stamp =
1007
+ `fxtest_ext${scope.progress.extensionCalls}_${scope.progress.ticks}`.replace(
1008
+ /[^A-Za-z0-9_]/g,
1009
+ "_",
1010
+ );
1011
+ const synthetic = [];
1012
+ let sequence = 0;
1013
+ const nextId = (label) => {
1014
+ const id = `${stamp}_${label}${sequence}`;
1015
+ sequence += 1;
1016
+ synthetic.push(id);
1017
+ return id;
1018
+ };
1019
+
1020
+ let setId = null;
1021
+ let varId = null;
1022
+ // An untouched variable means the reporter finished without writing a value.
1023
+ const missingValue = {};
1024
+ try {
1025
+ const callId = await buildCatalogCallBlock(node, entry, {
1026
+ target,
1027
+ scope,
1028
+ nextId,
1029
+ });
1030
+ const callBlock = blocks._blocks[callId];
1031
+
1032
+ // A reporter or boolean has to report into an input a thread can read back,
1033
+ // so wrap it in `set variable to` and inspect that variable afterwards.
1034
+ if (kind === "reporter" || kind === "boolean") {
1035
+ varId = nextId("var");
1036
+ const varName = `__fxTestExtension${scope.progress.extensionCalls}`;
1037
+ target.variables[varId] = {
1038
+ id: varId,
1039
+ name: varName,
1040
+ type: "",
1041
+ value: missingValue,
1042
+ isCloud: false,
1043
+ };
1044
+ setId = nextId("set");
1045
+ const valueShadowId = nextId("value");
1046
+ blocks._blocks[valueShadowId] = textBlock(valueShadowId, "", setId);
1047
+ blocks._blocks[setId] = {
1048
+ id: setId,
1049
+ opcode: "data_setvariableto",
1050
+ next: null,
1051
+ parent: null,
1052
+ inputs: {
1053
+ VALUE: { name: "VALUE", block: callId, shadow: valueShadowId },
1054
+ },
1055
+ fields: {
1056
+ VARIABLE: {
1057
+ name: "VARIABLE",
1058
+ value: varName,
1059
+ id: varId,
1060
+ variableType: "",
1061
+ },
1062
+ },
1063
+ shadow: false,
1064
+ topLevel: true,
1065
+ x: 0,
1066
+ y: 0,
1067
+ };
1068
+ callBlock.topLevel = false;
1069
+ callBlock.parent = setId;
1070
+ }
1071
+
1072
+ const thread = vm.runtime._pushThread(setId ?? callId, target);
1073
+ if (!thread)
1074
+ throw new TestError(
1075
+ `Could not start ${JSON.stringify(node.name)} in the VM`,
1076
+ { diagnostics: [locOf(node)] },
1077
+ );
1078
+ while (vm.runtime.threads.includes(thread)) await stepTicks(scope, 1);
1079
+ if (kind !== "reporter" && kind !== "boolean") return { value: 0, kind };
1080
+ const reported = target.variables[varId]?.value;
1081
+ if (reported === missingValue)
1082
+ throw new TestError(`${node.name} finished without returning a value`, {
1083
+ diagnostics: [locOf(node)],
1084
+ });
1085
+ return { value: reported, kind };
1086
+ } finally {
1087
+ for (const id of synthetic) delete blocks._blocks[id];
1088
+ if (varId) delete target.variables[varId];
1089
+ }
1090
+ }
1091
+
599
1092
  /** Resolve a `state.*` assertion query against the VM. */
600
- function stateQuery(segments, node, scope) {
1093
+ async function stateQuery(segments, node, scope) {
601
1094
  const [query, property] = segments;
602
- const args = node.args.map((arg) => evaluate(arg, scope));
1095
+ const args = [];
1096
+ for (const arg of node.args) args.push(await evaluate(arg, scope));
603
1097
  const { vm } = scope;
604
1098
 
605
1099
  if (segments.length > 2)
@@ -680,19 +1174,19 @@ function stateQuery(segments, node, scope) {
680
1174
  }
681
1175
 
682
1176
  /** Run a list of test statements in order. */
683
- function executeStatements(statements, scope) {
1177
+ async function executeStatements(statements, scope) {
684
1178
  for (const statement of statements) {
685
1179
  checkDeadline(scope);
686
- executeStatement(statement, scope);
1180
+ await executeStatement(statement, scope);
687
1181
  }
688
1182
  }
689
1183
 
690
1184
  /** Run one statement node. */
691
- function executeStatement(node, scope) {
1185
+ async function executeStatement(node, scope) {
692
1186
  switch (node.type) {
693
1187
  case "VarDecl":
694
1188
  scope.vars.set(node.name, {
695
- value: node.init ? evaluate(node.init, scope) : 0,
1189
+ value: node.init ? await evaluate(node.init, scope) : 0,
696
1190
  });
697
1191
  return;
698
1192
  case "FunctionDecl":
@@ -705,7 +1199,7 @@ function executeStatement(node, scope) {
705
1199
  { diagnostics: [locOf(node)] },
706
1200
  );
707
1201
  const previous = scope.vars.get(node.name).value;
708
- const value = evaluate(node.value, scope);
1202
+ const value = await evaluate(node.value, scope);
709
1203
  const next =
710
1204
  node.op === "="
711
1205
  ? value
@@ -722,36 +1216,38 @@ function executeStatement(node, scope) {
722
1216
  return;
723
1217
  }
724
1218
  case "If":
725
- if (truthy(evaluate(node.cond, scope)))
726
- executeStatements(node.then, scope);
727
- else if (node.else) executeStatements(node.else, scope);
1219
+ if (truthy(await evaluate(node.cond, scope)))
1220
+ await executeStatements(node.then, scope);
1221
+ else if (node.else) await executeStatements(node.else, scope);
728
1222
  return;
729
1223
  case "Repeat": {
730
- const count = Math.round(Number(evaluate(node.count, scope)));
1224
+ const count = Math.round(Number(await evaluate(node.count, scope)));
731
1225
  for (let index = 0; index < count; index += 1) {
732
1226
  checkDeadline(scope);
733
- executeStatements(node.body, scope);
1227
+ await executeStatements(node.body, scope);
734
1228
  }
735
1229
  return;
736
1230
  }
737
1231
  case "While":
738
- while (truthy(evaluate(node.cond, scope))) {
1232
+ while (truthy(await evaluate(node.cond, scope))) {
739
1233
  checkDeadline(scope);
740
- executeStatements(node.body, scope);
1234
+ await executeStatements(node.body, scope);
741
1235
  }
742
1236
  return;
743
1237
  case "Forever":
744
1238
  for (;;) {
745
1239
  checkDeadline(scope);
746
- executeStatements(node.body, scope);
1240
+ await executeStatements(node.body, scope);
747
1241
  }
748
1242
  case "Return":
749
- throw new ReturnSignal(node.value ? evaluate(node.value, scope) : 0);
1243
+ throw new ReturnSignal(
1244
+ node.value ? await evaluate(node.value, scope) : 0,
1245
+ );
750
1246
  case "Expect":
751
- assertExpectation(node, scope);
1247
+ await assertExpectation(node, scope);
752
1248
  return;
753
1249
  case "BlockCall":
754
- executeAction(node, scope);
1250
+ await executeAction(node, scope);
755
1251
  return;
756
1252
  default:
757
1253
  throw new TestError(`Unsupported statement ${node.type} in a test`, {
@@ -770,17 +1266,22 @@ const COMPARISONS = {
770
1266
  };
771
1267
 
772
1268
  /** Throw a detailed `AssertionFailure` when an `expect` is not truthy. */
773
- function assertExpectation(node, scope) {
774
- if (truthy(evaluate(node.value, scope))) return;
775
-
1269
+ async function assertExpectation(node, scope) {
776
1270
  let message = "expected a truthy value";
777
1271
  let expected;
778
1272
  let received;
1273
+ let result;
779
1274
  if (node.value.type === "Binary" && COMPARISONS[node.value.op]) {
780
- received = evaluate(node.value.left, scope);
781
- expected = evaluate(node.value.right, scope);
1275
+ // Evaluate each operand once so a side effect cannot change the values
1276
+ // reported after the comparison fails.
1277
+ received = await evaluate(node.value.left, scope);
1278
+ expected = await evaluate(node.value.right, scope);
1279
+ result = compareOperands(node.value.op, received, expected);
782
1280
  message = `expected ${formatValue(received)} ${COMPARISONS[node.value.op]} ${formatValue(expected)}`;
1281
+ } else {
1282
+ result = await evaluate(node.value, scope);
783
1283
  }
1284
+ if (truthy(result)) return;
784
1285
  if (node.message) message = `${node.message}: ${message}`;
785
1286
 
786
1287
  throw new AssertionFailure({
@@ -799,7 +1300,7 @@ function assertExpectation(node, scope) {
799
1300
  * real clock. Nothing here sleeps or waits on wall-clock time; the deadline
800
1301
  * check is the only place real time can stop a run.
801
1302
  */
802
- function stepTicks(scope, count) {
1303
+ async function stepTicks(scope, count) {
803
1304
  for (let index = 0; index < count; index += 1) {
804
1305
  checkDeadline(scope);
805
1306
  try {
@@ -807,14 +1308,27 @@ function stepTicks(scope, count) {
807
1308
  scope.vm.runtime._step();
808
1309
  } catch (error) {
809
1310
  scope.capture.errors.push(error?.message ?? String(error));
810
- if (scope.config.failOnRuntimeError) throw error;
1311
+ // Test-level failures must escape the VM even when runtime errors are
1312
+ // allowed; only unexpected runtime errors follow failOnRuntimeError.
1313
+ if (
1314
+ error instanceof AssertionFailure ||
1315
+ error instanceof TimeoutFailure ||
1316
+ error instanceof TestError ||
1317
+ scope.config.failOnRuntimeError
1318
+ )
1319
+ throw error;
811
1320
  }
812
1321
  scope.progress.ticks += 1;
1322
+ // Slow mode gives pending extension promises a chance to settle between
1323
+ // simulated frames. Without this a thread waiting on an async extension
1324
+ // would keep spinning while its promise callback never runs.
1325
+ if (scope.config.slow)
1326
+ await new Promise((resolve) => setImmediate(resolve));
813
1327
  }
814
1328
  }
815
1329
 
816
1330
  /** Run a built-in test action, falling back to a project block call. */
817
- function executeAction(node, scope) {
1331
+ async function executeAction(node, scope) {
818
1332
  const name = (node.segments ?? [node.name]).join(".");
819
1333
  const arg = (index) => evaluate(argument(node, index), scope);
820
1334
  const { vm } = scope;
@@ -831,10 +1345,13 @@ function executeAction(node, scope) {
831
1345
  vm.greenFlag();
832
1346
  return;
833
1347
  case "step":
834
- stepTicks(scope, node.args.length ? Math.round(Number(arg(0))) : 1);
1348
+ await stepTicks(
1349
+ scope,
1350
+ node.args.length ? Math.round(Number(await arg(0))) : 1,
1351
+ );
835
1352
  return;
836
1353
  case "broadcast": {
837
- const message = String(arg(0));
1354
+ const message = String(await arg(0));
838
1355
  scope.broadcasts.add(message);
839
1356
  vm.runtime.startHats("event_whenbroadcastreceived", {
840
1357
  BROADCAST_OPTION: message,
@@ -842,7 +1359,7 @@ function executeAction(node, scope) {
842
1359
  return;
843
1360
  }
844
1361
  case "broadcastAndWait": {
845
- const message = String(arg(0));
1362
+ const message = String(await arg(0));
846
1363
  scope.broadcasts.add(message);
847
1364
  const threads = vm.runtime.startHats("event_whenbroadcastreceived", {
848
1365
  BROADCAST_OPTION: message,
@@ -853,16 +1370,17 @@ function executeAction(node, scope) {
853
1370
  Array.isArray(threads) &&
854
1371
  threads.some((thread) => vm.runtime.threads.includes(thread))
855
1372
  )
856
- stepTicks(scope, 1);
1373
+ await stepTicks(scope, 1);
857
1374
  return;
858
1375
  }
859
1376
  case "click": {
1377
+ const clickedName = node.args.length ? String(await arg(0)) : null;
860
1378
  const target = node.args.length
861
- ? vm.runtime.getSpriteTargetByName(String(arg(0)))
1379
+ ? vm.runtime.getSpriteTargetByName(clickedName)
862
1380
  : null;
863
1381
  if (node.args.length && !target)
864
1382
  throw new TestError(
865
- `No sprite named ${JSON.stringify(String(arg(0)))} to click`,
1383
+ `No sprite named ${JSON.stringify(clickedName)} to click`,
866
1384
  { diagnostics: [locOf(node)] },
867
1385
  );
868
1386
  if (!target) {
@@ -879,14 +1397,24 @@ function executeAction(node, scope) {
879
1397
  case "keyDown":
880
1398
  case "keyUp":
881
1399
  vm.postIOData("keyboard", {
882
- key: String(arg(0)),
1400
+ key: String(await arg(0)),
883
1401
  isDown: name === "keyDown",
884
1402
  });
885
1403
  return;
886
- default:
887
- // Anything that is not a built-in test action may be a project block.
888
- callProjectProcedure(node, scope);
1404
+ default: {
1405
+ // Anything that is not a built-in test action may be a test function, a
1406
+ // catalog block or a project block.
1407
+ if (scope.functions.has(node.name)) {
1408
+ await callTestFunction(node, scope);
1409
+ return;
1410
+ }
1411
+ const catalog = await callCatalogBlock(node, scope, {
1412
+ asStatement: true,
1413
+ });
1414
+ if (catalog) return;
1415
+ await callProjectProcedure(node, scope);
889
1416
  return;
1417
+ }
890
1418
  }
891
1419
  }
892
1420
 
@@ -999,6 +1527,7 @@ async function runOneTestInVm({
999
1527
  sb3,
1000
1528
  config,
1001
1529
  seed,
1530
+ catalog,
1002
1531
  trustedExtensionUrls = [],
1003
1532
  }) {
1004
1533
  const started = performance.now();
@@ -1048,6 +1577,7 @@ async function runOneTestInVm({
1048
1577
  config,
1049
1578
  seed,
1050
1579
  capture,
1580
+ catalog,
1051
1581
  deadline: started + config.timeout,
1052
1582
  warnings: capture.warnings,
1053
1583
  });
@@ -1056,8 +1586,11 @@ async function runOneTestInVm({
1056
1586
  let status = "passed";
1057
1587
  let failure = null;
1058
1588
  try {
1059
- executeStatements(helpers, scope);
1060
- executeStatements(test.body, scope);
1589
+ await executeStatements(helpers, scope);
1590
+ await executeStatements(test.body, scope);
1591
+ // Work that finished within the budget still passes; only a late
1592
+ // completion that skipped the per-statement check is a timeout.
1593
+ checkDeadline(scope);
1061
1594
  if (config.failOnRuntimeError && capture.errors.length > 0)
1062
1595
  throw new AssertionFailure({
1063
1596
  name: "RuntimeError",
@@ -1135,6 +1668,7 @@ function describeFailure(error) {
1135
1668
  * @param {number} [options.timeout]
1136
1669
  * @param {number} [options.ticksPerSecond]
1137
1670
  * @param {boolean} [options.failOnRuntimeError]
1671
+ * @param {boolean} [options.slow] run asynchronously so async extensions can finish
1138
1672
  * @param {boolean} [options.allowProjectExtensions] trust this project's extensions
1139
1673
  * @param {boolean} [options.allowExternalIO] allow network access during tests
1140
1674
  * @param {(event: object) => void} [options.onEvent]
@@ -1152,6 +1686,7 @@ export async function runTests({
1152
1686
  timeout,
1153
1687
  ticksPerSecond,
1154
1688
  failOnRuntimeError,
1689
+ slow,
1155
1690
  allowProjectExtensions = false,
1156
1691
  allowExternalIO = false,
1157
1692
  onEvent = () => {},
@@ -1180,6 +1715,7 @@ export async function runTests({
1180
1715
  failOnRuntimeError ??
1181
1716
  settings.failOnRuntimeError ??
1182
1717
  DEFAULT_TESTS.failOnRuntimeError,
1718
+ slow: slow ?? settings.slow ?? DEFAULT_TESTS.slow,
1183
1719
  // Trust and network access belong to this invocation, never to the project
1184
1720
  // configuration, so a cloned project cannot grant them to itself.
1185
1721
  allowProjectExtensions: Boolean(allowProjectExtensions),
@@ -1355,6 +1891,7 @@ export async function runTests({
1355
1891
  sb3: built.sb3,
1356
1892
  config,
1357
1893
  seed: config.seed,
1894
+ catalog: extensions.catalog,
1358
1895
  extensionUrls: extensions.extensionUrls,
1359
1896
  trustedExtensionUrls: coreFeatureExtensionUrls(
1360
1897
  loaded,
@@ -2,5 +2,5 @@
2
2
  "name": "@penguinmod/packager",
3
3
  "version": "1.9.2",
4
4
  "commit": "53f868b85ec21d2edab9ce00fd2d709da93da6d6",
5
- "builtAt": "2026-11-29T03:42:32.489Z"
5
+ "builtAt": "2026-11-29T06:12:13.803Z"
6
6
  }
@@ -3,5 +3,5 @@
3
3
  "version": "0.2.0",
4
4
  "commit": "3822f284c8cda2c3a0a5c6dd928221dd9ff2cee1",
5
5
  "inputHash": "bb8f99fcce9f4ecdc563f11df5a0510dcc94c25d256c6931c7f1f113e0a1998b",
6
- "builtAt": "2026-11-29T03:43:29.870Z"
6
+ "builtAt": "2026-11-29T06:13:18.302Z"
7
7
  }