@statelyai/sdk 0.24.0 → 0.26.0

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.
@@ -1,5 +1,6 @@
1
1
  import { a as discriminatedUnion, c as object, d as union, f as unknown, i as custom, l as record, n as array, o as literal, r as boolean, s as number, t as _enum, u as string } from "./openapi-BTDjYWXd.mjs";
2
2
  import ts from "typescript";
3
+ import "xstate";
3
4
  import "xstate/graph";
4
5
 
5
6
  //#region ../../node_modules/.pnpm/js-yaml@4.2.0/node_modules/js-yaml/dist/js-yaml.mjs
@@ -2881,8 +2882,8 @@ function graphToMachineConfig(graph, options = {}) {
2881
2882
  id: inv.invocationId ?? inv.id,
2882
2883
  ...inv.registryKey ? { registryKey: inv.registryKey } : void 0,
2883
2884
  ...inv.timeout !== void 0 ? { timeout: inv.timeout } : void 0,
2884
- ...inv.input ? { input: inv.input } : void 0,
2885
- ...inv.output ? { output: inv.output } : void 0
2885
+ ...inv.input !== void 0 ? { input: inv.input } : void 0,
2886
+ ...inv.output !== void 0 ? { output: inv.output } : void 0
2886
2887
  })) } : void 0,
2887
2888
  ...node.data.output !== void 0 ? { output: node.data.output } : void 0,
2888
2889
  ...tags?.length ? { tags: tags.map(tagToString) } : void 0,
@@ -3436,88 +3437,117 @@ function schemasObjectToValue(node) {
3436
3437
  return result;
3437
3438
  }
3438
3439
  function propertyContext(parent, key) {
3440
+ const inherited = parent.imports ? { imports: parent.imports } : {};
3441
+ if (parent.machineValue && (key === "actors" || key === "actorSources")) return {
3442
+ ...inherited,
3443
+ v6: parent.v6,
3444
+ implementationMap: true
3445
+ };
3439
3446
  if (parent.setupValue && (key === "actions" || key === "guards" || key === "actors" || key === "delays")) return {
3447
+ ...inherited,
3440
3448
  v6: parent.v6,
3441
3449
  implementationMap: true
3442
3450
  };
3443
3451
  if (parent.implementationMap) return {
3452
+ ...inherited,
3444
3453
  v6: parent.v6,
3445
3454
  implementationValue: true
3446
3455
  };
3447
3456
  if (parent.effectArgumentValue) return {
3457
+ ...inherited,
3448
3458
  v6: parent.v6,
3449
3459
  effectArgumentValue: true
3450
3460
  };
3451
3461
  if (parent.invokeValue && key === "src") return {
3462
+ ...inherited,
3452
3463
  v6: parent.v6,
3453
3464
  actorSourceValue: true
3454
3465
  };
3455
3466
  if (parent.transitionMap) return {
3467
+ ...inherited,
3456
3468
  v6: parent.v6,
3457
3469
  transitionValue: true
3458
3470
  };
3459
3471
  if (parent.transitionValue && key === "actions") return {
3472
+ ...inherited,
3460
3473
  v6: parent.v6,
3461
3474
  actionValue: true
3462
3475
  };
3463
3476
  if (parent.transitionValue && key === "context") return {
3477
+ ...inherited,
3464
3478
  v6: parent.v6,
3465
3479
  assignmentMap: true,
3466
3480
  transitionContext: true
3467
3481
  };
3468
3482
  if (key === "context") return {
3483
+ ...inherited,
3469
3484
  v6: parent.v6,
3470
3485
  machineContextValue: true
3471
3486
  };
3472
3487
  if (parent.transitionValue && key === "target") return {
3488
+ ...inherited,
3473
3489
  v6: parent.v6,
3474
3490
  targetValue: true
3475
3491
  };
3476
3492
  if (parent.assignmentMap) return {
3493
+ ...inherited,
3477
3494
  v6: parent.v6,
3478
3495
  assignmentValue: true
3479
3496
  };
3480
3497
  if (key === "meta") return {
3498
+ ...inherited,
3481
3499
  v6: parent.v6,
3482
3500
  metaValue: true
3483
3501
  };
3484
3502
  if (parent.transitionValue && key === "to") return {
3503
+ ...inherited,
3485
3504
  v6: parent.v6,
3486
3505
  transitionValue: true
3487
3506
  };
3488
3507
  if (key === "entry" || key === "exit") return {
3508
+ ...inherited,
3489
3509
  v6: parent.v6,
3490
3510
  actionValue: true
3491
3511
  };
3492
3512
  if (key === "input" || key === "output") return {
3513
+ ...inherited,
3493
3514
  v6: parent.v6,
3494
3515
  ioValue: true
3495
3516
  };
3496
3517
  if (parent.ioValue || parent.ioPropertyValue) return {
3518
+ ...inherited,
3497
3519
  v6: parent.v6,
3498
3520
  ioPropertyValue: true
3499
3521
  };
3500
3522
  if (key === "invoke") return {
3523
+ ...inherited,
3501
3524
  v6: parent.v6,
3502
3525
  invokeValue: true
3503
3526
  };
3504
3527
  if (key === "timeout") return {
3528
+ ...inherited,
3505
3529
  v6: parent.v6,
3506
3530
  timeoutValue: true
3507
3531
  };
3508
3532
  if (key === "route") return {
3533
+ ...inherited,
3509
3534
  v6: parent.v6,
3510
3535
  routeValue: true
3511
3536
  };
3512
3537
  if (key === "on" || key === "after") return {
3538
+ ...inherited,
3513
3539
  v6: parent.v6,
3514
3540
  transitionMap: true
3515
3541
  };
3516
3542
  if (key === "always" || key === "choice" || key === "onDone" || key === "onError" || key === "onSnapshot" || key === "onTimeout") return {
3543
+ ...inherited,
3517
3544
  v6: parent.v6,
3518
3545
  transitionValue: true
3519
3546
  };
3520
- return { v6: parent.v6 };
3547
+ return {
3548
+ ...inherited,
3549
+ v6: parent.v6
3550
+ };
3521
3551
  }
3522
3552
  function fallbackFunctionTransition(fn) {
3523
3553
  return { meta: {
@@ -3531,7 +3561,7 @@ function conditionText(cond) {
3531
3561
  function simplifyConditions(conds) {
3532
3562
  const seen = /* @__PURE__ */ new Set();
3533
3563
  return conds.filter((cond) => {
3534
- if (cond.negated) return false;
3564
+ if (cond.negated && !cond.preserveNegation) return false;
3535
3565
  const key = conditionText(cond);
3536
3566
  if (seen.has(key)) return false;
3537
3567
  seen.add(key);
@@ -3755,18 +3785,21 @@ function statementBranches(statements, bindings, enqName, prefixes = [{
3755
3785
  ...prefix,
3756
3786
  conds: [...prefix.conds, { text: cond }]
3757
3787
  }]);
3788
+ const thenHasEffectiveTransition = thenBranches.every((branch) => branch.result !== void 0 && branch.result !== null || branch.actions.length > 0);
3758
3789
  const elseStatements = statement.elseStatement ? ts.isBlock(statement.elseStatement) ? statement.elseStatement.statements : [statement.elseStatement] : [];
3759
3790
  const elseBranches = elseStatements.length > 0 ? statementBranches(elseStatements, scopedBindings, enqName, [{
3760
3791
  ...prefix,
3761
3792
  conds: [...prefix.conds, {
3762
3793
  text: cond,
3763
- negated: true
3794
+ negated: true,
3795
+ preserveNegation: !thenHasEffectiveTransition
3764
3796
  }]
3765
3797
  }]) : [{
3766
3798
  ...prefix,
3767
3799
  conds: [...prefix.conds, {
3768
3800
  text: cond,
3769
- negated: true
3801
+ negated: true,
3802
+ preserveNegation: !thenHasEffectiveTransition
3770
3803
  }]
3771
3804
  }];
3772
3805
  for (const branch of [...thenBranches, ...elseBranches]) if ("result" in branch) done.push(branch);
@@ -3877,13 +3910,34 @@ function enqueueAction(fn) {
3877
3910
  }
3878
3911
  };
3879
3912
  }
3880
- function inlineCodeExpression(expr) {
3913
+ function inlineCodeExpression(expr, imports) {
3881
3914
  return {
3882
3915
  "@type": "code",
3883
3916
  lang: "ts",
3884
- expr
3917
+ expr,
3918
+ ...imports?.length ? { imports } : {}
3885
3919
  };
3886
3920
  }
3921
+ function codeImportsForExpression(expression, imports) {
3922
+ if (!imports?.size) return void 0;
3923
+ const sourceImports = imports;
3924
+ const file = sourceFile(`(${expression})`);
3925
+ const found = /* @__PURE__ */ new Map();
3926
+ const expressionNode = file.statements[0] && ts.isExpressionStatement(file.statements[0]) ? file.statements[0].expression : void 0;
3927
+ function visit(node) {
3928
+ if (expressionNode && ts.isIdentifier(node) && sourceImports.has(node.text) && !isShadowedWithinExpression(node, expressionNode)) {
3929
+ const parent = node.parent;
3930
+ if (ts.isPropertyAccessExpression(parent) && parent.name === node || ts.isPropertyAssignment(parent) && parent.name === node) {
3931
+ ts.forEachChild(node, visit);
3932
+ return;
3933
+ }
3934
+ found.set(node.text, sourceImports.get(node.text));
3935
+ }
3936
+ ts.forEachChild(node, visit);
3937
+ }
3938
+ visit(file);
3939
+ return found.size ? [...found.values()] : void 0;
3940
+ }
3887
3941
  function normalizeFunctionAction(fn, _bindings) {
3888
3942
  return enqueueAction(fn);
3889
3943
  }
@@ -3948,10 +4002,13 @@ function expressionToValue(expression, bindings, context = {}, depth = 0) {
3948
4002
  if (context.implementationValue) {
3949
4003
  if (ts.isIdentifier(node)) {
3950
4004
  const binding = bindings.get(node.text);
3951
- if (binding) return inlineCodeExpression(ts.isFunctionDeclaration(binding) ? binding.getText() : unwrapExpression(binding).getText());
4005
+ if (binding) {
4006
+ const code = ts.isFunctionDeclaration(binding) ? binding.getText() : unwrapExpression(binding).getText();
4007
+ return inlineCodeExpression(code, codeImportsForExpression(code, context.imports));
4008
+ }
3952
4009
  return;
3953
4010
  }
3954
- return inlineCodeExpression(node.getText());
4011
+ return inlineCodeExpression(node.getText(), codeImportsForExpression(node.getText(), context.imports));
3955
4012
  }
3956
4013
  if (context.machineContextValue && (ts.isArrowFunction(node) || ts.isFunctionExpression(node))) return inlineCodeExpression(node.getText());
3957
4014
  if (context.targetValue) {
@@ -4018,7 +4075,8 @@ function expressionToValue(expression, bindings, context = {}, depth = 0) {
4018
4075
  }
4019
4076
  return expressionToValue(binding, bindings, context, depth + 1);
4020
4077
  }
4021
- return context.metaValue ? inlineCodeExpression(node.getText()) : node.text;
4078
+ const imported = context.imports?.get(node.text);
4079
+ return imported ? inlineCodeExpression(node.text, [imported]) : context.metaValue ? inlineCodeExpression(node.getText()) : node.text;
4022
4080
  }
4023
4081
  if (ts.isObjectLiteralExpression(node)) return objectLiteralToValue(node, bindings, context, depth);
4024
4082
  if (ts.isArrayLiteralExpression(node)) {
@@ -4075,6 +4133,26 @@ function collectBindings(file) {
4075
4133
  }
4076
4134
  return bindings;
4077
4135
  }
4136
+ function collectSourceImports(file) {
4137
+ const imports = /* @__PURE__ */ new Map();
4138
+ for (const statement of file.statements) {
4139
+ if (!ts.isImportDeclaration(statement)) continue;
4140
+ const moduleSpecifier = statement.moduleSpecifier;
4141
+ if (!ts.isStringLiteral(moduleSpecifier)) continue;
4142
+ const namedBindings = statement.importClause?.namedBindings;
4143
+ if (!namedBindings || !ts.isNamedImports(namedBindings)) continue;
4144
+ for (const element of namedBindings.elements) {
4145
+ const imported = element.propertyName?.text ?? element.name.text;
4146
+ imports.set(element.name.text, {
4147
+ package: moduleSpecifier.text,
4148
+ import: imported,
4149
+ local: imported === element.name.text ? void 0 : element.name.text,
4150
+ importKind: "named"
4151
+ });
4152
+ }
4153
+ }
4154
+ return imports;
4155
+ }
4078
4156
  function isCreateMachineCall(node) {
4079
4157
  const expression = node.expression;
4080
4158
  if (ts.isIdentifier(expression)) return isMachineFactoryName(expression.text);
@@ -4173,6 +4251,7 @@ function xstateSourceToConfig(source, options = {}) {
4173
4251
  function extractXStateMachineConfigs(source, options = {}) {
4174
4252
  const file = sourceFile(source);
4175
4253
  const bindings = collectBindings(file);
4254
+ const imports = collectSourceImports(file);
4176
4255
  const found = [];
4177
4256
  const profile = options.profile === "auto" || !options.profile ? detectXStateSourceProfile(source) : options.profile;
4178
4257
  function visit(node) {
@@ -4182,12 +4261,17 @@ function extractXStateMachineConfigs(source, options = {}) {
4182
4261
  }
4183
4262
  const arg = node.arguments[0];
4184
4263
  if (!arg) return;
4185
- const value = expressionToValue(arg, bindings, { v6: profile === "xstate-v6-alpha" });
4264
+ const value = expressionToValue(arg, bindings, {
4265
+ v6: profile === "xstate-v6-alpha",
4266
+ machineValue: true,
4267
+ imports
4268
+ });
4186
4269
  if (value && typeof value === "object" && !Array.isArray(value)) {
4187
4270
  const setupArg = setupCallForCreateMachine(node, bindings)?.arguments[0];
4188
4271
  const setupValue = setupArg ? expressionToValue(setupArg, bindings, {
4189
4272
  v6: profile === "xstate-v6-alpha",
4190
- setupValue: true
4273
+ setupValue: true,
4274
+ imports
4191
4275
  }) : null;
4192
4276
  const setupRecord = setupValue && typeof setupValue === "object" && !Array.isArray(setupValue) ? Object.fromEntries(Object.entries(setupValue).filter(([, item]) => !(item && typeof item === "object" && !Array.isArray(item) && Object.keys(item).length === 0))) : {};
4193
4277
  found.push({
@@ -4231,7 +4315,7 @@ function objectType(schema) {
4231
4315
  const required = getRequiredKeys(schema);
4232
4316
  return `{ ${Object.entries(props).map(([key, def]) => {
4233
4317
  const type = jsonSchemaToTSType(resolveDef(def));
4234
- return `${key}${isRequiredProperty(key, def, required) ? "" : "?"}: ${type}`;
4318
+ return `${key}${isRequiredProperty$1(key, def, required) ? "" : "?"}: ${type}`;
4235
4319
  }).join("; ")} }`;
4236
4320
  }
4237
4321
  function resolveDef(def) {
@@ -4262,7 +4346,7 @@ function eventsSchemaToTSType(events) {
4262
4346
  const required = getRequiredKeys(schema);
4263
4347
  const extraProps = Object.entries(props).filter(([k]) => k !== "type").map(([key, def]) => {
4264
4348
  const type = jsonSchemaToTSType(resolveDef(def));
4265
- return `${key}${isRequiredProperty(key, def, required) ? "" : "?"}: ${type}`;
4349
+ return `${key}${isRequiredProperty$1(key, def, required) ? "" : "?"}: ${type}`;
4266
4350
  });
4267
4351
  if (extraProps.length === 0) return `{ type: '${eventType}' }`;
4268
4352
  return `{ type: '${eventType}'; ${extraProps.join("; ")} }`;
@@ -4271,13 +4355,138 @@ function eventsSchemaToTSType(events) {
4271
4355
  function getRequiredKeys(schema) {
4272
4356
  return new Set(Array.isArray(schema.required) ? schema.required : []);
4273
4357
  }
4274
- function isRequiredProperty(key, def, required) {
4358
+ function isRequiredProperty$1(key, def, required) {
4275
4359
  if (required.has(key)) return true;
4276
4360
  return typeof def === "object" && def !== null && def.required === true;
4277
4361
  }
4362
+ function jsonSchemaToZod(schema) {
4363
+ if (!schema) return "z.unknown()";
4364
+ if (schema.enum) return enumToZod(schema.enum);
4365
+ if (schema.const !== void 0) return `z.literal(${serializeJS(schema.const)})`;
4366
+ if (schema.oneOf) return xorToZod(schema.oneOf);
4367
+ if (schema.anyOf) return unionToZod(schema.anyOf);
4368
+ if (schema.allOf) {
4369
+ const schemas = schema.allOf.map(definitionToZod);
4370
+ if (schemas.length === 0) return "z.unknown()";
4371
+ return schemas.slice(1).reduce((result, next) => `z.intersection(${result}, ${next})`, schemas[0]);
4372
+ }
4373
+ if (Array.isArray(schema.type)) return unionToZod(schema.type.map((type) => ({
4374
+ ...schema,
4375
+ type
4376
+ })));
4377
+ if (schema.type === "array") {
4378
+ const items = schema.items;
4379
+ let result;
4380
+ if (Array.isArray(items)) result = `z.tuple(${serializeJS(items.map((item) => raw(definitionToZod(item))))})`;
4381
+ else result = `z.array(${definitionToZod(items)})`;
4382
+ return applyArrayConstraints(result, schema);
4383
+ }
4384
+ if (schema.type === "object" || schema.properties) return objectToZod(schema);
4385
+ if (schema.type) return primitiveToZod(schema, schema.type);
4386
+ return "z.unknown()";
4387
+ }
4388
+ /** Build a required object schema from the graph's context property map. */
4389
+ function contextSchemaToZod(context) {
4390
+ if (!context || Object.keys(context).length === 0) return null;
4391
+ return `z.object(${serializeJS(Object.fromEntries(Object.entries(context).map(([key, schema]) => [key, raw(jsonSchemaToZod(schema))])))})`;
4392
+ }
4393
+ /** Build an event payload schema without duplicating the discriminant. */
4394
+ function eventSchemaToZod(schema) {
4395
+ const properties = schema.properties ?? {};
4396
+ const payloadProperties = Object.fromEntries(Object.entries(properties).filter(([key]) => key !== "type"));
4397
+ return jsonSchemaToZod({
4398
+ ...schema,
4399
+ properties: payloadProperties,
4400
+ required: Array.isArray(schema.required) ? schema.required.filter((key) => key !== "type") : void 0
4401
+ });
4402
+ }
4403
+ function objectToZod(schema) {
4404
+ const properties = schema.properties ?? {};
4405
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
4406
+ let result = `z.object(${serializeJS(Object.fromEntries(Object.entries(properties).map(([key, definition]) => {
4407
+ return [key, raw(`${definitionToZod(definition)}${isRequiredProperty(key, definition, required) ? "" : ".optional()"}`)];
4408
+ })))})`;
4409
+ if (schema.additionalProperties === false) result += ".strict()";
4410
+ else if (schema.additionalProperties === true || schema.additionalProperties === void 0) result += ".passthrough()";
4411
+ else if (schema.additionalProperties) result += `.catchall(${jsonSchemaToZod(schema.additionalProperties)})`;
4412
+ return result;
4413
+ }
4414
+ function primitiveToZod(schema, type) {
4415
+ let result;
4416
+ switch (type) {
4417
+ case "string":
4418
+ result = "z.string()";
4419
+ if (schema.format === "email") result += ".email()";
4420
+ if (schema.format === "uri" || schema.format === "url") result += ".url()";
4421
+ if (schema.format === "uuid") result += ".uuid()";
4422
+ if (schema.format === "date-time") result += ".datetime({ offset: true })";
4423
+ if (typeof schema.minLength === "number") result += `.min(${schema.minLength})`;
4424
+ if (typeof schema.maxLength === "number") result += `.max(${schema.maxLength})`;
4425
+ if (schema.pattern) result += `.regex(new RegExp(${serializeJS(schema.pattern)}))`;
4426
+ break;
4427
+ case "number":
4428
+ case "integer":
4429
+ result = "z.number()";
4430
+ if (type === "integer") result += ".int()";
4431
+ if (typeof schema.minimum === "number") result += `.min(${schema.minimum})`;
4432
+ if (typeof schema.maximum === "number") result += `.max(${schema.maximum})`;
4433
+ if (typeof schema.exclusiveMinimum === "number") result += `.gt(${schema.exclusiveMinimum})`;
4434
+ if (typeof schema.exclusiveMaximum === "number") result += `.lt(${schema.exclusiveMaximum})`;
4435
+ if (typeof schema.multipleOf === "number") result += `.multipleOf(${schema.multipleOf})`;
4436
+ break;
4437
+ case "boolean":
4438
+ result = "z.boolean()";
4439
+ break;
4440
+ case "null":
4441
+ result = "z.null()";
4442
+ break;
4443
+ case "object":
4444
+ result = objectToZod(schema);
4445
+ break;
4446
+ default:
4447
+ result = "z.unknown()";
4448
+ break;
4449
+ }
4450
+ if (schema.default !== void 0) result += `.default(${serializeJS(schema.default)})`;
4451
+ return result;
4452
+ }
4453
+ function applyArrayConstraints(result, schema) {
4454
+ if (typeof schema.minItems === "number") result += `.min(${schema.minItems})`;
4455
+ if (typeof schema.maxItems === "number") result += `.max(${schema.maxItems})`;
4456
+ return result;
4457
+ }
4458
+ function enumToZod(values) {
4459
+ if (values.length === 0) return "z.never()";
4460
+ if (values.every((value) => typeof value === "string")) {
4461
+ if (values.length === 1) return `z.literal(${serializeJS(values[0])})`;
4462
+ return `z.enum(${serializeJS(values)})`;
4463
+ }
4464
+ return unionToZod(values.map((value) => ({ const: value })));
4465
+ }
4466
+ function unionToZod(definitions) {
4467
+ const schemas = definitions.map(definitionToZod);
4468
+ if (schemas.length === 0) return "z.never()";
4469
+ if (schemas.length === 1) return schemas[0];
4470
+ return `z.union(${serializeJS(schemas.map((schema) => raw(schema)))})`;
4471
+ }
4472
+ function xorToZod(definitions) {
4473
+ const schemas = definitions.map(definitionToZod);
4474
+ if (schemas.length === 0) return "z.never()";
4475
+ if (schemas.length === 1) return schemas[0];
4476
+ return `z.xor(${serializeJS(schemas.map((schema) => raw(schema)))})`;
4477
+ }
4478
+ function definitionToZod(definition) {
4479
+ if (definition === false) return "z.never()";
4480
+ if (definition === true || definition === void 0) return "z.unknown()";
4481
+ return jsonSchemaToZod(definition);
4482
+ }
4483
+ function isRequiredProperty(key, definition, required) {
4484
+ if (required.has(key)) return true;
4485
+ return typeof definition === "object" && definition !== null && definition.required === true;
4486
+ }
4278
4487
  function graphToXStateTS(graph, options = {}) {
4279
4488
  const inferredXStateVersion = isXStateV6ProfileRef(graph.data.profile ?? "xstate-v5") ? 6 : 5;
4280
- const { exportStyle = "named", targetLanguage = "typescript", xstateVersion = inferredXStateVersion, ...configOptions } = options;
4489
+ const { exportStyle = "named", targetLanguage = "typescript", xstateVersion = inferredXStateVersion, xstateV6SchemaFormat = "types", ...configOptions } = options;
4281
4490
  const schemas = graph.data.schemas;
4282
4491
  const impls = filterInlineImplementations(graph.data.implementations);
4283
4492
  const supportsTypeSyntax = targetLanguage === "typescript";
@@ -4286,10 +4495,11 @@ function graphToXStateTS(graph, options = {}) {
4286
4495
  const hasGuards = !!impls?.guards.length;
4287
4496
  const hasActors = !!impls?.actors.length;
4288
4497
  const hasDelays = !!impls?.delays.length;
4289
- const hasSetup = hasSchemas || hasActions || hasGuards || hasActors || hasDelays;
4498
+ const hasSetup = xstateVersion === 6 || hasSchemas || hasActions || hasGuards || hasActors || hasDelays;
4290
4499
  const builtInActions = getUsedBuiltInActions(graph, xstateVersion);
4291
4500
  const actorSourceImports = getActorSourceImports(graph);
4292
4501
  const implementationImports = getImplementationImports(impls);
4502
+ const codeImports = getCodeExpressionImports(graph);
4293
4503
  const imports = buildImports({
4294
4504
  hasSetup,
4295
4505
  hasActors,
@@ -4297,14 +4507,18 @@ function graphToXStateTS(graph, options = {}) {
4297
4507
  builtInActions,
4298
4508
  actorSourceImports,
4299
4509
  implementationImports,
4300
- usesTypes: xstateVersion === 6 && supportsTypeSyntax && hasSchemas
4510
+ codeImports,
4511
+ xstateVersion,
4512
+ usesTypes: xstateVersion === 6 && supportsTypeSyntax && hasSchemas && xstateV6SchemaFormat === "types",
4513
+ usesZod: xstateVersion === 6 && hasSchemas && xstateV6SchemaFormat === "zod"
4301
4514
  });
4302
4515
  const machineConfig = xstateVersion === 6 ? toV6MachineConfig(graphToMachineConfig(graph, configOptions)) : toV5MachineConfig(graphToMachineConfig(graph, configOptions));
4303
4516
  let machineExpr;
4304
4517
  if (hasSetup) {
4305
4518
  const setupObj = buildSetupObject(schemas, impls, {
4306
4519
  includeTypeSyntax: supportsTypeSyntax,
4307
- xstateVersion
4520
+ xstateVersion,
4521
+ xstateV6SchemaFormat
4308
4522
  });
4309
4523
  const configStr = serializeJS(machineConfig, 2);
4310
4524
  machineExpr = `setup(${serializeJS(setupObj, 0)}).createMachine(${configStr})`;
@@ -4408,7 +4622,9 @@ function toV6TransitionValue(value) {
4408
4622
  if (Array.isArray(value)) return buildV6TransitionFunction(value) ?? value.map((item) => toV6TransitionValue(item));
4409
4623
  if (!value || typeof value !== "object") return value;
4410
4624
  const transition = value;
4411
- if (transition.guard || transition.description || transition.input !== void 0) return mapV6MachineConfig(transition);
4625
+ if (transition.matches !== void 0) return buildV6TransitionFunction([transition]) ?? mapV6MachineConfig(transition);
4626
+ if (transition.guard) return buildV6TransitionFunction([transition]) ?? mapV6MachineConfig(transition);
4627
+ if (transition.description || transition.input !== void 0) return mapV6MachineConfig(transition);
4412
4628
  const target = transition.target;
4413
4629
  const context = transition.context;
4414
4630
  const actionsValue = transition.actions;
@@ -4424,7 +4640,20 @@ function toV6TransitionValue(value) {
4424
4640
  }
4425
4641
  function guardCondition(value) {
4426
4642
  const expression = inlineExpr(value);
4427
- if (!expression) return value === void 0 ? { condition: "true" } : null;
4643
+ if (!expression) {
4644
+ if (value === void 0) return { condition: "true" };
4645
+ if (value && typeof value === "object" && !Array.isArray(value)) {
4646
+ const guard = value;
4647
+ if (typeof guard.type === "string") {
4648
+ const params = guard.params === void 0 ? "" : `, ${serializeJS(guard.params)}`;
4649
+ return {
4650
+ condition: `guards[${serializeJS(guard.type)}]({ context, event }${params})`,
4651
+ firstParam: "{ context, event, guards }"
4652
+ };
4653
+ }
4654
+ }
4655
+ return null;
4656
+ }
4428
4657
  const arrow = expression.indexOf("=>");
4429
4658
  if (arrow < 0) return null;
4430
4659
  const params = expression.slice(0, arrow).trim();
@@ -4432,13 +4661,28 @@ function guardCondition(value) {
4432
4661
  if (body.startsWith("{")) return null;
4433
4662
  return {
4434
4663
  condition: body,
4664
+ callCondition: `(${expression})({ context, event, input, output, actions, guards, children, self, system })`,
4435
4665
  firstParam: params.startsWith("(") && params.endsWith(")") ? params.slice(1, -1).trim() : params
4436
4666
  };
4437
4667
  }
4668
+ function matchesCondition(value) {
4669
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
4670
+ const entries = Object.entries(value);
4671
+ if (entries.length === 0) return "true";
4672
+ return entries.map(([key, expected]) => `Object.is(event[${serializeJS(key)}], ${serializeJS(expected)})`).join(" && ");
4673
+ }
4674
+ function combineConditions(match, guard) {
4675
+ if (!match || match === "true") return guard;
4676
+ if (guard === "true") return match;
4677
+ return `${match} && (${guard})`;
4678
+ }
4438
4679
  const V6_ARG_BINDINGS = [
4439
4680
  "context",
4440
4681
  "event",
4682
+ "input",
4683
+ "output",
4441
4684
  "actions",
4685
+ "guards",
4442
4686
  "children",
4443
4687
  "self",
4444
4688
  "system"
@@ -4527,7 +4771,8 @@ function buildV6TransitionFunction(transitions) {
4527
4771
  for (const item of transitions) {
4528
4772
  if (!item || typeof item !== "object" || Array.isArray(item)) return;
4529
4773
  const transition = item;
4530
- if (transition.description !== void 0 || transition.input !== void 0 || transition.matches !== void 0) return;
4774
+ const match = transition.matches === void 0 ? void 0 : matchesCondition(transition.matches);
4775
+ if (match === null) return;
4531
4776
  const guard = guardCondition(transition.guard);
4532
4777
  if (!guard) return;
4533
4778
  if (guard.firstParam) {
@@ -4538,25 +4783,35 @@ function buildV6TransitionFunction(transitions) {
4538
4783
  const effects = (Array.isArray(actionValue) ? actionValue : actionValue === void 0 ? [] : [actionValue]).map(actionToV6Effect);
4539
4784
  if (effects.some((effect) => !effect)) return;
4540
4785
  const rendered = renderV6Effects(effects.filter((effect) => Boolean(effect)), transition.context === void 0 ? void 0 : serializeJS(unwrapTemplateExpressions(transition.context)));
4541
- const returnValue = buildV6TransitionReturnValue({
4786
+ const effectiveReturnValue = buildV6TransitionReturnValue({
4542
4787
  target: typeof transition.target === "string" ? transition.target : void 0,
4543
4788
  reenter: transition.reenter === true,
4544
- meta: transition.meta
4545
- }, rendered.contextValue);
4546
- if (!returnValue) return;
4547
- const body = [...rendered.statements.map(formatV6Statement), `return ${returnValue};`];
4789
+ meta: transition.meta,
4790
+ input: transition.input
4791
+ }, rendered.contextValue) ?? "{}";
4792
+ const body = [...rendered.statements.map(formatV6Statement), `return ${effectiveReturnValue};`];
4548
4793
  if (body.length === 0) return;
4549
4794
  branches.push({
4550
- condition: guard.condition,
4795
+ condition: combineConditions(match, guard.condition),
4796
+ callCondition: guard.callCondition ? combineConditions(match, guard.callCondition) : void 0,
4551
4797
  body
4552
4798
  });
4553
4799
  }
4554
4800
  if (branches.length === 0) return;
4555
- const generated = branches.flatMap((branch) => branch.body).join("\n");
4556
- const merged = mergeV6FirstParam(authoredFirstParam, inferV6ArgBindings(generated));
4801
+ const generated = branches.flatMap((branch) => [branch.condition, ...branch.body]).join("\n");
4802
+ let renderedBranches = branches;
4803
+ let merged = mergeV6FirstParam(authoredFirstParam, inferV6ArgBindings(generated));
4804
+ if (!merged) {
4805
+ if (branches.some((branch) => !branch.callCondition)) return;
4806
+ renderedBranches = branches.map((branch) => ({
4807
+ ...branch,
4808
+ condition: branch.callCondition
4809
+ }));
4810
+ merged = mergeV6FirstParam(void 0, inferV6ArgBindings(`${renderedBranches.map((branch) => branch.condition).join("\n")}\n${generated}`));
4811
+ }
4557
4812
  if (!merged) return;
4558
4813
  const lines = merged.prelude.map((statement) => ` ${statement}`);
4559
- for (const branch of branches) if (branch.condition === "true") lines.push(...branch.body.map((line) => ` ${line}`));
4814
+ for (const branch of renderedBranches) if (branch.condition === "true") lines.push(...branch.body.map((line) => ` ${line}`));
4560
4815
  else {
4561
4816
  lines.push(` if (${branch.condition}) {`);
4562
4817
  lines.push(...branch.body.map((line) => ` ${line}`));
@@ -4612,12 +4867,13 @@ function unwrapTemplateExpressions(value) {
4612
4867
  return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, unwrapTemplateExpressions(item)]));
4613
4868
  }
4614
4869
  function buildV6TransitionReturnValue(transition, contextValue) {
4615
- if (!transition.reenter && !transition.meta && !contextValue) return transition.target ? `{ target: ${serializeJS(transition.target)} }` : void 0;
4870
+ if (!transition.reenter && !transition.meta && !contextValue && transition.input === void 0) return transition.target ? `{ target: ${serializeJS(transition.target)} }` : void 0;
4616
4871
  return serializeJS({
4617
4872
  target: transition.target,
4618
4873
  reenter: transition.reenter ? true : void 0,
4619
4874
  meta: transition.meta,
4620
- context: contextValue ? raw(contextValue) : void 0
4875
+ context: contextValue ? raw(contextValue) : void 0,
4876
+ input: transition.input === void 0 ? void 0 : unwrapTemplateExpressions(transition.input)
4621
4877
  });
4622
4878
  }
4623
4879
  function mapMachineActionFields(value, mapActions) {
@@ -4740,7 +4996,7 @@ function actionOptions(params, consumedKeys) {
4740
4996
  const rest = Object.fromEntries(Object.entries(params).filter(([key, value]) => !consumedKeys.includes(key) && value !== void 0));
4741
4997
  return Object.keys(rest).length ? `, ${serializeJS(rest)}` : "";
4742
4998
  }
4743
- function buildImports({ hasSetup, hasActors, actors, builtInActions, actorSourceImports, implementationImports, usesTypes }) {
4999
+ function buildImports({ hasSetup, hasActors, actors, builtInActions, actorSourceImports, implementationImports, codeImports, xstateVersion, usesTypes, usesZod }) {
4744
5000
  const xstateImports = [];
4745
5001
  if (hasSetup) xstateImports.push("setup");
4746
5002
  else xstateImports.push("createMachine");
@@ -4749,9 +5005,51 @@ function buildImports({ hasSetup, hasActors, actors, builtInActions, actorSource
4749
5005
  for (const name of implementationImports) xstateImports.push(name);
4750
5006
  if (usesTypes) xstateImports.push("types");
4751
5007
  if (hasActors) {
4752
- if (actors.length > 0) xstateImports.push("fromPromise");
5008
+ if (actors.length > 0) xstateImports.push(xstateVersion === 6 ? "createAsyncLogic" : "fromPromise");
5009
+ }
5010
+ const externalImports = /* @__PURE__ */ new Map();
5011
+ for (const codeImport of codeImports) {
5012
+ const specifier = codeImport.local && codeImport.local !== codeImport.import ? `${codeImport.import} as ${codeImport.local}` : codeImport.import;
5013
+ if (codeImport.package === "xstate") {
5014
+ if ((codeImport.importKind ?? "named") === "named") xstateImports.push(specifier);
5015
+ continue;
5016
+ }
5017
+ if ((codeImport.importKind ?? "named") !== "named") continue;
5018
+ const names = externalImports.get(codeImport.package) ?? /* @__PURE__ */ new Set();
5019
+ names.add(specifier);
5020
+ externalImports.set(codeImport.package, names);
5021
+ }
5022
+ const imports = [`import { ${[...new Set(xstateImports)].join(", ")} } from 'xstate';`];
5023
+ for (const [packageName, names] of externalImports) imports.push(`import { ${[...names].sort().join(", ")} } from '${packageName}';`);
5024
+ if (usesZod && !externalImports.get("zod")?.has("z")) imports.push("import { z } from 'zod';");
5025
+ return imports.join("\n");
5026
+ }
5027
+ function getCodeExpressionImports(graph) {
5028
+ const imports = /* @__PURE__ */ new Map();
5029
+ function visit(value) {
5030
+ if (!value || typeof value !== "object") return;
5031
+ if (Array.isArray(value)) {
5032
+ value.forEach(visit);
5033
+ return;
5034
+ }
5035
+ const record = value;
5036
+ if (Array.isArray(record.imports)) for (const item of record.imports) {
5037
+ if (!item || typeof item !== "object") continue;
5038
+ const candidate = item;
5039
+ if (typeof candidate.package !== "string" || typeof candidate.import !== "string") continue;
5040
+ const key = `${candidate.package}:${candidate.import}:${candidate.local ?? ""}:${candidate.importKind ?? "named"}`;
5041
+ imports.set(key, {
5042
+ package: candidate.package,
5043
+ import: candidate.import,
5044
+ local: candidate.local,
5045
+ importKind: candidate.importKind,
5046
+ version: candidate.version
5047
+ });
5048
+ }
5049
+ Object.values(record).forEach(visit);
4753
5050
  }
4754
- return `import { ${[...new Set(xstateImports)].join(", ")} } from 'xstate';`;
5051
+ visit(graph);
5052
+ return [...imports.values()];
4755
5053
  }
4756
5054
  const XSTATE_ACTOR_LOGIC_HELPERS = new Set([
4757
5055
  "createMachine",
@@ -4814,7 +5112,10 @@ function buildSetupObject(schemas, impls, options) {
4814
5112
  }
4815
5113
  if (impls?.actions.length) setup.actions = buildActionsBlock(impls.actions, options);
4816
5114
  if (impls?.guards.length) setup.guards = buildGuardsBlock(impls.guards, options);
4817
- if (impls?.actors.length) setup.actors = buildActorsBlock(impls.actors, options);
5115
+ if (impls?.actors.length) setup.actors = buildActorsBlock(impls.actors, {
5116
+ ...options,
5117
+ xstateVersion: options.xstateVersion
5118
+ });
4818
5119
  if (impls?.delays.length) setup.delays = buildDelaysBlock(impls.delays);
4819
5120
  return setup;
4820
5121
  }
@@ -4830,7 +5131,9 @@ function buildTypesBlock(schemas, options) {
4830
5131
  return Object.keys(types).length > 0 ? types : void 0;
4831
5132
  }
4832
5133
  function buildV6SchemasBlock(schemas, options) {
4833
- if (!schemas || !options.includeTypeSyntax) return void 0;
5134
+ if (!schemas) return void 0;
5135
+ if (options.xstateV6SchemaFormat === "zod") return buildV6ZodSchemasBlock(schemas);
5136
+ if (!options.includeTypeSyntax) return void 0;
4834
5137
  const result = {};
4835
5138
  const contextType = contextSchemaToTSType(schemas.context);
4836
5139
  if (contextType) result.context = raw(`types<${contextType}>()`);
@@ -4839,6 +5142,16 @@ function buildV6SchemasBlock(schemas, options) {
4839
5142
  if (schemas.output) result.output = raw(`types<${jsonSchemaToTSType(schemas.output)}>()`);
4840
5143
  return Object.keys(result).length > 0 ? result : void 0;
4841
5144
  }
5145
+ function buildV6ZodSchemasBlock(schemas) {
5146
+ if (!schemas) return void 0;
5147
+ const result = {};
5148
+ const contextSchema = contextSchemaToZod(schemas.context);
5149
+ if (contextSchema) result.context = raw(contextSchema);
5150
+ if (schemas.events && Object.keys(schemas.events).length > 0) result.events = Object.fromEntries(Object.entries(schemas.events).map(([eventType, schema]) => [eventType, raw(eventSchemaToZod(schema))]));
5151
+ if (schemas.input) result.input = raw(jsonSchemaToZod(schemas.input));
5152
+ if (schemas.output) result.output = raw(jsonSchemaToZod(schemas.output));
5153
+ return Object.keys(result).length > 0 ? result : void 0;
5154
+ }
4842
5155
  function eventPayloadSchemaToTSType(schema) {
4843
5156
  const props = schema.properties ?? {};
4844
5157
  const payloadProps = Object.fromEntries(Object.entries(props).filter(([key]) => key !== "type"));
@@ -4885,6 +5198,7 @@ function buildGuardsBlock(guards, options) {
4885
5198
  }
4886
5199
  function buildActorsBlock(actors, options) {
4887
5200
  const block = {};
5201
+ const actorFactory = options.xstateVersion === 6 ? "createAsyncLogic" : "fromPromise";
4888
5202
  for (const actor of actors) if (actor.code?.body) {
4889
5203
  const inlineExpression = getActorLogicExpression(actor.code.body);
4890
5204
  if (inlineExpression) {
@@ -4893,12 +5207,12 @@ function buildActorsBlock(actors, options) {
4893
5207
  }
4894
5208
  const functionExpression = stripExportDefault(actor.code.body);
4895
5209
  if (isCompleteFunctionExpression(functionExpression)) {
4896
- block[actor.name] = raw(`fromPromise(${functionExpression})`);
5210
+ block[actor.name] = raw(options.xstateVersion === 6 ? `${actorFactory}({ run: ${functionExpression} })` : `${actorFactory}(${functionExpression})`);
4897
5211
  continue;
4898
5212
  }
4899
5213
  const inputType = options.includeTypeSyntax && hasSchemaProperties(actor.inputSchema) ? `: ${jsonSchemaToTSType(actor.inputSchema)}` : "";
4900
- block[actor.name] = raw(`fromPromise(async ({ input }${inputType ? `: { input${inputType} }` : ""}) => {\n ${dedent(actor.code.body)}\n})`);
4901
- } else block[actor.name] = raw(`fromPromise(async ({ input }) => {\n // TODO: implement ${actor.name}\n})`);
5214
+ block[actor.name] = raw(options.xstateVersion === 6 ? `${actorFactory}({ run: async ({ input }${inputType ? `: { input${inputType} }` : ""}) => {\n ${dedent(actor.code.body)}\n} })` : `${actorFactory}(async ({ input }${inputType ? `: { input${inputType} }` : ""}) => {\n ${dedent(actor.code.body)}\n})`);
5215
+ } else block[actor.name] = raw(options.xstateVersion === 6 ? `${actorFactory}({ run: async ({ input }) => {\n // TODO: implement ${actor.name}\n} })` : `${actorFactory}(async ({ input }) => {\n // TODO: implement ${actor.name}\n})`);
4902
5216
  return block;
4903
5217
  }
4904
5218
  function getActorLogicExpression(code) {