@nodetool-ai/game-runtime 0.8.1 → 0.8.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.
Files changed (238) hide show
  1. package/README.md +43 -0
  2. package/dist/.nodetool-build-stamp +1 -1
  3. package/dist/audio-mixer-references.d.ts +10 -0
  4. package/dist/audio-mixer-references.d.ts.map +1 -0
  5. package/dist/audio-mixer-references.js +21 -0
  6. package/dist/audio-mixer-references.js.map +1 -0
  7. package/dist/audio-source-ops.d.ts +24 -0
  8. package/dist/audio-source-ops.d.ts.map +1 -0
  9. package/dist/audio-source-ops.js +27 -0
  10. package/dist/audio-source-ops.js.map +1 -0
  11. package/dist/authoring-identity.d.ts +3 -0
  12. package/dist/authoring-identity.d.ts.map +1 -0
  13. package/dist/authoring-identity.js +12 -0
  14. package/dist/authoring-identity.js.map +1 -0
  15. package/dist/authoring-reconcile.d.ts +23 -0
  16. package/dist/authoring-reconcile.d.ts.map +1 -0
  17. package/dist/authoring-reconcile.js +375 -0
  18. package/dist/authoring-reconcile.js.map +1 -0
  19. package/dist/autoplay.d.ts.map +1 -1
  20. package/dist/autoplay.js +32 -5
  21. package/dist/autoplay.js.map +1 -1
  22. package/dist/document-ops.d.ts +2657 -368
  23. package/dist/document-ops.d.ts.map +1 -1
  24. package/dist/document-ops.js +135 -16
  25. package/dist/document-ops.js.map +1 -1
  26. package/dist/document-ops3d.d.ts +13390 -0
  27. package/dist/document-ops3d.d.ts.map +1 -0
  28. package/dist/document-ops3d.js +493 -0
  29. package/dist/document-ops3d.js.map +1 -0
  30. package/dist/gameplay/lifecycle.d.ts +91 -0
  31. package/dist/gameplay/lifecycle.d.ts.map +1 -0
  32. package/dist/gameplay/lifecycle.js +135 -0
  33. package/dist/gameplay/lifecycle.js.map +1 -0
  34. package/dist/index.d.ts +10 -0
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +10 -0
  37. package/dist/index.js.map +1 -1
  38. package/dist/open-session.d.ts +32 -0
  39. package/dist/open-session.d.ts.map +1 -0
  40. package/dist/open-session.js +51 -0
  41. package/dist/open-session.js.map +1 -0
  42. package/dist/ownership-ops.d.ts +45 -0
  43. package/dist/ownership-ops.d.ts.map +1 -0
  44. package/dist/ownership-ops.js +173 -0
  45. package/dist/ownership-ops.js.map +1 -0
  46. package/dist/prepared-collider3d.d.ts +11 -0
  47. package/dist/prepared-collider3d.d.ts.map +1 -0
  48. package/dist/prepared-collider3d.js +41 -0
  49. package/dist/prepared-collider3d.js.map +1 -0
  50. package/dist/sample3d.d.ts +4 -0
  51. package/dist/sample3d.d.ts.map +1 -0
  52. package/dist/sample3d.js +62 -0
  53. package/dist/sample3d.js.map +1 -0
  54. package/dist/script-clock.d.ts +19 -0
  55. package/dist/script-clock.d.ts.map +1 -0
  56. package/dist/script-clock.js +32 -0
  57. package/dist/script-clock.js.map +1 -0
  58. package/dist/script-declarations.d.ts +7 -0
  59. package/dist/script-declarations.d.ts.map +1 -0
  60. package/dist/script-declarations.js +99 -0
  61. package/dist/script-declarations.js.map +1 -0
  62. package/dist/script-lifecycle.d.ts +108 -0
  63. package/dist/script-lifecycle.d.ts.map +1 -0
  64. package/dist/script-lifecycle.js +253 -0
  65. package/dist/script-lifecycle.js.map +1 -0
  66. package/dist/script-params.d.ts +25 -0
  67. package/dist/script-params.d.ts.map +1 -0
  68. package/dist/script-params.js +63 -0
  69. package/dist/script-params.js.map +1 -0
  70. package/dist/script-persistence.d.ts +3 -0
  71. package/dist/script-persistence.d.ts.map +1 -0
  72. package/dist/script-persistence.js +67 -0
  73. package/dist/script-persistence.js.map +1 -0
  74. package/dist/script-props.d.ts +21 -0
  75. package/dist/script-props.d.ts.map +1 -0
  76. package/dist/script-props.js +42 -0
  77. package/dist/script-props.js.map +1 -0
  78. package/dist/script-transport.d.ts +5 -0
  79. package/dist/script-transport.d.ts.map +1 -0
  80. package/dist/script-transport.js +64 -0
  81. package/dist/script-transport.js.map +1 -0
  82. package/dist/script-types.d.ts +5 -1
  83. package/dist/script-types.d.ts.map +1 -1
  84. package/dist/script-types.js +13 -11
  85. package/dist/script-types.js.map +1 -1
  86. package/dist/script-types3d.d.ts +6 -0
  87. package/dist/script-types3d.d.ts.map +1 -0
  88. package/dist/script-types3d.js +28 -0
  89. package/dist/script-types3d.js.map +1 -0
  90. package/dist/script-world.d.ts +41 -0
  91. package/dist/script-world.d.ts.map +1 -0
  92. package/dist/script-world.js +169 -0
  93. package/dist/script-world.js.map +1 -0
  94. package/dist/scripts.d.ts +107 -4
  95. package/dist/scripts.d.ts.map +1 -1
  96. package/dist/scripts.js +513 -111
  97. package/dist/scripts.js.map +1 -1
  98. package/dist/scripts3d.d.ts +34 -0
  99. package/dist/scripts3d.d.ts.map +1 -0
  100. package/dist/scripts3d.js +14 -0
  101. package/dist/scripts3d.js.map +1 -0
  102. package/dist/session.d.ts +8 -3
  103. package/dist/session.d.ts.map +1 -1
  104. package/dist/session.js +249 -795
  105. package/dist/session.js.map +1 -1
  106. package/dist/session3d.d.ts +30 -0
  107. package/dist/session3d.d.ts.map +1 -0
  108. package/dist/session3d.js +603 -0
  109. package/dist/session3d.js.map +1 -0
  110. package/dist/spatial3d/camera.d.ts +7 -0
  111. package/dist/spatial3d/camera.d.ts.map +1 -0
  112. package/dist/spatial3d/camera.js +43 -0
  113. package/dist/spatial3d/camera.js.map +1 -0
  114. package/dist/spatial3d/digest.d.ts +4 -0
  115. package/dist/spatial3d/digest.d.ts.map +1 -0
  116. package/dist/spatial3d/digest.js +30 -0
  117. package/dist/spatial3d/digest.js.map +1 -0
  118. package/dist/spatial3d/layers.d.ts +30 -0
  119. package/dist/spatial3d/layers.d.ts.map +1 -0
  120. package/dist/spatial3d/layers.js +93 -0
  121. package/dist/spatial3d/layers.js.map +1 -0
  122. package/dist/spatial3d/math.d.ts +23 -0
  123. package/dist/spatial3d/math.d.ts.map +1 -0
  124. package/dist/spatial3d/math.js +39 -0
  125. package/dist/spatial3d/math.js.map +1 -0
  126. package/dist/spatial3d/state.d.ts +37 -0
  127. package/dist/spatial3d/state.d.ts.map +1 -0
  128. package/dist/spatial3d/state.js +4 -0
  129. package/dist/spatial3d/state.js.map +1 -0
  130. package/dist/spatial3d/world.d.ts +68 -0
  131. package/dist/spatial3d/world.d.ts.map +1 -0
  132. package/dist/spatial3d/world.js +446 -0
  133. package/dist/spatial3d/world.js.map +1 -0
  134. package/dist/systems/animation-graph3d.d.ts +24 -0
  135. package/dist/systems/animation-graph3d.d.ts.map +1 -0
  136. package/dist/systems/animation-graph3d.js +262 -0
  137. package/dist/systems/animation-graph3d.js.map +1 -0
  138. package/dist/systems/animation3d.d.ts +3 -0
  139. package/dist/systems/animation3d.d.ts.map +1 -0
  140. package/dist/systems/animation3d.js +14 -0
  141. package/dist/systems/animation3d.js.map +1 -0
  142. package/dist/systems/character3d.d.ts +3 -0
  143. package/dist/systems/character3d.d.ts.map +1 -0
  144. package/dist/systems/character3d.js +6 -0
  145. package/dist/systems/character3d.js.map +1 -0
  146. package/dist/systems/collision2d.d.ts +27 -0
  147. package/dist/systems/collision2d.d.ts.map +1 -0
  148. package/dist/systems/collision2d.js +154 -0
  149. package/dist/systems/collision2d.js.map +1 -0
  150. package/dist/systems/contacts2d.d.ts +3 -0
  151. package/dist/systems/contacts2d.d.ts.map +1 -0
  152. package/dist/systems/contacts2d.js +36 -0
  153. package/dist/systems/contacts2d.js.map +1 -0
  154. package/dist/systems/contacts3d.d.ts +3 -0
  155. package/dist/systems/contacts3d.d.ts.map +1 -0
  156. package/dist/systems/contacts3d.js +55 -0
  157. package/dist/systems/contacts3d.js.map +1 -0
  158. package/dist/systems/context2d.d.ts +41 -0
  159. package/dist/systems/context2d.d.ts.map +1 -0
  160. package/dist/systems/context2d.js +2 -0
  161. package/dist/systems/context2d.js.map +1 -0
  162. package/dist/systems/context3d.d.ts +67 -0
  163. package/dist/systems/context3d.d.ts.map +1 -0
  164. package/dist/systems/context3d.js +2 -0
  165. package/dist/systems/context3d.js.map +1 -0
  166. package/dist/systems/gameplay2d.d.ts +3 -0
  167. package/dist/systems/gameplay2d.d.ts.map +1 -0
  168. package/dist/systems/gameplay2d.js +88 -0
  169. package/dist/systems/gameplay2d.js.map +1 -0
  170. package/dist/systems/gameplay3d.d.ts +4 -0
  171. package/dist/systems/gameplay3d.d.ts.map +1 -0
  172. package/dist/systems/gameplay3d.js +170 -0
  173. package/dist/systems/gameplay3d.js.map +1 -0
  174. package/dist/systems/hierarchy3d.d.ts +3 -0
  175. package/dist/systems/hierarchy3d.d.ts.map +1 -0
  176. package/dist/systems/hierarchy3d.js +27 -0
  177. package/dist/systems/hierarchy3d.js.map +1 -0
  178. package/dist/systems/input2d.d.ts +3 -0
  179. package/dist/systems/input2d.d.ts.map +1 -0
  180. package/dist/systems/input2d.js +6 -0
  181. package/dist/systems/input2d.js.map +1 -0
  182. package/dist/systems/input3d.d.ts +3 -0
  183. package/dist/systems/input3d.d.ts.map +1 -0
  184. package/dist/systems/input3d.js +16 -0
  185. package/dist/systems/input3d.js.map +1 -0
  186. package/dist/systems/physics2d.d.ts +3 -0
  187. package/dist/systems/physics2d.d.ts.map +1 -0
  188. package/dist/systems/physics2d.js +244 -0
  189. package/dist/systems/physics2d.js.map +1 -0
  190. package/dist/systems/physics3d.d.ts +3 -0
  191. package/dist/systems/physics3d.d.ts.map +1 -0
  192. package/dist/systems/physics3d.js +4 -0
  193. package/dist/systems/physics3d.js.map +1 -0
  194. package/dist/systems/pipeline.d.ts +23 -0
  195. package/dist/systems/pipeline.d.ts.map +1 -0
  196. package/dist/systems/pipeline.js +65 -0
  197. package/dist/systems/pipeline.js.map +1 -0
  198. package/dist/systems/presentation2d.d.ts +9 -0
  199. package/dist/systems/presentation2d.d.ts.map +1 -0
  200. package/dist/systems/presentation2d.js +240 -0
  201. package/dist/systems/presentation2d.js.map +1 -0
  202. package/dist/systems/presentation3d.d.ts +9 -0
  203. package/dist/systems/presentation3d.d.ts.map +1 -0
  204. package/dist/systems/presentation3d.js +115 -0
  205. package/dist/systems/presentation3d.js.map +1 -0
  206. package/dist/systems/scripts2d.d.ts +7 -0
  207. package/dist/systems/scripts2d.d.ts.map +1 -0
  208. package/dist/systems/scripts2d.js +274 -0
  209. package/dist/systems/scripts2d.js.map +1 -0
  210. package/dist/systems/scripts3d.d.ts +7 -0
  211. package/dist/systems/scripts3d.d.ts.map +1 -0
  212. package/dist/systems/scripts3d.js +262 -0
  213. package/dist/systems/scripts3d.js.map +1 -0
  214. package/dist/systems/state2d.d.ts +65 -0
  215. package/dist/systems/state2d.d.ts.map +1 -0
  216. package/dist/systems/state2d.js +2 -0
  217. package/dist/systems/state2d.js.map +1 -0
  218. package/dist/systems/tick2d.d.ts +7 -0
  219. package/dist/systems/tick2d.d.ts.map +1 -0
  220. package/dist/systems/tick2d.js +15 -0
  221. package/dist/systems/tick2d.js.map +1 -0
  222. package/dist/systems/tick3d.d.ts +7 -0
  223. package/dist/systems/tick3d.d.ts.map +1 -0
  224. package/dist/systems/tick3d.js +17 -0
  225. package/dist/systems/tick3d.js.map +1 -0
  226. package/dist/validate-animation-graph3d.d.ts +8 -0
  227. package/dist/validate-animation-graph3d.d.ts.map +1 -0
  228. package/dist/validate-animation-graph3d.js +115 -0
  229. package/dist/validate-animation-graph3d.js.map +1 -0
  230. package/dist/validate.d.ts +5 -0
  231. package/dist/validate.d.ts.map +1 -1
  232. package/dist/validate.js +61 -2
  233. package/dist/validate.js.map +1 -1
  234. package/dist/validate3d.d.ts +20 -0
  235. package/dist/validate3d.d.ts.map +1 -0
  236. package/dist/validate3d.js +325 -0
  237. package/dist/validate3d.js.map +1 -0
  238. package/package.json +10 -3
package/dist/scripts.js CHANGED
@@ -1,4 +1,10 @@
1
1
  import { z } from "zod";
2
+ import { gameNonSpatialScriptCommand, gameUiScriptCommand, resolveGameScriptParams } from "@nodetool-ai/protocol";
3
+ import { defaultScriptCallClock, startScriptCallTimer } from "./script-clock.js";
4
+ import { commitScriptHooks, planScriptHooks, scriptHookIssue, SCRIPT_LIFECYCLE_DISPATCH } from "./script-lifecycle.js";
5
+ import { canPersistGameScript } from "./script-persistence.js";
6
+ import { gameScriptValue, scriptHandleResult } from "./script-transport.js";
7
+ import { ScriptWorldSnapshot } from "./script-world.js";
2
8
  const encoder = new TextEncoder();
3
9
  const finite = z.number().finite();
4
10
  const color = z.string().regex(/^#[0-9a-fA-F]{6}$/);
@@ -7,17 +13,18 @@ export const gameScriptCommand = z.discriminatedUnion("kind", [
7
13
  z.strictObject({ kind: z.literal("setPosition"), x: finite, y: finite }),
8
14
  z.strictObject({ kind: z.literal("setVisual"), tint: color.optional(), opacity: finite.min(0).max(1).optional(),
9
15
  rotation: finite.optional(), scaleX: finite.positive().optional(), scaleY: finite.positive().optional(), flipX: z.boolean().optional() }),
10
- z.strictObject({ kind: z.literal("playAnimation"), clip: z.string().min(1) }),
11
- z.strictObject({ kind: z.literal("hud"), id: z.string().min(1).max(64), text: z.string().max(256), x: finite, y: finite,
12
- size: finite.positive().max(256).optional(), color: color.optional(), align: z.enum(["left", "center", "right"]).optional(),
13
- fontId: z.string().min(1).optional() }),
14
- z.strictObject({ kind: z.literal("emit"), event: z.string().min(1).max(128) }),
16
+ gameNonSpatialScriptCommand.options[0],
17
+ gameNonSpatialScriptCommand.options[1],
18
+ gameNonSpatialScriptCommand.options[2],
15
19
  z.strictObject({ kind: z.literal("spawn"), prefabId: z.string().min(1), x: finite.optional(), y: finite.optional(),
16
20
  velocityX: finite.optional(), velocityY: finite.optional() }),
17
- z.strictObject({ kind: z.literal("despawn"), entityId: z.string().min(1) }),
18
- z.strictObject({ kind: z.literal("sceneTransition"), sceneId: z.string().min(1) })
21
+ gameNonSpatialScriptCommand.options[3],
22
+ gameNonSpatialScriptCommand.options[4],
23
+ gameNonSpatialScriptCommand.options[5],
24
+ gameNonSpatialScriptCommand.options[6],
25
+ gameNonSpatialScriptCommand.options[7],
26
+ gameUiScriptCommand
19
27
  ]);
20
- const result = z.strictObject({ state: z.json(), commands: z.array(gameScriptCommand) });
21
28
  export function scriptSourceKey(sceneId, entityId, behaviorIndex) {
22
29
  return JSON.stringify([sceneId, entityId, behaviorIndex]);
23
30
  }
@@ -25,18 +32,16 @@ export function hasGameScripts(document) {
25
32
  return document.scenes.some((scene) => scene.entities.some((entity) => entity.behaviors.some((behavior) => behavior.kind === "script")));
26
33
  }
27
34
  function evaluate(context, code) {
28
- const evaluation = context.evalCode(code, "game-script.js", { type: "global" });
29
- if (evaluation.error) {
30
- const error = context.dump(evaluation.error);
31
- evaluation.error.dispose();
32
- throw new Error(`Game script failed: ${error.message ?? "unknown error"}`);
35
+ const value = scriptHandleResult(context, context.evalCode(code, "game-script.js", { type: "global" }));
36
+ try {
37
+ return context.dump(value);
38
+ }
39
+ finally {
40
+ value.dispose();
33
41
  }
34
- const value = context.dump(evaluation.value);
35
- evaluation.value.dispose();
36
- return value;
37
42
  }
38
- function initializeContext(context, seed) {
39
- evaluate(context, `
43
+ function initializeContext(context, seed, helpers) {
44
+ return scriptHandleResult(context, context.evalCode(`
40
45
  globalThis.Date = undefined;
41
46
  Object.defineProperty(globalThis, "__gameRandom", {
42
47
  value: (() => {
@@ -50,15 +55,82 @@ function initializeContext(context, seed) {
50
55
  })(), writable: false, configurable: false
51
56
  });
52
57
  Object.defineProperty(Math, "random", { value: __gameRandom, writable: false, configurable: false });
53
- `);
58
+ ${helpers}
59
+ `, "game-transport.js", { type: "global" }));
60
+ }
61
+ function interrupted(budget) {
62
+ return new Error(`Game script interrupted: ${budget} budget exceeded`);
54
63
  }
55
64
  function assertBeforeDeadline(deadline, budget) {
56
65
  if (performance.now() >= deadline) {
57
- throw new Error(`Game script interrupted: ${budget} budget exceeded`);
66
+ throw interrupted(budget);
58
67
  }
59
68
  }
60
- /** Script calls use fresh contexts so only returned state and RNG survive a tick. */
61
- export async function prepareGameScripts(document) {
69
+ const EMPTY_PROPS = Object.freeze({});
70
+ function propsOf(table, id) {
71
+ return Object.hasOwn(table, id) ? table[id] : EMPTY_PROPS;
72
+ }
73
+ function disposeRealm(realm) {
74
+ realm.setWorldReader(undefined);
75
+ realm.worldGetter.dispose();
76
+ realm.queryJson.dispose();
77
+ realm.defineData.dispose();
78
+ realm.invoke.dispose();
79
+ realm.context.dispose();
80
+ }
81
+ /** Bounds the validated entry-scene realms held until the first batch, about 30 KiB each. */
82
+ const PREPARED_REALM_LIMIT = 64;
83
+ const SCRIPT_BATCH_MS = 50;
84
+ /** Prepare-time allowance for the warm-up batch, which runs before any tick budget starts. */
85
+ const WARMUP_BATCH_MS = 1000;
86
+ const WARMUP_SOURCES = [
87
+ ["warmup:fresh", "(input) => { const world = input.world; return { state: { tick: input.tick, entities: world.length, ids: world.map((entity) => entity.id) }, commands: [] }; }"],
88
+ ["warmup:persistent", "(input) => ({ state: [input.state, input.world], commands: [] })"]
89
+ ];
90
+ /** Warms the lifecycle-object path, only for documents that use it. */
91
+ const HOOK_WARMUP_SOURCE = ["warmup:hooks", "({ onStart(input) { after(1, \"tick\"); }, tick() {}, onUpdate(input) { return { state: [input.state, input.world] }; } })"];
92
+ // One envelope per command schema, so its parser is compiled once per process instead of once per runner.
93
+ const envelopeSchemas = new WeakMap();
94
+ const warmedCommandSchemas = new WeakSet();
95
+ const warmedHookSchemas = new WeakSet();
96
+ const compiledSchemas = new WeakSet();
97
+ /**
98
+ * Zod compiles each object schema's parser the first time it sees an object. Doing that here keeps the
99
+ * compilation out of the first batch that emits a given command kind, where it would count against the tick budget.
100
+ */
101
+ function compileObjectParsers(schema) {
102
+ if (compiledSchemas.has(schema)) {
103
+ return;
104
+ }
105
+ compiledSchemas.add(schema);
106
+ const def = schema._zod.def;
107
+ const children = [];
108
+ if (def["type"] === "object") {
109
+ z.safeParse(schema, {});
110
+ children.push(...Object.values(def["shape"]), def["catchall"]);
111
+ }
112
+ for (const key of ["innerType", "element", "in", "out", "keyType", "valueType", "left", "right", "rest"]) {
113
+ children.push(def[key]);
114
+ }
115
+ for (const key of ["options", "items"]) {
116
+ if (Array.isArray(def[key])) {
117
+ children.push(...def[key]);
118
+ }
119
+ }
120
+ for (const child of children) {
121
+ if (child instanceof z.core.$ZodType) {
122
+ compileObjectParsers(child);
123
+ }
124
+ }
125
+ }
126
+ export async function prepareIsolatedGameScripts(document, commandSchema, payloadExpression, options = {}) {
127
+ const callClock = options.callClock ?? defaultScriptCallClock;
128
+ let envelope = envelopeSchemas.get(commandSchema);
129
+ if (envelope === undefined) {
130
+ envelope = z.object({ value: z.strictObject({ state: z.json(), commands: z.array(commandSchema) }), rngState: z.number().int().nonnegative() });
131
+ envelopeSchemas.set(commandSchema, envelope);
132
+ }
133
+ const envelopeSchema = envelope;
62
134
  const [{ newQuickJSWASMModuleFromVariant }, quickJsVariantModule] = await Promise.all([
63
135
  import("quickjs-emscripten-core"),
64
136
  import("@jitl/quickjs-ng-wasmfile-release-sync")
@@ -69,133 +141,463 @@ export async function prepareGameScripts(document) {
69
141
  runtime.setMemoryLimit(16 * 1024 * 1024);
70
142
  runtime.setMaxStackSize(256 * 1024);
71
143
  const sources = new Map();
144
+ // Resolved `input.params` JSON per behavior definition. Values are document data, so this is serialized once per session.
145
+ const paramsJson = new Map();
146
+ const persistentSources = new Set();
147
+ const hookSources = new Set();
148
+ const eventSources = new Set();
149
+ const realms = new Map();
150
+ // Validated entry-scene realms, kept so the first tick does not compile every proven-safe script inside its budget.
151
+ const prepared = new Map();
152
+ const releasePrepared = () => {
153
+ for (const realm of prepared.values()) {
154
+ disposeRealm(realm);
155
+ }
156
+ prepared.clear();
157
+ };
158
+ const disposeRealms = () => {
159
+ for (const realm of realms.values()) {
160
+ disposeRealm(realm);
161
+ }
162
+ realms.clear();
163
+ releasePrepared();
164
+ };
165
+ const retain = (keys) => {
166
+ for (const [key, realm] of realms) {
167
+ if (!keys.has(key)) {
168
+ disposeRealm(realm);
169
+ realms.delete(key);
170
+ }
171
+ }
172
+ };
173
+ // Host-only setup. Creating a context can run a QuickJS cycle collection of earlier disposed contexts.
174
+ // Only lifecycle-object realms install the hook dispatcher, so function realms evaluate the same helpers as before.
175
+ const createRealmShell = (seed, persistent, hooks = false) => {
176
+ const context = runtime.newContext();
177
+ let invoke;
178
+ let defineData;
179
+ let queryJson;
180
+ let worldGetter;
181
+ let worldReader;
182
+ try {
183
+ worldGetter = persistent ? context.newFunction("legacyWorld", () => {
184
+ if (!worldReader) {
185
+ throw new Error("Legacy world read outside an active script call");
186
+ }
187
+ return worldReader();
188
+ }) : context.undefined.dup();
189
+ // Capture pristine helpers together, without introducing bindings visible to user source.
190
+ const helpers = initializeContext(context, seed, `[
191
+ ((define) => (object, key, value) => {
192
+ define(object, key, { value, writable: true, enumerable: true, configurable: true });
193
+ })(Object.defineProperty),
194
+ ((stringify) => (value) => {
195
+ const json = stringify(value);
196
+ if (typeof json !== "string" || json.length > 4096) { throw new Error("world query arguments exceed 4096 characters or are not JSON"); }
197
+ return json;
198
+ })(JSON.stringify),
199
+ ((defineProperty${hooks ? ", dispatch" : ""}) => (data, getWorld, rngState) => {
200
+ ${persistent ? "" : "data = JSON.parse(data);"}
201
+ const payload = ${payloadExpression};
202
+ ${persistent ? `defineProperty(payload, "world", {
203
+ enumerable: true, configurable: true, get: getWorld,
204
+ set(value) { defineProperty(this, "world", { value, writable: true, enumerable: true, configurable: true }); }
205
+ });` : ""}
206
+ const value = ${hooks ? "dispatch(__gameScript, payload, data.call.steps)" : "__gameScript(payload)"};
207
+ return JSON.stringify({ value, rngState: ${persistent ? "rngState" : "__gameRandom.state"} });
208
+ })(Object.defineProperty${hooks ? `, ${SCRIPT_LIFECYCLE_DISPATCH}` : ""})]`);
209
+ try {
210
+ defineData = context.getProp(helpers, 0);
211
+ queryJson = context.getProp(helpers, 1);
212
+ invoke = context.getProp(helpers, 2);
213
+ }
214
+ finally {
215
+ helpers.dispose();
216
+ }
217
+ return { context, invoke, defineData, queryJson, worldGetter, setWorldReader: (reader) => { worldReader = reader; } };
218
+ }
219
+ catch (error) {
220
+ worldGetter?.dispose();
221
+ queryJson?.dispose();
222
+ defineData?.dispose();
223
+ invoke?.dispose();
224
+ context.dispose();
225
+ throw error;
226
+ }
227
+ };
228
+ /** Evaluates user source in the shell, which this takes ownership of. */
229
+ const loadSource = (shell, sourceKey, source, hooks) => {
230
+ try {
231
+ if (evaluate(shell.context, `globalThis.__gameScript = (${source}); typeof __gameScript`) !== (hooks ? "object" : "function")) {
232
+ throw new Error(`Game script ${sourceKey} must be a ${hooks ? "lifecycle object" : "function expression"}`);
233
+ }
234
+ return { ...shell, sourceKey };
235
+ }
236
+ catch (error) {
237
+ disposeRealm(shell);
238
+ throw error;
239
+ }
240
+ };
241
+ /** Prepare-time evaluation: a function, or a lifecycle object whose hooks pass `scriptHookIssue`. */
242
+ const inspectSource = (sourceKey, source, persistent) => {
243
+ const shell = createRealmShell(0, persistent);
244
+ try {
245
+ const kind = evaluate(shell.context, `globalThis.__gameScript = (${source}); typeof __gameScript`);
246
+ let onEvent = false;
247
+ if (kind !== "function") {
248
+ const shape = kind === "object" && !persistent ? evaluate(shell.context, `(() => { const hooks = __gameScript;
249
+ if (hooks === null || Array.isArray(hooks)) { return null; }
250
+ const keys = Object.keys(hooks);
251
+ return [keys, keys.filter((key) => typeof hooks[key] === "function")]; })()`) : null;
252
+ if (!Array.isArray(shape)) {
253
+ throw new Error(`Game script ${sourceKey} must be a function expression or a lifecycle object`);
254
+ }
255
+ const issue = scriptHookIssue(shape[0], shape[1]);
256
+ if (issue !== undefined) {
257
+ throw new Error(`Game script ${sourceKey}: ${issue}`);
258
+ }
259
+ onEvent = shape[1].includes("onEvent");
260
+ }
261
+ return { realm: { ...shell, sourceKey }, hooks: kind !== "function", onEvent };
262
+ }
263
+ catch (error) {
264
+ disposeRealm(shell);
265
+ throw error;
266
+ }
267
+ };
72
268
  try {
73
269
  for (const scene of document.scenes) {
74
270
  for (const entity of scene.entities) {
75
271
  entity.behaviors.forEach((behavior, index) => {
76
- if (behavior.kind !== "script") {
272
+ if (behavior.kind !== "script" || behavior.source === undefined) {
77
273
  return;
78
274
  }
79
275
  const key = scriptSourceKey(scene.id, entity.id, index);
80
- const context = runtime.newContext();
81
276
  try {
82
277
  const deadline = performance.now() + 100;
83
278
  runtime.setInterruptHandler(() => performance.now() >= deadline);
84
- initializeContext(context, 0);
85
- if (evaluate(context, `globalThis.__gameScript = (${behavior.source}); typeof __gameScript`) !== "function") {
86
- throw new Error(`Game script ${key} must be a function expression`);
279
+ const persistent = canPersistGameScript(behavior.source);
280
+ const { realm, hooks, onEvent } = inspectSource(key, behavior.source, persistent);
281
+ if (persistent) {
282
+ persistentSources.add(key);
283
+ }
284
+ if (hooks) {
285
+ hookSources.add(key);
286
+ }
287
+ if (onEvent) {
288
+ eventSources.add(key);
289
+ }
290
+ // Inactive scenes and prefab definitions are validated without retaining their realms.
291
+ if (persistent && scene.id === document.entrySceneId && prepared.size < PREPARED_REALM_LIMIT) {
292
+ prepared.set(key, realm);
293
+ }
294
+ else {
295
+ disposeRealm(realm);
87
296
  }
88
297
  }
89
298
  catch (error) {
90
299
  throw new Error(`Game script ${key} could not be prepared: ${error instanceof Error ? error.message : String(error)}`);
91
300
  }
92
- finally {
93
- context.dispose();
94
- }
95
301
  sources.set(key, behavior.source);
302
+ if (behavior.params !== undefined) {
303
+ paramsJson.set(key, JSON.stringify(resolveGameScriptParams(behavior.params, behavior.values)));
304
+ }
96
305
  });
97
306
  }
98
307
  }
99
- return {
100
- run(calls, input, rngState) {
101
- if (calls.length === 0) {
102
- return { results: [], rngState, stats: { durationMs: 0, commands: 0, calls: 0, byEntity: {} } };
103
- }
104
- const started = performance.now();
105
- const batchDeadline = started + 50;
106
- // This limits the logical tick payload; each isolated call gets its own JSON copy.
107
- const serialized = JSON.stringify({ calls, input, rngState });
108
- const inputBytes = encoder.encode(serialized).byteLength;
109
- if (inputBytes > 64 * 1024) {
110
- throw new Error(`Game script input exceeds 64 KiB (${inputBytes} bytes, ${calls.length} calls, tick ${input.tick})`);
111
- }
112
- const batchBudget = `batch 50 ms at tick ${input.tick}`;
308
+ const execute = (calls, input, rngState, world, batchMs) => {
309
+ const started = performance.now();
310
+ const batchDeadline = started + batchMs;
311
+ // This limits the logical tick payload, which carries each entity's props once.
312
+ // Each isolated call gets its own JSON copy with props attached to the entries scripts read.
313
+ // Params belong to a behavior definition, so calls that share one count its params once, as a table keyed by source.
314
+ let paramsTable = "";
315
+ const counted = new Set();
316
+ for (const call of paramsJson.size === 0 ? [] : calls) {
317
+ const params = paramsJson.get(call.sourceKey);
318
+ if (params === undefined || counted.has(call.sourceKey)) {
319
+ continue;
320
+ }
321
+ paramsTable += `${counted.size > 0 ? "," : ""}${JSON.stringify(call.sourceKey)}:${params}`;
322
+ counted.add(call.sourceKey);
323
+ }
324
+ const logical = JSON.stringify({ calls, input, rngState });
325
+ const serialized = counted.size === 0 ? logical : `${logical.slice(0, -1)},"params":{${paramsTable}}}`;
326
+ const inputBytes = encoder.encode(serialized).byteLength;
327
+ if (inputBytes > 64 * 1024) {
328
+ throw new Error(`Game script input exceeds 64 KiB (${inputBytes} bytes, ${calls.length} calls, tick ${input.tick})`);
329
+ }
330
+ const batchBudget = `batch ${batchMs} ms at tick ${input.tick}`;
331
+ assertBeforeDeadline(batchDeadline, batchBudget);
332
+ const { props: propsTable, ...scriptInput } = input;
333
+ // Scripts read props on each world entry. The copies exist only in this guest-facing JSON.
334
+ let worldJson;
335
+ const scriptWorldJson = () => worldJson ??= JSON.stringify(propsTable === undefined ? scriptInput.world
336
+ : scriptInput.world.map((entity) => ({ ...entity, props: propsOf(propsTable, entity.id) })));
337
+ let fullInputJson;
338
+ const inputJson = () => {
339
+ if (fullInputJson === undefined) {
340
+ const { world: _world, ...withoutWorld } = scriptInput;
341
+ const rest = JSON.stringify(withoutWorld);
342
+ fullInputJson = `${rest.slice(0, -1)}${rest.length > 2 ? "," : ""}"world":${scriptWorldJson()}}`;
343
+ }
344
+ return fullInputJson;
345
+ };
346
+ let persistentInputJson;
347
+ const inputJsonWithoutWorld = () => {
348
+ if (persistentInputJson === undefined) {
349
+ const { world: _world, ...withoutWorld } = scriptInput;
350
+ persistentInputJson = JSON.stringify(withoutWorld);
351
+ }
352
+ return persistentInputJson;
353
+ };
354
+ const callJson = (call, plan) => {
355
+ // A lifecycle call shows its hooks the record's inner state and receives its hook steps instead of host facts.
356
+ const guest = plan === undefined ? call : { ...call, state: plan.state, lifecycle: undefined, steps: plan.steps };
357
+ return JSON.stringify(propsTable === undefined ? guest : { ...guest, props: propsOf(propsTable, call.entityId) });
358
+ };
359
+ let hostWorld;
360
+ const getHostWorld = () => hostWorld ??= new ScriptWorldSnapshot(world ?? input.world, propsTable);
361
+ let legacyWorld;
362
+ let legacyWorldReady = false;
363
+ const readLegacyWorld = () => {
364
+ if (!legacyWorldReady) {
365
+ // Parse the tick-start world only when a persistent script reads it.
366
+ legacyWorld = JSON.parse(scriptWorldJson());
367
+ legacyWorldReady = true;
368
+ }
369
+ return legacyWorld;
370
+ };
371
+ let nextRngState = rngState;
372
+ let serializedResultsBytes = 0;
373
+ let commandCount = 0;
374
+ const byEntity = Object.create(null);
375
+ const results = [];
376
+ for (const call of calls) {
113
377
  assertBeforeDeadline(batchDeadline, batchBudget);
114
- let nextRngState = rngState;
115
- let serializedResultsBytes = 0;
116
- let commandCount = 0;
117
- const byEntity = Object.create(null);
118
- const results = [];
119
- for (const call of calls) {
378
+ const source = sources.get(call.sourceKey);
379
+ if (source === undefined) {
380
+ throw new Error(`Game script source ${call.sourceKey} is missing for ${call.entityId} at tick ${input.tick}`);
381
+ }
382
+ let callStarted = performance.now();
383
+ let callExceeded = () => false;
384
+ const checkCallDeadline = () => {
385
+ assertBeforeDeadline(batchDeadline, batchBudget);
386
+ if (callExceeded()) {
387
+ throw interrupted(`call ${call.maxTickMs} ms for ${call.entityId} at tick ${input.tick}`);
388
+ }
389
+ };
390
+ runtime.setInterruptHandler(() => performance.now() >= batchDeadline);
391
+ const persistent = persistentSources.has(call.sourceKey);
392
+ let realm = realms.get(call.stateKey);
393
+ let shell;
394
+ let worldHandle;
395
+ let worldCall;
396
+ try {
397
+ if (realm && realm.sourceKey !== call.sourceKey) {
398
+ disposeRealm(realm);
399
+ realms.delete(call.stateKey);
400
+ realm = undefined;
401
+ }
402
+ if (!realm && persistent) {
403
+ realm = prepared.get(call.sourceKey);
404
+ prepared.delete(call.sourceKey);
405
+ }
406
+ // Context setup is host work, so it counts against the batch budget only. The call budget starts
407
+ // before any user source is evaluated, so the script's own execution limit is unchanged.
408
+ const hooks = hookSources.has(call.sourceKey);
409
+ if (!realm) {
410
+ shell = createRealmShell(nextRngState, persistent, hooks);
411
+ }
120
412
  assertBeforeDeadline(batchDeadline, batchBudget);
121
- const source = sources.get(call.sourceKey);
122
- if (source === undefined) {
123
- throw new Error(`Game script source ${call.sourceKey} is missing for ${call.entityId} at tick ${input.tick}`);
124
- }
125
- const callStarted = performance.now();
126
- const deadline = Math.min(batchDeadline, callStarted + call.maxTickMs);
127
- const checkCallDeadline = () => {
128
- assertBeforeDeadline(batchDeadline, batchBudget);
129
- assertBeforeDeadline(deadline, `call ${call.maxTickMs} ms for ${call.entityId} at tick ${input.tick}`);
130
- };
131
- runtime.setInterruptHandler(() => performance.now() >= deadline);
132
- const context = runtime.newContext();
413
+ callStarted = performance.now();
414
+ callExceeded = startScriptCallTimer(callClock, call.maxTickMs);
415
+ runtime.setInterruptHandler(() => performance.now() >= batchDeadline || callExceeded());
416
+ if (shell) {
417
+ const loading = shell;
418
+ shell = undefined;
419
+ realm = loadSource(loading, call.sourceKey, source, hooks);
420
+ }
421
+ if (!realm) {
422
+ throw new Error("Game script realm was not created");
423
+ }
424
+ if (persistent) {
425
+ realms.set(call.stateKey, realm);
426
+ }
427
+ const { context, invoke, defineData, worldGetter } = realm;
428
+ if (!persistent) {
429
+ worldCall = getHostWorld().install(context, checkCallDeadline, realm.defineData, realm.queryJson);
430
+ }
431
+ checkCallDeadline();
432
+ // The shared input is serialized once per tick; only the call is serialized per call.
433
+ const params = paramsJson.get(call.sourceKey);
434
+ const plan = hooks ? planScriptHooks(call.state, call.lifecycle, input.tick) : undefined;
435
+ const data = `{"call":${callJson(call, plan)},"input":${persistent ? inputJsonWithoutWorld() : inputJson()},"rngState":${JSON.stringify(nextRngState)}${params === undefined ? "" : `,"params":${params}`}}`;
436
+ checkCallDeadline();
437
+ const normalized = persistent ? JSON.parse(data) : data;
438
+ let argument;
439
+ let seed;
440
+ let output;
133
441
  try {
134
- initializeContext(context, nextRngState);
135
- checkCallDeadline();
136
- if (evaluate(context, `globalThis.__gameScript = (${source}); typeof __gameScript`) !== "function") {
137
- throw new Error("Source must be a function expression");
442
+ argument = gameScriptValue(context, normalized, defineData, persistent);
443
+ seed = context.newNumber(nextRngState);
444
+ realm.setWorldReader(() => {
445
+ checkCallDeadline();
446
+ worldHandle ??= gameScriptValue(context, readLegacyWorld(), defineData, true);
447
+ checkCallDeadline();
448
+ return worldHandle.dup();
449
+ });
450
+ const value = scriptHandleResult(context, context.callFunction(invoke, context.undefined, argument, worldGetter, seed));
451
+ try {
452
+ output = context.dump(value);
138
453
  }
139
- checkCallDeadline();
140
- const data = JSON.stringify({ call, input, rngState: nextRngState });
141
- checkCallDeadline();
142
- const output = evaluate(context, `(() => {
143
- const data = JSON.parse(${JSON.stringify(data)});
144
- const value = __gameScript({
145
- tick: data.input.tick, pressed: data.input.pressed, justPressed: data.input.justPressed,
146
- events: data.input.events, entity: {
147
- id: data.call.entityId, source: data.call.source, x: data.call.x, y: data.call.y,
148
- velocityX: data.call.velocityX, velocityY: data.call.velocityY,
149
- touching: data.call.touching
150
- }, world: data.input.world, state: data.call.state, random: __gameRandom
151
- });
152
- return JSON.stringify({ value, rngState: __gameRandom.state });
153
- })()`);
154
- if (typeof output !== "string") {
155
- throw new Error("Output is not JSON");
454
+ finally {
455
+ value.dispose();
156
456
  }
157
- checkCallDeadline();
158
- const rawOutputBytes = encoder.encode(output).byteLength;
159
- if (rawOutputBytes > 64 * 1024) {
160
- throw new Error(`Output exceeds 64 KiB (${rawOutputBytes} bytes in call ${results.length + 1})`);
161
- }
162
- const parsed = JSON.parse(output);
163
- const envelope = z.object({ value: result, rngState: z.number().int().nonnegative() }).parse(parsed);
164
- if (envelope.value.commands.length > call.maxCommands) {
165
- throw new Error(`Game script command limit exceeded for ${call.entityId}`);
166
- }
167
- const itemBytes = encoder.encode(JSON.stringify({ entityId: call.entityId, value: envelope.value })).byteLength;
168
- serializedResultsBytes += itemBytes + (results.length > 0 ? 1 : 0);
169
- const outputBytes = encoder.encode(JSON.stringify({ results: [], rngState: envelope.rngState })).byteLength + serializedResultsBytes;
170
- if (outputBytes > 64 * 1024) {
171
- throw new Error(`Output exceeds 64 KiB (${outputBytes} bytes across ${results.length + 1} calls)`);
172
- }
173
- checkCallDeadline();
174
- commandCount += envelope.value.commands.length;
175
- nextRngState = envelope.rngState;
176
- results.push({ entityId: call.entityId, state: envelope.value.state, commands: envelope.value.commands });
177
- }
178
- catch (error) {
179
- throw new Error(`Game script ${call.sourceKey} for ${call.entityId} at tick ${input.tick} failed: ${error instanceof Error ? error.message : String(error)}`);
457
+ worldCall?.assertWithinLimit();
180
458
  }
181
459
  finally {
182
- context.dispose();
460
+ realm.setWorldReader(undefined);
461
+ argument?.dispose();
462
+ seed?.dispose();
463
+ }
464
+ if (typeof output !== "string") {
465
+ throw new Error("Output is not JSON");
183
466
  }
184
467
  checkCallDeadline();
185
- const previous = byEntity[call.entityId] ?? { durationMs: 0, calls: 0 };
186
- byEntity[call.entityId] = { durationMs: previous.durationMs + performance.now() - callStarted, calls: previous.calls + 1 };
468
+ const rawOutputBytes = encoder.encode(output).byteLength;
469
+ if (rawOutputBytes > 64 * 1024) {
470
+ throw new Error(`Output exceeds 64 KiB (${rawOutputBytes} bytes in call ${results.length + 1})`);
471
+ }
472
+ const parsed = JSON.parse(output);
473
+ const envelope = envelopeSchema.parse(parsed);
474
+ const value = plan === undefined ? envelope.value
475
+ : { state: commitScriptHooks(envelope.value.state, plan, input.tick), commands: envelope.value.commands };
476
+ if (value.commands.length > call.maxCommands) {
477
+ throw new Error(`Game script command limit exceeded for ${call.entityId}`);
478
+ }
479
+ const itemBytes = encoder.encode(JSON.stringify({ entityId: call.entityId, value })).byteLength;
480
+ serializedResultsBytes += itemBytes + (results.length > 0 ? 1 : 0);
481
+ const outputBytes = encoder.encode(JSON.stringify({ results: [], rngState: envelope.rngState })).byteLength + serializedResultsBytes;
482
+ if (outputBytes > 64 * 1024) {
483
+ throw new Error(`Output exceeds 64 KiB (${outputBytes} bytes across ${results.length + 1} calls)`);
484
+ }
485
+ checkCallDeadline();
486
+ commandCount += value.commands.length;
487
+ nextRngState = envelope.rngState;
488
+ results.push({ entityId: call.entityId, state: value.state, commands: value.commands });
489
+ }
490
+ catch (error) {
491
+ // A failed batch cannot retain partially evaluated realms.
492
+ worldHandle?.dispose();
493
+ worldHandle = undefined;
494
+ if (shell) {
495
+ disposeRealm(shell);
496
+ shell = undefined;
497
+ }
498
+ if (!persistent && realm) {
499
+ disposeRealm(realm);
500
+ realm = undefined;
501
+ }
502
+ disposeRealms();
503
+ throw new Error(`Game script ${call.sourceKey} for ${call.entityId} at tick ${input.tick} failed: ${error instanceof Error ? error.message : String(error)}`);
504
+ }
505
+ finally {
506
+ worldCall?.end();
507
+ worldHandle?.dispose();
508
+ if (!persistent && realm) {
509
+ disposeRealm(realm);
510
+ }
511
+ }
512
+ checkCallDeadline();
513
+ const previous = byEntity[call.entityId] ?? { durationMs: 0, calls: 0 };
514
+ byEntity[call.entityId] = { durationMs: previous.durationMs + performance.now() - callStarted, calls: previous.calls + 1 };
515
+ }
516
+ assertBeforeDeadline(batchDeadline, batchBudget);
517
+ return { results, rngState: nextRngState, stats: { durationMs: performance.now() - started, commands: commandCount, calls: calls.length, byEntity } };
518
+ };
519
+ const warmCalls = !warmedCommandSchemas.has(commandSchema);
520
+ const warmHooks = hookSources.size > 0 && !warmedHookSchemas.has(commandSchema);
521
+ const warmups = [...(warmCalls ? WARMUP_SOURCES : []), ...(warmHooks ? [HOOK_WARMUP_SOURCE] : [])];
522
+ if (warmups.length > 0) {
523
+ // Run the per-call path once before any tick budget starts, so first-use costs in this process
524
+ // (host and zod parser compilation, QuickJS warm-up) are paid here instead of by the first batch.
525
+ compileObjectParsers(commandSchema);
526
+ const warmupCalls = warmups.map(([key, source]) => {
527
+ sources.set(key, source);
528
+ if (canPersistGameScript(source)) {
529
+ persistentSources.add(key);
530
+ }
531
+ if (key === HOOK_WARMUP_SOURCE[0]) {
532
+ hookSources.add(key);
533
+ }
534
+ return { sourceKey: key, stateKey: key, entityId: key, source: key, state: null, maxCommands: 0, maxTickMs: WARMUP_BATCH_MS };
535
+ });
536
+ try {
537
+ execute(warmupCalls, { tick: 0, world: [] }, 0, [], WARMUP_BATCH_MS);
538
+ if (warmCalls) {
539
+ warmedCommandSchemas.add(commandSchema);
540
+ }
541
+ if (warmHooks) {
542
+ warmedHookSchemas.add(commandSchema);
543
+ }
544
+ }
545
+ catch {
546
+ // The warm-up is only an optimization. Its error path already disposed every realm, including the
547
+ // prepared ones, so batches create realms on demand as they do past PREPARED_REALM_LIMIT. The next runner warms again.
548
+ }
549
+ finally {
550
+ retain(new Set());
551
+ for (const [key] of warmups) {
552
+ sources.delete(key);
553
+ persistentSources.delete(key);
554
+ hookSources.delete(key);
555
+ }
556
+ }
557
+ }
558
+ return {
559
+ hookSources,
560
+ eventSources,
561
+ retain,
562
+ run(calls, input, rngState, world) {
563
+ try {
564
+ retain(new Set(calls.map((call) => call.stateKey)));
565
+ if (calls.length === 0) {
566
+ return { results: [], rngState, stats: { durationMs: 0, commands: 0, calls: 0, byEntity: {} } };
567
+ }
568
+ return execute(calls, input, rngState, world, SCRIPT_BATCH_MS);
569
+ }
570
+ catch (error) {
571
+ disposeRealms();
572
+ throw error;
573
+ }
574
+ finally {
575
+ // Entities without a call in the first batch were not active at start. Later activations compile on demand.
576
+ releasePrepared();
187
577
  }
188
- assertBeforeDeadline(batchDeadline, batchBudget);
189
- return { results, rngState: nextRngState, stats: { durationMs: performance.now() - started, commands: commandCount, calls: calls.length, byEntity } };
190
578
  },
191
579
  dispose() {
580
+ disposeRealms();
192
581
  runtime.dispose();
193
582
  }
194
583
  };
195
584
  }
196
585
  catch (error) {
586
+ disposeRealms();
197
587
  runtime.dispose();
198
588
  throw error;
199
589
  }
200
590
  }
591
+ export function prepareGameScripts(document, options) {
592
+ return prepareIsolatedGameScripts(document, gameScriptCommand, `{
593
+ tick: data.input.tick, pressed: data.input.pressed, justPressed: data.input.justPressed,
594
+ events: data.input.events, entity: {
595
+ id: data.call.entityId, source: data.call.source, x: data.call.x, y: data.call.y,
596
+ velocityX: data.call.velocityX, velocityY: data.call.velocityY, touching: data.call.touching,
597
+ ...(data.call.props === undefined ? undefined
598
+ : { tags: data.call.tags, props: data.call.props, rotation: data.call.rotation, active: data.call.active })
599
+ }, world: data.input.world, state: data.call.state, random: __gameRandom,
600
+ ...(data.params === undefined ? undefined : { params: data.params })
601
+ }`, options);
602
+ }
201
603
  //# sourceMappingURL=scripts.js.map