@statelyai/sdk 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,13 +1,14 @@
1
1
  import { StatelyApiClientOptions, StatelyApiError, StatelyApiUrlOptions, createStatelyApiClient, createStatelyApiUrl } from "./api.mjs";
2
+ import { a as EmbedMode, c as ExportFormatMap, f as ProjectEmbedMachine, i as EmbedEventName, l as InitOptions, m as UploadResult, n as EmbedEventHandler, o as ExportCallOptions, r as EmbedEventMap, s as ExportFormat, t as CommentsConfig } from "./protocol-CDoCcaIP.mjs";
3
+ import { AssetUploadAdapter, AssetUploadContext, AssetUploadRequest, CreateS3AssetUploadAdapterOptions, CreateSupabaseAssetUploadAdapterOptions, S3UploadTarget, SupabaseStorageClient, createS3AssetUploadAdapter, createSupabaseAssetUploadAdapter } from "./assetStorage.mjs";
2
4
  import { ConnectedRepo, CreateMachineFromDefinitionInput, CreateMachineFromTemplateInput, CreateMachineInput, CreateMachineTemplate, CreateProjectInput, EnsureProjectInput, ExtractMachinesResponse, ExtractedMachine, GetMachineOptions, ProjectData, ProjectMachine, ProjectVisibility, RepoType, StudioApiError, StudioClient, StudioClientOptions, StudioMachineRecord, VerifyApiKeyResponse, XStateVersion, createStatelyClient } from "./studio.mjs";
3
- import { C as EventTypeData, S as DigraphNodeConfig, _ as studioMachineConverter, a as StatelyGraphData, b as DigraphConfig, c as StatelyInvoke, d as StudioAction, f as StudioEdge, g as fromStudioMachine, h as StudioNode, i as StatelyGraph, l as StatelyNodeData, m as StudioMachine, o as StatelyGuard, r as StatelyEdgeData, t as StatelyAction, v as toStudioMachine, w as StateNodeJSONData, x as DigraphEdgeConfig, y as DigraphAction } from "./graph-CB-ALrdk.mjs";
5
+ import { C as EventTypeData, S as DigraphNodeConfig, _ as studioMachineConverter, a as StatelyGraphData, b as DigraphConfig, c as StatelyInvoke, d as StudioAction, f as StudioEdge, g as fromStudioMachine, h as StudioNode, i as StatelyGraph, l as StatelyNodeData, m as StudioMachine, o as StatelyGuard, r as StatelyEdgeData, t as StatelyAction, v as toStudioMachine, w as StateNodeJSONData, x as DigraphEdgeConfig, y as DigraphAction } from "./graph-DpBGHZwl.mjs";
4
6
  import { PlanSyncOptions, PullSyncResult, PushSyncOptions, PushSyncProjectOptions, PushSyncResult, ResolvedSyncInput, SyncInputFormat, SyncPlan, SyncPlanSummary } from "./sync.mjs";
5
- import { a as EmbedMode, c as ExportFormatMap, f as ProjectEmbedMachine, i as EmbedEventName, l as InitOptions, m as UploadResult, n as EmbedEventHandler, o as ExportCallOptions, r as EmbedEventMap, s as ExportFormat, t as CommentsConfig } from "./protocol-CEbWQPYe.mjs";
6
7
  import { AssetConfig, StatelyEmbed, StatelyEmbedOptions, createStatelyEmbed } from "./embed.mjs";
7
- import { a as ManualActorOptions, c as createPostMessageTransport, i as InspectorEvents, l as createWebSocketTransport, n as CreateInspectorOptions, o as createStatelyInspector, r as Inspector, s as Transport, t as AdoptedActor } from "./inspect-DIxB2Tr3.mjs";
8
+ import { a as ManualActorOptions, c as createPostMessageTransport, i as InspectorEvents, l as createWebSocketTransport, n as CreateInspectorOptions, o as createStatelyInspector, r as Inspector, s as Transport, t as AdoptedActor } from "./inspect-BMIJcsFh.mjs";
8
9
  import { ActionLocation, GraphPatch } from "./patchTypes.mjs";
9
- import { CodeGenGraph, MachineConfigOptions, RawCode, graphToMachineConfig, raw, serializeJS } from "@statelyai/graph-tools";
10
10
  import { JSONSchema7 } from "json-schema";
11
+ import { UnknownMachineConfig } from "xstate";
11
12
 
12
13
  //#region src/statelyPragma.d.ts
13
14
  interface StatelyPragma {
@@ -31,12 +32,146 @@ declare function findStatelyPragmaAttachments(sourceText: string, fileName?: str
31
32
  declare function getStatelyPragma(sourceText: string, fileName?: string, machineIndex?: number): StatelyPragma | undefined;
32
33
  declare function upsertStatelyPragma(sourceText: string, id: string, options?: UpsertStatelyPragmaOptions): string;
33
34
  //#endregion
35
+ //#region ../graph-tools/src/codegenTypes.d.ts
36
+ interface CodeGenAction {
37
+ type: string;
38
+ params?: Record<string, unknown>;
39
+ }
40
+ interface CodeGenGuard {
41
+ type: string;
42
+ code?: string;
43
+ params?: Record<string, unknown>;
44
+ }
45
+ /**
46
+ * Serialized inline expression directive.
47
+ *
48
+ * Code generation treats this object as JavaScript/TypeScript source, not as a
49
+ * machine config object. It is used for fields such as invoke `input` and
50
+ * `output` where XState accepts mapper expressions.
51
+ */
52
+ interface CodeExpression {
53
+ '@type': 'code';
54
+ lang: 'js' | 'ts';
55
+ expr: string;
56
+ }
57
+ interface CodeGenInvoke {
58
+ src: string;
59
+ id: string;
60
+ input?: Record<string, unknown> | CodeExpression;
61
+ output?: Record<string, unknown> | CodeExpression;
62
+ }
63
+ interface CodeGenNodeData {
64
+ nodeId?: string | null;
65
+ key: string;
66
+ type?: 'normal' | 'parallel' | 'final' | 'history' | null;
67
+ initialId?: string | null;
68
+ history?: 'shallow' | 'deep' | boolean;
69
+ entry?: CodeGenAction[];
70
+ exit?: CodeGenAction[];
71
+ invokes?: CodeGenInvoke[];
72
+ tags?: Array<string | {
73
+ name: string;
74
+ }>;
75
+ description?: string | null;
76
+ meta?: Record<string, unknown> | null;
77
+ color?: string;
78
+ parentId?: string | null;
79
+ temp?: boolean;
80
+ }
81
+ interface CodeGenEdgeData {
82
+ eventType: string;
83
+ transitionType?: 'normal' | 'targetless' | 'reenter';
84
+ guard?: CodeGenGuard | null;
85
+ actions?: CodeGenAction[];
86
+ description?: string | null;
87
+ color?: string;
88
+ meta?: Record<string, unknown> | null;
89
+ temp?: boolean;
90
+ }
91
+ interface CodeGenImplementation {
92
+ id: string;
93
+ name: string;
94
+ description?: string | null;
95
+ icon?: string;
96
+ paramsSchema?: JSONSchema7 | null;
97
+ code?: {
98
+ body: string;
99
+ lang?: string;
100
+ } | null;
101
+ }
102
+ interface CodeGenActorImplementation {
103
+ id: string;
104
+ name: string;
105
+ description?: string | null;
106
+ icon?: string;
107
+ inputSchema?: JSONSchema7 | null;
108
+ outputSchema?: JSONSchema7 | null;
109
+ code?: {
110
+ body: string;
111
+ lang?: string;
112
+ } | null;
113
+ }
114
+ interface CodeGenGraphData {
115
+ schemas?: {
116
+ context?: Record<string, JSONSchema7> | null;
117
+ events?: Record<string, JSONSchema7> | null;
118
+ input?: JSONSchema7 | null;
119
+ output?: JSONSchema7 | null;
120
+ } | null;
121
+ implementations?: {
122
+ actions: CodeGenImplementation[];
123
+ guards: CodeGenImplementation[];
124
+ actors: CodeGenActorImplementation[];
125
+ delays: CodeGenImplementation[];
126
+ } | null;
127
+ }
128
+ interface CodeGenNode {
129
+ id: string;
130
+ parentId?: string | null;
131
+ data: CodeGenNodeData;
132
+ }
133
+ interface CodeGenEdge {
134
+ id: string;
135
+ sourceId: string;
136
+ targetId: string;
137
+ data: CodeGenEdgeData;
138
+ }
139
+ interface CodeGenGraph {
140
+ id: string;
141
+ nodes: CodeGenNode[];
142
+ edges: CodeGenEdge[];
143
+ data: CodeGenGraphData;
144
+ }
145
+ //#endregion
146
+ //#region ../graph-tools/src/graphToMachineConfig.d.ts
147
+ interface MachineConfigOptions {
148
+ showDescriptions?: boolean;
149
+ showMeta?: boolean;
150
+ }
151
+ declare function graphToMachineConfig(graph: CodeGenGraph, options?: MachineConfigOptions): UnknownMachineConfig;
152
+ //#endregion
34
153
  //#region src/graphToXStateTS.d.ts
35
154
  interface XStateTSOptions extends MachineConfigOptions {
36
155
  exportStyle?: 'named' | 'default' | 'none';
37
156
  }
38
157
  declare function graphToXStateTS(graph: CodeGenGraph, options?: XStateTSOptions): string;
39
158
  //#endregion
159
+ //#region ../graph-tools/src/serializeJS.d.ts
160
+ /**
161
+ * Serializes JavaScript values as JS source code (not JSON).
162
+ * - Unquoted keys for valid identifiers
163
+ * - Single-quoted strings
164
+ * - Omits undefined values
165
+ * - Supports RawCode for verbatim expressions
166
+ * - Supports inline expression directives for verbatim expressions
167
+ */
168
+ declare class RawCode {
169
+ code: string;
170
+ constructor(code: string);
171
+ }
172
+ declare function raw(code: string): RawCode;
173
+ declare function serializeJS(value: unknown, indent?: number, step?: number): string;
174
+ //#endregion
40
175
  //#region src/jsonSchemaToTSType.d.ts
41
176
  declare function jsonSchemaToTSType(schema: JSONSchema7 | undefined | null): string;
42
177
  /**
@@ -50,4 +185,4 @@ declare function contextSchemaToTSType(context: Record<string, JSONSchema7> | nu
50
185
  */
51
186
  declare function eventsSchemaToTSType(events: Record<string, JSONSchema7> | null | undefined): string | null;
52
187
  //#endregion
53
- export { type ActionLocation, type AdoptedActor, type AssetConfig, type CodeGenGraph, type CommentsConfig, type ConnectedRepo, type CreateInspectorOptions, type CreateMachineFromDefinitionInput, type CreateMachineFromTemplateInput, type CreateMachineInput, type CreateMachineTemplate, type CreateProjectInput, type DigraphAction, type DigraphConfig, type DigraphEdgeConfig, type DigraphNodeConfig, type EmbedEventHandler, type EmbedEventMap, type EmbedEventName, type EmbedMode, type EnsureProjectInput, type EventTypeData, type ExportCallOptions, type ExportFormat, type ExportFormatMap, type ExtractMachinesResponse, type ExtractedMachine, type GetMachineOptions, type GraphPatch, type InitOptions, type Inspector, type InspectorEvents, type MachineConfigOptions, type ManualActorOptions, type PlanSyncOptions, type ProjectData, type ProjectEmbedMachine, type ProjectMachine, type ProjectVisibility, type PullSyncResult, type PushSyncOptions, type PushSyncProjectOptions, type PushSyncResult, RawCode, type RepoType, type ResolvedSyncInput, type StateNodeJSONData, type StatelyAction, type StatelyApiClientOptions, StatelyApiError, type StatelyApiUrlOptions, type StatelyEdgeData, type StatelyEmbed, type StatelyEmbedOptions, type StatelyGraph, type StatelyGraphData, type StatelyGuard, type StatelyInvoke, type StatelyNodeData, type StatelyPragma, type StatelyPragmaAttachment, type StudioAction, StudioApiError, type StudioClient, type StudioClientOptions, type StudioEdge, type StudioMachine, type StudioMachineRecord, type StudioNode, type SyncInputFormat, type SyncPlan, type SyncPlanSummary, type Transport, type UploadResult, type UpsertStatelyPragmaOptions, type VerifyApiKeyResponse, type XStateTSOptions, type XStateVersion, contextSchemaToTSType, createPostMessageTransport, createStatelyApiClient, createStatelyApiUrl, createStatelyClient, createStatelyEmbed, createStatelyInspector, createWebSocketTransport, eventsSchemaToTSType, findStatelyPragmaAttachments, fromStudioMachine, getStatelyPragma, graphToMachineConfig, graphToXStateTS, jsonSchemaToTSType, raw, serializeJS, studioMachineConverter, toStudioMachine, upsertStatelyPragma };
188
+ export { type ActionLocation, type AdoptedActor, type AssetConfig, type AssetUploadAdapter, type AssetUploadContext, type AssetUploadRequest, type CodeGenGraph, type CommentsConfig, type ConnectedRepo, type CreateInspectorOptions, type CreateMachineFromDefinitionInput, type CreateMachineFromTemplateInput, type CreateMachineInput, type CreateMachineTemplate, type CreateProjectInput, type CreateS3AssetUploadAdapterOptions, type CreateSupabaseAssetUploadAdapterOptions, type DigraphAction, type DigraphConfig, type DigraphEdgeConfig, type DigraphNodeConfig, type EmbedEventHandler, type EmbedEventMap, type EmbedEventName, type EmbedMode, type EnsureProjectInput, type EventTypeData, type ExportCallOptions, type ExportFormat, type ExportFormatMap, type ExtractMachinesResponse, type ExtractedMachine, type GetMachineOptions, type GraphPatch, type InitOptions, type Inspector, type InspectorEvents, type MachineConfigOptions, type ManualActorOptions, type PlanSyncOptions, type ProjectData, type ProjectEmbedMachine, type ProjectMachine, type ProjectVisibility, type PullSyncResult, type PushSyncOptions, type PushSyncProjectOptions, type PushSyncResult, RawCode, type RepoType, type ResolvedSyncInput, type S3UploadTarget, type StateNodeJSONData, type StatelyAction, type StatelyApiClientOptions, StatelyApiError, type StatelyApiUrlOptions, type StatelyEdgeData, type StatelyEmbed, type StatelyEmbedOptions, type StatelyGraph, type StatelyGraphData, type StatelyGuard, type StatelyInvoke, type StatelyNodeData, type StatelyPragma, type StatelyPragmaAttachment, type StudioAction, StudioApiError, type StudioClient, type StudioClientOptions, type StudioEdge, type StudioMachine, type StudioMachineRecord, type StudioNode, type SupabaseStorageClient, type SyncInputFormat, type SyncPlan, type SyncPlanSummary, type Transport, type UploadResult, type UpsertStatelyPragmaOptions, type VerifyApiKeyResponse, type XStateTSOptions, type XStateVersion, contextSchemaToTSType, createPostMessageTransport, createS3AssetUploadAdapter, createStatelyApiClient, createStatelyApiUrl, createStatelyClient, createStatelyEmbed, createStatelyInspector, createSupabaseAssetUploadAdapter, createWebSocketTransport, eventsSchemaToTSType, findStatelyPragmaAttachments, fromStudioMachine, getStatelyPragma, graphToMachineConfig, graphToXStateTS, jsonSchemaToTSType, raw, serializeJS, studioMachineConverter, toStudioMachine, upsertStatelyPragma };
package/dist/index.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  import { n as createWebSocketTransport, t as createPostMessageTransport } from "./transport-C0eTgNNu.mjs";
2
2
  import { createStatelyEmbed } from "./embed.mjs";
3
+ import { createS3AssetUploadAdapter, createSupabaseAssetUploadAdapter } from "./assetStorage.mjs";
3
4
  import { createStatelyInspector } from "./inspect.mjs";
4
5
  import { StudioApiError, createStatelyClient } from "./studio.mjs";
5
6
  import { StatelyApiError, createStatelyApiClient, createStatelyApiUrl } from "./api.mjs";
6
- import { a as RawCode, c as graphToMachineConfig, d as upsertStatelyPragma, i as jsonSchemaToTSType, l as findStatelyPragmaAttachments, n as contextSchemaToTSType, o as raw, r as eventsSchemaToTSType, s as serializeJS, t as graphToXStateTS, u as getStatelyPragma } from "./graphToXStateTS-CvXM8wHL.mjs";
7
+ import { a as graphToMachineConfig, c as serializeJS, d as upsertStatelyPragma, i as jsonSchemaToTSType, l as findStatelyPragmaAttachments, n as contextSchemaToTSType, o as RawCode, r as eventsSchemaToTSType, s as raw, t as graphToXStateTS, u as getStatelyPragma } from "./graphToXStateTS-Gzh0ZqbN.mjs";
7
8
  import { fromStudioMachine, studioMachineConverter, toStudioMachine } from "./graph.mjs";
8
9
 
9
- export { RawCode, StatelyApiError, StudioApiError, contextSchemaToTSType, createPostMessageTransport, createStatelyApiClient, createStatelyApiUrl, createStatelyClient, createStatelyEmbed, createStatelyInspector, createWebSocketTransport, eventsSchemaToTSType, findStatelyPragmaAttachments, fromStudioMachine, getStatelyPragma, graphToMachineConfig, graphToXStateTS, jsonSchemaToTSType, raw, serializeJS, studioMachineConverter, toStudioMachine, upsertStatelyPragma };
10
+ export { RawCode, StatelyApiError, StudioApiError, contextSchemaToTSType, createPostMessageTransport, createS3AssetUploadAdapter, createStatelyApiClient, createStatelyApiUrl, createStatelyClient, createStatelyEmbed, createStatelyInspector, createSupabaseAssetUploadAdapter, createWebSocketTransport, eventsSchemaToTSType, findStatelyPragmaAttachments, fromStudioMachine, getStatelyPragma, graphToMachineConfig, graphToXStateTS, jsonSchemaToTSType, raw, serializeJS, studioMachineConverter, toStudioMachine, upsertStatelyPragma };
@@ -1,4 +1,4 @@
1
- import { c as ExportFormatMap, o as ExportCallOptions, p as ProtocolMessage, r as EmbedEventMap, s as ExportFormat } from "./protocol-CEbWQPYe.mjs";
1
+ import { c as ExportFormatMap, o as ExportCallOptions, p as ProtocolMessage, r as EmbedEventMap, s as ExportFormat } from "./protocol-CDoCcaIP.mjs";
2
2
 
3
3
  //#region src/transport.d.ts
4
4
  interface Transport {
@@ -1,3 +1,3 @@
1
- import { a as EmbedMode, c as ExportFormatMap, i as EmbedEventName, n as EmbedEventHandler, o as ExportCallOptions, r as EmbedEventMap, s as ExportFormat } from "./protocol-CEbWQPYe.mjs";
2
- import { a as ManualActorOptions, i as InspectorEvents, n as CreateInspectorOptions, o as createStatelyInspector, r as Inspector, s as Transport, t as AdoptedActor } from "./inspect-DIxB2Tr3.mjs";
1
+ import { a as EmbedMode, c as ExportFormatMap, i as EmbedEventName, n as EmbedEventHandler, o as ExportCallOptions, r as EmbedEventMap, s as ExportFormat } from "./protocol-CDoCcaIP.mjs";
2
+ import { a as ManualActorOptions, i as InspectorEvents, n as CreateInspectorOptions, o as createStatelyInspector, r as Inspector, s as Transport, t as AdoptedActor } from "./inspect-BMIJcsFh.mjs";
3
3
  export { AdoptedActor, CreateInspectorOptions, EmbedEventHandler, EmbedEventMap, EmbedEventName, EmbedMode, ExportCallOptions, ExportFormat, ExportFormatMap, Inspector, InspectorEvents, ManualActorOptions, Transport, createStatelyInspector };
package/dist/sync.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CreateProjectInput, ProjectData, StudioClient, StudioMachineRecord, XStateVersion } from "./studio.mjs";
2
- import { b as DigraphConfig, i as StatelyGraph } from "./graph-CB-ALrdk.mjs";
2
+ import { b as DigraphConfig, i as StatelyGraph } from "./graph-DpBGHZwl.mjs";
3
3
  import { GraphDiff } from "@statelyai/graph";
4
4
 
5
5
  //#region src/sync.d.ts
package/dist/sync.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createStatelyClient } from "./studio.mjs";
2
- import { d as upsertStatelyPragma, t as graphToXStateTS } from "./graphToXStateTS-CvXM8wHL.mjs";
2
+ import { d as upsertStatelyPragma, t as graphToXStateTS } from "./graphToXStateTS-Gzh0ZqbN.mjs";
3
3
  import { fromStudioMachine, toStudioMachine } from "./graph.mjs";
4
4
  import { getDiff, isEmptyDiff } from "@statelyai/graph";
5
5
  import fs from "node:fs/promises";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statelyai/sdk",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "license": "MIT",
5
5
  "bin": {
6
6
  "statelyai": "./dist/cli.mjs"
@@ -49,6 +49,10 @@
49
49
  "types": "./dist/api.d.mts",
50
50
  "import": "./dist/api.mjs"
51
51
  },
52
+ "./assetStorage": {
53
+ "types": "./dist/assetStorage.d.mts",
54
+ "import": "./dist/assetStorage.mjs"
55
+ },
52
56
  "./statelyai.schema.json": "./schemas/statelyai.schema.json",
53
57
  "./schemas/statelyai.schema.json": "./schemas/statelyai.schema.json"
54
58
  },
@@ -56,8 +60,7 @@
56
60
  "@oclif/core": "^4.10.3",
57
61
  "@statelyai/graph": "^0.9.0",
58
62
  "typescript": "^5.9.3",
59
- "xstate": "^5.0.0",
60
- "@statelyai/graph-tools": "0.0.0"
63
+ "xstate": "^5.0.0"
61
64
  },
62
65
  "devDependencies": {
63
66
  "@types/json-schema": "^7.0.15",
@@ -1,344 +0,0 @@
1
- import ts from "typescript";
2
- import { RawCode, graphToMachineConfig, raw, serializeJS } from "@statelyai/graph-tools";
3
-
4
- //#region src/statelyPragma.ts
5
- function findStatelyPragmaAttachments(sourceText, fileName = "machine.ts") {
6
- const sourceFile = ts.createSourceFile(fileName, sourceText, ts.ScriptTarget.Latest, true, getScriptKind(fileName));
7
- const attachments = [];
8
- const visit = (node) => {
9
- if (ts.isCallExpression(node) && isCreateMachineExpression(node.expression)) {
10
- const attachNode = findAttachNode(node);
11
- if (attachNode) attachments.push({
12
- machineStart: getMachineExpressionStart(node.expression, sourceFile),
13
- attachStart: attachNode.getStart(sourceFile),
14
- pragma: findAttachedStatelyPragma(sourceText, attachNode)
15
- });
16
- }
17
- ts.forEachChild(node, visit);
18
- };
19
- visit(sourceFile);
20
- return attachments;
21
- }
22
- function getStatelyPragma(sourceText, fileName = "machine.ts", machineIndex = 0) {
23
- return findStatelyPragmaAttachments(sourceText, fileName)[machineIndex]?.pragma;
24
- }
25
- function upsertStatelyPragma(sourceText, id, options = {}) {
26
- const attachment = findStatelyPragmaAttachments(sourceText, options.fileName ?? "machine.ts")[options.machineIndex ?? 0];
27
- if (!attachment) return sourceText;
28
- const lineEnding = options.lineEnding ?? detectLineEnding(sourceText);
29
- const canonicalComment = `// @statelyai id=${id}`;
30
- if (attachment.pragma) return sourceText.slice(0, attachment.pragma.start) + canonicalComment + sourceText.slice(attachment.pragma.end);
31
- const insertText = `${getIndentationAtOffset(sourceText, attachment.attachStart)}${canonicalComment}${lineEnding}`;
32
- return sourceText.slice(0, attachment.attachStart) + insertText + sourceText.slice(attachment.attachStart);
33
- }
34
- function findAttachedStatelyPragma(sourceText, node) {
35
- const comments = ts.getLeadingCommentRanges(sourceText, node.getFullStart()) ?? [];
36
- for (let index = comments.length - 1; index >= 0; index -= 1) {
37
- const comment = comments[index];
38
- const parsed = parseStatelyPragma(sourceText, comment.pos, comment.end);
39
- if (parsed) return parsed;
40
- }
41
- }
42
- function parseStatelyPragma(sourceText, start, end) {
43
- const match = normalizeCommentContent(sourceText.slice(start, end)).match(/^@statelyai(?:\s+(.*))?$/s);
44
- if (!match) return;
45
- const fields = parseFields(match[1] ?? "");
46
- return {
47
- tag: "@statelyai",
48
- id: fields.id,
49
- fields,
50
- start,
51
- end
52
- };
53
- }
54
- function normalizeCommentContent(rawComment) {
55
- if (rawComment.startsWith("//")) return rawComment.slice(2).trim();
56
- if (rawComment.startsWith("/*")) return rawComment.slice(2, rawComment.endsWith("*/") ? -2 : void 0).split(/\r?\n/).map((line) => line.replace(/^\s*\*\s?/, "")).join(" ").trim();
57
- return rawComment.trim();
58
- }
59
- function parseFields(input) {
60
- const fields = {};
61
- for (const token of input.split(/\s+/)) {
62
- if (!token) continue;
63
- const equalsIndex = token.indexOf("=");
64
- if (equalsIndex <= 0) continue;
65
- const key = token.slice(0, equalsIndex);
66
- const value = token.slice(equalsIndex + 1);
67
- if (!key || !value) continue;
68
- fields[key] = value;
69
- }
70
- return fields;
71
- }
72
- function findAttachNode(node) {
73
- let current = node;
74
- while (current?.parent) {
75
- if (ts.isVariableStatement(current.parent) || ts.isExpressionStatement(current.parent) || ts.isExportAssignment(current.parent)) return current.parent;
76
- current = current.parent;
77
- }
78
- return current;
79
- }
80
- function isCreateMachineExpression(expression) {
81
- return ts.isIdentifier(expression) && expression.text === "createMachine" || ts.isPropertyAccessExpression(expression) && expression.name.text === "createMachine";
82
- }
83
- function getMachineExpressionStart(expression, sourceFile) {
84
- if (ts.isPropertyAccessExpression(expression)) return expression.name.getStart(sourceFile);
85
- return expression.getStart(sourceFile);
86
- }
87
- function getIndentationAtOffset(sourceText, offset) {
88
- const lineStart = sourceText.lastIndexOf("\n", Math.max(0, offset - 1)) + 1;
89
- return sourceText.slice(lineStart, offset).match(/^[ \t]*/)?.[0] ?? "";
90
- }
91
- function detectLineEnding(sourceText) {
92
- return sourceText.includes("\r\n") ? "\r\n" : "\n";
93
- }
94
- function getScriptKind(fileName) {
95
- if (fileName.endsWith(".tsx")) return ts.ScriptKind.TSX;
96
- if (fileName.endsWith(".jsx")) return ts.ScriptKind.JSX;
97
- if (fileName.endsWith(".js")) return ts.ScriptKind.JS;
98
- return ts.ScriptKind.TS;
99
- }
100
-
101
- //#endregion
102
- //#region src/jsonSchemaToTSType.ts
103
- function jsonSchemaToTSType(schema) {
104
- if (!schema) return "unknown";
105
- if (schema.enum) return schema.enum.map((v) => typeof v === "string" ? `'${v}'` : String(v)).join(" | ");
106
- if (schema.const !== void 0) return typeof schema.const === "string" ? `'${schema.const}'` : String(schema.const);
107
- if (schema.oneOf) return schema.oneOf.map((s) => jsonSchemaToTSType(resolveDef(s))).join(" | ");
108
- if (schema.anyOf) return schema.anyOf.map((s) => jsonSchemaToTSType(resolveDef(s))).join(" | ");
109
- if (schema.allOf) return schema.allOf.map((s) => jsonSchemaToTSType(resolveDef(s))).join(" & ");
110
- if (schema.type === "array") return `Array<${jsonSchemaToTSType(resolveDef(schema.items))}>`;
111
- if (Array.isArray(schema.type)) return schema.type.map((t) => primitiveType(t)).join(" | ");
112
- if (schema.type === "object" || schema.properties) return objectType(schema);
113
- if (schema.type) return primitiveType(schema.type);
114
- return "unknown";
115
- }
116
- function primitiveType(type) {
117
- switch (type) {
118
- case "string": return "string";
119
- case "number":
120
- case "integer": return "number";
121
- case "boolean": return "boolean";
122
- case "null": return "null";
123
- default: return "unknown";
124
- }
125
- }
126
- function objectType(schema) {
127
- const props = schema.properties;
128
- if (!props || Object.keys(props).length === 0) {
129
- if (schema.additionalProperties) return `Record<string, ${jsonSchemaToTSType(resolveDef(schema.additionalProperties))}>`;
130
- return "Record<string, unknown>";
131
- }
132
- const required = new Set(schema.required ?? []);
133
- return `{ ${Object.entries(props).map(([key, def]) => {
134
- const type = jsonSchemaToTSType(resolveDef(def));
135
- return `${key}${required.has(key) ? "" : "?"}: ${type}`;
136
- }).join("; ")} }`;
137
- }
138
- function resolveDef(def) {
139
- if (!def) return void 0;
140
- if (Array.isArray(def)) return resolveDef(def[0]);
141
- if (typeof def === "boolean") return void 0;
142
- return def;
143
- }
144
- /**
145
- * Build an inline context type string from the schemas.context record.
146
- * Each key is a context property name, value is its JSONSchema7.
147
- */
148
- function contextSchemaToTSType(context) {
149
- if (!context || Object.keys(context).length === 0) return null;
150
- return `{ ${Object.entries(context).map(([key, schema]) => {
151
- return `${key}: ${jsonSchemaToTSType(schema)}`;
152
- }).join("; ")} }`;
153
- }
154
- /**
155
- * Build an event union type from the schemas.events record.
156
- * Each key is the event type name, value describes the payload properties.
157
- */
158
- function eventsSchemaToTSType(events) {
159
- if (!events || Object.keys(events).length === 0) return null;
160
- return Object.entries(events).map(([eventType, schema]) => {
161
- const props = schema.properties;
162
- if (!props || Object.keys(props).length === 0) return `{ type: '${eventType}' }`;
163
- const required = new Set(schema.required ?? []);
164
- const extraProps = Object.entries(props).filter(([k]) => k !== "type").map(([key, def]) => {
165
- const type = jsonSchemaToTSType(resolveDef(def));
166
- return `${key}${required.has(key) ? "" : "?"}: ${type}`;
167
- });
168
- if (extraProps.length === 0) return `{ type: '${eventType}' }`;
169
- return `{ type: '${eventType}'; ${extraProps.join("; ")} }`;
170
- }).join("\n | ");
171
- }
172
-
173
- //#endregion
174
- //#region src/textUtils.ts
175
- /**
176
- * Pure string utilities used by codegen.
177
- */
178
- /**
179
- * Removes common leading whitespace from all non-empty lines.
180
- */
181
- function dedent(text) {
182
- const lines = text.split("\n");
183
- const nonEmptyLines = lines.filter((l) => l.trim().length > 0);
184
- if (nonEmptyLines.length === 0) return text;
185
- const minIndent = Math.min(...nonEmptyLines.map((l) => l.match(/^(\s*)/)[1].length));
186
- if (minIndent === 0) return text;
187
- return lines.map((l) => l.trim().length > 0 ? l.slice(minIndent) : l).join("\n");
188
- }
189
- /**
190
- * Strips `export default` wrapper from an expression string.
191
- * E.g. `"export default assign({ ... })"` → `"assign({ ... })"`
192
- */
193
- function stripExportDefault(code) {
194
- const trimmed = code.trim();
195
- if (trimmed.startsWith("export default ")) return trimmed.slice(15).replace(/;$/, "");
196
- return trimmed;
197
- }
198
-
199
- //#endregion
200
- //#region src/graphToXStateTS.ts
201
- function graphToXStateTS(graph, options = {}) {
202
- const { exportStyle = "named", ...configOptions } = options;
203
- const schemas = graph.data.schemas;
204
- const impls = graph.data.implementations;
205
- const hasSchemas = !!(schemas && (schemas.context || schemas.events || schemas.input || schemas.output));
206
- const hasActions = !!impls?.actions.length;
207
- const hasGuards = !!impls?.guards.length;
208
- const hasActors = !!impls?.actors.length;
209
- const hasDelays = !!impls?.delays.length;
210
- const hasSetup = hasSchemas || hasActions || hasGuards || hasActors || hasDelays;
211
- const builtInActions = getUsedBuiltInActions(graph);
212
- const imports = buildImports({
213
- hasSetup,
214
- hasActors,
215
- actors: impls?.actors ?? [],
216
- builtInActions
217
- });
218
- const machineConfig = graphToMachineConfig(graph, configOptions);
219
- let machineExpr;
220
- if (hasSetup) {
221
- const setupObj = buildSetupObject(schemas, impls);
222
- const configStr = serializeJS(machineConfig, 2);
223
- machineExpr = `setup(${serializeJS(setupObj, 0)}).createMachine(${configStr})`;
224
- } else machineExpr = `createMachine(${serializeJS(machineConfig, 0)})`;
225
- const lines = [];
226
- lines.push(imports);
227
- lines.push("");
228
- lines.push(`const machine = ${machineExpr};`);
229
- if (exportStyle === "named") {
230
- lines.push("");
231
- lines.push("export { machine };");
232
- } else if (exportStyle === "default") {
233
- lines.push("");
234
- lines.push("export default machine;");
235
- }
236
- return lines.join("\n") + "\n";
237
- }
238
- /** Map from xstate action type to the import name */
239
- const BUILTIN_ACTION_IMPORTS = {
240
- "xstate.raise": "raise",
241
- "xstate.sendTo": "sendTo",
242
- "xstate.cancel": "cancel",
243
- "xstate.emit": "emit",
244
- "xstate.spawnChild": "spawnChild",
245
- "xstate.stopChild": "stopChild",
246
- "xstate.log": "log",
247
- "xstate.assign": "assign"
248
- };
249
- /** Check inline action/entry/exit code for references to xstate builtins */
250
- function scanInlineCodeForBuiltins(code, used) {
251
- const expr = stripExportDefault(code);
252
- for (const importName of Object.values(BUILTIN_ACTION_IMPORTS)) if (new RegExp(`\\b${importName}\\b`).test(expr)) used.add(importName);
253
- }
254
- function getExprActionCode(action) {
255
- return action.type === "xstate.expr" && typeof action.params?.code === "string" ? action.params.code : void 0;
256
- }
257
- function getUsedBuiltInActions(graph) {
258
- const used = /* @__PURE__ */ new Set();
259
- for (const node of graph.nodes) for (const action of [...node.data.entry ?? [], ...node.data.exit ?? []]) {
260
- const imp = BUILTIN_ACTION_IMPORTS[action.type];
261
- if (imp) used.add(imp);
262
- const exprCode = getExprActionCode(action);
263
- if (exprCode) scanInlineCodeForBuiltins(exprCode, used);
264
- }
265
- for (const edge of graph.edges) for (const action of edge.data.actions ?? []) {
266
- const imp = BUILTIN_ACTION_IMPORTS[action.type];
267
- if (imp) used.add(imp);
268
- const exprCode = getExprActionCode(action);
269
- if (exprCode) scanInlineCodeForBuiltins(exprCode, used);
270
- }
271
- return used;
272
- }
273
- function buildImports({ hasSetup, hasActors, actors, builtInActions }) {
274
- const xstateImports = [];
275
- if (hasSetup) xstateImports.push("setup");
276
- else xstateImports.push("createMachine");
277
- for (const name of builtInActions) xstateImports.push(name);
278
- if (hasActors) {
279
- if (actors.some((a) => a.code?.body)) xstateImports.push("fromPromise");
280
- }
281
- return `import { ${xstateImports.join(", ")} } from 'xstate';`;
282
- }
283
- function buildSetupObject(schemas, impls) {
284
- const setup = {};
285
- const types = buildTypesBlock(schemas);
286
- if (types) setup.types = types;
287
- if (impls?.actions.length) setup.actions = buildActionsBlock(impls.actions);
288
- if (impls?.guards.length) setup.guards = buildGuardsBlock(impls.guards);
289
- if (impls?.actors.length) setup.actors = buildActorsBlock(impls.actors);
290
- if (impls?.delays.length) setup.delays = buildDelaysBlock(impls.delays);
291
- return setup;
292
- }
293
- function buildTypesBlock(schemas) {
294
- if (!schemas) return void 0;
295
- const types = {};
296
- const contextType = contextSchemaToTSType(schemas.context);
297
- if (contextType) types.context = raw(`{} as ${contextType}`);
298
- const eventsType = eventsSchemaToTSType(schemas.events);
299
- if (eventsType) types.events = raw(`{} as\n | ${eventsType}`);
300
- if (schemas.input) types.input = raw(`{} as ${jsonSchemaToTSType(schemas.input)}`);
301
- if (schemas.output) types.output = raw(`{} as ${jsonSchemaToTSType(schemas.output)}`);
302
- return Object.keys(types).length > 0 ? types : void 0;
303
- }
304
- function hasSchemaProperties(schema) {
305
- if (!schema) return false;
306
- if (schema.type === "object" || schema.properties) {
307
- const props = schema.properties;
308
- return !!props && Object.keys(props).length > 0;
309
- }
310
- return true;
311
- }
312
- function buildActionsBlock(actions) {
313
- const block = {};
314
- for (const implementation of actions) if (implementation.code?.body) {
315
- const params = hasSchemaProperties(implementation.paramsSchema) ? `, params: ${jsonSchemaToTSType(implementation.paramsSchema)}` : "";
316
- block[implementation.name] = raw(`function ({ context, event }${params ? params : ""}) {\n ${dedent(implementation.code.body)}\n}`);
317
- } else block[implementation.name] = raw(`function ({ context, event }) {\n // TODO: implement ${implementation.name}\n}`);
318
- return block;
319
- }
320
- function buildGuardsBlock(guards) {
321
- const block = {};
322
- for (const guard of guards) if (guard.code?.body) {
323
- const params = hasSchemaProperties(guard.paramsSchema) ? `, params: ${jsonSchemaToTSType(guard.paramsSchema)}` : "";
324
- block[guard.name] = raw(`function ({ context, event }${params ? params : ""}) {\n ${dedent(guard.code.body)}\n}`);
325
- } else block[guard.name] = raw(`function ({ context, event }) {\n // TODO: implement ${guard.name}\n return false;\n}`);
326
- return block;
327
- }
328
- function buildActorsBlock(actors) {
329
- const block = {};
330
- for (const actor of actors) if (actor.code?.body) {
331
- const inputType = hasSchemaProperties(actor.inputSchema) ? `: ${jsonSchemaToTSType(actor.inputSchema)}` : "";
332
- block[actor.name] = raw(`fromPromise(async ({ input }${inputType ? `: { input${inputType} }` : ""}) => {\n ${dedent(actor.code.body)}\n})`);
333
- } else block[actor.name] = raw(`fromPromise(async ({ input }) => {\n // TODO: implement ${actor.name}\n})`);
334
- return block;
335
- }
336
- function buildDelaysBlock(delays) {
337
- const block = {};
338
- for (const delay of delays) if (delay.code?.body) block[delay.name] = raw(`function ({ context, event }) {\n ${dedent(delay.code.body)}\n}`);
339
- else block[delay.name] = raw(`function () {\n // TODO: implement ${delay.name}\n return 1000;\n}`);
340
- return block;
341
- }
342
-
343
- //#endregion
344
- export { RawCode as a, graphToMachineConfig as c, upsertStatelyPragma as d, jsonSchemaToTSType as i, findStatelyPragmaAttachments as l, contextSchemaToTSType as n, raw as o, eventsSchemaToTSType as r, serializeJS as s, graphToXStateTS as t, getStatelyPragma as u };