xstate 6.0.0-alpha.47 → 6.0.0-alpha.49

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 (84) hide show
  1. package/README.md +30 -1
  2. package/dist/{StateMachine-7046f677.cjs.js → StateMachine-0adb3a70.cjs.js} +15 -12
  3. package/dist/{StateMachine-70c06bdd.development.cjs.js → StateMachine-29450e6d.development.cjs.js} +15 -12
  4. package/dist/{StateMachine-74929087.esm.js → StateMachine-2af31c11.esm.js} +10 -7
  5. package/dist/{StateMachine-ee10f67e.development.esm.js → StateMachine-faf50c5c.development.esm.js} +10 -7
  6. package/dist/{createActor-915ea40c.esm.js → createActor-268165d4.esm.js} +79 -23
  7. package/dist/{createActor-ff132afa.development.esm.js → createActor-88709f74.development.esm.js} +79 -23
  8. package/dist/{createActor-6736cbbe.development.cjs.js → createActor-a1e0dffb.development.cjs.js} +78 -25
  9. package/dist/{createActor-bfe8b6bd.cjs.js → createActor-b4dd05ae.cjs.js} +78 -25
  10. package/dist/declarations/src/createMachineFromConfig.d.ts +5 -77
  11. package/dist/declarations/src/fsm/createFSMActor.d.ts +67 -0
  12. package/dist/declarations/src/fsm/index.d.ts +2 -0
  13. package/dist/declarations/src/fsm.d.ts +5 -4
  14. package/dist/declarations/src/scxml/index.d.ts +1 -0
  15. package/dist/declarations/src/scxml/runtime.d.ts +251 -0
  16. package/dist/declarations/src/scxml/scxml.d.ts +19 -0
  17. package/dist/declarations/src/types.d.ts +1 -0
  18. package/dist/{effectDescriptor-8be60443.esm.js → effectDescriptor-30c9a744.esm.js} +1 -1
  19. package/dist/{effectDescriptor-fbe67d5a.development.esm.js → effectDescriptor-39d22100.development.esm.js} +1 -1
  20. package/dist/{effectDescriptor-3c699328.development.cjs.js → effectDescriptor-7ff6802f.development.cjs.js} +1 -1
  21. package/dist/{effectDescriptor-a7e2d4d1.cjs.js → effectDescriptor-be348e50.cjs.js} +1 -1
  22. package/dist/fsm-7a2e9697.cjs.js +777 -0
  23. package/dist/fsm-b804b3e9.esm.js +775 -0
  24. package/dist/fsm-c1316948.development.cjs.js +777 -0
  25. package/dist/fsm-e18a7cb4.development.esm.js +775 -0
  26. package/dist/types-3c3455f7.esm.js +185 -0
  27. package/dist/types-adda3842.development.esm.js +185 -0
  28. package/dist/types-b3fea5bd.development.cjs.js +189 -0
  29. package/dist/types-fbabaeee.cjs.js +189 -0
  30. package/dist/validation-05f1d517.esm.js +8 -0
  31. package/dist/validation-4561b43c.cjs.js +10 -0
  32. package/dist/validation-e69470ad.development.esm.js +8 -0
  33. package/dist/validation-f2714a35.development.cjs.js +10 -0
  34. package/dist/xstate-actors.cjs.js +934 -9
  35. package/dist/xstate-actors.development.cjs.js +934 -9
  36. package/dist/xstate-actors.development.esm.js +932 -2
  37. package/dist/xstate-actors.esm.js +932 -2
  38. package/dist/xstate-durable.cjs.js +2 -2
  39. package/dist/xstate-durable.development.cjs.js +2 -2
  40. package/dist/xstate-durable.development.esm.js +2 -2
  41. package/dist/xstate-durable.esm.js +2 -2
  42. package/dist/xstate-fsm.cjs.d.mts +2 -0
  43. package/dist/xstate-fsm.cjs.d.ts +2 -0
  44. package/dist/xstate-fsm.cjs.js +409 -0
  45. package/dist/xstate-fsm.cjs.mjs +5 -0
  46. package/dist/xstate-fsm.development.cjs.js +409 -0
  47. package/dist/xstate-fsm.development.cjs.mjs +5 -0
  48. package/dist/xstate-fsm.development.esm.js +403 -0
  49. package/dist/xstate-fsm.esm.js +403 -0
  50. package/dist/xstate-fsm.umd.min.js +2 -0
  51. package/dist/xstate-fsm.umd.min.js.map +1 -0
  52. package/dist/xstate-graph.cjs.js +4 -3
  53. package/dist/xstate-graph.development.cjs.js +4 -3
  54. package/dist/xstate-graph.development.esm.js +4 -3
  55. package/dist/xstate-graph.esm.js +4 -3
  56. package/dist/xstate-graph.umd.min.js +1 -1
  57. package/dist/xstate-graph.umd.min.js.map +1 -1
  58. package/dist/xstate-scxml.cjs.d.mts +2 -0
  59. package/dist/xstate-scxml.cjs.d.ts +2 -0
  60. package/dist/xstate-scxml.cjs.js +2387 -0
  61. package/dist/xstate-scxml.cjs.mjs +3 -0
  62. package/dist/xstate-scxml.development.cjs.js +2387 -0
  63. package/dist/xstate-scxml.development.cjs.mjs +3 -0
  64. package/dist/xstate-scxml.development.esm.js +2383 -0
  65. package/dist/xstate-scxml.esm.js +2383 -0
  66. package/dist/xstate-scxml.umd.min.js +26 -0
  67. package/dist/xstate-scxml.umd.min.js.map +1 -0
  68. package/dist/xstate-validation.cjs.js +1 -1
  69. package/dist/xstate-validation.development.cjs.js +1 -1
  70. package/dist/xstate-validation.development.esm.js +1 -1
  71. package/dist/xstate-validation.esm.js +1 -1
  72. package/dist/xstate.cjs.js +143 -1412
  73. package/dist/xstate.development.cjs.js +143 -1412
  74. package/dist/xstate.development.esm.js +143 -1411
  75. package/dist/xstate.esm.js +143 -1411
  76. package/dist/xstate.umd.min.js +1 -1
  77. package/dist/xstate.umd.min.js.map +1 -1
  78. package/fsm/package.json +8 -0
  79. package/package.json +37 -3
  80. package/scxml/package.json +8 -0
  81. package/dist/index-0f498ef2.development.cjs.js +0 -946
  82. package/dist/index-70d56425.development.esm.js +0 -937
  83. package/dist/index-b051c924.esm.js +0 -937
  84. package/dist/index-b3fe59bc.cjs.js +0 -946
@@ -0,0 +1,2387 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var saxes = require('saxes');
6
+ var types = require('./types-fbabaeee.cjs.js');
7
+ var createActor = require('./createActor-b4dd05ae.cjs.js');
8
+ require('./StateMachine-0adb3a70.cjs.js');
9
+ require('./validation-4561b43c.cjs.js');
10
+
11
+ function delayToMs$1(delay) {
12
+ const parsedDelay = createActor.parseDelayToMilliseconds(delay);
13
+ if (parsedDelay !== undefined) return parsedDelay;
14
+ return typeof delay === 'string' ? parseFloat(delay) || 0 : delay;
15
+ }
16
+ function normalizeScxmlEventType$1(eventType) {
17
+ return /^error(\.|$)/.test(eventType) ? `xstate.${eventType}` : eventType;
18
+ }
19
+ function toScxmlEventName(eventType) {
20
+ return eventType.startsWith('xstate.error.') ? eventType.slice('xstate.'.length) : eventType;
21
+ }
22
+ function matchesScxmlEventDescriptor(descriptor, event) {
23
+ if (descriptor === '*') return true;
24
+ if (descriptor.endsWith('.*')) {
25
+ const prefix = descriptor.slice(0, -2);
26
+ return event.type === prefix || event.type.startsWith(`${prefix}.`);
27
+ }
28
+ if (descriptor.startsWith('xstate.done.actor.')) {
29
+ return event.type === 'xstate.done.actor' && event.actorId === descriptor.slice('xstate.done.actor.'.length);
30
+ }
31
+ if (descriptor.startsWith('xstate.done.state.')) {
32
+ return event.type === 'xstate.done.state' && event.stateId === descriptor.slice('xstate.done.state.'.length);
33
+ }
34
+ return event.type === descriptor || event.type.startsWith(`${descriptor}.`);
35
+ }
36
+
37
+ /**
38
+ * Isolated executable-content block. Errors in nested actions stop this block
39
+ * but do not propagate to the surrounding action list. Used to model SCXML's
40
+ * separate <onentry>/<onexit> blocks: each is its own block per spec.
41
+ */
42
+
43
+ function isExpression(value) {
44
+ return !!value && typeof value === 'object' && typeof value['@expr'] === 'string';
45
+ }
46
+ function isCode(value) {
47
+ return !!value && typeof value === 'object' && typeof value['@code'] === 'string';
48
+ }
49
+ function isResolvable(value) {
50
+ return isExpression(value) || isCode(value);
51
+ }
52
+ function isBuiltInActionType(type) {
53
+ return type.startsWith('@xstate.');
54
+ }
55
+ function isScxmlActionType(type) {
56
+ return type.startsWith('scxml.');
57
+ }
58
+ function toPath(parent, key) {
59
+ return typeof key === 'number' ? `${parent}[${key}]` : `${parent}.${key}`;
60
+ }
61
+ function extractSerializableDelays(delays) {
62
+ const result = {};
63
+ if (!delays) {
64
+ return result;
65
+ }
66
+ for (const key of Object.keys(delays)) {
67
+ const value = delays[key];
68
+ if (typeof value === 'number') {
69
+ result[key] = value;
70
+ } else if (value && typeof value === 'object' && typeof value.duration === 'number') {
71
+ result[key] = value.duration;
72
+ }
73
+ }
74
+ return result;
75
+ }
76
+ function mergeSources(json, sources) {
77
+ return {
78
+ actions: sources.actions ?? {},
79
+ guards: sources.guards ?? {},
80
+ actors: sources.actors ?? {},
81
+ delays: {
82
+ ...extractSerializableDelays(json.delays),
83
+ ...(sources.delays ?? {})
84
+ },
85
+ evaluators: sources.evaluators ?? {}
86
+ };
87
+ }
88
+ function createExpressionResolver(expressionLanguage, sources) {
89
+ function getEvaluator(value, path) {
90
+ const lang = value['@lang'] ?? expressionLanguage;
91
+ if (!lang) {
92
+ throw new Error(`Missing @exprLang for expression at ${path}`);
93
+ }
94
+ const evaluator = sources.evaluators[lang];
95
+ if (!evaluator) {
96
+ throw new Error(`Missing evaluator for @lang '${lang}' at ${path}`);
97
+ }
98
+ return evaluator;
99
+ }
100
+ function evaluateResolvable(value, slot, scope, path) {
101
+ const kind = isExpression(value) ? 'expr' : 'code';
102
+ const source = isExpression(value) ? value['@expr'] : value['@code'];
103
+ return getEvaluator(value, path)({
104
+ source,
105
+ kind,
106
+ slot,
107
+ scope,
108
+ path
109
+ });
110
+ }
111
+ function resolveValue(value, slot, scope, path) {
112
+ if (isResolvable(value)) {
113
+ return evaluateResolvable(value, slot, scope, path);
114
+ }
115
+ if (Array.isArray(value)) {
116
+ return value.map((item, index) => resolveValue(item, slot, scope, toPath(path, index)));
117
+ }
118
+ if (!value || typeof value !== 'object') {
119
+ return value;
120
+ }
121
+ const result = {};
122
+ for (const key of Object.keys(value)) {
123
+ result[key] = resolveValue(value[key], slot, scope, toPath(path, key));
124
+ }
125
+ return result;
126
+ }
127
+ function makeScope(x, extra) {
128
+ return {
129
+ context: x.context,
130
+ event: x.event,
131
+ input: x.input,
132
+ self: x.self,
133
+ children: x.children,
134
+ params: x.params,
135
+ ...extra
136
+ };
137
+ }
138
+ function getDurationConfig(value, path) {
139
+ if (!isResolvable(value)) {
140
+ return value;
141
+ }
142
+ return args => delayToMs$1(resolveValue(value, 'delay', makeScope(args), path));
143
+ }
144
+ function assertResolvable(value, path) {
145
+ if (isResolvable(value)) {
146
+ getEvaluator(value, path);
147
+ return;
148
+ }
149
+ if (Array.isArray(value)) {
150
+ value.forEach((item, index) => assertResolvable(item, toPath(path, index)));
151
+ return;
152
+ }
153
+ if (!value || typeof value !== 'object') {
154
+ return;
155
+ }
156
+ for (const key of Object.keys(value)) {
157
+ assertResolvable(value[key], toPath(path, key));
158
+ }
159
+ }
160
+ return {
161
+ evaluateResolvable,
162
+ resolveValue,
163
+ makeScope,
164
+ getDurationConfig,
165
+ assertResolvable
166
+ };
167
+ }
168
+ function toActionArray(actions) {
169
+ return actions === undefined ? [] : Array.isArray(actions) ? actions : [actions];
170
+ }
171
+ function validateChoiceConfig(choice, path) {
172
+ if (!Array.isArray(choice)) {
173
+ return;
174
+ }
175
+ choice.forEach((branch, index) => {
176
+ if (branch.when === undefined && index !== choice.length - 1) {
177
+ throw new Error(`Choice fallback branch at ${path}[${index}] must be last.`);
178
+ }
179
+ });
180
+ }
181
+ function assertMachineJSON(json, resolvedSources, expressionResolver) {
182
+ const {
183
+ assertResolvable
184
+ } = expressionResolver;
185
+ function assertCondition(condition, path) {
186
+ if (!condition) {
187
+ return;
188
+ }
189
+ if (isResolvable(condition)) {
190
+ assertResolvable(condition, path);
191
+ return;
192
+ }
193
+ assertResolvable(condition.params, `${path}.params`);
194
+ if (json.guards?.[condition.type]) {
195
+ assertCondition(json.guards[condition.type].when, `$.guards.${condition.type}.when`);
196
+ return;
197
+ }
198
+ if (!resolvedSources.guards[condition.type] && !['scxml.cond', 'xstate.stateIn', 'xstate.not'].includes(condition.type)) {
199
+ throw new Error(`Missing guard source "${condition.type}"`);
200
+ }
201
+ }
202
+ function assertAction(action, path, stack = []) {
203
+ if (isResolvable(action)) {
204
+ assertResolvable(action, path);
205
+ return;
206
+ }
207
+ if (!action || typeof action.type !== 'string') {
208
+ throw new Error(`Invalid action at ${path}`);
209
+ }
210
+ assertResolvable(action.params, `${path}.params`);
211
+ if (isBuiltInActionType(action.type) || isScxmlActionType(action.type)) {
212
+ assertResolvable(action, path);
213
+ return;
214
+ }
215
+ const definition = json.actions?.[action.type];
216
+ if (definition) {
217
+ if (stack.includes(action.type)) {
218
+ throw new Error(`Circular action reference: ${stack.concat(action.type).join(' -> ')}`);
219
+ }
220
+ const definitions = Array.isArray(definition) ? definition : [definition];
221
+ definitions.forEach((item, index) => assertAction(item, `${path}.actions.${action.type}${definitions.length > 1 ? `[${index}]` : ''}`, stack.concat(action.type)));
222
+ return;
223
+ }
224
+ if (!resolvedSources.actions[action.type]) {
225
+ throw new Error(`Missing action source "${action.type}"`);
226
+ }
227
+ }
228
+ function assertActions(actions, path) {
229
+ toActionArray(actions).forEach((action, index) => assertAction(action, `${path}[${index}]`));
230
+ }
231
+ function assertTransition(transition, path) {
232
+ const transitions = Array.isArray(transition) ? transition : transition ? [transition] : [];
233
+ transitions.forEach((t, index) => {
234
+ const transitionPath = Array.isArray(transition) ? `${path}[${index}]` : path;
235
+ if (isResolvable(t)) {
236
+ assertResolvable(t, transitionPath);
237
+ return;
238
+ }
239
+ assertCondition(t.guard, `${transitionPath}.guard`);
240
+ assertActions(t.actions, `${transitionPath}.actions`);
241
+ assertResolvable(t.context, `${transitionPath}.context`);
242
+ assertResolvable(t.input, `${transitionPath}.input`);
243
+ });
244
+ }
245
+ function assertStateNode(node, path) {
246
+ if ((node.type === 'history' || node.history !== undefined) && !(typeof node.target === 'string' && node.target.trim().length > 0 || Array.isArray(node.target) && node.target.length > 0 && node.target.every(target => target.trim().length > 0))) {
247
+ throw new Error(`History state at ${path} must declare a non-empty target.`);
248
+ }
249
+ assertResolvable(node.context, `${path}.context`);
250
+ assertResolvable(node.input, `${path}.input`);
251
+ assertResolvable(node.output, `${path}.output`);
252
+ assertResolvable(node.timeout, `${path}.timeout`);
253
+ assertActions(node.entry, `${path}.entry`);
254
+ assertActions(node.exit, `${path}.exit`);
255
+ if (node.type === 'choice') {
256
+ if (!node.choice) {
257
+ throw new Error(`Choice state at ${path} must declare choice.`);
258
+ }
259
+ if (Array.isArray(node.choice)) {
260
+ validateChoiceConfig(node.choice, `${path}.choice`);
261
+ node.choice.forEach((branch, index) => {
262
+ assertCondition(branch.when, `${path}.choice[${index}].when`);
263
+ assertResolvable(branch.context, `${path}.choice[${index}].context`);
264
+ assertResolvable(branch.input, `${path}.choice[${index}].input`);
265
+ });
266
+ } else {
267
+ assertResolvable(node.choice, `${path}.choice`);
268
+ }
269
+ }
270
+ if (isResolvable(node.route)) {
271
+ assertResolvable(node.route, `${path}.route`);
272
+ }
273
+ if (node.invoke) {
274
+ const invokes = Array.isArray(node.invoke) ? node.invoke : [node.invoke];
275
+ invokes.forEach((invoke, index) => {
276
+ const invokePath = `${path}.invoke${Array.isArray(node.invoke) ? `[${index}]` : ''}`;
277
+ const extInv = invoke;
278
+ if (!extInv._nestedScxmlIR && !resolvedSources.actors[invoke.src]) {
279
+ throw new Error(`Missing actor source "${invoke.src}"`);
280
+ }
281
+ assertResolvable(invoke.input, `${invokePath}.input`);
282
+ assertResolvable(invoke.timeout, `${invokePath}.timeout`);
283
+ assertTransition(invoke.onDone, `${invokePath}.onDone`);
284
+ assertTransition(invoke.onError, `${invokePath}.onError`);
285
+ assertTransition(invoke.onSnapshot, `${invokePath}.onSnapshot`);
286
+ assertTransition(invoke.onTimeout, `${invokePath}.onTimeout`);
287
+ });
288
+ }
289
+ if (node.on) {
290
+ for (const descriptor of Object.keys(node.on)) {
291
+ assertTransition(node.on[descriptor], `${path}.on.${descriptor}`);
292
+ }
293
+ }
294
+ if (node.after) {
295
+ for (const delay of Object.keys(node.after)) {
296
+ if (Number.isNaN(Number(delay)) && createActor.parseDelayToMilliseconds(delay) === undefined && !json.delays?.[delay] && !resolvedSources.delays[delay]) {
297
+ throw new Error(`Missing delay source "${delay}"`);
298
+ }
299
+ assertTransition(node.after[delay], `${path}.after.${delay}`);
300
+ }
301
+ }
302
+ assertTransition(node.always, `${path}.always`);
303
+ assertTransition(node.onError, `${path}.onError`);
304
+ assertTransition(node.onTimeout, `${path}.onTimeout`);
305
+ if (node.states) {
306
+ for (const key of Object.keys(node.states)) {
307
+ assertStateNode(node.states[key], `${path}.states.${key}`);
308
+ }
309
+ }
310
+ }
311
+ if (json.actions) {
312
+ for (const key of Object.keys(json.actions)) {
313
+ const actions = Array.isArray(json.actions[key]) ? json.actions[key] : [json.actions[key]];
314
+ actions.forEach((action, index) => assertAction(action, `$.actions.${key}${actions.length > 1 ? `[${index}]` : ''}`, [key]));
315
+ }
316
+ }
317
+ if (json.guards) {
318
+ for (const key of Object.keys(json.guards)) {
319
+ assertCondition(json.guards[key].when, `$.guards.${key}.when`);
320
+ }
321
+ }
322
+ if (json.delays) {
323
+ for (const key of Object.keys(json.delays)) {
324
+ const delay = json.delays[key];
325
+ assertResolvable(delay && typeof delay === 'object' && 'duration' in delay ? delay.duration : delay, `$.delays.${key}`);
326
+ }
327
+ }
328
+ assertStateNode(json, '$');
329
+ }
330
+ const SCXML_SYSTEM_VARIABLES = new Set(['_sessionid', '_name', '_ioprocessors', '_event', '_xstateScxmlInputKeys']);
331
+ const scxmlScriptEnvironments = new WeakMap();
332
+ const scxmlMachineNames = new WeakMap();
333
+ const scxmlIoProcessors = new WeakMap();
334
+ const scxmlEvents = new WeakMap();
335
+ const scxmlEnteringStates = new WeakMap();
336
+ function getScxmlIoProcessors(self, sessionId) {
337
+ let processors = scxmlIoProcessors.get(self);
338
+ if (!processors) {
339
+ const processor = {
340
+ location: `#_scxml_${sessionId}`
341
+ };
342
+ processors = {
343
+ scxml: processor,
344
+ 'http://www.w3.org/TR/scxml/#SCXMLEventProcessor': processor
345
+ };
346
+ scxmlIoProcessors.set(self, processors);
347
+ }
348
+ return processors;
349
+ }
350
+ function getFunctionDeclarations(code) {
351
+ const declarations = [];
352
+ const pattern = /\bfunction\s+[$_a-zA-Z][$_a-zA-Z0-9]*\s*\([^)]*\)\s*\{/g;
353
+ for (const match of code.matchAll(pattern)) {
354
+ let depth = 1;
355
+ let index = match.index + match[0].length;
356
+ while (index < code.length && depth) {
357
+ if (code[index] === '{') depth++;
358
+ if (code[index] === '}') depth--;
359
+ index++;
360
+ }
361
+ declarations.push(code.slice(match.index, index));
362
+ }
363
+ return declarations;
364
+ }
365
+
366
+ /** Evaluates an SCXML expression with context variables available via `with`. */
367
+ function evaluateExpr(context, expr, event, self) {
368
+ const normalizedExpr = expr.replace(/;+\s*$/, '');
369
+ const sessionId = self?.sessionId ?? 'session_scxml';
370
+ const machineName = self ? scxmlMachineNames.get(self) ?? '(machine)' : '(machine)';
371
+ const dataContext = Object.fromEntries(Object.entries(context).filter(([key]) => !SCXML_SYSTEM_VARIABLES.has(key)));
372
+ const fnBody = `
373
+ ${self ? scxmlScriptEnvironments.get(self)?.declarations.join('\n') ?? '' : ''}
374
+ with (context) {
375
+ return (${normalizedExpr});
376
+ }
377
+ `.trim();
378
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
379
+ const fn = new Function('context', '_event', '_sessionid', '_name', '_ioprocessors', 'In', fnBody);
380
+ const In = stateId => {
381
+ if (!self) return false;
382
+ const sanitized = stateId.replace(/\./g, '$');
383
+ if (scxmlEnteringStates.get(self)?.some(id => id === sanitized || id.endsWith('.' + sanitized))) {
384
+ return true;
385
+ }
386
+ try {
387
+ const snap = self.getSnapshot?.();
388
+ if (snap?.nodes) {
389
+ return snap.nodes.some(node => node.id === sanitized || node.id.endsWith('.' + sanitized));
390
+ }
391
+ } catch {
392
+ // ignore
393
+ }
394
+ return false;
395
+ };
396
+ const SCXML_ORIGIN = `#_scxml_${sessionId}`;
397
+ const SCXML_ORIGIN_TYPE = 'http://www.w3.org/TR/scxml/#SCXMLEventProcessor';
398
+ const isExternal = event && event._scxmlExternal;
399
+ const isInitEvent = event && event.type === '@xstate.init';
400
+ // Per SCXML spec, _event has these fields. Fields that don't apply to a
401
+ // particular event are present with value `undefined` (so `'name' in _event`
402
+ // is true but `typeof _event.name === 'undefined'` for unset fields).
403
+ // For xstate.done.* events, _event.data is the `output` payload (matches
404
+ // SCXML's done event semantics where data is the donedata).
405
+ const isDoneEvent = event && typeof event.type === 'string' && event.type.startsWith('xstate.done.');
406
+ const explicitType = event && event._scxmlEventType;
407
+ let scxmlEvent;
408
+ if (event && !isInitEvent) {
409
+ scxmlEvent = scxmlEvents.get(event);
410
+ if (!scxmlEvent) {
411
+ scxmlEvent = {
412
+ name: event._scxmlEventName ?? toScxmlEventName(event.type),
413
+ type: explicitType || (isExternal ? 'external' : 'internal'),
414
+ sendid: event._scxmlSendId,
415
+ origin: isExternal ? SCXML_ORIGIN : undefined,
416
+ origintype: isExternal ? SCXML_ORIGIN_TYPE : undefined,
417
+ invokeid: event._scxmlInvokeId ?? event.actorId,
418
+ data: isDoneEvent ? event.output : event._scxmlEventData !== undefined ? event._scxmlEventData : event
419
+ };
420
+ scxmlEvents.set(event, scxmlEvent);
421
+ }
422
+ }
423
+ const result = fn(dataContext, scxmlEvent, sessionId, machineName, self ? getScxmlIoProcessors(self, sessionId) : {
424
+ scxml: {
425
+ location: `#_scxml_${sessionId}`
426
+ }
427
+ }, In);
428
+ return result;
429
+ }
430
+
431
+ /** Executes an SCXML script block and returns updated context values. */
432
+ function executeScript(context, code, self, global) {
433
+ // Create a proxy to track which properties are modified
434
+ const updates = {};
435
+ const contextKeys = Object.keys(context);
436
+ const mutableContextKeys = contextKeys.filter(key => !SCXML_SYSTEM_VARIABLES.has(key));
437
+
438
+ // Build variable declarations and reassignment capture
439
+ const varDeclarations = mutableContextKeys.map(k => `var ${k} = context.${k};`).join('\n');
440
+ const captureUpdates = mutableContextKeys.map(k => `updates.${k} = ${k};`).join('\n');
441
+ const codeWithoutComments = code.replace(/\/\/.*$/gm, '');
442
+ const declarations = getFunctionDeclarations(code);
443
+ const codeWithoutFunctions = declarations.reduce((source, declaration) => source.replace(declaration, ''), codeWithoutComments);
444
+ const declaredVariables = global ? [...codeWithoutFunctions.matchAll(/\bvar\s+([$_a-zA-Z][$_a-zA-Z0-9]*)/g)].map(match => match[1]) : [];
445
+ const captureVariables = declaredVariables.filter(name => !contextKeys.includes(name) && !SCXML_SYSTEM_VARIABLES.has(name)).map(name => `updates.${name} = ${name};`).join('\n');
446
+ const environment = scxmlScriptEnvironments.get(self) ?? {
447
+ declarations: []
448
+ };
449
+ scxmlScriptEnvironments.set(self, environment);
450
+ for (const declaration of declarations) {
451
+ if (!environment.declarations.includes(declaration)) {
452
+ environment.declarations.push(declaration);
453
+ }
454
+ }
455
+ const fnBody = `
456
+ ${varDeclarations}
457
+ ${environment.declarations.join('\n')}
458
+ ${code}
459
+ ${captureUpdates}
460
+ ${captureVariables}
461
+ return updates;
462
+ `;
463
+ const sessionId = self.sessionId;
464
+ const machineName = scxmlMachineNames.get(self) ?? '(machine)';
465
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
466
+ const fn = new Function('context', 'updates', '_sessionid', '_name', '_ioprocessors', fnBody);
467
+ return fn(context, updates, sessionId, machineName, getScxmlIoProcessors(self, sessionId));
468
+ }
469
+ function createScxmlDomElement(element) {
470
+ const children = (element.children ?? []).map(createScxmlDomElement);
471
+ return {
472
+ tagName: element.name,
473
+ getAttribute: name => element.attributes?.[name] ?? null,
474
+ getElementsByTagName: name => [...(element.name === name ? [createScxmlDomElement(element)] : []), ...children.flatMap(child => child.getElementsByTagName(name))]
475
+ };
476
+ }
477
+ function createMachineFromSCXMLConfig(json, sources = {}) {
478
+ const resolvedSources = mergeSources(json, sources);
479
+ const expressionResolver = createExpressionResolver(json['@exprLang'], resolvedSources);
480
+ const {
481
+ evaluateResolvable,
482
+ resolveValue,
483
+ makeScope,
484
+ getDurationConfig
485
+ } = expressionResolver;
486
+ const sendCounters = new WeakMap();
487
+ function resolveCondition(condition, slot, path) {
488
+ if (!condition) {
489
+ return undefined;
490
+ }
491
+ if (isResolvable(condition)) {
492
+ return args => !!evaluateResolvable(condition, slot, makeScope(args), path);
493
+ }
494
+ return args => {
495
+ const params = resolveValue(condition.params, slot, makeScope(args), `${path}.params`);
496
+ const declarativeGuard = json.guards?.[condition.type];
497
+ if (declarativeGuard) {
498
+ const guard = resolveCondition(declarativeGuard.when, 'guard', `$.guards.${condition.type}.when`);
499
+ return !!guard?.({
500
+ ...args,
501
+ params
502
+ });
503
+ }
504
+ const guardImpl = args.guards?.[condition.type];
505
+ if (!guardImpl) {
506
+ throw new Error(getMissingGuardMessage(condition.type, args.guards ?? {}));
507
+ }
508
+ return guardImpl(args, params);
509
+ };
510
+ }
511
+ function makeChoiceConfig(choice, path) {
512
+ if (!choice) {
513
+ return undefined;
514
+ }
515
+ if (isResolvable(choice)) {
516
+ return args => evaluateResolvable(choice, 'choice', makeScope(args), path);
517
+ }
518
+ validateChoiceConfig(choice, path);
519
+ return args => {
520
+ for (let index = 0; index < choice.length; index++) {
521
+ const branch = choice[index];
522
+ const guard = resolveCondition(branch.when, 'choice', `${path}[${index}].when`);
523
+ if (!guard || guard(args)) {
524
+ return {
525
+ target: branch.target,
526
+ context: branch.context ? resolveValue(branch.context, 'transitionContext', makeScope(args), `${path}[${index}].context`) : undefined,
527
+ input: branch.input !== undefined ? resolveValue(branch.input, 'input', makeScope(args), `${path}[${index}].input`) : undefined,
528
+ description: branch.description,
529
+ reenter: branch.reenter,
530
+ meta: branch.meta
531
+ };
532
+ }
533
+ }
534
+ throw new Error(`Choice state at ${path} did not match any branch.`);
535
+ };
536
+ }
537
+
538
+ // Pending transition actions: set by .to functions, consumed by entry functions.
539
+ // This bridges SCXML's exit→transition→entry action ordering with XState's
540
+ // .to function receiving pre-exit context.
541
+ // Map keyed by target state ID so parallel transitions don't overwrite each other.
542
+ const pendingTransitionActionsMap = {};
543
+
544
+ // Ordered queue of ALL transition actions (targeted + targetless) for parallel
545
+ // context sharing. In SCXML, all transition actions execute sequentially in
546
+ // document order with a shared evolving data model.
547
+ const allTransitionActions = [];
548
+ // Pre-transition context saved when a targetless .to executes. Used by entry
549
+ // functions to re-execute all transition actions from scratch when parallel
550
+ // targetless transitions coexist with targeted transitions.
551
+ let contextBeforeTargetless = null;
552
+ let targetlessEvent = null;
553
+ // Platform errors collected during transition selection (e.g., failing
554
+ // <transition cond>). Drained by the next state's entry into the internal
555
+ // event queue so they're processed before any external events.
556
+ const pendingPlatformErrors = [];
557
+ const scxmlDonedataValues = new WeakMap();
558
+ function evaluateDonedataValue(donedata, context, event, self) {
559
+ if (donedata.params?.length) {
560
+ const out = {};
561
+ for (const param of donedata.params) {
562
+ out[param.name] = evaluateExpr(context, param.expr, event, self);
563
+ }
564
+ return out;
565
+ }
566
+ if (donedata.contentExpr !== undefined) {
567
+ return evaluateExpr(context, donedata.contentExpr, event, self);
568
+ }
569
+ if (donedata.contentText !== undefined) {
570
+ try {
571
+ return evaluateExpr(context, donedata.contentText, event, self);
572
+ } catch {
573
+ return donedata.contentText;
574
+ }
575
+ }
576
+ return undefined;
577
+ }
578
+ function getMissingGuardMessage(type, guards) {
579
+ return `Guard '${type}' is not implemented in machine '${json.id ?? '(machine)'}'. Available guards: ${Object.keys(guards).map(key => `'${key}'`).join(', ') || '(none)'}.`;
580
+ }
581
+ function resolveRouteConfig(route, path) {
582
+ if (!route || typeof route === 'function') {
583
+ return route;
584
+ }
585
+ if (isResolvable(route)) {
586
+ return args => evaluateResolvable(route, 'transition', makeScope(args), path);
587
+ }
588
+ const {
589
+ guard,
590
+ ...routeConfig
591
+ } = route;
592
+ if (!guard) {
593
+ return routeConfig;
594
+ }
595
+ const resolvedGuard = resolveCondition({
596
+ type: guard
597
+ }, 'guard', path);
598
+ return args => resolvedGuard(args) ? routeConfig : undefined;
599
+ }
600
+ function iterNode(node, nodeKey, ancestorIds = []) {
601
+ const originalEntryActions = [...(node._scxmlData?.length ? [{
602
+ type: 'scxml.datamodel',
603
+ data: node._scxmlData
604
+ }] : []), ...toActionArray(node.entry)];
605
+ const stateId = node.id || nodeKey;
606
+
607
+ // Wrap entry to first execute any pending transition actions, then normal entry.
608
+ // This ensures SCXML execution order: exit → transition_actions → entry_actions
609
+ // because pending transition actions are set by .to (before exit) but executed
610
+ // in entry (after exit), thus seeing post-exit context.
611
+ const entryFn = (x, enq) => {
612
+ scxmlMachineNames.set(x.self, json.id ?? '(machine)');
613
+ if (stateId) {
614
+ scxmlEnteringStates.set(x.self, [...ancestorIds, stateId]);
615
+ }
616
+ // Drain any platform errors queued during transition selection (e.g.,
617
+ // failing <transition cond="..."> evaluations). These must be raised
618
+ // internally so they're processed before subsequent external events.
619
+ while (pendingPlatformErrors.length) {
620
+ const err = pendingPlatformErrors.shift();
621
+ enq.raise({
622
+ type: 'xstate.error.execution',
623
+ error: err,
624
+ _scxmlEventType: 'platform',
625
+ _scxmlEventName: 'error.execution',
626
+ _scxmlEventData: err
627
+ });
628
+ }
629
+ let context;
630
+
631
+ // If targetless transitions were interleaved with targeted transitions
632
+ // (parallel state), re-execute ALL transition actions from the original
633
+ // pre-transition context. This overrides any .to-produced context with
634
+ // the correct SCXML document-order sequential execution.
635
+ // Only trigger when BOTH targeted (pending in map) and targetless fired
636
+ // in the same microstep — prevents stale data from previous events.
637
+ if (contextBeforeTargetless && targetlessEvent === x.event && allTransitionActions.length > 0 && Object.keys(pendingTransitionActionsMap).length > 0) {
638
+ let ctx = contextBeforeTargetless;
639
+ for (const actions of allTransitionActions) {
640
+ const mergedX = {
641
+ ...x,
642
+ context: ctx
643
+ };
644
+ const result = executeActions(actions, mergedX, enq);
645
+ if (result.context) {
646
+ ctx = result.context;
647
+ }
648
+ }
649
+ allTransitionActions.length = 0;
650
+ contextBeforeTargetless = null;
651
+ targetlessEvent = null;
652
+ // Clear per-target map since we re-processed everything
653
+ for (const key of Object.keys(pendingTransitionActionsMap)) {
654
+ delete pendingTransitionActionsMap[key];
655
+ }
656
+ context = ctx;
657
+ } else {
658
+ // Normal path: consume pending transition actions for THIS state.
659
+ // In parallel states, each target gets its own pending actions.
660
+ const transActions = stateId ? pendingTransitionActionsMap[stateId] : undefined;
661
+ if (transActions) {
662
+ delete pendingTransitionActionsMap[stateId];
663
+ const result = executeActions(transActions, x, enq);
664
+ if (result.context) {
665
+ context = result.context;
666
+ }
667
+ }
668
+ // Clear stale targetless data from previous microsteps
669
+ contextBeforeTargetless = null;
670
+ targetlessEvent = null;
671
+ allTransitionActions.length = 0;
672
+ }
673
+
674
+ // Execute normal entry actions
675
+ if (originalEntryActions.length) {
676
+ const mergedX = context ? {
677
+ ...x,
678
+ context
679
+ } : x;
680
+ const result = executeActions(originalEntryActions, mergedX, enq);
681
+ if (result.context) {
682
+ context = result.context;
683
+ }
684
+ }
685
+ if (node._scxmlDonedata && stateId) {
686
+ let values = scxmlDonedataValues.get(x.self);
687
+ if (!values) {
688
+ values = new Map();
689
+ scxmlDonedataValues.set(x.self, values);
690
+ }
691
+ try {
692
+ values.set(stateId, evaluateDonedataValue(node._scxmlDonedata, context ?? x.context, x.event, x.self));
693
+ } catch (err) {
694
+ values.set(stateId, undefined);
695
+ raiseErrorExecution({
696
+ enq,
697
+ self: x.self,
698
+ errored: false
699
+ }, 'donedata', err);
700
+ }
701
+ }
702
+ scxmlEnteringStates.delete(x.self);
703
+ return {
704
+ context
705
+ };
706
+ };
707
+ const nodeConfig = {
708
+ id: node.id,
709
+ initial: node._scxmlInitial ? {
710
+ target: node._scxmlInitial.targets,
711
+ to: node._scxmlInitial.actions ? (x, enq) => ({
712
+ ...executeActions(node._scxmlInitial.actions, x, enq),
713
+ target: node._scxmlInitial.targets
714
+ }) : undefined
715
+ } : node.initial,
716
+ type: node.type,
717
+ history: node.history,
718
+ target: node.target,
719
+ _historyDefaultTransition: node._scxmlHistoryActions ? (x, enq) => ({
720
+ ...executeActions(node._scxmlHistoryActions, x, enq),
721
+ target: node.target
722
+ }) : undefined,
723
+ description: node.description,
724
+ tags: node.tags,
725
+ input: node.input,
726
+ timeout: getDurationConfig(node.timeout, `$.states.${nodeKey}.timeout`),
727
+ states: node.states ? Object.entries(node.states).reduce((acc, [key, value]) => {
728
+ acc[key] = iterNode(value, key, stateId ? [...ancestorIds, stateId] : ancestorIds);
729
+ return acc;
730
+ }, {}) : undefined,
731
+ on: node.on ? Object.entries(node.on).reduce((acc, [key, value]) => {
732
+ acc[key] = getTransitionConfig(value);
733
+ return acc;
734
+ }, {}) : undefined,
735
+ always: node.always ? getTransitionConfig(node.always) : undefined,
736
+ onError: node.onError ? getTransitionConfig(node.onError) : undefined,
737
+ choice: makeChoiceConfig(node.choice, `$.states.${nodeKey}.choice`),
738
+ route: resolveRouteConfig(node.route, `$.states.${nodeKey}.route`),
739
+ after: node.after ? Object.entries(node.after).reduce((acc, [key, value]) => {
740
+ acc[key] = getTransitionConfig(value);
741
+ return acc;
742
+ }, {}) : undefined,
743
+ onTimeout: node.onTimeout ? getTransitionConfig(node.onTimeout) : undefined,
744
+ entry: node.type === 'choice' ? undefined : entryFn,
745
+ exit: node.exit ? iterActions(toActionArray(node.exit)) : undefined,
746
+ invoke: node.invoke ? iterInvokeConfigs(node.invoke) : undefined,
747
+ meta: node.meta,
748
+ output: node._scxmlDonedata ? makeDonedataOutput(stateId) : isResolvable(node.output) ? ({
749
+ context,
750
+ event,
751
+ self
752
+ }) => evaluateResolvable(node.output, 'output', {
753
+ context,
754
+ event,
755
+ self
756
+ }, `$.states.${nodeKey}.output`) : node.output
757
+ };
758
+ return nodeConfig;
759
+ }
760
+ function makeDonedataOutput(stateId) {
761
+ return ({
762
+ self
763
+ }) => scxmlDonedataValues.get(self)?.get(stateId);
764
+ }
765
+ function iterInvokeConfigs(invokes) {
766
+ const invokeArray = Array.isArray(invokes) ? invokes : [invokes];
767
+ return invokeArray.map(inv => {
768
+ const extInv = inv;
769
+ // Create child machine from nested SCXML JSON
770
+ let src;
771
+ if (extInv._nestedScxmlIR) {
772
+ src = createMachineFromSCXMLConfig(extInv._nestedScxmlIR, resolvedSources);
773
+ } else {
774
+ src = resolvedSources.actors[inv.src] ?? inv.src;
775
+ }
776
+ return {
777
+ src,
778
+ id: inv.id,
779
+ registryKey: inv.registryKey,
780
+ input: inv._scxmlInput ? ({
781
+ context,
782
+ event,
783
+ self
784
+ }) => {
785
+ const input = {};
786
+ for (const name of inv._scxmlInput.namelist ?? []) {
787
+ if (!(name in context)) {
788
+ throw new ReferenceError(`${name} is not defined`);
789
+ }
790
+ input[name] = context[name];
791
+ }
792
+ for (const param of inv._scxmlInput.params ?? []) {
793
+ input[param.name] = param.expr ? evaluateExpr(context, param.expr, event, self) : param.location ? evaluateExpr(context, param.location, event, self) : undefined;
794
+ }
795
+ return input;
796
+ } : inv.input !== undefined ? args => resolveValue(inv.input, 'input', makeScope(args), '$.invoke.input') : undefined,
797
+ onDone: inv.onDone ? getTransitionConfig(inv.onDone) : undefined,
798
+ onError: inv.onError ? getTransitionConfig(inv.onError) : undefined,
799
+ onSnapshot: inv.onSnapshot ? getTransitionConfig(inv.onSnapshot) : undefined,
800
+ timeout: getDurationConfig(inv.timeout, '$.invoke.timeout'),
801
+ onTimeout: inv.onTimeout ? getTransitionConfig(inv.onTimeout) : undefined
802
+ };
803
+ });
804
+ }
805
+
806
+ /**
807
+ * Raise an SCXML error.execution platform event onto the internal queue. Per
808
+ * spec, error.execution is type='platform' and _event.data contains error
809
+ * info. The surrounding block of executable content stops.
810
+ */
811
+ function raiseErrorExecution(state, tagname, err, sendId) {
812
+ const message = err instanceof Error ? err.message : typeof err === 'string' ? err : 'unknown error';
813
+ const errorEvent = {
814
+ type: 'xstate.error.execution',
815
+ error: {
816
+ tagname,
817
+ message,
818
+ line: 0,
819
+ column: 0,
820
+ reason: message
821
+ },
822
+ _scxmlEventType: 'platform',
823
+ _scxmlEventName: 'error.execution',
824
+ ...(sendId ? {
825
+ _scxmlSendId: sendId
826
+ } : {}),
827
+ _scxmlEventData: {
828
+ tagname,
829
+ message,
830
+ line: 0,
831
+ column: 0,
832
+ reason: message
833
+ }
834
+ };
835
+ state.enq.raise(errorEvent);
836
+ state.errored = true;
837
+ }
838
+ function executeActionDefinition(action, x, enq, params, parentState, stack) {
839
+ const definition = json.actions?.[action.type];
840
+ if (!definition) {
841
+ enq(x.actions[action.type], params);
842
+ return {
843
+ context: undefined,
844
+ errored: parentState.errored
845
+ };
846
+ }
847
+ if (stack.includes(action.type)) {
848
+ raiseErrorExecution(parentState, 'action', new Error(`Circular action reference: ${stack.concat(action.type).join(' -> ')}`));
849
+ return {
850
+ context: undefined,
851
+ errored: true
852
+ };
853
+ }
854
+ const definitions = Array.isArray(definition) ? definition : [definition];
855
+ return executeActions(definitions, {
856
+ ...x,
857
+ params
858
+ }, enq, parentState, stack.concat(action.type));
859
+ }
860
+
861
+ /** Execute an array of SCXML action JSON descriptors with context and enqueue. */
862
+ function executeActions(actions, x, enq, parentState, stack = []) {
863
+ const state = parentState ?? {
864
+ enq,
865
+ self: x.self,
866
+ errored: false
867
+ };
868
+ let context;
869
+ for (const action of actions) {
870
+ if (state.errored) break;
871
+ if (isResolvable(action)) {
872
+ const result = evaluateResolvable(action, 'action', makeScope(x, {
873
+ params: x.params,
874
+ enq
875
+ }), '$.actions');
876
+ if (result && typeof result === 'object' && 'context' in result && result.context) {
877
+ context ??= {};
878
+ Object.assign(context, result.context);
879
+ }
880
+ } else if (isBuiltInActionJSON(action)) {
881
+ switch (action.type) {
882
+ case '@xstate.raise':
883
+ {
884
+ // Tag as external if it has a delay (from <send>, not <raise>).
885
+ // Attach _scxmlSendId so _event.sendid can be read in expressions.
886
+ const isExternal = action.delay !== undefined;
887
+ const resolvedEvent = resolveValue(action.event, 'actionParams', makeScope(x, {
888
+ params: x.params
889
+ }), '$.actions.event');
890
+ const event = isExternal || action.id !== undefined ? {
891
+ ...resolvedEvent,
892
+ ...(isExternal ? {
893
+ _scxmlExternal: true
894
+ } : {}),
895
+ ...(action.id !== undefined ? {
896
+ _scxmlSendId: action.id
897
+ } : {})
898
+ } : resolvedEvent;
899
+ enq.raise(event, {
900
+ id: action.id,
901
+ delay: action.delay
902
+ });
903
+ break;
904
+ }
905
+ case '@xstate.cancel':
906
+ enq.cancel(action.id);
907
+ break;
908
+ case '@xstate.log':
909
+ enq.log(...action.args);
910
+ break;
911
+ case '@xstate.emit':
912
+ enq.emit(resolveValue(action.event, 'actionParams', makeScope(x, {
913
+ params: x.params
914
+ }), '$.actions.event'));
915
+ break;
916
+ case '@xstate.assign':
917
+ context ??= {};
918
+ Object.assign(context, resolveValue(action.context, 'transitionContext', makeScope(x, {
919
+ params: x.params
920
+ }), '$.actions.context'));
921
+ break;
922
+ default:
923
+ throw new Error(`Unknown built-in action: ${action.type}`);
924
+ }
925
+ } else if (action.type === 'scxml.finalize') {
926
+ const finalize = action;
927
+ const invokeId = x.event._scxmlInvokeId ?? x.event.actorId;
928
+ if (invokeId === finalize.invokeId) {
929
+ const result = executeActions(finalize.actions, {
930
+ ...x,
931
+ context: {
932
+ ...x.context,
933
+ ...context
934
+ }
935
+ }, enq, state);
936
+ if (result.context) {
937
+ context = result.context;
938
+ }
939
+ }
940
+ } else if (action.type === 'scxml.forward') {
941
+ const child = x.children?.[action.invokeId];
942
+ if (child) {
943
+ enq.sendTo(child, {
944
+ ...x.event,
945
+ _scxmlExternal: true
946
+ });
947
+ }
948
+ } else if (action.type === 'scxml.log') {
949
+ const scxmlAction = action;
950
+ try {
951
+ const value = scxmlAction.expr ? evaluateExpr({
952
+ ...x.context,
953
+ ...context
954
+ }, scxmlAction.expr, x.event, x.self) : undefined;
955
+ enq.log(...(scxmlAction.label ? [scxmlAction.label, value] : [value]));
956
+ } catch (err) {
957
+ raiseErrorExecution(state, 'log', err);
958
+ }
959
+ } else if (action.type === 'scxml.assign') {
960
+ const scxmlAction = action;
961
+ const mergedContext = {
962
+ ...x.context,
963
+ ...context
964
+ };
965
+ let value;
966
+ try {
967
+ value = evaluateExpr(mergedContext, scxmlAction.expr, x.event, x.self);
968
+ } catch (err) {
969
+ raiseErrorExecution(state, 'assign', err);
970
+ continue;
971
+ }
972
+ if (SCXML_SYSTEM_VARIABLES.has(scxmlAction.location.split('.')[0])) {
973
+ raiseErrorExecution(state, 'assign', new Error(`Cannot assign to SCXML system variable: ${scxmlAction.location}`));
974
+ continue;
975
+ }
976
+ if (scxmlAction.location.includes('.')) {
977
+ const path = scxmlAction.location.split('.');
978
+ const root = path.shift();
979
+ let target = mergedContext[root];
980
+ if (!target || typeof target !== 'object') {
981
+ raiseErrorExecution(state, 'assign', new Error(`Invalid assign location: ${scxmlAction.location}`));
982
+ continue;
983
+ }
984
+ const clonedRoot = Array.isArray(target) ? [...target] : {
985
+ ...target
986
+ };
987
+ target = clonedRoot;
988
+ for (const segment of path.slice(0, -1)) {
989
+ const child = target[segment];
990
+ if (!child || typeof child !== 'object') {
991
+ raiseErrorExecution(state, 'assign', new Error(`Invalid assign location: ${scxmlAction.location}`));
992
+ break;
993
+ }
994
+ const clonedChild = Array.isArray(child) ? [...child] : {
995
+ ...child
996
+ };
997
+ target[segment] = clonedChild;
998
+ target = clonedChild;
999
+ }
1000
+ if (state.errored) continue;
1001
+ target[path.at(-1)] = value;
1002
+ context ??= {};
1003
+ context[root] = clonedRoot;
1004
+ continue;
1005
+ }
1006
+ context ??= {};
1007
+ context[scxmlAction.location] = value;
1008
+ } else if (action.type === 'scxml.datamodel') {
1009
+ const scxmlAction = action;
1010
+ context ??= {};
1011
+ for (const data of scxmlAction.data) {
1012
+ if (Array.isArray(x.context._xstateScxmlInputKeys) && x.context._xstateScxmlInputKeys.includes(data.id)) {
1013
+ continue;
1014
+ }
1015
+ if (data.src) {
1016
+ raiseErrorExecution(state, 'data', new Error(`Unresolved data resource: ${data.src}`));
1017
+ break;
1018
+ }
1019
+ if (data.expr !== undefined) {
1020
+ try {
1021
+ context[data.id] = evaluateExpr({
1022
+ ...x.context,
1023
+ ...context
1024
+ }, data.expr, x.event, x.self);
1025
+ } catch (err) {
1026
+ raiseErrorExecution(state, 'data', err);
1027
+ break;
1028
+ }
1029
+ } else if (data.content !== undefined) {
1030
+ try {
1031
+ context[data.id] = evaluateExpr({
1032
+ ...x.context,
1033
+ ...context
1034
+ }, data.content, x.event, x.self);
1035
+ } catch {
1036
+ context[data.id] = data.content.replace(/\s+/g, ' ').trim();
1037
+ }
1038
+ } else if (data.xml) {
1039
+ context[data.id] = createScxmlDomElement(data.xml);
1040
+ } else {
1041
+ if (x.context[data.id] === undefined) {
1042
+ context[data.id] = undefined;
1043
+ }
1044
+ }
1045
+ }
1046
+ } else if (action.type === 'scxml.raise') {
1047
+ const scxmlAction = action;
1048
+ const mergedContext = {
1049
+ ...x.context,
1050
+ ...context
1051
+ };
1052
+ let eventType;
1053
+ let eventData;
1054
+ let target;
1055
+ let delay;
1056
+ try {
1057
+ if (scxmlAction.processorType && !['scxml', 'http://www.w3.org/TR/scxml/#SCXMLEventProcessor'].includes(scxmlAction.processorType)) {
1058
+ throw new Error(`Unsupported send type: ${scxmlAction.processorType}`);
1059
+ }
1060
+ eventType = scxmlAction.eventexpr ? evaluateExpr(mergedContext, scxmlAction.eventexpr, x.event, x.self) : scxmlAction.event || 'unknown';
1061
+ eventType = normalizeScxmlEventType$1(eventType);
1062
+ eventData = {
1063
+ type: eventType,
1064
+ _scxmlEventName: toScxmlEventName(eventType)
1065
+ };
1066
+ const payload = {};
1067
+ if (scxmlAction.namelist) {
1068
+ for (const name of scxmlAction.namelist) {
1069
+ payload[name] = evaluateExpr(mergedContext, name, x.event, x.self);
1070
+ }
1071
+ }
1072
+ if (scxmlAction.params) {
1073
+ for (const param of scxmlAction.params) {
1074
+ payload[param.name] = evaluateExpr(mergedContext, param.expr ?? param.location, x.event, x.self);
1075
+ }
1076
+ }
1077
+ if (scxmlAction.content) {
1078
+ const content = scxmlAction.content;
1079
+ let contentValue;
1080
+ if (content.expr !== undefined) {
1081
+ contentValue = evaluateExpr(mergedContext, content.expr, x.event, x.self);
1082
+ } else if (content.xml) {
1083
+ contentValue = createScxmlDomElement(content.xml);
1084
+ } else {
1085
+ const text = content.text?.replace(/\s+/g, ' ').trim() ?? '';
1086
+ try {
1087
+ contentValue = evaluateExpr(mergedContext, text, x.event, x.self);
1088
+ } catch {
1089
+ contentValue = text;
1090
+ }
1091
+ }
1092
+ eventData._scxmlEventData = contentValue;
1093
+ } else if (Object.keys(payload).length) {
1094
+ Object.assign(eventData, payload);
1095
+ eventData._scxmlEventData = payload;
1096
+ }
1097
+ if (scxmlAction.idlocation) {
1098
+ const nextId = (sendCounters.get(x.self) ?? 0) + 1;
1099
+ sendCounters.set(x.self, nextId);
1100
+ const generatedId = `${x.self.sessionId}.send.${nextId}`;
1101
+ context ??= {};
1102
+ context[scxmlAction.idlocation] = generatedId;
1103
+ eventData._scxmlSendId = generatedId;
1104
+ }
1105
+ target = scxmlAction.targetexpr ? evaluateExpr(mergedContext, scxmlAction.targetexpr, x.event, x.self) : scxmlAction.target;
1106
+ const isInternalTarget = target === '#_internal';
1107
+ delay = scxmlAction.delayexpr ? delayToMs$1(evaluateExpr(mergedContext, scxmlAction.delayexpr, x.event, x.self)) : isInternalTarget ? undefined : scxmlAction.delay;
1108
+ } catch (err) {
1109
+ raiseErrorExecution(state, 'send', err);
1110
+ continue;
1111
+ }
1112
+ const isInternalTarget = target === '#_internal';
1113
+ const isParentTarget = target === '#_parent';
1114
+ if (!isInternalTarget) {
1115
+ eventData._scxmlExternal = true;
1116
+ }
1117
+ if (isParentTarget) {
1118
+ eventData._scxmlInvokeId = x.self.id;
1119
+ }
1120
+
1121
+ // Validate target. SCXML targets must be '#_internal', '#_parent',
1122
+ // or '#_<id>'. A bare string without the '#_' prefix is invalid and
1123
+ // raises error.execution.
1124
+ if (typeof target === 'string' && target.length > 0 && !target.startsWith('#_')) {
1125
+ raiseErrorExecution(state, 'send', new Error(`Invalid send target: ${target}`), eventData._scxmlSendId);
1126
+ continue;
1127
+ }
1128
+ // Attach send id so _event.sendid can be read in expressions.
1129
+ if (scxmlAction.id !== undefined && eventData._scxmlSendId === undefined) {
1130
+ eventData._scxmlSendId = scxmlAction.id;
1131
+ }
1132
+ // Resolve target at runtime: parent, child, or self
1133
+ if (isParentTarget && x.parent) {
1134
+ // Send to parent via sendTo; pass delay if present
1135
+ enq.sendTo(x.parent, eventData, delay !== undefined ? {
1136
+ delay
1137
+ } : undefined);
1138
+ } else if (typeof target === 'string' && target.startsWith('#_') && !isParentTarget && !isInternalTarget) {
1139
+ // #_<invokeId> → try to send to child actor, fall back to self-raise
1140
+ const childId = target.slice(2); // strip '#_'
1141
+ const childRef = x.children?.[childId];
1142
+ if (childRef) {
1143
+ enq.sendTo(childRef, eventData);
1144
+ } else if (childId.startsWith('scxml_') && childId !== `scxml_${x.self.sessionId}`) {
1145
+ const message = `Unable to dispatch event to target: ${target}`;
1146
+ enq.raise({
1147
+ type: 'xstate.error.communication',
1148
+ error: {
1149
+ tagname: 'send',
1150
+ message,
1151
+ line: NaN,
1152
+ column: NaN,
1153
+ reason: message
1154
+ },
1155
+ _scxmlEventType: 'platform',
1156
+ _scxmlEventName: 'error.communication',
1157
+ _scxmlEventData: {
1158
+ tagname: 'send',
1159
+ message,
1160
+ line: NaN,
1161
+ column: NaN,
1162
+ reason: message
1163
+ }
1164
+ });
1165
+ } else {
1166
+ // This SCXML session id uses the external event queue.
1167
+ eventData._scxmlExternal = true;
1168
+ enq.sendTo(x.self, eventData, {
1169
+ id: scxmlAction.id,
1170
+ delay
1171
+ });
1172
+ }
1173
+ } else {
1174
+ // #_internal uses the internal queue; self-send/no target use the
1175
+ // external event queue.
1176
+ if (isInternalTarget) {
1177
+ enq.raise(eventData, {
1178
+ id: scxmlAction.id,
1179
+ delay
1180
+ });
1181
+ } else {
1182
+ eventData._scxmlExternal = true;
1183
+ enq.sendTo(x.self, eventData, {
1184
+ id: scxmlAction.id,
1185
+ delay
1186
+ });
1187
+ }
1188
+ }
1189
+ } else if (action.type === 'scxml.cancel') {
1190
+ const scxmlAction = action;
1191
+ const mergedContext = {
1192
+ ...x.context,
1193
+ ...context
1194
+ };
1195
+ try {
1196
+ const sendId = evaluateExpr(mergedContext, scxmlAction.sendidexpr, x.event, x.self);
1197
+ if (sendId) {
1198
+ enq.cancel(sendId);
1199
+ }
1200
+ } catch {
1201
+ // ignore evaluation errors
1202
+ }
1203
+ } else if (action.type === 'scxml.script') {
1204
+ const scxmlAction = action;
1205
+ const mergedContext = {
1206
+ ...x.context,
1207
+ ...context
1208
+ };
1209
+ try {
1210
+ const updatedContext = executeScript(mergedContext, scxmlAction.code, x.self, scxmlAction.global ?? false);
1211
+ context ??= {};
1212
+ Object.assign(context, updatedContext);
1213
+ } catch (err) {
1214
+ raiseErrorExecution(state, 'script', err);
1215
+ }
1216
+ } else if (action.type === 'scxml.foreach') {
1217
+ const scxmlAction = action;
1218
+ const mergedContext = {
1219
+ ...x.context,
1220
+ ...context
1221
+ };
1222
+ // SCXML: `item` (and `index` if present) must be valid datamodel
1223
+ // locations — i.e. legal identifiers. Reject things like 'continue'
1224
+ // (string literal) or '7' (number).
1225
+ const isLegalIdentifier = s => /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(s);
1226
+ if (!isLegalIdentifier(scxmlAction.item) || scxmlAction.index && !isLegalIdentifier(scxmlAction.index)) {
1227
+ raiseErrorExecution(state, 'foreach', new Error('foreach item/index is not a legal location'));
1228
+ continue;
1229
+ }
1230
+ let arr;
1231
+ try {
1232
+ arr = evaluateExpr(mergedContext, scxmlAction.array, x.event, x.self);
1233
+ } catch (err) {
1234
+ raiseErrorExecution(state, 'foreach', err);
1235
+ continue;
1236
+ }
1237
+ if (!Array.isArray(arr)) {
1238
+ raiseErrorExecution(state, 'foreach', new Error('foreach array is not iterable'));
1239
+ continue;
1240
+ }
1241
+ context ??= {};
1242
+ for (let i = 0; i < arr.length; i++) {
1243
+ context[scxmlAction.item] = arr[i];
1244
+ if (scxmlAction.index) {
1245
+ context[scxmlAction.index] = i;
1246
+ }
1247
+ const iterX = {
1248
+ ...x,
1249
+ context: {
1250
+ ...x.context,
1251
+ ...context
1252
+ }
1253
+ };
1254
+ const iterResult = executeActions(scxmlAction.actions, iterX, enq, state);
1255
+ if (iterResult.context) {
1256
+ Object.assign(context, iterResult.context);
1257
+ }
1258
+ if (state.errored) break;
1259
+ }
1260
+ } else if (action.type === 'scxml.block') {
1261
+ const scxmlAction = action;
1262
+ const blockX = {
1263
+ ...x,
1264
+ context: {
1265
+ ...x.context,
1266
+ ...context
1267
+ }
1268
+ };
1269
+ // Block has its own ExecState — errors don't propagate to parent.
1270
+ const blockResult = executeActions(scxmlAction.actions, blockX, enq);
1271
+ if (blockResult.context) {
1272
+ context ??= {};
1273
+ for (const key of Object.keys(blockResult.context)) {
1274
+ if (blockResult.context[key] !== x.context[key]) {
1275
+ context[key] = blockResult.context[key];
1276
+ }
1277
+ }
1278
+ }
1279
+ } else if (action.type === 'scxml.if') {
1280
+ const scxmlAction = action;
1281
+ const mergedContext = {
1282
+ ...x.context,
1283
+ ...context
1284
+ };
1285
+ for (const branch of scxmlAction.branches) {
1286
+ let condResult;
1287
+ if (branch.cond) {
1288
+ try {
1289
+ condResult = !!evaluateExpr(mergedContext, branch.cond, x.event, x.self);
1290
+ } catch (err) {
1291
+ raiseErrorExecution(state, 'if', err);
1292
+ condResult = false;
1293
+ }
1294
+ } else {
1295
+ condResult = true;
1296
+ }
1297
+ if (condResult) {
1298
+ if (branch.actions.length) {
1299
+ const branchX = {
1300
+ ...x,
1301
+ context: mergedContext
1302
+ };
1303
+ const branchResult = executeActions(branch.actions, branchX, enq, state);
1304
+ if (branchResult.context) {
1305
+ context ??= {};
1306
+ for (const key of Object.keys(branchResult.context)) {
1307
+ if (branchResult.context[key] !== x.context[key]) {
1308
+ context[key] = branchResult.context[key];
1309
+ }
1310
+ }
1311
+ }
1312
+ }
1313
+ break;
1314
+ }
1315
+ }
1316
+ } else {
1317
+ const params = resolveValue(action.params, 'actionParams', makeScope(x, {
1318
+ params: x.params
1319
+ }), '$.actions.params');
1320
+ const result = executeActionDefinition(action, x, enq, params, state, stack);
1321
+ if (result.context) {
1322
+ context ??= {};
1323
+ Object.assign(context, result.context);
1324
+ }
1325
+ }
1326
+ }
1327
+ return {
1328
+ context: context ? {
1329
+ ...x.context,
1330
+ ...context
1331
+ } : undefined,
1332
+ errored: state.errored
1333
+ };
1334
+ }
1335
+ function iterActions(actions) {
1336
+ return (x, enq) => executeActions(actions, x, enq);
1337
+ }
1338
+ function getFinalizedGuardContext(context, event, self, finalizers) {
1339
+ const invokeId = event._scxmlInvokeId ?? event.actorId;
1340
+ const finalized = {
1341
+ ...context
1342
+ };
1343
+ for (const finalizer of finalizers ?? []) {
1344
+ if (finalizer.invokeId !== invokeId) continue;
1345
+ for (const action of finalizer.actions) {
1346
+ if (!('type' in action) || action.type !== 'scxml.assign') continue;
1347
+ const assignAction = action;
1348
+ finalized[assignAction.location] = evaluateExpr(finalized, assignAction.expr, event, self);
1349
+ }
1350
+ }
1351
+ return finalized;
1352
+ }
1353
+ function getTransitionConfig(transition) {
1354
+ const transitions = Array.isArray(transition) ? transition : [transition];
1355
+
1356
+ // Return an array of transition configs. Each SCXML transition becomes
1357
+ // a separate XState transition with its own guard and optional .to.
1358
+ // This ensures guards are evaluated by XState's evaluateCandidate (once,
1359
+ // with pre-exit context) and NOT re-evaluated in computeEntrySet.
1360
+ return transitions.map((t, index) => {
1361
+ if (isResolvable(t)) {
1362
+ return (x, enq) => evaluateResolvable(t, 'transition', makeScope(x, {
1363
+ enq
1364
+ }), `$.transition${transitions.length > 1 ? `[${index}]` : ''}`);
1365
+ }
1366
+ const target = Array.isArray(t.target) ? t.target[0] : t.target;
1367
+ const targetConfig = t.target;
1368
+ const resolvedGuard = resolveCondition(t.guard, 'guard', '$.transition.guard');
1369
+ const guard = resolvedGuard && t._scxml?.finalize?.length ? args => resolvedGuard({
1370
+ ...args,
1371
+ context: getFinalizedGuardContext(args.context, args.event, args.self, t._scxml.finalize)
1372
+ }) : resolvedGuard;
1373
+ const resolveTransitionContext = x => t.context ? resolveValue(t.context, 'transitionContext', makeScope(x), '$.transition.context') : undefined;
1374
+ const resolveTransitionInput = x => t.input !== undefined ? resolveValue(t.input, 'input', makeScope(x), '$.transition.input') : undefined;
1375
+ const eventMatcher = t._scxml?.eventDescriptors ? event => t._scxml.eventDescriptors.some(descriptor => matchesScxmlEventDescriptor(descriptor, event)) : undefined;
1376
+
1377
+ // No guard and no actions: simple static config
1378
+ if (!guard && !t.actions?.length) {
1379
+ if (t.context) {
1380
+ return {
1381
+ matches: t.matches,
1382
+ _transitionDomain: t._scxml?.type,
1383
+ _eventMatcher: eventMatcher,
1384
+ to: x => ({
1385
+ target: targetConfig,
1386
+ context: resolveTransitionContext(x),
1387
+ reenter: t.reenter
1388
+ }),
1389
+ description: t.description,
1390
+ meta: t.meta,
1391
+ input: t.input !== undefined ? resolveTransitionInput : undefined
1392
+ };
1393
+ }
1394
+ return {
1395
+ matches: t.matches,
1396
+ _transitionDomain: t._scxml?.type,
1397
+ _eventMatcher: eventMatcher,
1398
+ target: targetConfig,
1399
+ description: t.description,
1400
+ reenter: t.reenter,
1401
+ meta: t.meta,
1402
+ input: t.input !== undefined ? resolveTransitionInput : undefined
1403
+ };
1404
+ }
1405
+
1406
+ // Guard but no actions: static config with guard
1407
+ if (guard && !t.actions?.length) {
1408
+ if (t.context) {
1409
+ return {
1410
+ matches: t.matches,
1411
+ _transitionDomain: t._scxml?.type,
1412
+ _eventMatcher: eventMatcher,
1413
+ guard,
1414
+ to: x => ({
1415
+ target: targetConfig,
1416
+ context: resolveTransitionContext(x),
1417
+ reenter: t.reenter
1418
+ }),
1419
+ description: t.description,
1420
+ meta: t.meta,
1421
+ input: t.input !== undefined ? resolveTransitionInput : undefined
1422
+ };
1423
+ }
1424
+ return {
1425
+ matches: t.matches,
1426
+ _transitionDomain: t._scxml?.type,
1427
+ _eventMatcher: eventMatcher,
1428
+ target: targetConfig,
1429
+ guard,
1430
+ description: t.description,
1431
+ reenter: t.reenter,
1432
+ meta: t.meta,
1433
+ input: t.input !== undefined ? resolveTransitionInput : undefined
1434
+ };
1435
+ }
1436
+
1437
+ // Targetless transitions: execute actions directly in .to AND track for
1438
+ // parallel re-execution. For non-parallel, .to result is used directly.
1439
+ // For parallel (entries exist), first entry re-executes all in document order.
1440
+ if (!target) {
1441
+ return {
1442
+ matches: t.matches,
1443
+ _transitionDomain: t._scxml?.type,
1444
+ _eventMatcher: eventMatcher,
1445
+ guard,
1446
+ description: t.description,
1447
+ reenter: t.reenter,
1448
+ meta: t.meta,
1449
+ input: t.input !== undefined ? resolveTransitionInput : undefined,
1450
+ to: (x, enq) => {
1451
+ const context = resolveTransitionContext(x);
1452
+ if (t.actions?.length) {
1453
+ // Track for parallel re-execution (dedup by reference)
1454
+ if (!allTransitionActions.includes(t.actions)) {
1455
+ allTransitionActions.push(t.actions);
1456
+ }
1457
+ // Save pre-transition context for parallel override
1458
+ contextBeforeTargetless ??= x.context;
1459
+ targetlessEvent ??= x.event;
1460
+ // Execute immediately (fallback for non-parallel case)
1461
+ const result = executeActions(t.actions, x, enq);
1462
+ if (result.context) {
1463
+ return {
1464
+ context: {
1465
+ ...context,
1466
+ ...result.context
1467
+ }
1468
+ };
1469
+ }
1470
+ }
1471
+ return context ? {
1472
+ context
1473
+ } : {};
1474
+ }
1475
+ };
1476
+ }
1477
+
1478
+ // Has target + actions: use guard (for XState evaluation) + .to (for pending actions).
1479
+ // The .to function does NOT re-check the guard — XState's evaluateCandidate
1480
+ // already validated it. The .to just stores actions for entry to execute.
1481
+ // Map by target state ID so parallel transitions each get their own actions.
1482
+ return {
1483
+ matches: t.matches,
1484
+ _transitionDomain: t._scxml?.type,
1485
+ _eventMatcher: eventMatcher,
1486
+ guard,
1487
+ description: t.description,
1488
+ reenter: t.reenter,
1489
+ meta: t.meta,
1490
+ input: t.input !== undefined ? resolveTransitionInput : undefined,
1491
+ to: (_x, _enq) => {
1492
+ const context = resolveTransitionContext(_x);
1493
+ if (t.actions?.length) {
1494
+ const targetId = target.replace(/^#/, '');
1495
+ pendingTransitionActionsMap[targetId] = t.actions;
1496
+ // Track for parallel re-execution (dedup by reference)
1497
+ if (!allTransitionActions.includes(t.actions)) {
1498
+ allTransitionActions.push(t.actions);
1499
+ }
1500
+ }
1501
+ return {
1502
+ target: targetConfig,
1503
+ context,
1504
+ reenter: t.reenter
1505
+ };
1506
+ }
1507
+ };
1508
+ });
1509
+ }
1510
+ if (json.delays) {
1511
+ for (const key of Object.keys(json.delays)) {
1512
+ const delay = json.delays[key];
1513
+ if (typeof delay === 'number') {
1514
+ resolvedSources.delays[key] = delay;
1515
+ } else if (typeof delay === 'string') {
1516
+ resolvedSources.delays[key] = delayToMs$1(delay);
1517
+ } else if (delay && typeof delay === 'object') {
1518
+ resolvedSources.delays[key] = args => delayToMs$1(resolveValue(delay.duration, 'delay', makeScope(args), `$.delays.${key}.duration`));
1519
+ }
1520
+ }
1521
+ }
1522
+ assertMachineJSON(json, resolvedSources, expressionResolver);
1523
+ const rootNodeConfig = iterNode(json);
1524
+ const contextConfig = json.context || json._scxmlDataIds?.length ? {
1525
+ context: args => ({
1526
+ ...Object.fromEntries((json._scxmlDataIds ?? []).map(id => [id, undefined])),
1527
+ ...(json.context ? resolveValue(json.context, 'context', args, '$.context') : {}),
1528
+ ...(json._scxmlDataIds?.length && args.input && typeof args.input === 'object' ? args.input : {}),
1529
+ ...(json._scxmlDataIds?.length && args.input && typeof args.input === 'object' ? {
1530
+ _xstateScxmlInputKeys: Object.keys(args.input)
1531
+ } : {})
1532
+ })
1533
+ } : {};
1534
+ const machine = types.createMachine({
1535
+ ...rootNodeConfig,
1536
+ ...contextConfig,
1537
+ version: json.version
1538
+ });
1539
+
1540
+ // Register SCXML guard sources
1541
+ const providedGuards = {
1542
+ 'scxml.cond': ({
1543
+ context,
1544
+ event,
1545
+ self
1546
+ }, params) => {
1547
+ const expr = params?.expr;
1548
+ if (!expr) return true;
1549
+ try {
1550
+ return !!evaluateExpr(context, expr, event, self);
1551
+ } catch (err) {
1552
+ // Per SCXML spec, a cond that fails to evaluate is treated as false
1553
+ // AND raises error.execution. We can't enqueue from a guard, so
1554
+ // queue it for the next entry to drain.
1555
+ const message = err instanceof Error ? err.message : typeof err === 'string' ? err : 'unknown error';
1556
+ pendingPlatformErrors.push({
1557
+ tagname: 'cond',
1558
+ message,
1559
+ line: NaN,
1560
+ column: NaN,
1561
+ reason: message
1562
+ });
1563
+ return false;
1564
+ }
1565
+ },
1566
+ 'xstate.stateIn': (args, params) => {
1567
+ const stateId = params?.stateId;
1568
+ if (!stateId) return false;
1569
+ const normalizedId = stateId.replace(/^#/, '');
1570
+ const snapshot = args._snapshot;
1571
+ if (snapshot?.nodes) {
1572
+ return snapshot.nodes.some(node => node.id === normalizedId);
1573
+ }
1574
+ return false;
1575
+ },
1576
+ 'xstate.not': (args, params) => {
1577
+ const inner = params?.guard;
1578
+ const innerImpl = inner && args.guards?.[inner.type];
1579
+ if (!innerImpl) {
1580
+ throw new Error(`Guard '${inner?.type}' referenced by 'xstate.not' is not implemented.`);
1581
+ }
1582
+ return !innerImpl(args, inner.params);
1583
+ }
1584
+ };
1585
+ const provided = machine.provide({
1586
+ actions: resolvedSources.actions,
1587
+ actors: resolvedSources.actors,
1588
+ guards: {
1589
+ ...providedGuards,
1590
+ ...resolvedSources.guards
1591
+ },
1592
+ delays: resolvedSources.delays
1593
+ });
1594
+
1595
+ // Keep the original JSON so `serializeMachine(machine)`
1596
+ // round-trip losslessly.
1597
+ provided._json = json;
1598
+ return provided;
1599
+ }
1600
+ function isBuiltInActionJSON(action) {
1601
+ return !isResolvable(action) && action.type.startsWith('@xstate.');
1602
+ }
1603
+
1604
+ /**
1605
+ * SCXML machine creation and conversion utilities for the `xstate/scxml`
1606
+ * entry point. Only createMachineFromSCXML and SCXMLConversionOptions are
1607
+ * public; the compiler representation remains internal.
1608
+ */
1609
+ function parseXml(xml) {
1610
+ const root = {
1611
+ elements: []
1612
+ };
1613
+ const stack = [root];
1614
+ const append = element => stack[stack.length - 1].elements.push(element);
1615
+ const parser = new saxes.SaxesParser();
1616
+ parser.on('opentag', tag => {
1617
+ const attributes = {
1618
+ ...tag.attributes
1619
+ };
1620
+ const element = {
1621
+ type: 'element',
1622
+ name: tag.name,
1623
+ ...(Object.keys(attributes).length ? {
1624
+ attributes
1625
+ } : undefined),
1626
+ elements: []
1627
+ };
1628
+ append(element);
1629
+ stack.push(element);
1630
+ });
1631
+ parser.on('closetag', () => {
1632
+ const element = stack.pop();
1633
+ if (!element.elements?.length) {
1634
+ delete element.elements;
1635
+ }
1636
+ });
1637
+ parser.on('text', text => {
1638
+ if (text.trim()) append({
1639
+ type: 'text',
1640
+ text
1641
+ });
1642
+ });
1643
+ parser.on('cdata', cdata => append({
1644
+ type: 'cdata',
1645
+ cdata
1646
+ }));
1647
+ parser.on('comment', text => append({
1648
+ type: 'comment',
1649
+ text
1650
+ }));
1651
+ parser.write(xml).close();
1652
+ return root;
1653
+ }
1654
+ function sanitizeStateId(id) {
1655
+ return id.replace(/\./g, '$');
1656
+ }
1657
+ function normalizeElementNames(element) {
1658
+ if (element.name?.includes(':')) {
1659
+ element.name = element.name.slice(element.name.lastIndexOf(':') + 1);
1660
+ }
1661
+ for (const child of element.elements ?? []) {
1662
+ normalizeElementNames(child);
1663
+ }
1664
+ return element;
1665
+ }
1666
+ function resolveResource(options, src, kind) {
1667
+ if (!options.resolveResource) {
1668
+ throw new Error(`No SCXML resource resolver provided for ${kind}: ${src}`);
1669
+ }
1670
+ return options.resolveResource(src, kind);
1671
+ }
1672
+ function getAttribute(element, attribute) {
1673
+ return element.attributes ? element.attributes[attribute] : undefined;
1674
+ }
1675
+ function toScxmlXmlJSON(element) {
1676
+ return {
1677
+ name: element.name,
1678
+ ...(element.attributes ? {
1679
+ attributes: Object.fromEntries(Object.entries(element.attributes).map(([key, value]) => [key, String(value)]))
1680
+ } : undefined),
1681
+ ...((element.elements ?? []).some(child => child.name) ? {
1682
+ children: (element.elements ?? []).filter(child => child.name).map(toScxmlXmlJSON)
1683
+ } : undefined)
1684
+ };
1685
+ }
1686
+ function getContentDescriptor(element) {
1687
+ if (element.attributes?.expr !== undefined) {
1688
+ return {
1689
+ expr: String(element.attributes.expr)
1690
+ };
1691
+ }
1692
+ const xml = element.elements?.find(child => child.name);
1693
+ if (xml) {
1694
+ return {
1695
+ xml: toScxmlXmlJSON(xml)
1696
+ };
1697
+ }
1698
+ return {
1699
+ text: (element.elements ?? []).filter(child => child.type === 'text' || child.type === 'cdata').map(child => String(child.text ?? child.cdata ?? '')).join('')
1700
+ };
1701
+ }
1702
+ function delayToMs(delay) {
1703
+ if (!delay) {
1704
+ return undefined;
1705
+ }
1706
+ const parsedDelay = createActor.parseDelayToMilliseconds(delay);
1707
+ if (parsedDelay !== undefined) {
1708
+ return parsedDelay;
1709
+ }
1710
+ throw new Error(`Can't parse "${delay} delay."`);
1711
+ }
1712
+ function getTargets(targetAttr) {
1713
+ return targetAttr ? `${targetAttr}`.split(/\s+/).map(target => `#${sanitizeStateId(target)}`) : undefined;
1714
+ }
1715
+ function normalizeScxmlEventType(eventType) {
1716
+ return /^error(\.|$)/.test(eventType) ? `xstate.${eventType}` : eventType;
1717
+ }
1718
+ function parseIfElement(element, options) {
1719
+ const branches = [];
1720
+ let currentCond = element.attributes?.cond;
1721
+ let currentActions = [];
1722
+ if (element.elements) {
1723
+ for (const child of element.elements) {
1724
+ if (child.type === 'comment') continue;
1725
+ if (child.name === 'elseif') {
1726
+ branches.push({
1727
+ cond: currentCond,
1728
+ actions: currentActions
1729
+ });
1730
+ currentCond = child.attributes?.cond;
1731
+ currentActions = [];
1732
+ } else if (child.name === 'else') {
1733
+ branches.push({
1734
+ cond: currentCond,
1735
+ actions: currentActions
1736
+ });
1737
+ currentCond = undefined; // else has no condition
1738
+ currentActions = [];
1739
+ } else {
1740
+ currentActions.push(mapAction(child, options));
1741
+ }
1742
+ }
1743
+ }
1744
+ // Push the last branch
1745
+ branches.push({
1746
+ cond: currentCond,
1747
+ actions: currentActions
1748
+ });
1749
+ return {
1750
+ type: 'scxml.if',
1751
+ branches
1752
+ };
1753
+ }
1754
+ function mapAction(element, options) {
1755
+ switch (element.name) {
1756
+ case 'raise':
1757
+ {
1758
+ const action = {
1759
+ type: '@xstate.raise',
1760
+ event: {
1761
+ type: normalizeScxmlEventType(element.attributes.event)
1762
+ }
1763
+ };
1764
+ return action;
1765
+ }
1766
+ case 'assign':
1767
+ {
1768
+ // SCXML assign uses location and expr attributes
1769
+ const location = element.attributes.location;
1770
+ const expr = element.attributes?.expr !== undefined ? String(element.attributes.expr) : JSON.stringify(toScxmlXmlJSON(element.elements.find(child => child.name)));
1771
+ return {
1772
+ type: 'scxml.assign',
1773
+ location,
1774
+ expr
1775
+ };
1776
+ }
1777
+ case 'cancel':
1778
+ {
1779
+ if ('sendid' in element.attributes) {
1780
+ const action = {
1781
+ type: '@xstate.cancel',
1782
+ id: element.attributes.sendid
1783
+ };
1784
+ return action;
1785
+ }
1786
+ if ('sendidexpr' in element.attributes) {
1787
+ return {
1788
+ type: 'scxml.cancel',
1789
+ sendidexpr: element.attributes.sendidexpr
1790
+ };
1791
+ }
1792
+ return {
1793
+ type: '@xstate.cancel',
1794
+ id: ''
1795
+ };
1796
+ }
1797
+ case 'send':
1798
+ {
1799
+ const {
1800
+ event,
1801
+ eventexpr,
1802
+ target,
1803
+ targetexpr,
1804
+ id,
1805
+ idlocation,
1806
+ delay,
1807
+ delayexpr,
1808
+ namelist,
1809
+ type
1810
+ } = element.attributes;
1811
+
1812
+ // Extract params from child elements
1813
+ const params = [];
1814
+ let content;
1815
+ if (element.elements) {
1816
+ for (const child of element.elements) {
1817
+ if (child.name === 'param') {
1818
+ params.push({
1819
+ name: child.attributes.name,
1820
+ ...(child.attributes.expr !== undefined ? {
1821
+ expr: child.attributes.expr
1822
+ } : {
1823
+ location: child.attributes.location
1824
+ })
1825
+ });
1826
+ } else if (child.name === 'content') {
1827
+ content = getContentDescriptor(child);
1828
+ }
1829
+ }
1830
+ }
1831
+ const isInternal = target === String(types.SpecialTargets.Internal);
1832
+ const resolvedDelay = delay ? delayToMs(delay) : undefined;
1833
+
1834
+ // Any send with a special target (except internal), params, or expressions
1835
+ // uses ScxmlRaiseJSON. Target resolution happens at runtime in executeActions.
1836
+ const hasNonInternalTarget = typeof target === 'string' && target.length > 0 && !isInternal;
1837
+ if (hasNonInternalTarget || params.length || eventexpr || delayexpr || targetexpr || namelist || content || idlocation || type) {
1838
+ const action = {
1839
+ type: 'scxml.raise',
1840
+ event: typeof event === 'string' ? normalizeScxmlEventType(event) : undefined,
1841
+ eventexpr: eventexpr,
1842
+ params: params.length ? params : undefined,
1843
+ namelist: typeof namelist === 'string' ? namelist.trim().split(/\s+/) : undefined,
1844
+ id: id,
1845
+ idlocation: idlocation,
1846
+ delay: resolvedDelay,
1847
+ delayexpr: delayexpr,
1848
+ target: target,
1849
+ targetexpr: targetexpr,
1850
+ processorType: type,
1851
+ content
1852
+ };
1853
+ return action;
1854
+ }
1855
+
1856
+ // Simple send (no special target, no expressions)
1857
+ const action = {
1858
+ type: 'scxml.raise',
1859
+ event: event,
1860
+ eventexpr: undefined,
1861
+ params: undefined,
1862
+ namelist: undefined,
1863
+ id: id,
1864
+ idlocation: idlocation,
1865
+ delay: resolvedDelay,
1866
+ target: target,
1867
+ targetexpr: undefined,
1868
+ processorType: type,
1869
+ content
1870
+ };
1871
+ return action;
1872
+ }
1873
+ case 'log':
1874
+ {
1875
+ const label = element.attributes.label;
1876
+ const expr = element.attributes.expr;
1877
+ const action = {
1878
+ type: 'scxml.log',
1879
+ ...(label !== undefined ? {
1880
+ label: String(label)
1881
+ } : undefined),
1882
+ ...(expr !== undefined ? {
1883
+ expr: String(expr)
1884
+ } : undefined)
1885
+ };
1886
+ return action;
1887
+ }
1888
+ case 'if':
1889
+ {
1890
+ return parseIfElement(element, options);
1891
+ }
1892
+ case 'foreach':
1893
+ {
1894
+ const array = element.attributes.array;
1895
+ const item = element.attributes.item;
1896
+ const index = element.attributes?.index;
1897
+ const actions = element.elements ? mapActions(element.elements, options) : [];
1898
+ const foreach = {
1899
+ type: 'scxml.foreach',
1900
+ array,
1901
+ item,
1902
+ index,
1903
+ actions
1904
+ };
1905
+ return foreach;
1906
+ }
1907
+ case 'script':
1908
+ {
1909
+ if (element.attributes?.src) {
1910
+ return {
1911
+ type: 'scxml.script',
1912
+ code: resolveResource(options, String(element.attributes.src), 'script')
1913
+ };
1914
+ }
1915
+ // Get the script text content
1916
+ const textElement = element.elements?.find(el => el.type === 'text');
1917
+ const code = textElement?.text || '';
1918
+ return {
1919
+ type: 'scxml.script',
1920
+ code: code.trim()
1921
+ };
1922
+ }
1923
+ default:
1924
+ throw new Error(`Conversion of "${element.name}" elements is not implemented yet.`);
1925
+ }
1926
+ }
1927
+ function mapActions(elements, options) {
1928
+ const mapped = [];
1929
+ for (const element of elements) {
1930
+ if (element.type === 'comment') {
1931
+ continue;
1932
+ }
1933
+ mapped.push(mapAction(element, options));
1934
+ }
1935
+ return mapped;
1936
+ }
1937
+ function createGuard(cond) {
1938
+ // Handle In() predicate
1939
+ if (cond.startsWith('In')) {
1940
+ const inMatch = cond.trim().match(/^In\('(.*)'\)/);
1941
+ if (inMatch) {
1942
+ return {
1943
+ type: 'xstate.stateIn',
1944
+ params: {
1945
+ stateId: `#${sanitizeStateId(inMatch[1])}`
1946
+ }
1947
+ };
1948
+ }
1949
+ }
1950
+
1951
+ // Handle !In() predicate
1952
+ if (cond.startsWith('!In')) {
1953
+ const notInMatch = cond.trim().match(/^!In\('(.*)'\)/);
1954
+ if (notInMatch) {
1955
+ return {
1956
+ type: 'xstate.not',
1957
+ params: {
1958
+ guard: {
1959
+ type: 'xstate.stateIn',
1960
+ params: {
1961
+ stateId: `#${sanitizeStateId(notInMatch[1])}`
1962
+ }
1963
+ }
1964
+ }
1965
+ };
1966
+ }
1967
+ }
1968
+
1969
+ // For other conditions, store the expression for runtime evaluation
1970
+ return {
1971
+ type: 'scxml.cond',
1972
+ params: {
1973
+ expr: cond
1974
+ }
1975
+ };
1976
+ }
1977
+ function getDataDescriptors(element, options) {
1978
+ return (element.elements ?? []).filter(child => child.name === 'datamodel').flatMap(datamodel => (datamodel.elements ?? []).filter(child => child.name === 'data').map(data => {
1979
+ const src = data.attributes?.src;
1980
+ const resolvedSource = src !== undefined ? resolveResource(options, String(src), 'data') : undefined;
1981
+ const text = (data.elements ?? []).filter(child => child.type === 'text' || child.type === 'cdata').map(child => String(child.text ?? child.cdata ?? '')).join('').trim();
1982
+ const xml = data.elements?.find(child => child.name);
1983
+ let resourceXml;
1984
+ if (resolvedSource !== undefined) {
1985
+ try {
1986
+ resourceXml = normalizeElementNames(parseXml(resolvedSource)).elements?.find(child => child.name);
1987
+ } catch {
1988
+ resourceXml = undefined;
1989
+ }
1990
+ }
1991
+ return {
1992
+ id: String(data.attributes.id),
1993
+ ...(data.attributes?.expr !== undefined ? {
1994
+ expr: String(data.attributes.expr)
1995
+ } : undefined),
1996
+ ...(resolvedSource !== undefined && !resourceXml ? {
1997
+ content: resolvedSource.trim()
1998
+ } : text ? {
1999
+ content: text
2000
+ } : undefined),
2001
+ ...(resourceXml ? {
2002
+ xml: toScxmlXmlJSON(resourceXml)
2003
+ } : xml ? {
2004
+ xml: toScxmlXmlJSON(xml)
2005
+ } : undefined)
2006
+ };
2007
+ }));
2008
+ }
2009
+ function collectDataDescriptors(element, options) {
2010
+ return [...getDataDescriptors(element, options), ...(element.elements ?? []).filter(child => ['state', 'parallel', 'final'].includes(child.name ?? '')).flatMap(child => collectDataDescriptors(child, options))];
2011
+ }
2012
+ function toStateNodeJSON(nodeJson, id, parentId, binding = 'early', options = {}) {
2013
+ const parallel = nodeJson.name === 'parallel';
2014
+ let initial = parallel ? undefined : nodeJson.attributes?.initial;
2015
+ let initialActions;
2016
+ const hasInitialAttribute = initial !== undefined;
2017
+ const {
2018
+ elements
2019
+ } = nodeJson;
2020
+ const stateId = parentId ? `${parentId}.${id}` : id;
2021
+
2022
+ // Handle history states
2023
+ if (nodeJson.name === 'history') {
2024
+ const history = getAttribute(nodeJson, 'type') || 'shallow';
2025
+ if (!elements) {
2026
+ return {
2027
+ id: sanitizeStateId(id),
2028
+ type: 'history',
2029
+ history
2030
+ };
2031
+ }
2032
+ const [transitionElement] = elements.filter(element => element.name === 'transition');
2033
+ const target = getAttribute(transitionElement, 'target');
2034
+ return {
2035
+ id: sanitizeStateId(id),
2036
+ type: 'history',
2037
+ history,
2038
+ target: target ? `#${sanitizeStateId(target)}` : undefined,
2039
+ ...(transitionElement.elements?.length ? {
2040
+ _scxmlHistoryActions: mapActions(transitionElement.elements, options)
2041
+ } : undefined)
2042
+ };
2043
+ }
2044
+ if (!nodeJson.elements) {
2045
+ return {
2046
+ id: sanitizeStateId(id),
2047
+ ...(nodeJson.name === 'final' ? {
2048
+ type: 'final'
2049
+ } : undefined)
2050
+ };
2051
+ }
2052
+
2053
+ // Parse <donedata> for final states
2054
+ let donedataConfig;
2055
+ if (nodeJson.name === 'final') {
2056
+ const donedataElement = nodeJson.elements.find(el => el.name === 'donedata');
2057
+ if (donedataElement?.elements) {
2058
+ const params = [];
2059
+ let contentExpr;
2060
+ let contentText;
2061
+ for (const child of donedataElement.elements) {
2062
+ if (child.name === 'param') {
2063
+ params.push({
2064
+ name: child.attributes.name,
2065
+ expr: String(child.attributes?.expr ?? child.attributes?.location ?? '').trim()
2066
+ });
2067
+ } else if (child.name === 'content') {
2068
+ if (child.attributes?.expr) {
2069
+ contentExpr = child.attributes.expr;
2070
+ } else if (child.elements) {
2071
+ const textEl = child.elements.find(el => el.type === 'text' || el.type === 'cdata');
2072
+ contentText = textEl ? String(textEl.text ?? textEl.cdata ?? '').trim() : '';
2073
+ }
2074
+ }
2075
+ }
2076
+ donedataConfig = {
2077
+ params,
2078
+ contentExpr,
2079
+ contentText
2080
+ };
2081
+ }
2082
+ }
2083
+ const stateElements = nodeJson.elements.filter(element => element.name === 'state' || element.name === 'parallel' || element.name === 'final' || element.name === 'history');
2084
+ stateElements.forEach((element, index) => {
2085
+ if (element.attributes?.id === undefined) {
2086
+ element.attributes = {
2087
+ ...element.attributes,
2088
+ id: `${id}.anonymous.${index}`
2089
+ };
2090
+ }
2091
+ });
2092
+ const transitionElements = nodeJson.elements.filter(element => element.name === 'transition');
2093
+ const invokeElements = nodeJson.elements.filter(element => element.name === 'invoke');
2094
+ const onEntryElements = nodeJson.elements.filter(element => element.name === 'onentry');
2095
+ const onExitElements = nodeJson.elements.filter(element => element.name === 'onexit');
2096
+ const directScripts = nodeJson.elements.filter(element => element.name === 'script').map(element => ({
2097
+ ...mapAction(element, options),
2098
+ global: true
2099
+ }));
2100
+
2101
+ // Build states object
2102
+ const states = {};
2103
+ for (const stateElement of stateElements) {
2104
+ const childId = sanitizeStateId(`${stateElement.attributes.id}`);
2105
+ states[childId] = toStateNodeJSON(stateElement, childId, stateId, binding, options);
2106
+ }
2107
+
2108
+ // Determine initial state
2109
+ const initialElement = !initial ? nodeJson.elements.find(element => element.name === 'initial') : undefined;
2110
+ if (initialElement && initialElement.elements?.length) {
2111
+ const initialTransition = initialElement.elements.find(element => element.name === 'transition');
2112
+ initial = initialTransition.attributes.target;
2113
+ initialActions = initialTransition.elements?.length ? mapActions(initialTransition.elements, options) : undefined;
2114
+ } else if (!initial && !initialElement && stateElements.length) {
2115
+ initial = stateElements[0].attributes.id;
2116
+ }
2117
+
2118
+ // Build transitions
2119
+ const always = [];
2120
+ const on = {};
2121
+ transitionElements.forEach(value => {
2122
+ const eventTypes = (getAttribute(value, 'event') || '').trim().split(/\s+/);
2123
+ const targets = getAttribute(value, 'target');
2124
+ const internal = getAttribute(value, 'type') === 'internal';
2125
+ const hasTarget = targets !== undefined;
2126
+ const eventDescriptors = eventTypes.filter(Boolean).map(eventType => {
2127
+ if (/^(error|done\.state)(\.|$)/.test(eventType)) {
2128
+ return `xstate.${eventType}`;
2129
+ }
2130
+ if (/^done\.invoke(\.|$)/.test(eventType)) {
2131
+ return eventType.replace(/^done\.invoke/, 'xstate.done.actor');
2132
+ }
2133
+ return eventType;
2134
+ });
2135
+ const transitionConfig = {
2136
+ target: getTargets(targets),
2137
+ _scxml: {
2138
+ ...(hasTarget && {
2139
+ type: internal ? 'internal' : 'external'
2140
+ }),
2141
+ ...(eventDescriptors.length && {
2142
+ eventDescriptors
2143
+ })
2144
+ },
2145
+ ...(value.elements?.length ? {
2146
+ actions: mapActions(value.elements, options)
2147
+ } : undefined),
2148
+ ...(value.attributes?.cond ? {
2149
+ guard: createGuard(value.attributes.cond)
2150
+ } : undefined),
2151
+ ...(hasTarget && !internal && {
2152
+ reenter: true
2153
+ })
2154
+ };
2155
+ if (!eventDescriptors.length) {
2156
+ always.push(transitionConfig);
2157
+ return;
2158
+ }
2159
+ const existing = on['*'];
2160
+ if (!existing) {
2161
+ on['*'] = transitionConfig;
2162
+ } else if (Array.isArray(existing)) {
2163
+ existing.push(transitionConfig);
2164
+ } else {
2165
+ on['*'] = [existing, transitionConfig];
2166
+ }
2167
+ });
2168
+
2169
+ // Build entry/exit actions. Per SCXML, each <onentry>/<onexit> block is a
2170
+ // separate executable-content block — errors in one block must not stop
2171
+ // execution of subsequent blocks. Wrap each block in scxml.block so the
2172
+ // runtime executes them with isolated error state.
2173
+ const entry = [...directScripts, ...onEntryElements.map(onEntryElement => ({
2174
+ type: 'scxml.block',
2175
+ actions: mapActions(onEntryElement.elements || [], options)
2176
+ }))];
2177
+ const exit = onExitElements.length ? onExitElements.map(onExitElement => ({
2178
+ type: 'scxml.block',
2179
+ actions: mapActions(onExitElement.elements || [], options)
2180
+ })) : undefined;
2181
+
2182
+ // Build invokes
2183
+ const invoke = invokeElements.map((element, invokeIndex) => {
2184
+ const invokeType = element.attributes?.type;
2185
+ if (invokeType !== undefined && !['scxml', 'http://www.w3.org/TR/scxml', 'http://www.w3.org/TR/scxml/'].includes(invokeType)) {
2186
+ throw new Error(`Currently only converting invoke elements of type SCXML is supported (received ${String(invokeType)}).`);
2187
+ }
2188
+ const content = element.elements?.find(el => el.name === 'content');
2189
+
2190
+ // Convert nested SCXML content to a machine JSON
2191
+ const nestedScxml = content?.elements?.find(el => el.name === 'scxml');
2192
+ const findEntryAssignment = location => onEntryElements.flatMap(onEntry => onEntry.elements ?? []).find(child => child.name === 'assign' && child.attributes?.location === location);
2193
+ let _nestedScxmlIR;
2194
+ if (nestedScxml) {
2195
+ // Create a wrapper that looks like parser output: { elements: [scxmlElement] }
2196
+ const wrapper = {
2197
+ elements: [nestedScxml]
2198
+ };
2199
+ _nestedScxmlIR = compileScxmlElement(wrapper, options);
2200
+ } else if (element.attributes?.src) {
2201
+ const source = resolveResource(options, String(element.attributes.src), 'invoke');
2202
+ _nestedScxmlIR = compileScxmlElement(normalizeElementNames(parseXml(source)), options);
2203
+ } else if (element.attributes?.srcexpr) {
2204
+ const assignment = findEntryAssignment(String(element.attributes.srcexpr));
2205
+ const assignedSource = String(assignment?.attributes?.expr ?? '').match(/^(['"])(.*)\1$/s)?.[2];
2206
+ if (assignedSource) {
2207
+ _nestedScxmlIR = compileScxmlElement(normalizeElementNames(parseXml(resolveResource(options, assignedSource, 'invoke'))), options);
2208
+ }
2209
+ } else if (content?.attributes?.expr) {
2210
+ const assignment = findEntryAssignment(String(content.attributes.expr));
2211
+ const assignedScxml = assignment?.elements?.find(child => child.name === 'scxml');
2212
+ if (assignedScxml) {
2213
+ _nestedScxmlIR = compileScxmlElement({
2214
+ elements: [assignedScxml]
2215
+ }, options);
2216
+ }
2217
+ }
2218
+ const invokeId = String(element.attributes?.id ?? `${sanitizeStateId(id)}.invoke.${invokeIndex}`);
2219
+ const params = (element.elements ?? []).filter(child => child.name === 'param').map(param => ({
2220
+ name: String(param.attributes.name),
2221
+ ...(param.attributes?.expr !== undefined ? {
2222
+ expr: String(param.attributes.expr)
2223
+ } : undefined),
2224
+ ...(param.attributes?.location !== undefined ? {
2225
+ location: String(param.attributes.location)
2226
+ } : undefined)
2227
+ }));
2228
+ const namelist = String(element.attributes?.namelist ?? '').trim().split(/\s+/).filter(Boolean);
2229
+ if (element.attributes?.idlocation) {
2230
+ entry.push({
2231
+ type: 'scxml.assign',
2232
+ location: String(element.attributes.idlocation),
2233
+ expr: JSON.stringify(invokeId)
2234
+ });
2235
+ }
2236
+ return {
2237
+ id: invokeId,
2238
+ src: 'scxml.nested',
2239
+ _nestedScxmlIR,
2240
+ ...((params.length || namelist.length) && {
2241
+ _scxmlInput: {
2242
+ ...(params.length ? {
2243
+ params
2244
+ } : undefined),
2245
+ ...(namelist.length ? {
2246
+ namelist
2247
+ } : undefined)
2248
+ }
2249
+ })
2250
+ };
2251
+ });
2252
+ const autoForwardIds = invokeElements.flatMap((element, index) => String(element.attributes?.autoforward) === 'true' ? [invoke[index].id] : []);
2253
+ const finalizers = invokeElements.flatMap((element, index) => {
2254
+ const finalize = element.elements?.find(child => child.name === 'finalize');
2255
+ return finalize ? [{
2256
+ invokeId: invoke[index].id,
2257
+ actions: mapActions(finalize.elements ?? [], options)
2258
+ }] : [];
2259
+ });
2260
+ if (finalizers.length) {
2261
+ for (const transitions of Object.values(on)) {
2262
+ for (const transition of Array.isArray(transitions) ? transitions : [transitions]) {
2263
+ transition._scxml = {
2264
+ ...transition._scxml,
2265
+ finalize: finalizers
2266
+ };
2267
+ transition.actions = [...finalizers.map(finalizer => ({
2268
+ type: 'scxml.finalize',
2269
+ ...finalizer
2270
+ })), ...(transition.actions ?? [])];
2271
+ }
2272
+ }
2273
+ }
2274
+ if (autoForwardIds.length) {
2275
+ for (const transitions of Object.values(on)) {
2276
+ for (const transition of Array.isArray(transitions) ? transitions : [transitions]) {
2277
+ transition.actions = [...autoForwardIds.map(invokeId => ({
2278
+ type: 'scxml.forward',
2279
+ invokeId
2280
+ })), ...(transition.actions ?? [])];
2281
+ }
2282
+ }
2283
+ }
2284
+ const resolvedInitial = initial && String(initial).split(' ');
2285
+ const hasExplicitInitial = hasInitialAttribute || !!initialElement;
2286
+ return {
2287
+ id: sanitizeStateId(id),
2288
+ ...(resolvedInitial && !hasExplicitInitial ? {
2289
+ initial: sanitizeStateId(resolvedInitial[0])
2290
+ } : undefined),
2291
+ ...(resolvedInitial && hasExplicitInitial ? {
2292
+ _scxmlInitial: {
2293
+ targets: resolvedInitial.map(target => `#${sanitizeStateId(target)}`),
2294
+ ...(initialActions?.length ? {
2295
+ actions: initialActions
2296
+ } : undefined)
2297
+ }
2298
+ } : undefined),
2299
+ ...(parallel ? {
2300
+ type: 'parallel'
2301
+ } : undefined),
2302
+ ...(nodeJson.name === 'final' ? {
2303
+ type: 'final'
2304
+ } : undefined),
2305
+ ...(donedataConfig ? {
2306
+ _scxmlDonedata: donedataConfig
2307
+ } : undefined),
2308
+ ...(Object.keys(states).length ? {
2309
+ states
2310
+ } : undefined),
2311
+ ...(Object.keys(on).length ? {
2312
+ on
2313
+ } : undefined),
2314
+ ...(always.length ? {
2315
+ always
2316
+ } : undefined),
2317
+ ...(entry.length ? {
2318
+ entry
2319
+ } : undefined),
2320
+ ...(exit?.length ? {
2321
+ exit
2322
+ } : undefined),
2323
+ ...(invoke.length ? {
2324
+ invoke
2325
+ } : undefined),
2326
+ ...(binding === 'late' && getDataDescriptors(nodeJson, options).length ? {
2327
+ _scxmlData: getDataDescriptors(nodeJson, options)
2328
+ } : undefined)
2329
+ };
2330
+ }
2331
+ function compileScxmlElement(scxmlJson, options) {
2332
+ const machineElement = scxmlJson.elements.find(element => element.name === 'scxml');
2333
+ if (!machineElement) {
2334
+ throw new Error('SCXML document must contain an <scxml> root element.');
2335
+ }
2336
+ const binding = machineElement.attributes?.binding === 'late' ? 'late' : 'early';
2337
+ const data = collectDataDescriptors(machineElement, options);
2338
+ const machineId = machineElement.attributes?.name || '(machine)';
2339
+ const stateNodeJSON = toStateNodeJSON(machineElement, machineId, undefined, binding, options);
2340
+ const declaredData = new Set(data.map(({
2341
+ id
2342
+ }) => id));
2343
+ const removeStaticallyInvalidInvokes = node => {
2344
+ if (node.invoke) {
2345
+ const invokes = Array.isArray(node.invoke) ? node.invoke : [node.invoke];
2346
+ const valid = invokes.filter(invocation => (invocation._scxmlInput?.namelist ?? []).every(name => declaredData.has(name)));
2347
+ node.invoke = valid.length ? valid : undefined;
2348
+ }
2349
+ for (const child of Object.values(node.states ?? {})) {
2350
+ removeStaticallyInvalidInvokes(child);
2351
+ }
2352
+ };
2353
+ removeStaticallyInvalidInvokes(stateNodeJSON);
2354
+ return {
2355
+ ...stateNodeJSON,
2356
+ ...(binding === 'early' && data.length ? {
2357
+ _scxmlData: data
2358
+ } : undefined),
2359
+ ...(data.length ? {
2360
+ _scxmlDataIds: data.map(({
2361
+ id
2362
+ }) => id)
2363
+ } : undefined)
2364
+ };
2365
+ }
2366
+
2367
+ /**
2368
+ * Converts an SCXML string to a JSON representation that can be used with
2369
+ * the SCXML runtime compiler.
2370
+ */
2371
+ function compileSCXML(xml, options = {}) {
2372
+ const json = normalizeElementNames(parseXml(xml));
2373
+ return compileScxmlElement(json, options);
2374
+ }
2375
+
2376
+ /**
2377
+ * Creates an XState machine from an SCXML document.
2378
+ *
2379
+ * Expressions and external resources are evaluated using SCXML semantics.
2380
+ * Only create machines from trusted SCXML because ECMAScript expressions and
2381
+ * script elements execute JavaScript in the current environment.
2382
+ */
2383
+ function createMachineFromSCXML(xml, options = {}) {
2384
+ return createMachineFromSCXMLConfig(compileSCXML(xml, options));
2385
+ }
2386
+
2387
+ exports.createMachineFromSCXML = createMachineFromSCXML;