@statelyai/sdk 0.17.0 → 0.20.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.
Files changed (33) hide show
  1. package/README.md +38 -2
  2. package/dist/auth.d.mts +1 -1
  3. package/dist/editor-sync-types-D8_EZm0A.d.mts +94 -0
  4. package/dist/editorHostProtocol-D_h4y3rX.mjs +5 -0
  5. package/dist/editorHostSession-CZHd22pZ.mjs +478 -0
  6. package/dist/editorHostSession-jnC5mQDN.d.mts +184 -0
  7. package/dist/editorHostSession.d.mts +2 -0
  8. package/dist/editorHostSession.mjs +4 -0
  9. package/dist/embed.d.mts +3 -3
  10. package/dist/embed.mjs +33 -3
  11. package/dist/{graph-DuOeLGvh.d.mts → graph-DxeqWHC3.d.mts} +1 -1
  12. package/dist/graph.d.mts +1 -1
  13. package/dist/index.d.mts +8 -7
  14. package/dist/index.mjs +8 -6
  15. package/dist/{inspect-BZFzyeew.d.mts → inspect-CGJR4iZK.d.mts} +13 -3
  16. package/dist/{inspect-CF_6aEnv.mjs → inspect-CWwLGwLq.mjs} +58 -31
  17. package/dist/inspect.d.mts +1 -1
  18. package/dist/inspect.mjs +2 -1
  19. package/dist/patchTypes.d.mts +1 -1
  20. package/dist/protocol.d.mts +66 -50
  21. package/dist/protocol.mjs +17 -3
  22. package/dist/{studio-txdyJHD7.mjs → schemas-C2raUv-n.mjs} +1 -396
  23. package/dist/{statelyPragma-Th0gdXfx.mjs → statelyPragma-GN-bfuC_.mjs} +2 -1
  24. package/dist/{studio-Bk_u41gu.d.mts → studio-DLduJRSp.d.mts} +2 -2
  25. package/dist/studio-EKd7cQN7.mjs +397 -0
  26. package/dist/studio.d.mts +1 -1
  27. package/dist/studio.mjs +1 -1
  28. package/dist/sync.d.mts +2 -2
  29. package/dist/sync.mjs +2 -2
  30. package/dist/{transport-B_ig9Znn.mjs → version-TY9EZF0F.mjs} +39 -5
  31. package/package.json +6 -2
  32. /package/dist/{auth-2Thaw42j.d.mts → auth-B0ZTKri2.d.mts} +0 -0
  33. /package/dist/{index-ag6K2iAS.d.mts → index-CKFbG_Ix.d.mts} +0 -0
@@ -1,3 +1,3 @@
1
1
  import { EditorCapabilities, EmbedEventHandler, EmbedEventMap, EmbedEventName, EmbedMode, ExportCallOptions, ExportFormat, ExportFormatMap, InspectionAction, InspectionSentEvent, InspectionTakenTransition } from "./protocol.mjs";
2
- import { a as InspectedTransition, c as InspectorInspectionEvent, d as createStatelyInspector, f as Transport, i as InspectedSnapshot, l as ManualActorOptions, n as CreateInspectorOptions, o as Inspector, r as InspectedEvent, s as InspectorEvents, t as AdoptedActor, u as createInspector } from "./inspect-BZFzyeew.mjs";
2
+ import { a as InspectedTransition, c as InspectorInspectionEvent, d as createStatelyInspector, f as Transport, i as InspectedSnapshot, l as ManualActorOptions, n as CreateInspectorOptions, o as Inspector, r as InspectedEvent, s as InspectorEvents, t as AdoptedActor, u as createInspector } from "./inspect-CGJR4iZK.mjs";
3
3
  export { AdoptedActor, CreateInspectorOptions, EditorCapabilities, EmbedEventHandler, EmbedEventMap, EmbedEventName, EmbedMode, ExportCallOptions, ExportFormat, ExportFormatMap, InspectedEvent, InspectedSnapshot, InspectedTransition, InspectionAction, InspectionSentEvent, InspectionTakenTransition, Inspector, InspectorEvents, InspectorInspectionEvent, ManualActorOptions, Transport, createInspector, createStatelyInspector };
package/dist/inspect.mjs CHANGED
@@ -1,3 +1,4 @@
1
- import { n as createStatelyInspector, t as createInspector } from "./inspect-CF_6aEnv.mjs";
1
+ import "./version-TY9EZF0F.mjs";
2
+ import { n as createStatelyInspector, t as createInspector } from "./inspect-CWwLGwLq.mjs";
2
3
 
3
4
  export { createInspector, createStatelyInspector };
@@ -1,2 +1,2 @@
1
- import { a as EditorStateType, n as CanvasColor, o as GraphPatch, s as ImplementationSourceType, t as ActionLocation } from "./index-ag6K2iAS.mjs";
1
+ import { a as EditorStateType, n as CanvasColor, o as GraphPatch, s as ImplementationSourceType, t as ActionLocation } from "./index-CKFbG_Ix.mjs";
2
2
  export { type ActionLocation, type CanvasColor, type EditorStateType, type GraphPatch, type ImplementationSourceType };
@@ -1,12 +1,13 @@
1
- import { i as StatelyGraph } from "./graph-DuOeLGvh.mjs";
1
+ import { i as StatelyGraph } from "./graph-DxeqWHC3.mjs";
2
+ import { c as EditorSyncSourceLocation, f as MachineSourceLocations$1, l as EditorSyncSourceRange, t as EditorCapabilities$1, u as EditorSyncStateSourceLocation } from "./editor-sync-types-D8_EZm0A.mjs";
2
3
 
3
4
  //#region src/protocol.d.ts
4
5
  /** Query parameter carrying the unguessable inspection room capability. */
5
6
  declare const INSPECTION_ROOM_QUERY_PARAM = "r";
6
7
  /**
7
8
  * Create the room-global identity for one producer-local actor session.
8
- * XState session ids are process-local; the producer id supplies the missing
9
- * cross-process namespace.
9
+ * Runtime and producer-resolved session ids may use different uniqueness
10
+ * domains; the producer id supplies a stable room namespace.
10
11
  */
11
12
  declare function createInspectionActorId(producerId: string, sessionId: string): string;
12
13
  interface InspectionRoomUrls {
@@ -35,23 +36,28 @@ interface ProjectEmbedMachine {
35
36
  name?: string;
36
37
  machine: unknown;
37
38
  }
39
+ declare const EMBED_DOCUMENT_LANGUAGES: readonly ["markdown", "typescript", "javascript", "json", "xml", "mermaid", "text"];
40
+ type EmbedDocumentLanguage = (typeof EMBED_DOCUMENT_LANGUAGES)[number];
41
+ declare const EMBED_DOCUMENT_LIMITS: {
42
+ readonly maxDocuments: 100;
43
+ readonly maxDocumentLength: number;
44
+ readonly maxTotalLength: number;
45
+ };
46
+ /** Read-only text supplied by an embed host for display beside a machine. */
47
+ interface EmbedDocument {
48
+ /** Relative POSIX path used as the document's stable identity. */
49
+ path: string;
50
+ content: string;
51
+ /** Overrides renderer detection from the path's file extension. */
52
+ language?: EmbedDocumentLanguage;
53
+ }
38
54
  interface ValidationIssue {
39
55
  nodeIds: string[];
40
56
  edgeIds: string[];
41
57
  level: 'info' | 'warning' | 'error';
42
58
  message: string;
43
59
  }
44
- interface EditorCapabilities {
45
- edit?: boolean;
46
- export?: boolean;
47
- ai?: boolean;
48
- simulate?: boolean;
49
- inspect?: boolean;
50
- navigateHierarchy?: boolean;
51
- maxDepth?: number;
52
- panels?: string[];
53
- commands?: string[];
54
- }
60
+ type EditorCapabilities = EditorCapabilities$1;
55
61
  type ReadOnlyReason = 'free-plan' | 'access-unverified';
56
62
  type CapabilityDeniedCapability = 'edit' | 'export' | 'ai' | 'simulate' | 'inspect' | 'navigateHierarchy' | 'panel' | 'mode';
57
63
  interface CapabilityDeniedEvent {
@@ -61,39 +67,10 @@ interface CapabilityDeniedEvent {
61
67
  message: string;
62
68
  dedupeKey: string;
63
69
  }
64
- interface SourceRange {
65
- startLine: number;
66
- startChar: number;
67
- endLine: number;
68
- endChar: number;
69
- }
70
- interface SourceLocation {
71
- uri: string;
72
- range: SourceRange;
73
- }
74
- interface StateSourceLocation extends SourceLocation {
75
- path: string[];
76
- kind: 'inline' | 'objectReference' | 'createStateConfig';
77
- symbol?: string;
78
- keyRange?: SourceRange;
79
- referenceRange?: SourceRange;
80
- keySource?: {
81
- kind: 'const' | 'enumMember' | 'computedLiteral';
82
- symbol?: string;
83
- valueRange?: SourceRange;
84
- machineLocal?: boolean;
85
- };
86
- keyReplacementText?: string;
87
- }
88
- interface MachineSourceLocations {
89
- version: 1;
90
- root?: SourceLocation;
91
- statesObject?: StateSourceLocation;
92
- states: StateSourceLocation[];
93
- staticValues?: Array<SourceLocation & {
94
- value: string;
95
- }>;
96
- }
70
+ type SourceRange = EditorSyncSourceRange;
71
+ type SourceLocation = EditorSyncSourceLocation;
72
+ type StateSourceLocation = EditorSyncStateSourceLocation;
73
+ type MachineSourceLocations = MachineSourceLocations$1;
97
74
  interface ExportFormatMap {
98
75
  xstate: {
99
76
  options: {
@@ -198,6 +175,8 @@ type EmbedEventName = keyof EmbedEventMap;
198
175
  type EmbedEventHandler<K extends EmbedEventName> = (data: EmbedEventMap[K]) => void;
199
176
  interface MachineInitOptions {
200
177
  machine: unknown;
178
+ /** Ephemeral, read-only reference documents owned by the embed host. */
179
+ documents?: EmbedDocument[];
201
180
  format?: string;
202
181
  mode?: EmbedMode;
203
182
  theme?: 'light' | 'dark';
@@ -232,6 +211,8 @@ interface MachineInitOptions {
232
211
  }
233
212
  interface ProjectInitOptions {
234
213
  machines: ProjectEmbedMachine[];
214
+ /** Ephemeral, read-only reference documents shared across the project. */
215
+ documents?: EmbedDocument[];
235
216
  currentMachineId?: string;
236
217
  mode?: EmbedMode;
237
218
  theme?: 'light' | 'dark';
@@ -254,6 +235,7 @@ type InitOptions = MachineInitOptions | ProjectInitOptions;
254
235
  interface InitMessage {
255
236
  type: '@statelyai.init';
256
237
  machine: unknown;
238
+ documents?: EmbedDocument[];
257
239
  format?: string;
258
240
  mode?: EmbedMode;
259
241
  theme?: 'light' | 'dark';
@@ -277,9 +259,33 @@ interface SetApiKeyMessage {
277
259
  type: '@statelyai.setApiKey';
278
260
  apiKey: string;
279
261
  }
262
+ interface SavedMessage {
263
+ type: '@statelyai.saved';
264
+ graph: unknown;
265
+ }
266
+ interface ClipboardReadResponseMessage {
267
+ type: '@statelyai.clipboardReadResponse';
268
+ requestId: string;
269
+ text: string;
270
+ }
271
+ interface ClipboardWriteResponseMessage {
272
+ type: '@statelyai.clipboardWriteResponse';
273
+ requestId: string;
274
+ ok: boolean;
275
+ }
276
+ interface ClipboardReadMessage {
277
+ type: '@statelyai.clipboardRead';
278
+ requestId: string;
279
+ }
280
+ interface ClipboardWriteMessage {
281
+ type: '@statelyai.clipboardWrite';
282
+ requestId: string;
283
+ text: string;
284
+ }
280
285
  interface ProjectInitMessage {
281
286
  type: '@statelyai.project.init';
282
287
  machines: ProjectEmbedMachine[];
288
+ documents?: EmbedDocument[];
283
289
  currentMachineId?: string;
284
290
  mode?: EmbedMode;
285
291
  theme?: 'light' | 'dark';
@@ -384,6 +390,7 @@ interface SystemInitMessage {
384
390
  actors: ActorSystemEntry[];
385
391
  /** Actor session id the viz should focus first. Defaults to the root. */
386
392
  selectedSessionId?: string;
393
+ documents?: EmbedDocument[];
387
394
  mode?: EmbedMode;
388
395
  theme?: 'light' | 'dark';
389
396
  readOnly?: boolean;
@@ -441,6 +448,15 @@ interface SystemActorStoppedMessage {
441
448
  interface ReadyMessage {
442
449
  type: '@statelyai.ready';
443
450
  version: string;
451
+ protocolVersion?: number;
452
+ }
453
+ interface EditorHandshakeMessage {
454
+ type: '@statelyai.handshake';
455
+ protocolVersion: number;
456
+ client?: {
457
+ name: string;
458
+ version: string;
459
+ };
444
460
  }
445
461
  interface LoadedMessage {
446
462
  type: '@statelyai.loaded';
@@ -524,9 +540,9 @@ interface UploadResponseMessage {
524
540
  result: UploadResult;
525
541
  }
526
542
  /** All messages a client (embed/inspector) can send to the viz. */
527
- type ClientMessage = InitMessage | SetApiKeyMessage | ProjectInitMessage | ProjectUpdateMessage | ProjectSelectMachineMessage | UpdateMessage | SetModeMessage | SetThemeMessage | SetSettingsMessage | RetrieveMessage | ToastMessage | InspectSnapshotMessage | SystemInitMessage | SystemSelectActorMessage | SystemActorRegisteredMessage | SystemActorEventMessage | SystemActorSnapshotMessage | SystemActorStoppedMessage | UploadCapabilitiesMessage | UploadResponseMessage | ErrorMessage;
543
+ type ClientMessage = InitMessage | SetApiKeyMessage | EditorHandshakeMessage | SavedMessage | ClipboardReadResponseMessage | ClipboardWriteResponseMessage | ProjectInitMessage | ProjectUpdateMessage | ProjectSelectMachineMessage | UpdateMessage | SetModeMessage | SetThemeMessage | SetSettingsMessage | RetrieveMessage | ToastMessage | InspectSnapshotMessage | SystemInitMessage | SystemSelectActorMessage | SystemActorRegisteredMessage | SystemActorEventMessage | SystemActorSnapshotMessage | SystemActorStoppedMessage | UploadCapabilitiesMessage | UploadResponseMessage | ErrorMessage;
528
544
  /** All messages the viz can send back to a client. */
529
- type VizMessage = ReadyMessage | LoadedMessage | ChangeMessage | SaveMessage | ProjectMachineSelectedMessage | RetrievedMessage | ErrorMessage | CapabilityDeniedMessage | UploadRequestMessage;
545
+ type VizMessage = ReadyMessage | LoadedMessage | ChangeMessage | SaveMessage | ProjectMachineSelectedMessage | RetrievedMessage | ErrorMessage | CapabilityDeniedMessage | ClipboardReadMessage | ClipboardWriteMessage | UploadRequestMessage;
530
546
  interface InspectionClientMetadata {
531
547
  name?: string;
532
548
  machineId?: string;
@@ -555,4 +571,4 @@ declare const PREFIX = "@statelyai.";
555
571
  /** Current WebSocket inspection protocol version. */
556
572
  declare const INSPECTION_PROTOCOL_VERSION = 2;
557
573
  //#endregion
558
- export { ActorSystemEntry, CapabilityDeniedCapability, CapabilityDeniedEvent, CapabilityDeniedMessage, ChangeMessage, ClientMessage, CommentsConfig, EditorCapabilities, EmbedEventHandler, EmbedEventMap, EmbedEventName, EmbedMode, ErrorMessage, ExportCallOptions, ExportFormat, ExportFormatMap, INSPECTION_PROTOCOL_VERSION, INSPECTION_ROOM_QUERY_PARAM, InitMessage, InitOptions, InspectSnapshotMessage, InspectionAction, InspectionClientMetadata, InspectionRoomUrls, InspectionSentEvent, InspectionTakenTransition, LoadedMessage, MachineInitOptions, MachineSourceLocations, PREFIX, ProjectEmbedMachine, ProjectInitMessage, ProjectInitOptions, ProjectMachineSelectedMessage, ProjectSelectMachineMessage, ProjectUpdateMessage, ProtocolMessage, ReadOnlyReason, ReadyMessage, RegisterMessage, RegisteredMessage, RetrieveMessage, RetrievedMessage, SaveMessage, SessionMessage, SetApiKeyMessage, SetModeMessage, SetSettingsMessage, SetThemeMessage, SourceLocation, SourceRange, StateSourceLocation, SystemActorEventMessage, SystemActorRegisteredMessage, SystemActorSnapshotMessage, SystemActorStoppedMessage, SystemInitMessage, SystemSelectActorMessage, ToastMessage, UpdateMessage, UploadCapabilitiesMessage, UploadFileInfo, UploadRequestMessage, UploadResponseMessage, UploadResult, ValidationIssue, VizMessage, createInspectionActorId, createInspectionRoomUrls, getInspectionRoomId };
574
+ export { ActorSystemEntry, CapabilityDeniedCapability, CapabilityDeniedEvent, CapabilityDeniedMessage, ChangeMessage, ClientMessage, ClipboardReadMessage, ClipboardReadResponseMessage, ClipboardWriteMessage, ClipboardWriteResponseMessage, CommentsConfig, EMBED_DOCUMENT_LANGUAGES, EMBED_DOCUMENT_LIMITS, EditorCapabilities, EditorHandshakeMessage, EmbedDocument, EmbedDocumentLanguage, EmbedEventHandler, EmbedEventMap, EmbedEventName, EmbedMode, ErrorMessage, ExportCallOptions, ExportFormat, ExportFormatMap, INSPECTION_PROTOCOL_VERSION, INSPECTION_ROOM_QUERY_PARAM, InitMessage, InitOptions, InspectSnapshotMessage, InspectionAction, InspectionClientMetadata, InspectionRoomUrls, InspectionSentEvent, InspectionTakenTransition, LoadedMessage, MachineInitOptions, MachineSourceLocations, PREFIX, ProjectEmbedMachine, ProjectInitMessage, ProjectInitOptions, ProjectMachineSelectedMessage, ProjectSelectMachineMessage, ProjectUpdateMessage, ProtocolMessage, ReadOnlyReason, ReadyMessage, RegisterMessage, RegisteredMessage, RetrieveMessage, RetrievedMessage, SaveMessage, SavedMessage, SessionMessage, SetApiKeyMessage, SetModeMessage, SetSettingsMessage, SetThemeMessage, SourceLocation, SourceRange, StateSourceLocation, SystemActorEventMessage, SystemActorRegisteredMessage, SystemActorSnapshotMessage, SystemActorStoppedMessage, SystemInitMessage, SystemSelectActorMessage, ToastMessage, UpdateMessage, UploadCapabilitiesMessage, UploadFileInfo, UploadRequestMessage, UploadResponseMessage, UploadResult, ValidationIssue, VizMessage, createInspectionActorId, createInspectionRoomUrls, getInspectionRoomId };
package/dist/protocol.mjs CHANGED
@@ -3,8 +3,8 @@
3
3
  const INSPECTION_ROOM_QUERY_PARAM = "r";
4
4
  /**
5
5
  * Create the room-global identity for one producer-local actor session.
6
- * XState session ids are process-local; the producer id supplies the missing
7
- * cross-process namespace.
6
+ * Runtime and producer-resolved session ids may use different uniqueness
7
+ * domains; the producer id supplies a stable room namespace.
8
8
  */
9
9
  function createInspectionActorId(producerId, sessionId) {
10
10
  return `${encodeURIComponent(producerId)}:${encodeURIComponent(sessionId)}`;
@@ -38,9 +38,23 @@ function createInspectionRoomUrls(options) {
38
38
  function getInspectionRoomId(value) {
39
39
  return new URL(value).searchParams.get(INSPECTION_ROOM_QUERY_PARAM)?.trim() || null;
40
40
  }
41
+ const EMBED_DOCUMENT_LANGUAGES = [
42
+ "markdown",
43
+ "typescript",
44
+ "javascript",
45
+ "json",
46
+ "xml",
47
+ "mermaid",
48
+ "text"
49
+ ];
50
+ const EMBED_DOCUMENT_LIMITS = {
51
+ maxDocuments: 100,
52
+ maxDocumentLength: 512 * 1024,
53
+ maxTotalLength: 2 * 1024 * 1024
54
+ };
41
55
  const PREFIX = "@statelyai.";
42
56
  /** Current WebSocket inspection protocol version. */
43
57
  const INSPECTION_PROTOCOL_VERSION = 2;
44
58
 
45
59
  //#endregion
46
- export { INSPECTION_PROTOCOL_VERSION, INSPECTION_ROOM_QUERY_PARAM, PREFIX, createInspectionActorId, createInspectionRoomUrls, getInspectionRoomId };
60
+ export { EMBED_DOCUMENT_LANGUAGES, EMBED_DOCUMENT_LIMITS, INSPECTION_PROTOCOL_VERSION, INSPECTION_ROOM_QUERY_PARAM, PREFIX, createInspectionActorId, createInspectionRoomUrls, getInspectionRoomId };
@@ -1,5 +1,3 @@
1
- import { createAuthorizationHeader, getCredentialToken } from "./auth.mjs";
2
-
3
1
  //#region ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js
4
2
  var _a$1;
5
3
  function $constructor(name, initializer, params) {
@@ -4329,397 +4327,4 @@ const describe = describe$1;
4329
4327
  const meta = meta$1;
4330
4328
 
4331
4329
  //#endregion
4332
- //#region ../api-contract/dist/errors.mjs
4333
- /**
4334
- * Error shape returned by every `/api/v1` machine operation (and by the shared
4335
- * auth guard). Each operation registers its own error schema component in the
4336
- * OpenAPI document, so this is a factory rather than a single shared instance.
4337
- */
4338
- function createApiErrorResponseSchema() {
4339
- return object({
4340
- error: string(),
4341
- issues: array(unknown()).optional()
4342
- });
4343
- }
4344
- const apiErrorResponseSchema = createApiErrorResponseSchema();
4345
- /**
4346
- * Canonical error codes for the `/api/v1` resource operations. Machine
4347
- * operations keep the flat `{ error: string }` shape above unchanged; the
4348
- * nested envelope below applies to resource operations only.
4349
- */
4350
- const resourceErrorCodeSchema = _enum([
4351
- "bad_request",
4352
- "unauthenticated",
4353
- "forbidden",
4354
- "not_found",
4355
- "conflict",
4356
- "payload_too_large",
4357
- "rate_limited",
4358
- "capability_disabled",
4359
- "upstream_error",
4360
- "internal_error"
4361
- ]);
4362
- /** Factory, matching `createApiErrorResponseSchema`, for per-route OpenAPI components. */
4363
- function createResourceApiErrorResponseSchema() {
4364
- return object({ error: object({
4365
- code: resourceErrorCodeSchema,
4366
- message: string(),
4367
- issues: array(unknown()).optional(),
4368
- retryable: boolean().optional()
4369
- }) });
4370
- }
4371
- const resourceApiErrorResponseSchema = createResourceApiErrorResponseSchema();
4372
-
4373
- //#endregion
4374
- //#region ../api-contract/dist/resources.mjs
4375
- /**
4376
- * Canonical schemas for persistent `/api/v1` resources plus the owned,
4377
- * deterministic code-extraction operation.
4378
- *
4379
- * These models are canonical, not upstream-shaped: providers (e.g. the Stately
4380
- * Registry adapter) are responsible for translating upstream envelopes,
4381
- * identifier quirks and casing into these shapes. No `{ data }` envelope
4382
- * appears anywhere; all timestamps are ISO strings.
4383
- */
4384
- /**
4385
- * XState major versions the editor targets (see
4386
- * `packages/editor/src/formats/xstate.ts`).
4387
- */
4388
- const xstateVersionSchema = union([literal(5), literal(6)]);
4389
- const projectVisibilitySchema = _enum([
4390
- "public",
4391
- "unlisted",
4392
- "private"
4393
- ]);
4394
- const verifyResultSchema = object({
4395
- valid: literal(true),
4396
- tokenScope: _enum(["user", "project"])
4397
- });
4398
- const projectSummarySchema = object({
4399
- projectId: string(),
4400
- projectVersionId: string(),
4401
- name: string(),
4402
- description: string().nullable(),
4403
- visibility: projectVisibilitySchema,
4404
- createdAt: string(),
4405
- updatedAt: string()
4406
- });
4407
- const projectSchema = projectSummarySchema.extend({
4408
- rootMachineId: string().nullable(),
4409
- machines: array(object({ machineId: string() }))
4410
- });
4411
- /**
4412
- * `name` is optional: the Registry project envelope only returns machine ids.
4413
- * Providers that can supply names cheaply should.
4414
- */
4415
- const projectMachineSummarySchema = object({
4416
- machineId: string(),
4417
- name: string().optional()
4418
- });
4419
- const machineSchema = object({
4420
- machineId: string(),
4421
- name: string(),
4422
- projectId: string().optional(),
4423
- projectVersionId: string(),
4424
- definition: unknown(),
4425
- createdAt: string().optional(),
4426
- updatedAt: string().optional()
4427
- });
4428
- const machineVersionSchema = object({
4429
- machineVersionId: string(),
4430
- machineId: string(),
4431
- versionNumber: number(),
4432
- name: string(),
4433
- definition: unknown(),
4434
- createdAt: string(),
4435
- updatedAt: string()
4436
- });
4437
- const extractedMachinesSchema = object({ machines: array(object({ config: record(string(), unknown()) })) });
4438
- const projectsCreateRequestSchema = object({
4439
- name: string().min(1),
4440
- visibility: projectVisibilitySchema
4441
- });
4442
- const projectsUpdateRequestSchema = object({
4443
- name: string().min(1).optional(),
4444
- description: string().nullable().optional(),
4445
- visibility: projectVisibilitySchema.optional()
4446
- }).refine((value) => value.name !== void 0 || value.description !== void 0 || value.visibility !== void 0, { message: "At least one of `name`, `description` or `visibility` is required." });
4447
- const machinesCreateRequestSchema = object({
4448
- projectVersionId: string().min(1),
4449
- xstateVersion: xstateVersionSchema,
4450
- name: string().min(1).optional(),
4451
- definition: unknown().optional()
4452
- });
4453
- const machinesUpdateRequestSchema = object({
4454
- name: string().min(1).optional(),
4455
- definition: unknown().optional()
4456
- }).refine((value) => value.name !== void 0 || value.definition !== void 0, { message: "At least one of `name` or `definition` is required." });
4457
- const codeExtractMachinesRequestSchema = object({
4458
- code: string().min(1),
4459
- xstateVersion: xstateVersionSchema.optional()
4460
- });
4461
- const authVerifyResponseSchema = verifyResultSchema;
4462
- const projectsListResponseSchema = array(projectSummarySchema);
4463
- const projectsGetResponseSchema = projectSchema;
4464
- const projectsCreateResponseSchema = projectSchema;
4465
- const projectsUpdateResponseSchema = projectSchema;
4466
- const projectsDeleteResponseSchema = object({ projectId: string() });
4467
- const projectsListMachinesResponseSchema = array(projectMachineSummarySchema);
4468
- const machinesCreateResponseSchema = machineSchema;
4469
- const machinesGetResponseSchema = machineSchema;
4470
- const machinesUpdateResponseSchema = machineSchema;
4471
- const machinesGetVersionResponseSchema = machineVersionSchema;
4472
- const codeExtractMachinesResponseSchema = extractedMachinesSchema;
4473
- /**
4474
- * Request/response schema pairs keyed by resource capability name. Kept here
4475
- * rather than on the `Capability` metadata entries so that the capability
4476
- * registry stays plain, serialisable data.
4477
- */
4478
- const resourceOperationSchemas = {
4479
- "auth.verify": { response: authVerifyResponseSchema },
4480
- "projects.list": { response: projectsListResponseSchema },
4481
- "projects.create": {
4482
- request: projectsCreateRequestSchema,
4483
- response: projectsCreateResponseSchema
4484
- },
4485
- "projects.get": { response: projectsGetResponseSchema },
4486
- "projects.update": {
4487
- request: projectsUpdateRequestSchema,
4488
- response: projectsUpdateResponseSchema
4489
- },
4490
- "projects.delete": { response: projectsDeleteResponseSchema },
4491
- "projects.listMachines": { response: projectsListMachinesResponseSchema },
4492
- "machines.create": {
4493
- request: machinesCreateRequestSchema,
4494
- response: machinesCreateResponseSchema
4495
- },
4496
- "machines.get": { response: machinesGetResponseSchema },
4497
- "machines.getVersion": { response: machinesGetVersionResponseSchema },
4498
- "machines.update": {
4499
- request: machinesUpdateRequestSchema,
4500
- response: machinesUpdateResponseSchema
4501
- }
4502
- };
4503
- /** Provider-independent operations implemented by this repository. */
4504
- const codeOperationSchemas = { "code.extractMachines": {
4505
- request: codeExtractMachinesRequestSchema,
4506
- response: codeExtractMachinesResponseSchema
4507
- } };
4508
- /** Every owned API operation with a canonical request/response contract. */
4509
- const operationSchemas = {
4510
- ...resourceOperationSchemas,
4511
- ...codeOperationSchemas
4512
- };
4513
-
4514
- //#endregion
4515
- //#region src/studio.ts
4516
- /**
4517
- * Remote client for the owned Stately resource contract (`/api/v1/*`).
4518
- *
4519
- * Every method targets our own routes (never the legacy Registry API), sends
4520
- * JSON bodies with a bearer credential, and validates responses against the
4521
- * canonical Zod schemas from `@statelyai/api-contract`. Responses are canonical
4522
- * values directly: there is no `{ data }` envelope. Errors use the nested
4523
- * envelope `{ error: { code, message, issues?, retryable? } }`.
4524
- */
4525
- /** Default base URL of the editor/API deployment hosting `/api/v1`. */
4526
- const DEFAULT_STATELY_BASE_URL = "https://editor.stately.ai";
4527
- var StudioApiError = class extends Error {
4528
- status;
4529
- /** Canonical resource error code, when the server sent one. */
4530
- code;
4531
- issues;
4532
- retryable;
4533
- constructor(message, status, options = {}) {
4534
- super(message);
4535
- this.name = "StudioApiError";
4536
- this.status = status;
4537
- this.code = options.code;
4538
- this.issues = options.issues;
4539
- this.retryable = options.retryable;
4540
- }
4541
- };
4542
- function getFetch(fetchImpl) {
4543
- const resolvedFetch = fetchImpl ?? globalThis.fetch;
4544
- if (!resolvedFetch) throw new Error("No fetch implementation available. Pass one via createStatelyClient({ fetch }).");
4545
- return resolvedFetch;
4546
- }
4547
- function joinApiUrl(baseUrl, path) {
4548
- return `${baseUrl.replace(/\/+$/, "")}/api/v1${path}`;
4549
- }
4550
- async function parseJson(response) {
4551
- if (!response.headers.get("content-type")?.includes("application/json")) return null;
4552
- return response.json().catch(() => null);
4553
- }
4554
- function toApiError(data, status) {
4555
- const parsed = resourceApiErrorResponseSchema.safeParse(data);
4556
- if (parsed.success) {
4557
- const { code, message, issues, retryable } = parsed.data.error;
4558
- return new StudioApiError(message, status, {
4559
- code,
4560
- issues,
4561
- retryable
4562
- });
4563
- }
4564
- if (typeof data === "object" && data !== null && "error" in data && typeof data.error === "string") return new StudioApiError(data.error, status);
4565
- return new StudioApiError(`HTTP ${status}`, status);
4566
- }
4567
- function normalizeVisibility(visibility) {
4568
- return visibility.toLowerCase();
4569
- }
4570
- function normalizeXStateVersion(xstateVersion) {
4571
- return xstateVersion === void 0 || xstateVersion === 4 ? 5 : xstateVersion;
4572
- }
4573
- function normalizeExtractXStateVersion(xstateVersion) {
4574
- return xstateVersion === 4 ? 5 : xstateVersion;
4575
- }
4576
- function withMachineAlias(machine) {
4577
- return {
4578
- ...machine,
4579
- definition: machine.definition,
4580
- id: machine.machineId
4581
- };
4582
- }
4583
- function withProjectAlias(project) {
4584
- return {
4585
- ...project,
4586
- id: project.projectVersionId
4587
- };
4588
- }
4589
- function isCredentialLike(value) {
4590
- if (typeof value === "string") return true;
4591
- return typeof value === "object" && value !== null && "type" in value && (value.type === "api_key" || value.type === "oauth");
4592
- }
4593
- function createStatelyClient(options = {}) {
4594
- const baseUrl = options.baseUrl ?? DEFAULT_STATELY_BASE_URL;
4595
- const fetchImpl = getFetch(options.fetch);
4596
- const defaultCredential = options.credential ?? (options.apiKey ? {
4597
- type: "api_key",
4598
- token: options.apiKey
4599
- } : void 0);
4600
- const defaultAuthMode = options.authMode ?? "auto";
4601
- async function request(path, init, schema, requestOptions = {}) {
4602
- const headers = new Headers(init.headers);
4603
- const authMode = requestOptions.authMode ?? defaultAuthMode;
4604
- const credential = requestOptions.credential ?? defaultCredential;
4605
- if (authMode !== "none") {
4606
- const token = getCredentialToken(credential);
4607
- if (authMode === "bearer" && (!token || !credential)) throw new StudioApiError("No Stately credential configured. Pass createStatelyClient({ credential }) or use authMode: \"auto\" to let the server decide whether authentication is required.", 401, { code: "unauthenticated" });
4608
- if (token && credential) headers.set("Authorization", createAuthorizationHeader(credential));
4609
- }
4610
- const response = await fetchImpl(joinApiUrl(baseUrl, path), {
4611
- ...init,
4612
- headers,
4613
- ...requestOptions.signal ? { signal: requestOptions.signal } : {}
4614
- });
4615
- const data = await parseJson(response);
4616
- if (!response.ok) throw toApiError(data, response.status);
4617
- const parsed = schema.safeParse(data);
4618
- if (!parsed.success) throw new StudioApiError(`Unexpected response for ${path}: ${parsed.error.message}`, response.status, {
4619
- code: "internal_error",
4620
- issues: [...parsed.error.issues]
4621
- });
4622
- return parsed.data;
4623
- }
4624
- function jsonInit(method, body) {
4625
- return {
4626
- method,
4627
- headers: { "Content-Type": "application/json" },
4628
- body: JSON.stringify(body)
4629
- };
4630
- }
4631
- const projects = {
4632
- list(requestOptions) {
4633
- return request("/projects", { method: "GET" }, projectsListResponseSchema, requestOptions);
4634
- },
4635
- create(input, requestOptions) {
4636
- return request("/projects", jsonInit("POST", {
4637
- name: input.name,
4638
- visibility: normalizeVisibility(input.visibility)
4639
- }), projectSchema, requestOptions).then(withProjectAlias);
4640
- },
4641
- get(projectId, requestOptions) {
4642
- return request(`/projects/${encodeURIComponent(projectId)}`, { method: "GET" }, projectSchema, requestOptions).then(withProjectAlias);
4643
- },
4644
- update(projectId, input, requestOptions) {
4645
- return request(`/projects/${encodeURIComponent(projectId)}`, jsonInit("PATCH", {
4646
- ...input.name !== void 0 ? { name: input.name } : {},
4647
- ...input.description !== void 0 ? { description: input.description } : {},
4648
- ...input.visibility !== void 0 ? { visibility: normalizeVisibility(input.visibility) } : {}
4649
- }), projectSchema, requestOptions).then(withProjectAlias);
4650
- },
4651
- delete(projectId, requestOptions) {
4652
- return request(`/projects/${encodeURIComponent(projectId)}`, { method: "DELETE" }, projectsDeleteResponseSchema, requestOptions);
4653
- },
4654
- listMachines(projectId, requestOptions) {
4655
- return request(`/projects/${encodeURIComponent(projectId)}/machines`, { method: "GET" }, projectsListMachinesResponseSchema, requestOptions);
4656
- },
4657
- async ensure(input, requestOptions) {
4658
- if (input.matchConnectedRepo !== false) {
4659
- const match = (await projects.list(requestOptions)).find((candidate) => candidate.name === input.name);
4660
- if (match) return projects.get(match.projectId, requestOptions);
4661
- }
4662
- return projects.create(input, requestOptions);
4663
- }
4664
- };
4665
- const machines = {
4666
- create(input, requestOptions) {
4667
- return request("/machines", jsonInit("POST", {
4668
- projectVersionId: input.projectVersionId,
4669
- xstateVersion: normalizeXStateVersion(input.xstateVersion),
4670
- ...input.name !== void 0 ? { name: input.name } : {},
4671
- ...input.definition !== void 0 ? { definition: input.definition } : {}
4672
- }), machineSchema, requestOptions).then((machine) => withMachineAlias(machine));
4673
- },
4674
- async createMany(input, requestOptions) {
4675
- return [await machines.create(input, requestOptions)];
4676
- },
4677
- get(machineId, getOptions = {}) {
4678
- return request(`/machines/${encodeURIComponent(machineId)}`, { method: "GET" }, machineSchema, getOptions).then((machine) => withMachineAlias(machine));
4679
- },
4680
- getVersion(machineId, versionId, requestOptions) {
4681
- return request(`/machines/${encodeURIComponent(machineId)}/versions/${encodeURIComponent(versionId)}`, { method: "GET" }, machineVersionSchema, requestOptions);
4682
- },
4683
- update(machineIdOrInput, inputOrOptions, maybeOptions) {
4684
- const machineId = typeof machineIdOrInput === "string" ? machineIdOrInput : machineIdOrInput.machineId ?? machineIdOrInput.id;
4685
- if (!machineId) throw new StudioApiError("machines.update requires a machine id.", 400, { code: "bad_request" });
4686
- const input = (typeof machineIdOrInput === "string" ? inputOrOptions : machineIdOrInput) ?? {};
4687
- const requestOptions = typeof machineIdOrInput === "string" ? maybeOptions : inputOrOptions;
4688
- return request(`/machines/${encodeURIComponent(machineId)}`, jsonInit("PATCH", {
4689
- ...input.name !== void 0 ? { name: input.name } : {},
4690
- ...input.definition !== void 0 ? { definition: input.definition } : {}
4691
- }), machineSchema, requestOptions).then((machine) => withMachineAlias(machine));
4692
- }
4693
- };
4694
- return {
4695
- auth: { verify(credentialOrOptions, verifyOptions) {
4696
- return request("/auth/verify", { method: "GET" }, verifyResultSchema, isCredentialLike(credentialOrOptions) ? {
4697
- ...verifyOptions,
4698
- credential: credentialOrOptions
4699
- } : credentialOrOptions ?? verifyOptions ?? {});
4700
- } },
4701
- projects,
4702
- machines,
4703
- code: { extractMachines(codeOrInput, extractOptions = {}) {
4704
- const input = typeof codeOrInput === "string" ? {
4705
- code: codeOrInput,
4706
- xstateVersion: extractOptions.xstateVersion
4707
- } : codeOrInput;
4708
- const legacyOptions = extractOptions;
4709
- const credential = legacyOptions.credential ?? (legacyOptions.apiKey ? {
4710
- type: "api_key",
4711
- token: legacyOptions.apiKey
4712
- } : void 0);
4713
- return request("/code/extract-machines", jsonInit("POST", {
4714
- code: input.code,
4715
- xstateVersion: normalizeExtractXStateVersion(input.xstateVersion)
4716
- }), extractedMachinesSchema, {
4717
- ...extractOptions,
4718
- credential
4719
- });
4720
- } }
4721
- };
4722
- }
4723
-
4724
- //#endregion
4725
- export { array as a, literal as c, record as d, string as f, _enum as i, number as l, unknown as m, StudioApiError as n, boolean as o, union as p, createStatelyClient as r, discriminatedUnion as s, DEFAULT_STATELY_BASE_URL as t, object as u };
4330
+ export { literal as a, record as c, unknown as d, discriminatedUnion as i, string as l, array as n, number as o, boolean as r, object as s, _enum as t, union as u };
@@ -1,5 +1,6 @@
1
- import { a as array, c as literal, d as record, f as string, i as _enum, l as number, m as unknown, o as boolean, p as union, s as discriminatedUnion, u as object } from "./studio-txdyJHD7.mjs";
1
+ import { a as literal, c as record, d as unknown, i as discriminatedUnion, l as string, n as array, o as number, r as boolean, s as object, t as _enum, u as union } from "./schemas-C2raUv-n.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