@hatchet-dev/typescript-sdk 1.28.2 → 1.29.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,4 +1,4 @@
1
- import { APIErrors, APIMeta, AcceptInviteRequest, BulkCreateEventRequest, CancelEventRequest, CreateAPITokenRequest, CreateAPITokenResponse, CreateCronWorkflowTriggerRequest, CreateEventRequest, CreateSNSIntegrationRequest, CreateTenantAlertEmailGroupRequest, CreateTenantInviteRequest, CreateTenantRequest, CronWorkflows, CronWorkflowsList, CronWorkflowsOrderByField, Event, EventData, EventKey, EventKeyList, EventList, EventOrderByDirection, EventOrderByField, EventSearch, Events, FeatureFlagEvaluationResult, FeatureFlagId, ListAPIMetaIntegration, ListAPITokensResponse, ListSNSIntegrations, ListSlackWebhooks, OtelSpanList, RateLimitList, RateLimitOrderByDirection, RateLimitOrderByField, RejectInviteRequest, ReplayEventRequest, ReplayWorkflowRunsRequest, ReplayWorkflowRunsResponse, RerunStepRunRequest, SNSIntegration, ScheduleWorkflowRunRequest, ScheduledRunStatus, ScheduledWorkflows, ScheduledWorkflowsBulkDeleteRequest, ScheduledWorkflowsBulkDeleteResponse, ScheduledWorkflowsBulkUpdateRequest, ScheduledWorkflowsBulkUpdateResponse, ScheduledWorkflowsList, ScheduledWorkflowsOrderByField, StepRun, StepRunArchiveList, StepRunEventList, TaskStats, Tenant, TenantAlertEmailGroup, TenantAlertEmailGroupList, TenantAlertingSettings, TenantInvite, TenantInviteList, TenantMember, TenantMemberList, TenantQueueMetrics, TenantResourcePolicy, TenantStepRunQueueMetrics, TriggerRunResult, TriggerWorkflowRunRequest, UpdateCronWorkflowTriggerRequest, UpdateScheduledWorkflowRunRequest, UpdateTenantAlertEmailGroupRequest, UpdateTenantInviteRequest, UpdateTenantMemberRequest, UpdateTenantRequest, UpdateWorkerRequest, User, UserChangePasswordRequest, UserLoginRequest, UserRegisterRequest, UserTenantMembershipsList, V1AdditionalMetadataOperator, V1BranchDurableTaskRequest, V1BranchDurableTaskResponse, V1CELDebugRequest, V1CELDebugResponse, V1CancelTaskRequest, V1CancelledTasks, V1CreateFilterRequest, V1CreateWebhookRequest, V1DagChildren, V1DurableEventLogList, V1Event, V1EventList, V1Filter, V1FilterList, V1LogLineLevel, V1LogLineList, V1LogLineOrderByDirection, V1LogsPointMetrics, V1ReplayTaskRequest, V1ReplayedTasks, V1RestoreTaskResponse, V1RunningFilter, V1TaskEventList, V1TaskPointMetrics, V1TaskRunMetrics, V1TaskStatus, V1TaskSummary, V1TaskSummaryList, V1TaskTimingList, V1TriggerWorkflowRunRequest, V1UpdateFilterRequest, V1UpdateWebhookRequest, V1Webhook, V1WebhookList, V1WebhookResponse, V1WebhookSourceName, V1WorkflowRunDetails, V1WorkflowRunDisplayNameList, V1WorkflowRunExternalIdList, WebhookWorkerCreateRequest, WebhookWorkerCreated, WebhookWorkerListResponse, WebhookWorkerRequestListResponse, Worker, WorkerList, WorkerStatus, Workflow, WorkflowID, WorkflowKindList, WorkflowList, WorkflowMetrics, WorkflowRun, WorkflowRunList, WorkflowRunOrderByDirection, WorkflowRunOrderByField, WorkflowRunShape, WorkflowRunStatus, WorkflowRunStatusList, WorkflowRunsCancelRequest, WorkflowRunsMetrics, WorkflowUpdateRequest, WorkflowVersion, WorkflowWorkersCount } from './data-contracts';
1
+ import { APIErrors, APIMeta, AcceptInviteRequest, BulkCreateEventRequest, CancelEventRequest, CreateAPITokenRequest, CreateAPITokenResponse, CreateCronWorkflowTriggerRequest, CreateEventRequest, CreateSNSIntegrationRequest, CreateTenantAlertEmailGroupRequest, CreateTenantInviteRequest, CreateTenantRequest, CronWorkflows, CronWorkflowsList, CronWorkflowsOrderByField, Event, EventData, EventKey, EventKeyList, EventList, EventOrderByDirection, EventOrderByField, EventSearch, Events, FeatureFlagEvaluationResult, FeatureFlagId, ListAPIMetaIntegration, ListAPITokensResponse, ListSNSIntegrations, ListSlackWebhooks, OtelSpanList, RateLimitList, RateLimitOrderByDirection, RateLimitOrderByField, RejectInviteRequest, ReplayEventRequest, ReplayWorkflowRunsRequest, ReplayWorkflowRunsResponse, RerunStepRunRequest, SNSIntegration, ScheduleWorkflowRunRequest, ScheduledRunStatus, ScheduledWorkflows, ScheduledWorkflowsBulkDeleteRequest, ScheduledWorkflowsBulkDeleteResponse, ScheduledWorkflowsBulkUpdateRequest, ScheduledWorkflowsBulkUpdateResponse, ScheduledWorkflowsList, ScheduledWorkflowsOrderByField, StepRun, StepRunArchiveList, StepRunEventList, TaskStats, Tenant, TenantAlertEmailGroup, TenantAlertEmailGroupList, TenantAlertingSettings, TenantInvite, TenantInviteList, TenantMember, TenantMemberList, TenantQueueMetrics, TenantResourcePolicy, TenantStepRunQueueMetrics, TriggerRunResult, TriggerWorkflowRunRequest, UpdateCronWorkflowTriggerRequest, UpdateScheduledWorkflowRunRequest, UpdateTenantAlertEmailGroupRequest, UpdateTenantInviteRequest, UpdateTenantMemberRequest, UpdateTenantRequest, UpdateWorkerRequest, User, UserChangePasswordRequest, UserLoginRequest, UserRegisterRequest, UserTenantMembershipsList, V1AdditionalMetadataOperator, V1BranchDurableTaskRequest, V1BranchDurableTaskResponse, V1CELDebugRequest, V1CELDebugResponse, V1CancelTaskRequest, V1CancelledTasks, V1CreateFilterRequest, V1CreateHTTPOperatorRequest, V1CreateWebhookRequest, V1DagChildren, V1DurableEventLogList, V1Event, V1EventList, V1Filter, V1FilterList, V1HTTPOperator, V1HTTPOperatorList, V1LogLineLevel, V1LogLineList, V1LogLineOrderByDirection, V1LogsPointMetrics, V1ReplayTaskRequest, V1ReplayedTasks, V1RestoreTaskResponse, V1RunningFilter, V1TaskEventList, V1TaskPointMetrics, V1TaskRunMetrics, V1TaskStatus, V1TaskSummary, V1TaskSummaryList, V1TaskTimingList, V1TriggerWorkflowRunRequest, V1UpdateFilterRequest, V1UpdateHTTPOperatorRequest, V1UpdateWebhookRequest, V1Webhook, V1WebhookList, V1WebhookResponse, V1WebhookSourceName, V1WorkflowRunDetails, V1WorkflowRunDisplayNameList, V1WorkflowRunExternalIdList, WebhookWorkerCreateRequest, WebhookWorkerCreated, WebhookWorkerListResponse, WebhookWorkerRequestListResponse, Worker, WorkerList, WorkerStatus, Workflow, WorkflowID, WorkflowKindList, WorkflowList, WorkflowMetrics, WorkflowRun, WorkflowRunList, WorkflowRunOrderByDirection, WorkflowRunOrderByField, WorkflowRunShape, WorkflowRunStatus, WorkflowRunStatusList, WorkflowRunsCancelRequest, WorkflowRunsMetrics, WorkflowUpdateRequest, WorkflowVersion, WorkflowWorkersCount } from './data-contracts';
2
2
  import { HttpClient, RequestParams } from './http-client';
3
3
  export declare class Api<SecurityDataType = unknown> extends HttpClient<SecurityDataType> {
4
4
  /**
@@ -601,6 +601,7 @@ export declare class Api<SecurityDataType = unknown> extends HttpClient<Security
601
601
  *
602
602
  * @tags Filter
603
603
  * @name V1FilterDelete
604
+ * @summary Delete a filter
604
605
  * @request DELETE:/api/v1/stable/tenants/{tenant}/filters/{v1-filter}
605
606
  * @secure
606
607
  */
@@ -610,6 +611,7 @@ export declare class Api<SecurityDataType = unknown> extends HttpClient<Security
610
611
  *
611
612
  * @tags Filter
612
613
  * @name V1FilterUpdate
614
+ * @summary Update a filter
613
615
  * @request PATCH:/api/v1/stable/tenants/{tenant}/filters/{v1-filter}
614
616
  * @secure
615
617
  */
@@ -664,6 +666,7 @@ export declare class Api<SecurityDataType = unknown> extends HttpClient<Security
664
666
  *
665
667
  * @tags Webhook
666
668
  * @name V1WebhookDelete
669
+ * @summary Delete a webhook
667
670
  * @request DELETE:/api/v1/stable/tenants/{tenant}/webhooks/{v1-webhook}
668
671
  * @secure
669
672
  */
@@ -687,6 +690,67 @@ export declare class Api<SecurityDataType = unknown> extends HttpClient<Security
687
690
  * @secure
688
691
  */
689
692
  v1WebhookUpdate: (tenant: string, v1Webhook: string, data: V1UpdateWebhookRequest, params?: RequestParams) => Promise<import("axios").AxiosResponse<V1Webhook, any, {}>>;
693
+ /**
694
+ * @description Lists all HTTP operators for a tenant.
695
+ *
696
+ * @tags Operator
697
+ * @name V1HttpOperatorList
698
+ * @summary List HTTP operators
699
+ * @request GET:/api/v1/stable/tenants/{tenant}/operators/http
700
+ * @secure
701
+ */
702
+ v1HttpOperatorList: (tenant: string, query?: {
703
+ /**
704
+ * The number to skip
705
+ * @format int64
706
+ */
707
+ offset?: number;
708
+ /**
709
+ * The number to limit by
710
+ * @format int64
711
+ */
712
+ limit?: number;
713
+ }, params?: RequestParams) => Promise<import("axios").AxiosResponse<V1HTTPOperatorList, any, {}>>;
714
+ /**
715
+ * @description Create a new HTTP operator
716
+ *
717
+ * @tags Operator
718
+ * @name V1HttpOperatorCreate
719
+ * @summary Create an HTTP operator
720
+ * @request POST:/api/v1/stable/tenants/{tenant}/operators/http
721
+ * @secure
722
+ */
723
+ v1HttpOperatorCreate: (tenant: string, data: V1CreateHTTPOperatorRequest, params?: RequestParams) => Promise<import("axios").AxiosResponse<V1HTTPOperator, any, {}>>;
724
+ /**
725
+ * @description Get an HTTP operator by its id
726
+ *
727
+ * @tags Operator
728
+ * @name V1HttpOperatorGet
729
+ * @summary Get an HTTP operator
730
+ * @request GET:/api/v1/stable/operators/http/{v1-http-operator}
731
+ * @secure
732
+ */
733
+ v1HttpOperatorGet: (v1HttpOperator: string, params?: RequestParams) => Promise<import("axios").AxiosResponse<V1HTTPOperator, any, {}>>;
734
+ /**
735
+ * @description Update an HTTP operator
736
+ *
737
+ * @tags Operator
738
+ * @name V1HttpOperatorUpdate
739
+ * @summary Update an HTTP operator
740
+ * @request PATCH:/api/v1/stable/operators/http/{v1-http-operator}
741
+ * @secure
742
+ */
743
+ v1HttpOperatorUpdate: (v1HttpOperator: string, data: V1UpdateHTTPOperatorRequest, params?: RequestParams) => Promise<import("axios").AxiosResponse<V1HTTPOperator, any, {}>>;
744
+ /**
745
+ * @description Delete an HTTP operator
746
+ *
747
+ * @tags Operator
748
+ * @name V1HttpOperatorDelete
749
+ * @summary Delete an HTTP operator
750
+ * @request DELETE:/api/v1/stable/operators/http/{v1-http-operator}
751
+ * @secure
752
+ */
753
+ v1HttpOperatorDelete: (v1HttpOperator: string, params?: RequestParams) => Promise<import("axios").AxiosResponse<V1HTTPOperator, any, {}>>;
690
754
  /**
691
755
  * @description Evaluate a CEL expression against provided input data.
692
756
  *
@@ -301,6 +301,7 @@ class Api extends http_client_1.HttpClient {
301
301
  *
302
302
  * @tags Filter
303
303
  * @name V1FilterDelete
304
+ * @summary Delete a filter
304
305
  * @request DELETE:/api/v1/stable/tenants/{tenant}/filters/{v1-filter}
305
306
  * @secure
306
307
  */
@@ -310,6 +311,7 @@ class Api extends http_client_1.HttpClient {
310
311
  *
311
312
  * @tags Filter
312
313
  * @name V1FilterUpdate
314
+ * @summary Update a filter
313
315
  * @request PATCH:/api/v1/stable/tenants/{tenant}/filters/{v1-filter}
314
316
  * @secure
315
317
  */
@@ -349,6 +351,7 @@ class Api extends http_client_1.HttpClient {
349
351
  *
350
352
  * @tags Webhook
351
353
  * @name V1WebhookDelete
354
+ * @summary Delete a webhook
352
355
  * @request DELETE:/api/v1/stable/tenants/{tenant}/webhooks/{v1-webhook}
353
356
  * @secure
354
357
  */
@@ -372,6 +375,56 @@ class Api extends http_client_1.HttpClient {
372
375
  * @secure
373
376
  */
374
377
  this.v1WebhookUpdate = (tenant, v1Webhook, data, params = {}) => this.request(Object.assign({ path: `/api/v1/stable/tenants/${tenant}/webhooks/${v1Webhook}`, method: 'PATCH', body: data, secure: true, type: http_client_1.ContentType.Json, format: 'json' }, params));
378
+ /**
379
+ * @description Lists all HTTP operators for a tenant.
380
+ *
381
+ * @tags Operator
382
+ * @name V1HttpOperatorList
383
+ * @summary List HTTP operators
384
+ * @request GET:/api/v1/stable/tenants/{tenant}/operators/http
385
+ * @secure
386
+ */
387
+ this.v1HttpOperatorList = (tenant, query, params = {}) => this.request(Object.assign({ path: `/api/v1/stable/tenants/${tenant}/operators/http`, method: 'GET', query: query, secure: true, format: 'json' }, params));
388
+ /**
389
+ * @description Create a new HTTP operator
390
+ *
391
+ * @tags Operator
392
+ * @name V1HttpOperatorCreate
393
+ * @summary Create an HTTP operator
394
+ * @request POST:/api/v1/stable/tenants/{tenant}/operators/http
395
+ * @secure
396
+ */
397
+ this.v1HttpOperatorCreate = (tenant, data, params = {}) => this.request(Object.assign({ path: `/api/v1/stable/tenants/${tenant}/operators/http`, method: 'POST', body: data, secure: true, type: http_client_1.ContentType.Json, format: 'json' }, params));
398
+ /**
399
+ * @description Get an HTTP operator by its id
400
+ *
401
+ * @tags Operator
402
+ * @name V1HttpOperatorGet
403
+ * @summary Get an HTTP operator
404
+ * @request GET:/api/v1/stable/operators/http/{v1-http-operator}
405
+ * @secure
406
+ */
407
+ this.v1HttpOperatorGet = (v1HttpOperator, params = {}) => this.request(Object.assign({ path: `/api/v1/stable/operators/http/${v1HttpOperator}`, method: 'GET', secure: true, format: 'json' }, params));
408
+ /**
409
+ * @description Update an HTTP operator
410
+ *
411
+ * @tags Operator
412
+ * @name V1HttpOperatorUpdate
413
+ * @summary Update an HTTP operator
414
+ * @request PATCH:/api/v1/stable/operators/http/{v1-http-operator}
415
+ * @secure
416
+ */
417
+ this.v1HttpOperatorUpdate = (v1HttpOperator, data, params = {}) => this.request(Object.assign({ path: `/api/v1/stable/operators/http/${v1HttpOperator}`, method: 'PATCH', body: data, secure: true, type: http_client_1.ContentType.Json, format: 'json' }, params));
418
+ /**
419
+ * @description Delete an HTTP operator
420
+ *
421
+ * @tags Operator
422
+ * @name V1HttpOperatorDelete
423
+ * @summary Delete an HTTP operator
424
+ * @request DELETE:/api/v1/stable/operators/http/{v1-http-operator}
425
+ * @secure
426
+ */
427
+ this.v1HttpOperatorDelete = (v1HttpOperator, params = {}) => this.request(Object.assign({ path: `/api/v1/stable/operators/http/${v1HttpOperator}`, method: 'DELETE', secure: true, format: 'json' }, params));
375
428
  /**
376
429
  * @description Evaluate a CEL expression against provided input data.
377
430
  *
@@ -141,6 +141,10 @@ export declare enum ScheduledWorkflowsMethod {
141
141
  DEFAULT = "DEFAULT",
142
142
  API = "API"
143
143
  }
144
+ export declare enum WorkflowPauseScheduledCronRunQueueBehavior {
145
+ DROP = "DROP",
146
+ QUEUE = "QUEUE"
147
+ }
144
148
  export declare enum RateLimitOrderByDirection {
145
149
  Asc = "asc",
146
150
  Desc = "desc"
@@ -169,7 +173,8 @@ export declare enum WorkflowRunStatus {
169
173
  export declare enum TenantMemberRole {
170
174
  OWNER = "OWNER",
171
175
  ADMIN = "ADMIN",
172
- MEMBER = "MEMBER"
176
+ MEMBER = "MEMBER",
177
+ VIEWER = "VIEWER"
173
178
  }
174
179
  export declare enum TenantResource {
175
180
  WORKER = "WORKER",
@@ -415,6 +420,8 @@ export interface V1TaskSummary {
415
420
  parentTaskExternalId?: string;
416
421
  /** The idempotency key that was claimed by the task run */
417
422
  idempotencyKey?: string;
423
+ /** True when input, output, and event payload fields were omitted because the caller cannot view payloads. Additional metadata is still included. */
424
+ payloadsRestricted?: boolean;
418
425
  }
419
426
  export interface APIError {
420
427
  /**
@@ -638,6 +645,8 @@ export interface V1WorkflowRun {
638
645
  * @maxLength 36
639
646
  */
640
647
  parentTaskExternalId?: string;
648
+ /** True when input, output, and event payload fields were omitted because the caller cannot view payloads. Additional metadata is still included. */
649
+ payloadsRestricted?: boolean;
641
650
  }
642
651
  export interface WorkflowRunShapeItemForWorkflowRunDetails {
643
652
  /**
@@ -957,6 +966,8 @@ export interface V1Event {
957
966
  triggeredRuns?: V1EventTriggeredRun[];
958
967
  /** The name of the webhook that triggered this event, if applicable. */
959
968
  triggeringWebhookName?: string;
969
+ /** True when the event payload was omitted because the caller cannot view payloads. Additional metadata is still included. */
970
+ payloadsRestricted?: boolean;
960
971
  }
961
972
  export interface V1EventList {
962
973
  pagination?: PaginationResponse;
@@ -1104,6 +1115,58 @@ export interface V1UpdateWebhookRequest {
1104
1115
  /** Whether to return the triggered event as the response payload when this webhook is triggered */
1105
1116
  returnEventAsResponsePayload?: boolean;
1106
1117
  }
1118
+ export interface V1HTTPOperator {
1119
+ metadata: APIResourceMeta;
1120
+ /**
1121
+ * The ID of the tenant associated with this operator.
1122
+ * @format uuid
1123
+ */
1124
+ tenantId: string;
1125
+ /** The name of the operator. */
1126
+ name: string;
1127
+ /** The HTTPS endpoint (https, port 443) that assigned tasks are delivered to. */
1128
+ triggerEndpoint: string;
1129
+ /** The HTTPS endpoint polled periodically to discover the actions this operator handles. */
1130
+ healthcheckEndpoint: string;
1131
+ /**
1132
+ * The per-request timeout backstop, in seconds.
1133
+ * @format int32
1134
+ */
1135
+ requestTimeoutSeconds: number;
1136
+ }
1137
+ export interface V1HTTPOperatorList {
1138
+ pagination?: PaginationResponse;
1139
+ rows?: V1HTTPOperator[];
1140
+ }
1141
+ export interface V1CreateHTTPOperatorRequest {
1142
+ /** The name of the operator. */
1143
+ name: string;
1144
+ /** The HTTPS endpoint (https, port 443) that assigned tasks are delivered to. */
1145
+ triggerEndpoint: string;
1146
+ /** The HTTPS endpoint polled periodically to discover the actions this operator handles. */
1147
+ healthcheckEndpoint: string;
1148
+ /** The secret used to HMAC-sign delivered requests (sent in the X-Hatchet-Signature header). Write-only: it is never returned in responses. */
1149
+ signingSecret: string;
1150
+ /**
1151
+ * The per-request timeout backstop, in seconds.
1152
+ * @format int32
1153
+ */
1154
+ requestTimeoutSeconds: number;
1155
+ }
1156
+ /** Fields to update on an HTTP operator. Omitted fields are left unchanged. */
1157
+ export interface V1UpdateHTTPOperatorRequest {
1158
+ /** The HTTPS endpoint (https, port 443) that assigned tasks are delivered to. */
1159
+ triggerEndpoint?: string;
1160
+ /** An optional HTTPS endpoint polled to verify the operator endpoint is reachable. */
1161
+ healthcheckEndpoint?: string;
1162
+ /** The secret used to HMAC-sign delivered requests. Write-only: it is never returned in responses. Provide a new value to rotate it. */
1163
+ signingSecret?: string;
1164
+ /**
1165
+ * Optional override for the per-request timeout backstop, in seconds.
1166
+ * @format int32
1167
+ */
1168
+ requestTimeoutSeconds?: number;
1169
+ }
1107
1170
  export interface V1CELDebugRequest {
1108
1171
  /** The CEL expression to evaluate */
1109
1172
  expression: string;
@@ -1189,6 +1252,11 @@ export interface APIMeta {
1189
1252
  * @example "eyJhbGciOiJFUzI1NiIs..."
1190
1253
  */
1191
1254
  authDisabledToken?: string;
1255
+ /**
1256
+ * whether this instance is running in embedded mode
1257
+ * @example false
1258
+ */
1259
+ embedded?: boolean;
1192
1260
  }
1193
1261
  export interface APIMetaIntegration {
1194
1262
  /**
@@ -1336,6 +1404,8 @@ export interface TenantMember {
1336
1404
  user: UserTenantPublic;
1337
1405
  /** The role of the user in the tenant. */
1338
1406
  role: TenantMemberRole;
1407
+ /** Whether this member can view task, event, and log payloads in the dashboard and REST API. OWNER and ADMIN always can, regardless of this flag. Defaults to true. */
1408
+ canViewPayloads?: boolean;
1339
1409
  /** The tenant associated with this tenant member. */
1340
1410
  tenant?: Tenant;
1341
1411
  /** Whether this membership was explicitly granted (as opposed to synced via user-group tags). Only explicit members can have their role edited or be removed. */
@@ -1351,6 +1421,8 @@ export interface TenantInvite {
1351
1421
  email: string;
1352
1422
  /** The role of the user in the tenant. */
1353
1423
  role: TenantMemberRole;
1424
+ /** Whether the invited user can view payloads. Defaults to true. */
1425
+ canViewPayloads?: boolean;
1354
1426
  /** The tenant id associated with this tenant invite. */
1355
1427
  tenantId: string;
1356
1428
  /** The tenant name for the tenant. */
@@ -1434,10 +1506,14 @@ export interface CreateTenantInviteRequest {
1434
1506
  email: string;
1435
1507
  /** The role of the user in the tenant. */
1436
1508
  role: TenantMemberRole;
1509
+ /** Whether the invited user can view payloads. Defaults to true. */
1510
+ canViewPayloads?: boolean;
1437
1511
  }
1438
1512
  export interface UpdateTenantInviteRequest {
1439
1513
  /** The role of the user in the tenant. */
1440
1514
  role: TenantMemberRole;
1515
+ /** Whether the invited user can view payloads. */
1516
+ canViewPayloads?: boolean;
1441
1517
  }
1442
1518
  export interface APIToken {
1443
1519
  metadata: APIResourceMeta;
@@ -1597,6 +1673,8 @@ export interface TenantMemberList {
1597
1673
  export interface UpdateTenantMemberRequest {
1598
1674
  /** The role of the user in the tenant. */
1599
1675
  role: TenantMemberRole;
1676
+ /** Whether this member can view payloads. Ignored for OWNER and ADMIN, who always can. */
1677
+ canViewPayloads?: boolean;
1600
1678
  }
1601
1679
  export interface EventData {
1602
1680
  /** The data for the event (JSON bytes). */
@@ -1610,6 +1688,10 @@ export interface Workflow {
1610
1688
  description?: string;
1611
1689
  /** Whether the workflow is paused. */
1612
1690
  isPaused?: boolean;
1691
+ /** The behavior of cron runs triggered while the workflow is paused. */
1692
+ pausedWorkflowCronRunQueueBehavior?: WorkflowPauseScheduledCronRunQueueBehavior;
1693
+ /** The behavior of scheduled runs triggered while the workflow is paused. */
1694
+ pausedWorkflowScheduledRunQueueBehavior?: WorkflowPauseScheduledCronRunQueueBehavior;
1613
1695
  versions?: WorkflowVersionMeta[];
1614
1696
  /** The tags of the workflow. */
1615
1697
  tags?: WorkflowTag[];
@@ -1831,9 +1913,23 @@ export interface UpdateCronWorkflowTriggerRequest {
1831
1913
  export interface WorkflowRunsCancelRequest {
1832
1914
  workflowRunIds: string[];
1833
1915
  }
1916
+ export interface PauseWorkflowRequestPause {
1917
+ /** Discriminator indicating this request pauses the workflow. */
1918
+ action: 'pause';
1919
+ /** The behavior of cron runs triggered while the workflow is paused. */
1920
+ pausedWorkflowCronRunQueueBehavior: WorkflowPauseScheduledCronRunQueueBehavior;
1921
+ /** The behavior of scheduled runs triggered while the workflow is paused. */
1922
+ pausedWorkflowScheduledRunQueueBehavior: WorkflowPauseScheduledCronRunQueueBehavior;
1923
+ /** The TTL for queued runs while the workflow is paused before they get dropped, expressed as a Go-style duration string (e.g. "1d7h30m"). */
1924
+ pausedWorkflowQueueTTL: string;
1925
+ }
1926
+ export interface PauseWorkflowRequestUnpause {
1927
+ /** Discriminator indicating this request unpauses the workflow. */
1928
+ action: 'unpause';
1929
+ }
1930
+ export type PauseWorkflowRequest = PauseWorkflowRequestPause | PauseWorkflowRequestUnpause;
1834
1931
  export interface WorkflowUpdateRequest {
1835
- /** Whether the workflow is paused. */
1836
- isPaused?: boolean;
1932
+ pause?: PauseWorkflowRequest;
1837
1933
  }
1838
1934
  export interface WorkflowConcurrency {
1839
1935
  /**
@@ -11,7 +11,7 @@
11
11
  * ---------------------------------------------------------------
12
12
  */
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.V1TaskStatus = exports.V1WorkflowType = exports.V1TaskEventType = exports.V1LogLineLevel = exports.V1LogLineOrderByDirection = exports.V1AdditionalMetadataOperator = exports.V1RunningFilter = exports.V1DurableEventLogKind = exports.V1DurableWaitConditionKind = exports.OtelSpanKind = exports.OtelStatusCode = exports.TenantVersion = exports.TenantEnvironment = exports.V1WebhookSourceName = exports.V1WebhookAuthType = exports.V1WebhookHMACAlgorithm = exports.V1WebhookHMACEncoding = exports.V1CELDebugResponseStatus = exports.TenantResource = exports.TenantMemberRole = exports.WorkflowRunStatus = exports.EventOrderByField = exports.EventOrderByDirection = exports.RateLimitOrderByField = exports.RateLimitOrderByDirection = exports.ScheduledWorkflowsMethod = exports.ScheduledWorkflowsOrderByField = exports.WorkflowRunOrderByDirection = exports.ScheduledRunStatus = exports.CronWorkflowsMethod = exports.CronWorkflowsOrderByField = exports.ConcurrencyLimitStrategy = exports.ConcurrencyScope = exports.StepRunStatus = exports.JobRunStatus = exports.StepRunEventReason = exports.StepRunEventSeverity = exports.WorkflowKind = exports.WorkflowRunOrderByField = exports.WorkerStatus = exports.WorkerType = exports.WorkerRuntimeSDKs = exports.WebhookWorkerRequestMethod = exports.FeatureFlagId = exports.PullRequestState = exports.LogLineLevel = exports.LogLineOrderByField = exports.LogLineOrderByDirection = exports.V1TaskRunStatus = void 0;
14
+ exports.V1TaskStatus = exports.V1WorkflowType = exports.V1TaskEventType = exports.V1LogLineLevel = exports.V1LogLineOrderByDirection = exports.V1AdditionalMetadataOperator = exports.V1RunningFilter = exports.V1DurableEventLogKind = exports.V1DurableWaitConditionKind = exports.OtelSpanKind = exports.OtelStatusCode = exports.TenantVersion = exports.TenantEnvironment = exports.V1WebhookSourceName = exports.V1WebhookAuthType = exports.V1WebhookHMACAlgorithm = exports.V1WebhookHMACEncoding = exports.V1CELDebugResponseStatus = exports.TenantResource = exports.TenantMemberRole = exports.WorkflowRunStatus = exports.EventOrderByField = exports.EventOrderByDirection = exports.RateLimitOrderByField = exports.RateLimitOrderByDirection = exports.WorkflowPauseScheduledCronRunQueueBehavior = exports.ScheduledWorkflowsMethod = exports.ScheduledWorkflowsOrderByField = exports.WorkflowRunOrderByDirection = exports.ScheduledRunStatus = exports.CronWorkflowsMethod = exports.CronWorkflowsOrderByField = exports.ConcurrencyLimitStrategy = exports.ConcurrencyScope = exports.StepRunStatus = exports.JobRunStatus = exports.StepRunEventReason = exports.StepRunEventSeverity = exports.WorkflowKind = exports.WorkflowRunOrderByField = exports.WorkerStatus = exports.WorkerType = exports.WorkerRuntimeSDKs = exports.WebhookWorkerRequestMethod = exports.FeatureFlagId = exports.PullRequestState = exports.LogLineLevel = exports.LogLineOrderByField = exports.LogLineOrderByDirection = exports.V1TaskRunStatus = void 0;
15
15
  var V1TaskRunStatus;
16
16
  (function (V1TaskRunStatus) {
17
17
  V1TaskRunStatus["PENDING"] = "PENDING";
@@ -179,6 +179,11 @@ var ScheduledWorkflowsMethod;
179
179
  ScheduledWorkflowsMethod["DEFAULT"] = "DEFAULT";
180
180
  ScheduledWorkflowsMethod["API"] = "API";
181
181
  })(ScheduledWorkflowsMethod || (exports.ScheduledWorkflowsMethod = ScheduledWorkflowsMethod = {}));
182
+ var WorkflowPauseScheduledCronRunQueueBehavior;
183
+ (function (WorkflowPauseScheduledCronRunQueueBehavior) {
184
+ WorkflowPauseScheduledCronRunQueueBehavior["DROP"] = "DROP";
185
+ WorkflowPauseScheduledCronRunQueueBehavior["QUEUE"] = "QUEUE";
186
+ })(WorkflowPauseScheduledCronRunQueueBehavior || (exports.WorkflowPauseScheduledCronRunQueueBehavior = WorkflowPauseScheduledCronRunQueueBehavior = {}));
182
187
  var RateLimitOrderByDirection;
183
188
  (function (RateLimitOrderByDirection) {
184
189
  RateLimitOrderByDirection["Asc"] = "asc";
@@ -214,6 +219,7 @@ var TenantMemberRole;
214
219
  TenantMemberRole["OWNER"] = "OWNER";
215
220
  TenantMemberRole["ADMIN"] = "ADMIN";
216
221
  TenantMemberRole["MEMBER"] = "MEMBER";
222
+ TenantMemberRole["VIEWER"] = "VIEWER";
217
223
  })(TenantMemberRole || (exports.TenantMemberRole = TenantMemberRole = {}));
218
224
  var TenantResource;
219
225
  (function (TenantResource) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hatchet-dev/typescript-sdk",
3
- "version": "1.28.2",
3
+ "version": "1.29.0",
4
4
  "description": "Background task orchestration & visibility for developers",
5
5
  "types": "dist/index.d.ts",
6
6
  "files": [
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * This is the TypeScript SDK reference, documenting methods available for interacting with Hatchet resources.
3
- * Check out the [user guide](https://docs.hatchet.run/home/) for an introduction to getting your first tasks running.
3
+ * Check out the [user guide](https://docs.hatchet.run/v1) for an introduction to getting your first tasks running.
4
4
  *
5
5
  * @module Hatchet TypeScript SDK Reference
6
6
  */
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  /**
3
3
  * This is the TypeScript SDK reference, documenting methods available for interacting with Hatchet resources.
4
- * Check out the [user guide](https://docs.hatchet.run/home/) for an introduction to getting your first tasks running.
4
+ * Check out the [user guide](https://docs.hatchet.run/v1) for an introduction to getting your first tasks running.
5
5
  *
6
6
  * @module Hatchet TypeScript SDK Reference
7
7
  */
@@ -1,6 +1,3 @@
1
- /**
2
- * @module Tenant Client
3
- */
4
1
  import { Tenant } from '../../../clients/rest/generated/data-contracts';
5
2
  import { HatchetClient } from '../client';
6
3
  /**
@@ -87,7 +87,7 @@ export declare class Context<T, K = {}> {
87
87
  worker: ContextWorker;
88
88
  overridesData: Record<string, any>;
89
89
  _logger: Logger;
90
- /** @deprecated kept for backward compat; prefer {@link nextChildIndex}. */
90
+ /** @deprecated Kept for backward compat; prefer {@link nextChildIndex}. */
91
91
  spawnIndex: number;
92
92
  streamIndex: number;
93
93
  protected nextChildIndex(n?: number): number;
@@ -89,7 +89,7 @@ class Context {
89
89
  // @deprecated use ctx.abortController instead
90
90
  this.controller = new AbortController();
91
91
  this.overridesData = {};
92
- /** @deprecated kept for backward compat; prefer {@link nextChildIndex}. */
92
+ /** @deprecated Kept for backward compat; prefer {@link nextChildIndex}. */
93
93
  this.spawnIndex = 0;
94
94
  this.streamIndex = 0;
95
95
  try {
@@ -139,7 +139,7 @@ class Context {
139
139
  var _a, _b;
140
140
  if (this.action.batchId) {
141
141
  // Batch tasks share one context across every buffered member, so there is no single
142
- // task-run id to cancel cancel every member of the batch instead. `this.data` is
142
+ // task-run id to cancel, so cancel every member of the batch instead. `this.data` is
143
143
  // the raw batch-items map for a START_BATCH action, keyed by each member's
144
144
  // task-run external id.
145
145
  const memberIds = Object.keys((_a = this.data) !== null && _a !== void 0 ? _a : {});
package/v1/declaration.js CHANGED
@@ -93,7 +93,7 @@ class BaseWorkflowDeclaration {
93
93
  : undefined,
94
94
  warn: (message) => this.client.admin.logger.warn(message),
95
95
  });
96
- // Snapshot childIndex before incrementing shared with Context.spawnIndex
96
+ // Snapshot childIndex before incrementing (shared with Context.spawnIndex)
97
97
  // via parentRunContextManager so both spawning APIs produce unique indices.
98
98
  const baseChildIndex = parentRunContext === null || parentRunContext === void 0 ? void 0 : parentRunContext.childIndex;
99
99
  const inputCount = Array.isArray(input) ? input.length : 1;
@@ -0,0 +1,60 @@
1
+ import type { AxiosRequestConfig } from 'axios';
2
+ import type { ClientConfig, HatchetClientOptions } from '../clients/hatchet-client';
3
+ import { HatchetClient } from './client/client';
4
+ export interface EmbeddedOptions {
5
+ /**
6
+ * hatchet-embedded release tag to download (defaults to HATCHET_CLIENT_EMBEDDED_VERSION or
7
+ * latest). Tags correspond to the Hatchet engine version baked into the sidecar,
8
+ * so pinning this pins the engine.
9
+ */
10
+ version?: string;
11
+ /** path to an existing sidecar binary, skips the download (or HATCHET_CLIENT_EMBEDDED_BINARY_PATH) */
12
+ binaryPath?: string;
13
+ /**
14
+ * expected sha256 hex digest of the sidecar binary. When set, it replaces the
15
+ * release's checksums.txt as the trust anchor, so a compromised release
16
+ * channel cannot substitute the binary. Pin it together with `version`.
17
+ */
18
+ checksum?: string;
19
+ /** use an existing Postgres instead of the bundled one */
20
+ databaseUrl?: string;
21
+ /** store the bundled Postgres runtime and data under this directory */
22
+ postgresDataDir?: string;
23
+ grpcPort?: number;
24
+ apiPort?: number;
25
+ /** set to false to start only the engine + gRPC, no REST API */
26
+ startApi?: boolean;
27
+ /** set to false to skip running migrations on startup */
28
+ runMigrations?: boolean;
29
+ /** use RabbitMQ instead of the Postgres message queue */
30
+ rabbitmqUrl?: string;
31
+ logLevel?: string;
32
+ readyTimeoutMs?: number;
33
+ }
34
+ export interface EmbeddedSidecar {
35
+ token: string;
36
+ tenantId: string;
37
+ grpcAddress: string;
38
+ apiUrl: string;
39
+ stop: () => Promise<void>;
40
+ }
41
+ /**
42
+ * Downloads (and caches) the hatchet-embedded sidecar binary, spawns it, and
43
+ * waits until the embedded engine is ready. The sidecar shuts down when this
44
+ * process exits. Use `HatchetEmbedded()` unless you need the raw
45
+ * connection details.
46
+ */
47
+ export declare function startEmbeddedSidecar(opts?: EmbeddedOptions): Promise<EmbeddedSidecar>;
48
+ export declare class HatchetEmbeddedClient {
49
+ /**
50
+ * Runs a full Hatchet engine locally via the hatchet-embedded sidecar (downloaded
51
+ * on first use) and returns a client wired to it. By default the sidecar starts a
52
+ * bundled Postgres; pass `databaseUrl` to point it at your own instead.
53
+ * @param embeddedOpts - Options for the embedded engine (version, ports, database, ...).
54
+ * @param config - Optional configuration overrides for the client.
55
+ * @param options - Optional client options.
56
+ * @param axiosConfig - Optional Axios configuration for HTTP requests.
57
+ * @returns A new Hatchet client instance connected to the embedded engine.
58
+ */
59
+ static init<T extends Record<string, any> = {}, U extends Record<string, any> = {}>(embeddedOpts?: EmbeddedOptions, config?: Omit<Partial<ClientConfig>, 'middleware'>, options?: HatchetClientOptions, axiosConfig?: AxiosRequestConfig): Promise<HatchetClient<T, U>>;
60
+ }
package/v1/embedded.js ADDED
@@ -0,0 +1,319 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
45
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
46
+ var m = o[Symbol.asyncIterator], i;
47
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
48
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
49
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
50
+ };
51
+ Object.defineProperty(exports, "__esModule", { value: true });
52
+ exports.HatchetEmbeddedClient = void 0;
53
+ exports.startEmbeddedSidecar = startEmbeddedSidecar;
54
+ const child_process_1 = require("child_process");
55
+ const client_1 = require("./client/client");
56
+ const crypto_1 = require("crypto");
57
+ const fs_1 = require("fs");
58
+ const fs = __importStar(require("fs/promises"));
59
+ const os = __importStar(require("os"));
60
+ const path = __importStar(require("path"));
61
+ const stream_1 = require("stream");
62
+ const net_1 = require("net");
63
+ const promises_1 = require("stream/promises");
64
+ const REPO_URL = 'https://github.com/hatchet-dev/hatchet-embedded';
65
+ const DEFAULT_READY_TIMEOUT_MS = 300000;
66
+ function sidecarAssetName() {
67
+ const platform = { darwin: 'darwin', linux: 'linux' }[process.platform];
68
+ const arch = { x64: 'amd64', arm64: 'arm64' }[process.arch];
69
+ if (!platform || !arch) {
70
+ throw new Error(`hatchet embedded is not supported on ${process.platform}/${process.arch}`);
71
+ }
72
+ return `hatchet-embedded-sidecar_${platform}_${arch}`;
73
+ }
74
+ function resolveVersion(version) {
75
+ return __awaiter(this, void 0, void 0, function* () {
76
+ var _a;
77
+ const requested = (_a = version !== null && version !== void 0 ? version : process.env.HATCHET_CLIENT_EMBEDDED_VERSION) !== null && _a !== void 0 ? _a : 'latest';
78
+ if (requested !== 'latest') {
79
+ return requested;
80
+ }
81
+ const res = yield fetch(`${REPO_URL}/releases/latest`, { redirect: 'manual' });
82
+ const location = res.headers.get('location');
83
+ const tag = location === null || location === void 0 ? void 0 : location.split('/').pop();
84
+ if (!tag || !tag.startsWith('v')) {
85
+ throw new Error(`could not resolve the latest hatchet-embedded release from ${REPO_URL}`);
86
+ }
87
+ return tag;
88
+ });
89
+ }
90
+ function expectedChecksum(tag, asset) {
91
+ return __awaiter(this, void 0, void 0, function* () {
92
+ const url = `${REPO_URL}/releases/download/${tag}/checksums.txt`;
93
+ const res = yield fetch(url, { signal: AbortSignal.timeout(10000) });
94
+ if (!res.ok) {
95
+ throw new Error(`could not download ${url}: ${res.status}`);
96
+ }
97
+ for (const line of (yield res.text()).split('\n')) {
98
+ const parts = line.split(/\s+/).filter(Boolean);
99
+ if (parts.length === 2 && parts[1] === asset) {
100
+ return parts[0];
101
+ }
102
+ }
103
+ throw new Error(`no checksum for ${asset} in ${url}`);
104
+ });
105
+ }
106
+ function sha256File(filePath) {
107
+ return __awaiter(this, void 0, void 0, function* () {
108
+ var _a, e_1, _b, _c;
109
+ const digest = (0, crypto_1.createHash)('sha256');
110
+ try {
111
+ for (var _d = true, _e = __asyncValues((0, fs_1.createReadStream)(filePath)), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
112
+ _c = _f.value;
113
+ _d = false;
114
+ const chunk = _c;
115
+ digest.update(chunk);
116
+ }
117
+ }
118
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
119
+ finally {
120
+ try {
121
+ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
122
+ }
123
+ finally { if (e_1) throw e_1.error; }
124
+ }
125
+ return digest.digest('hex');
126
+ });
127
+ }
128
+ function resolveExpectedChecksum(tag, asset, binPath) {
129
+ return __awaiter(this, void 0, void 0, function* () {
130
+ const checksumPath = path.join(path.dirname(binPath), `${asset}.sha256`);
131
+ // fall back to the checksum cached at download time so a pinned, already
132
+ // verified binary still starts when GitHub is unreachable
133
+ let expected;
134
+ try {
135
+ expected = yield expectedChecksum(tag, asset);
136
+ }
137
+ catch (err) {
138
+ const cachedDigest = yield fs.readFile(checksumPath, 'utf8').then((s) => s.trim(), () => undefined);
139
+ const hasBinary = yield fs.access(binPath).then(() => true, () => false);
140
+ if (cachedDigest && hasBinary) {
141
+ return cachedDigest;
142
+ }
143
+ throw err;
144
+ }
145
+ yield fs.writeFile(checksumPath, `${expected}\n`);
146
+ return expected;
147
+ });
148
+ }
149
+ function ensureSidecarBinary(version, checksum) {
150
+ return __awaiter(this, void 0, void 0, function* () {
151
+ const tag = yield resolveVersion(version);
152
+ const asset = sidecarAssetName();
153
+ const binPath = path.join(os.homedir(), '.hatchet', 'embedded', tag, asset);
154
+ yield fs.mkdir(path.dirname(binPath), { recursive: true });
155
+ // verified on every start, not just at download; a cached binary that no
156
+ // longer matches the expected checksum is re-downloaded
157
+ const expected = checksum !== null && checksum !== void 0 ? checksum : (yield resolveExpectedChecksum(tag, asset, binPath));
158
+ const cached = yield fs.access(binPath).then(() => true, () => false);
159
+ if (cached && (yield sha256File(binPath)) === expected) {
160
+ return binPath;
161
+ }
162
+ const url = `${REPO_URL}/releases/download/${tag}/${asset}`;
163
+ const res = yield fetch(url);
164
+ if (!res.ok || !res.body) {
165
+ throw new Error(`could not download the hatchet embedded sidecar from ${url}: ${res.status}`);
166
+ }
167
+ // unique temp name per call (not per process) so concurrent downloads of
168
+ // the same version never clobber each other, even within one process; the
169
+ // final rename is atomic and last-writer-wins
170
+ const tmpPath = `${binPath}.${(0, crypto_1.randomUUID)()}.download`;
171
+ try {
172
+ yield (0, promises_1.pipeline)(stream_1.Readable.fromWeb(res.body), (0, fs_1.createWriteStream)(tmpPath, { mode: 0o755 }));
173
+ const actual = yield sha256File(tmpPath);
174
+ if (actual !== expected) {
175
+ throw new Error(`checksum mismatch for ${url}: expected ${expected}, got ${actual}`);
176
+ }
177
+ yield fs.rename(tmpPath, binPath);
178
+ }
179
+ finally {
180
+ yield fs.rm(tmpPath, { force: true });
181
+ }
182
+ return binPath;
183
+ });
184
+ }
185
+ function waitForHandshake(child, handshakePath, timeoutMs) {
186
+ return __awaiter(this, void 0, void 0, function* () {
187
+ const deadline = Date.now() + timeoutMs;
188
+ let exited;
189
+ child.once('exit', (code) => {
190
+ exited = new Error(`hatchet embedded sidecar exited with code ${code} before becoming ready`);
191
+ });
192
+ while (Date.now() < deadline) {
193
+ if (exited) {
194
+ throw exited;
195
+ }
196
+ try {
197
+ const handshake = JSON.parse(yield fs.readFile(handshakePath, 'utf8'));
198
+ if (handshake.token) {
199
+ return handshake;
200
+ }
201
+ }
202
+ catch (_a) {
203
+ // not ready yet
204
+ }
205
+ yield new Promise((resolve) => {
206
+ setTimeout(resolve, 200);
207
+ });
208
+ }
209
+ child.kill();
210
+ throw new Error(`hatchet embedded sidecar did not become ready within ${timeoutMs}ms`);
211
+ });
212
+ }
213
+ /**
214
+ * Downloads (and caches) the hatchet-embedded sidecar binary, spawns it, and
215
+ * waits until the embedded engine is ready. The sidecar shuts down when this
216
+ * process exits. Use `HatchetEmbedded()` unless you need the raw
217
+ * connection details.
218
+ */
219
+ function startEmbeddedSidecar() {
220
+ return __awaiter(this, arguments, void 0, function* (opts = {}) {
221
+ var _a, _b;
222
+ const suppliedPath = (_a = opts.binaryPath) !== null && _a !== void 0 ? _a : process.env.HATCHET_CLIENT_EMBEDDED_BINARY_PATH;
223
+ let binPath;
224
+ if (suppliedPath) {
225
+ if (opts.checksum) {
226
+ const actual = yield sha256File(suppliedPath);
227
+ if (actual !== opts.checksum) {
228
+ throw new Error(`checksum mismatch for ${suppliedPath}: expected ${opts.checksum}, got ${actual}`);
229
+ }
230
+ }
231
+ binPath = suppliedPath;
232
+ }
233
+ else {
234
+ binPath = yield ensureSidecarBinary(opts.version, opts.checksum);
235
+ }
236
+ const handshakePath = path.join(yield fs.mkdtemp(path.join(os.tmpdir(), 'hatchet-embedded-')), 'handshake.json');
237
+ const args = ['-handshake-file', handshakePath];
238
+ if (opts.databaseUrl) {
239
+ args.push('-database-url', opts.databaseUrl);
240
+ }
241
+ if (opts.rabbitmqUrl) {
242
+ args.push('-rabbitmq-url', opts.rabbitmqUrl);
243
+ }
244
+ if (opts.postgresDataDir) {
245
+ args.push('-postgres-data-dir', opts.postgresDataDir);
246
+ }
247
+ if (opts.grpcPort) {
248
+ args.push('-grpc-port', String(opts.grpcPort));
249
+ }
250
+ if (opts.apiPort) {
251
+ args.push('-api-port', String(opts.apiPort));
252
+ }
253
+ if (opts.startApi === false) {
254
+ args.push('-no-api');
255
+ }
256
+ if (opts.runMigrations === false) {
257
+ args.push('-no-migrations');
258
+ }
259
+ if (opts.logLevel) {
260
+ args.push('-log-level', opts.logLevel);
261
+ }
262
+ // the sidecar shuts down when its stdin closes, so it never outlives this
263
+ // process, no matter how this process dies
264
+ const child = (0, child_process_1.spawn)(binPath, args, { stdio: ['pipe', 'ignore', 'inherit'] });
265
+ const killChild = () => child.kill();
266
+ process.once('exit', killChild);
267
+ let handshake;
268
+ try {
269
+ handshake = yield waitForHandshake(child, handshakePath, (_b = opts.readyTimeoutMs) !== null && _b !== void 0 ? _b : DEFAULT_READY_TIMEOUT_MS);
270
+ }
271
+ finally {
272
+ yield fs.rm(path.dirname(handshakePath), { recursive: true, force: true }).catch(() => { });
273
+ }
274
+ child.unref();
275
+ if (child.stdin instanceof net_1.Socket) {
276
+ child.stdin.unref();
277
+ }
278
+ return {
279
+ token: handshake.token,
280
+ tenantId: handshake.tenant_id,
281
+ grpcAddress: handshake.grpc_address,
282
+ apiUrl: handshake.api_url,
283
+ stop: () => new Promise((resolve) => {
284
+ var _a;
285
+ process.removeListener('exit', killChild);
286
+ if (child.exitCode !== null) {
287
+ resolve();
288
+ return;
289
+ }
290
+ const forceKill = setTimeout(() => child.kill('SIGKILL'), 30000);
291
+ (_a = forceKill.unref) === null || _a === void 0 ? void 0 : _a.call(forceKill);
292
+ child.once('exit', () => {
293
+ clearTimeout(forceKill);
294
+ resolve();
295
+ });
296
+ child.kill();
297
+ }),
298
+ };
299
+ });
300
+ }
301
+ class HatchetEmbeddedClient {
302
+ /**
303
+ * Runs a full Hatchet engine locally via the hatchet-embedded sidecar (downloaded
304
+ * on first use) and returns a client wired to it. By default the sidecar starts a
305
+ * bundled Postgres; pass `databaseUrl` to point it at your own instead.
306
+ * @param embeddedOpts - Options for the embedded engine (version, ports, database, ...).
307
+ * @param config - Optional configuration overrides for the client.
308
+ * @param options - Optional client options.
309
+ * @param axiosConfig - Optional Axios configuration for HTTP requests.
310
+ * @returns A new Hatchet client instance connected to the embedded engine.
311
+ */
312
+ static init(embeddedOpts, config, options, axiosConfig) {
313
+ return __awaiter(this, void 0, void 0, function* () {
314
+ const sidecar = yield startEmbeddedSidecar(embeddedOpts);
315
+ return client_1.HatchetClient.init(Object.assign(Object.assign(Object.assign({ token: sidecar.token, tenant_id: sidecar.tenantId, host_port: sidecar.grpcAddress }, (sidecar.apiUrl ? { api_url: sidecar.apiUrl } : {})), { tls_config: { tls_strategy: 'none' } }), config), options, axiosConfig);
316
+ });
317
+ }
318
+ }
319
+ exports.HatchetEmbeddedClient = HatchetEmbeddedClient;
@@ -0,0 +1,76 @@
1
+ import { HatchetClient } from '../..';
2
+ export declare const hatchet: HatchetClient<{}, {}, {}, {}>;
3
+ export type OrderInput = {
4
+ orderId: string;
5
+ correlationId: string;
6
+ };
7
+ export type ValidateOutput = {
8
+ valid: boolean;
9
+ };
10
+ export type FulfillOutput = {
11
+ fulfilled: boolean;
12
+ shipmentId: string;
13
+ };
14
+ export type SignupInput = {
15
+ userId: string;
16
+ email: string;
17
+ };
18
+ export type EmailOutput = {
19
+ sent: boolean;
20
+ };
21
+ export declare const validateOrder: import("../..").TaskWorkflowDeclaration<OrderInput, ValidateOutput, {}, {}, {}, {}>;
22
+ export type ChargeOutput = {
23
+ charged: boolean;
24
+ amountCents: number;
25
+ };
26
+ export declare const chargeOrder: import("../..").TaskWorkflowDeclaration<OrderInput, ChargeOutput, {}, {}, {}, {}>;
27
+ export declare const fulfillOrder: import("../..").TaskWorkflowDeclaration<OrderInput, FulfillOutput, {}, {}, {}, {}>;
28
+ export declare const processOrder: import("../..").TaskWorkflowDeclaration<OrderInput, FulfillOutput, {}, {}, {}, {}>;
29
+ export declare const sendWelcomeEmail: import("../..").TaskWorkflowDeclaration<SignupInput, EmailOutput, {}, {}, {}, {}>;
30
+ export declare const sendFollowupEmail: import("../..").TaskWorkflowDeclaration<SignupInput, EmailOutput, {}, {}, {}, {}>;
31
+ export declare const onboardingFlow: import("../..").TaskWorkflowDeclaration<SignupInput, EmailOutput, {}, {}, {}, {}>;
32
+ export declare const chargeOrderWithRetries: import("../..").TaskWorkflowDeclaration<OrderInput, ChargeOutput, {}, {}, {}, {}>;
33
+ export declare const orderFollowUp: import("../..").TaskWorkflowDeclaration<OrderInput, EmailOutput, {}, {}, {}, {}>;
34
+ export declare const approvalFlow: import("../..").TaskWorkflowDeclaration<OrderInput, FulfillOutput, {}, {}, {}, {}>;
35
+ export type ItemInput = {
36
+ item: string;
37
+ };
38
+ export type ItemOutput = {
39
+ packed: boolean;
40
+ };
41
+ export declare const processItem: import("../..").TaskWorkflowDeclaration<ItemInput, ItemOutput, {}, {}, {}, {}>;
42
+ export declare const packOrder: import("../..").TaskWorkflowDeclaration<{
43
+ items: string[];
44
+ }, {
45
+ packed: number;
46
+ }, {}, {}, {}, {}>;
47
+ export type ReportInput = {
48
+ kind: string;
49
+ };
50
+ export type ReportOutput = {
51
+ generate: {
52
+ rows: number;
53
+ };
54
+ };
55
+ export declare const weeklyReport: import("../..").WorkflowDeclaration<ReportInput, ReportOutput, {}>;
56
+ export type SyncInput = {
57
+ customerId: string;
58
+ };
59
+ export type SyncOutput = {
60
+ sync: {
61
+ synced: number;
62
+ };
63
+ };
64
+ export type PromptInput = {
65
+ prompt: string;
66
+ };
67
+ export declare const syncCustomer: import("../..").WorkflowDeclaration<SyncInput, SyncOutput, {}>;
68
+ export declare const callModel: import("../..").TaskWorkflowDeclaration<PromptInput, {
69
+ completion: string;
70
+ }, {}, {}, {}, {}>;
71
+ export type OrderDagOutput = {
72
+ validate: ValidateOutput;
73
+ charge: ChargeOutput;
74
+ fulfill: FulfillOutput;
75
+ };
76
+ export declare const orderWorkflow: import("../..").WorkflowDeclaration<OrderInput, OrderDagOutput, {}>;
@@ -0,0 +1,280 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.orderWorkflow = exports.callModel = exports.syncCustomer = exports.weeklyReport = exports.packOrder = exports.processItem = exports.approvalFlow = exports.orderFollowUp = exports.chargeOrderWithRetries = exports.onboardingFlow = exports.sendFollowupEmail = exports.sendWelcomeEmail = exports.processOrder = exports.fulfillOrder = exports.chargeOrder = exports.validateOrder = exports.hatchet = void 0;
13
+ // > Hatchet worker
14
+ const v1_1 = require("../..");
15
+ exports.hatchet = v1_1.HatchetClient.init();
16
+ function main() {
17
+ return __awaiter(this, void 0, void 0, function* () {
18
+ const worker = yield exports.hatchet.worker('order-worker', {
19
+ workflows: [exports.validateOrder, exports.chargeOrder, exports.fulfillOrder, exports.processOrder],
20
+ slots: 10,
21
+ });
22
+ yield worker.start();
23
+ });
24
+ }
25
+ const payments = {
26
+ charge: (orderId) => __awaiter(void 0, void 0, void 0, function* () { return 2500 + orderId.length; }),
27
+ };
28
+ const warehouse = {
29
+ reserve: (orderId) => __awaiter(void 0, void 0, void 0, function* () { return orderId.length > 0; }),
30
+ ship: (orderId) => __awaiter(void 0, void 0, void 0, function* () { return `shp_${orderId}`; }),
31
+ pack: (item) => __awaiter(void 0, void 0, void 0, function* () { return item.length > 0; }),
32
+ };
33
+ const emails = {
34
+ send: (address, template) => __awaiter(void 0, void 0, void 0, function* () { return address.includes('@') && template.length > 0; }),
35
+ };
36
+ const models = {
37
+ complete: (prompt) => __awaiter(void 0, void 0, void 0, function* () { return prompt.toUpperCase(); }),
38
+ };
39
+ const crm = {
40
+ sync: (customerId) => __awaiter(void 0, void 0, void 0, function* () { return customerId.length; }),
41
+ };
42
+ const reports = {
43
+ build: (kind) => __awaiter(void 0, void 0, void 0, function* () { return kind.length; }),
44
+ };
45
+ exports.validateOrder = exports.hatchet.task({
46
+ name: 'validate-order',
47
+ fn: (input, ctx) => __awaiter(void 0, void 0, void 0, function* () {
48
+ // > Hatchet context logging
49
+ ctx.logger.info(`validating order ${input.orderId}`);
50
+ // !!
51
+ return { valid: yield warehouse.reserve(input.orderId) };
52
+ }),
53
+ });
54
+ exports.chargeOrder = exports.hatchet.task({
55
+ name: 'charge-order',
56
+ fn: (input) => __awaiter(void 0, void 0, void 0, function* () {
57
+ const amountCents = yield payments.charge(input.orderId);
58
+ return { charged: amountCents > 0, amountCents };
59
+ }),
60
+ });
61
+ // !!
62
+ exports.fulfillOrder = exports.hatchet.task({
63
+ name: 'fulfill-order',
64
+ fn: (input) => __awaiter(void 0, void 0, void 0, function* () {
65
+ const shipmentId = yield warehouse.ship(input.orderId);
66
+ return { fulfilled: true, shipmentId };
67
+ }),
68
+ });
69
+ // > Hatchet workflow as durable task
70
+ exports.processOrder = exports.hatchet.durableTask({
71
+ name: 'ProcessOrder',
72
+ executionTimeout: '10m',
73
+ fn: (input) => __awaiter(void 0, void 0, void 0, function* () {
74
+ yield exports.validateOrder.run(input);
75
+ yield exports.chargeOrder.run(input);
76
+ return exports.fulfillOrder.run(input);
77
+ }),
78
+ });
79
+ // !!
80
+ exports.sendWelcomeEmail = exports.hatchet.task({
81
+ name: 'send-welcome-email',
82
+ fn: (input) => __awaiter(void 0, void 0, void 0, function* () {
83
+ return ({
84
+ sent: yield emails.send(input.email, 'welcome'),
85
+ });
86
+ }),
87
+ });
88
+ exports.sendFollowupEmail = exports.hatchet.task({
89
+ name: 'send-followup-email',
90
+ fn: (input) => __awaiter(void 0, void 0, void 0, function* () {
91
+ return ({
92
+ sent: yield emails.send(input.email, 'followup'),
93
+ });
94
+ }),
95
+ });
96
+ // > Hatchet durable task with sleep
97
+ exports.onboardingFlow = exports.hatchet.durableTask({
98
+ name: 'OnboardingFlow',
99
+ // The timeout has to cover the whole wall-clock span of the run, sleeps included.
100
+ executionTimeout: '168h',
101
+ fn: (input, ctx) => __awaiter(void 0, void 0, void 0, function* () {
102
+ yield exports.sendWelcomeEmail.run(input);
103
+ yield ctx.sleepFor('72h');
104
+ return exports.sendFollowupEmail.run(input);
105
+ }),
106
+ });
107
+ // !!
108
+ function invoke(input) {
109
+ return __awaiter(this, void 0, void 0, function* () {
110
+ // > Hatchet task invocation
111
+ const run = yield exports.processOrder.runNoWait(input);
112
+ // It may be helpful to store this run id somewhere durable.
113
+ const runId = yield run.getWorkflowRunId();
114
+ const result = yield run.output;
115
+ // !!
116
+ return { runId, result };
117
+ });
118
+ }
119
+ // > Hatchet retries and timeouts
120
+ exports.chargeOrderWithRetries = exports.hatchet.task({
121
+ name: 'charge-order-with-retries',
122
+ retries: 10,
123
+ backoff: {
124
+ // Factor to increase the wait time between retries.
125
+ factor: 2,
126
+ // Maximum number of seconds to wait between retries.
127
+ maxSeconds: 10,
128
+ },
129
+ executionTimeout: '30s',
130
+ scheduleTimeout: '10m',
131
+ fn: (input) => __awaiter(void 0, void 0, void 0, function* () {
132
+ const amountCents = yield payments.charge(input.orderId);
133
+ return { charged: amountCents > 0, amountCents };
134
+ }),
135
+ });
136
+ // !!
137
+ exports.orderFollowUp = exports.hatchet.durableTask({
138
+ name: 'OrderFollowUp',
139
+ executionTimeout: '48h',
140
+ fn: (input, ctx) => __awaiter(void 0, void 0, void 0, function* () {
141
+ // > Hatchet durable sleep
142
+ yield ctx.sleepFor('24h');
143
+ // !!
144
+ return { sent: yield emails.send(`${input.orderId}@example.com`, 'order-followup') };
145
+ }),
146
+ });
147
+ function grantApproval(input) {
148
+ return __awaiter(this, void 0, void 0, function* () {
149
+ // > Hatchet event push
150
+ yield exports.hatchet.events.push('approval:granted', {
151
+ correlationId: input.correlationId,
152
+ });
153
+ // !!
154
+ });
155
+ }
156
+ // > Hatchet durable event wait
157
+ exports.approvalFlow = exports.hatchet.durableTask({
158
+ name: 'ApprovalFlow',
159
+ executionTimeout: '10m',
160
+ fn: (input, ctx) => __awaiter(void 0, void 0, void 0, function* () {
161
+ // The expression is compiled as CEL, so correlate on an id that cannot contain a quote.
162
+ yield ctx.waitForEvent('approval:granted', `input.correlationId == '${input.correlationId}'`);
163
+ return exports.fulfillOrder.run(input);
164
+ }),
165
+ });
166
+ exports.processItem = exports.hatchet.task({
167
+ name: 'process-item',
168
+ fn: (input) => __awaiter(void 0, void 0, void 0, function* () {
169
+ return ({
170
+ packed: yield warehouse.pack(input.item),
171
+ });
172
+ }),
173
+ });
174
+ // > Hatchet fan out children
175
+ exports.packOrder = exports.hatchet.durableTask({
176
+ name: 'PackOrder',
177
+ executionTimeout: '30m',
178
+ fn: (input) => __awaiter(void 0, void 0, void 0, function* () {
179
+ const results = yield Promise.all(input.items.map((item) => exports.processItem.run({ item })));
180
+ return { packed: results.filter((result) => result.packed).length };
181
+ }),
182
+ });
183
+ // > Hatchet cron declaration
184
+ exports.weeklyReport = exports.hatchet.workflow({
185
+ name: 'weekly-report',
186
+ on: {
187
+ cron: '0 9 * * 1',
188
+ },
189
+ });
190
+ exports.weeklyReport.task({
191
+ name: 'generate',
192
+ fn: (input) => __awaiter(void 0, void 0, void 0, function* () {
193
+ return { rows: yield reports.build(input.kind) };
194
+ }),
195
+ });
196
+ // !!
197
+ function schedule() {
198
+ return __awaiter(this, void 0, void 0, function* () {
199
+ // > Hatchet runtime schedules
200
+ // A recurring schedule, created at runtime.
201
+ yield exports.hatchet.crons.create('weekly-report', {
202
+ name: 'weekly-report-acme',
203
+ expression: '0 9 * * 1',
204
+ input: { kind: 'weekly' },
205
+ });
206
+ // A one-shot future run.
207
+ yield exports.hatchet.schedules.create('weekly-report', {
208
+ triggerAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
209
+ input: { kind: 'weekly' },
210
+ });
211
+ // !!
212
+ });
213
+ }
214
+ // > Hatchet concurrency and rate limits
215
+ const v1_2 = require("../..");
216
+ // One in-flight run per customer, newest cancels the oldest.
217
+ exports.syncCustomer = exports.hatchet.workflow({
218
+ name: 'SyncCustomer',
219
+ concurrency: {
220
+ expression: 'input.customerId',
221
+ maxRuns: 1,
222
+ limitStrategy: v1_2.ConcurrencyLimitStrategy.CANCEL_IN_PROGRESS,
223
+ },
224
+ });
225
+ exports.syncCustomer.task({
226
+ name: 'sync',
227
+ fn: (input) => __awaiter(void 0, void 0, void 0, function* () {
228
+ return { synced: yield crm.sync(input.customerId) };
229
+ }),
230
+ });
231
+ // A global budget shared by every worker, not per-process.
232
+ exports.callModel = exports.hatchet.task({
233
+ name: 'call-model',
234
+ rateLimits: [
235
+ {
236
+ staticKey: 'openai',
237
+ units: 1,
238
+ },
239
+ ],
240
+ fn: (input) => __awaiter(void 0, void 0, void 0, function* () {
241
+ return { completion: yield models.complete(input.prompt) };
242
+ }),
243
+ });
244
+ // > Hatchet DAG workflow
245
+ exports.orderWorkflow = exports.hatchet.workflow({
246
+ name: 'ProcessOrderDag',
247
+ });
248
+ const validate = exports.orderWorkflow.task({
249
+ name: 'validate',
250
+ executionTimeout: '30s',
251
+ fn: (input) => __awaiter(void 0, void 0, void 0, function* () {
252
+ return { valid: yield warehouse.reserve(input.orderId) };
253
+ }),
254
+ });
255
+ const charge = exports.orderWorkflow.task({
256
+ name: 'charge',
257
+ parents: [validate],
258
+ executionTimeout: '30s',
259
+ fn: (input, ctx) => __awaiter(void 0, void 0, void 0, function* () {
260
+ const validated = yield ctx.parentOutput(validate);
261
+ if (!validated.valid) {
262
+ return { charged: false, amountCents: 0 };
263
+ }
264
+ const amountCents = yield payments.charge(input.orderId);
265
+ return { charged: true, amountCents };
266
+ }),
267
+ });
268
+ exports.orderWorkflow.task({
269
+ name: 'fulfill',
270
+ parents: [charge],
271
+ executionTimeout: '30s',
272
+ fn: (input, ctx) => __awaiter(void 0, void 0, void 0, function* () {
273
+ const charged = yield ctx.parentOutput(charge);
274
+ if (!charged.charged) {
275
+ return { fulfilled: false, shipmentId: '' };
276
+ }
277
+ return { fulfilled: true, shipmentId: yield warehouse.ship(input.orderId) };
278
+ }),
279
+ });
280
+ // !!
package/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const HATCHET_VERSION = "1.28.2";
1
+ export declare const HATCHET_VERSION = "1.29.0";
package/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.HATCHET_VERSION = void 0;
4
- exports.HATCHET_VERSION = '1.28.2';
4
+ exports.HATCHET_VERSION = '1.29.0';