@hatchet-dev/typescript-sdk 1.34.0-alpha.1 → 1.34.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 (71) hide show
  1. package/README.md +1 -0
  2. package/clients/admin/rpc.d.ts +1 -1
  3. package/clients/admin/rpc.js +3 -3
  4. package/clients/admin/trigger-request.d.ts +18 -0
  5. package/clients/admin/trigger-request.js +66 -0
  6. package/clients/event/event-client.d.ts +4 -17
  7. package/clients/event/event-client.js +5 -43
  8. package/clients/event/rpc.d.ts +22 -3
  9. package/clients/event/rpc.js +66 -3
  10. package/clients/transport/fetch-transport.d.ts +73 -0
  11. package/clients/transport/fetch-transport.js +152 -0
  12. package/clients/transport/grpc-target.js +48 -3
  13. package/clients/transport/index.d.ts +2 -1
  14. package/clients/transport/index.js +6 -1
  15. package/clients/transport/node-transport.js +1 -2
  16. package/clients/transport/transport.d.ts +6 -0
  17. package/clients/transport/transport.js +7 -0
  18. package/clients/transport/ts-proto-client.js +16 -2
  19. package/core/client.d.ts +102 -0
  20. package/core/client.js +250 -0
  21. package/core/features/events.d.ts +25 -0
  22. package/core/features/events.js +57 -0
  23. package/core/features/logs.d.ts +26 -0
  24. package/core/features/logs.js +51 -0
  25. package/core/features/rate-limits.d.ts +19 -0
  26. package/core/features/rate-limits.js +30 -0
  27. package/core/features/runs.d.ts +33 -0
  28. package/core/features/runs.js +84 -0
  29. package/core/features/streams.d.ts +11 -0
  30. package/core/features/streams.js +23 -0
  31. package/core/features/workflows.d.ts +22 -0
  32. package/core/features/workflows.js +46 -0
  33. package/core/index.d.ts +42 -4
  34. package/core/index.js +79 -5
  35. package/core/logger.d.ts +19 -0
  36. package/core/logger.js +45 -0
  37. package/core/run-detail.d.ts +14 -0
  38. package/core/run-detail.js +79 -0
  39. package/core/run-ref.d.ts +63 -0
  40. package/core/run-ref.js +217 -0
  41. package/core/types.d.ts +182 -0
  42. package/core/types.js +2 -0
  43. package/dist/check-edge-entry.mjs +72 -14
  44. package/dist/check-edge-entry.test.ts +57 -0
  45. package/package.json +5 -2
  46. package/protoc/v1/streams.d.ts +79 -0
  47. package/protoc/v1/streams.js +511 -0
  48. package/protoc-es/v1/streams_pb.d.ts +133 -0
  49. package/protoc-es/v1/streams_pb.js +41 -0
  50. package/scripts/check-edge-entry.mjs +72 -14
  51. package/scripts/check-edge-entry.test.ts +57 -0
  52. package/util/batch.js +2 -1
  53. package/util/config-loader/token.d.ts +5 -0
  54. package/util/config-loader/token.js +8 -0
  55. package/util/errors/bulk-trigger-partial-error.d.ts +17 -0
  56. package/util/errors/bulk-trigger-partial-error.js +55 -0
  57. package/v1/client/admin.d.ts +4 -54
  58. package/v1/client/admin.js +9 -72
  59. package/v1/client/client.d.ts +14 -1
  60. package/v1/client/client.js +18 -0
  61. package/v1/client/features/index.d.ts +1 -0
  62. package/v1/client/features/index.js +1 -0
  63. package/v1/client/features/runs.d.ts +9 -27
  64. package/v1/client/features/runs.js +10 -55
  65. package/v1/client/features/streams.d.ts +47 -0
  66. package/v1/client/features/streams.js +210 -0
  67. package/v1/examples/durable-streams/publish-latency.d.ts +15 -0
  68. package/v1/examples/durable-streams/publish-latency.js +50 -0
  69. package/v1/examples/durable_callback_ordering/workflow.js +5 -1
  70. package/version.d.ts +1 -1
  71. package/version.js +1 -1
@@ -0,0 +1,30 @@
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.RateLimitsClient = void 0;
13
+ const retrier_1 = require("../../util/retrier");
14
+ /** Tenant-wide rate limits that tasks declare against by key. */
15
+ class RateLimitsClient {
16
+ constructor(deps) {
17
+ this.deps = deps;
18
+ }
19
+ /**
20
+ * Creates or updates a rate limit.
21
+ * @returns the rate limit's key
22
+ */
23
+ put(opts) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ yield (0, retrier_1.retrier)(() => this.deps.rpc.putRateLimit({ key: opts.key, limit: opts.limit, duration: opts.duration }), this.deps.logger, this.deps.retrier);
26
+ return opts.key;
27
+ });
28
+ }
29
+ }
30
+ exports.RateLimitsClient = RateLimitsClient;
@@ -0,0 +1,33 @@
1
+ import type { AdminServiceClient } from '../../protoc/v1/workflows';
2
+ import { WorkflowRunRef } from '../run-ref';
3
+ import type { CallOptions, CancelRunOpts, ReplayRunOpts, RunDetail } from '../types';
4
+ /**
5
+ * Task and workflow runs, over the v1 `AdminService`. Everything here is a unary call, so
6
+ * it works from any runtime the client runs on; listing runs is a REST feature of the Node
7
+ * client and is not available here.
8
+ */
9
+ export declare class RunsClient {
10
+ private readonly rpc;
11
+ constructor(rpc: AdminServiceClient);
12
+ /**
13
+ * Gets a run's state: its status, whether it is done, its input and metadata, and each of
14
+ * its tasks with their status, output and error.
15
+ * @param run - The run id or a reference to the run.
16
+ * @param options - A signal or deadline for the call.
17
+ */
18
+ get<T = unknown>(run: string | WorkflowRunRef<T>, options?: CallOptions): Promise<RunDetail>;
19
+ /** @alias get */
20
+ getDetails<T = unknown>(run: string | WorkflowRunRef<T>, options?: CallOptions): Promise<RunDetail>;
21
+ /**
22
+ * Cancels runs by id, or every run matching the filter when no ids are given.
23
+ * @returns the ids of the cancelled tasks
24
+ */
25
+ cancel(opts: CancelRunOpts): Promise<import("../../protoc/v1/workflows").CancelTasksResponse>;
26
+ /**
27
+ * Replays runs by id, or every run matching the filter when no ids are given.
28
+ * @returns the ids of the replayed tasks
29
+ */
30
+ replay(opts: ReplayRunOpts): Promise<import("../../protoc/v1/workflows").ReplayTasksResponse>;
31
+ /** A reference to an existing run, to wait on, cancel or replay it. */
32
+ runRef<T = unknown>(id: string): WorkflowRunRef<T>;
33
+ }
@@ -0,0 +1,84 @@
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.RunsClient = void 0;
13
+ const run_detail_1 = require("../run-detail");
14
+ const run_ref_1 = require("../run-ref");
15
+ /**
16
+ * Task and workflow runs, over the v1 `AdminService`. Everything here is a unary call, so
17
+ * it works from any runtime the client runs on; listing runs is a REST feature of the Node
18
+ * client and is not available here.
19
+ */
20
+ class RunsClient {
21
+ constructor(rpc) {
22
+ this.rpc = rpc;
23
+ }
24
+ /**
25
+ * Gets a run's state: its status, whether it is done, its input and metadata, and each of
26
+ * its tasks with their status, output and error.
27
+ * @param run - The run id or a reference to the run.
28
+ * @param options - A signal or deadline for the call.
29
+ */
30
+ get(run, options) {
31
+ return __awaiter(this, void 0, void 0, function* () {
32
+ return this.getDetails(run, options);
33
+ });
34
+ }
35
+ /** @alias get */
36
+ getDetails(run, options) {
37
+ return __awaiter(this, void 0, void 0, function* () {
38
+ const externalId = typeof run === 'string' ? run : yield run.getWorkflowRunId();
39
+ return (0, run_detail_1.toRunDetail)(yield this.rpc.getRunDetails({ externalId }, options));
40
+ });
41
+ }
42
+ /**
43
+ * Cancels runs by id, or every run matching the filter when no ids are given.
44
+ * @returns the ids of the cancelled tasks
45
+ */
46
+ cancel(opts) {
47
+ return __awaiter(this, void 0, void 0, function* () {
48
+ var _a, _b;
49
+ return this.rpc.cancelTasks({
50
+ externalIds: (_a = opts.ids) !== null && _a !== void 0 ? _a : [],
51
+ filter: opts.ids ? undefined : prepareFilter((_b = opts.filters) !== null && _b !== void 0 ? _b : {}),
52
+ });
53
+ });
54
+ }
55
+ /**
56
+ * Replays runs by id, or every run matching the filter when no ids are given.
57
+ * @returns the ids of the replayed tasks
58
+ */
59
+ replay(opts) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ var _a, _b;
62
+ return this.rpc.replayTasks({
63
+ externalIds: (_a = opts.ids) !== null && _a !== void 0 ? _a : [],
64
+ filter: opts.ids ? undefined : prepareFilter((_b = opts.filters) !== null && _b !== void 0 ? _b : {}),
65
+ });
66
+ });
67
+ }
68
+ /** A reference to an existing run, to wait on, cancel or replay it. */
69
+ runRef(id) {
70
+ return new run_ref_1.WorkflowRunRef(id, this);
71
+ }
72
+ }
73
+ exports.RunsClient = RunsClient;
74
+ /** Builds the proto filter; `since` defaults to one hour ago, as the Node client's does. */
75
+ function prepareFilter(filter) {
76
+ var _a, _b, _c, _d;
77
+ return {
78
+ since: (_a = filter.since) !== null && _a !== void 0 ? _a : new Date(Date.now() - 60 * 60 * 1000),
79
+ until: filter.until,
80
+ statuses: (_b = filter.statuses) !== null && _b !== void 0 ? _b : [],
81
+ workflowIds: (_c = filter.workflowIds) !== null && _c !== void 0 ? _c : [],
82
+ additionalMetadata: Object.entries((_d = filter.additionalMetadata) !== null && _d !== void 0 ? _d : {}).map(([key, value]) => `${key}:${value}`),
83
+ };
84
+ }
@@ -0,0 +1,11 @@
1
+ import type { EventsServiceClient, PutStreamEventResponse } from '../../protoc/events/events';
2
+ /** Publishes stream chunks from a task run, the way `ctx.putStream` does from a worker. */
3
+ export declare class StreamsClient {
4
+ private readonly rpc;
5
+ constructor(rpc: EventsServiceClient);
6
+ /**
7
+ * Publishes one chunk on a task run's stream. `index` orders chunks that are published
8
+ * concurrently. Resolves once the engine has the chunk.
9
+ */
10
+ put(taskRunExternalId: string, data: string | Uint8Array, index?: number): Promise<PutStreamEventResponse>;
11
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StreamsClient = void 0;
4
+ /** Publishes stream chunks from a task run, the way `ctx.putStream` does from a worker. */
5
+ class StreamsClient {
6
+ constructor(rpc) {
7
+ this.rpc = rpc;
8
+ }
9
+ /**
10
+ * Publishes one chunk on a task run's stream. `index` orders chunks that are published
11
+ * concurrently. Resolves once the engine has the chunk.
12
+ */
13
+ put(taskRunExternalId, data, index) {
14
+ const message = typeof data === 'string' ? new TextEncoder().encode(data) : data;
15
+ return this.rpc.putStreamEvent({
16
+ taskRunExternalId,
17
+ createdAt: new Date(),
18
+ message,
19
+ eventIndex: index,
20
+ });
21
+ }
22
+ }
23
+ exports.StreamsClient = StreamsClient;
@@ -0,0 +1,22 @@
1
+ import { type RetrierConfig } from '../../util/retrier';
2
+ import type { Logger } from '../../util/logger/logger';
3
+ import type { AdminServiceClient, CreateWorkflowVersionRequest, CreateWorkflowVersionResponse } from '../../protoc/v1/workflows';
4
+ import type { BaseWorkflowDeclaration, WorkflowDefinition } from '../../v1/declaration';
5
+ import type { InputType, OutputType } from '../../v1/types';
6
+ export interface WorkflowsClientDeps {
7
+ rpc: AdminServiceClient;
8
+ logger: Logger;
9
+ namespace?: string;
10
+ retrier?: RetrierConfig;
11
+ }
12
+ /** Registers workflow definitions with the engine. */
13
+ export declare class WorkflowsClient {
14
+ private readonly deps;
15
+ constructor(deps: WorkflowsClientDeps);
16
+ /**
17
+ * Creates or updates a workflow. A declaration from `/edge` (or its definition) is
18
+ * converted with the client's namespace the way a worker registers it; a
19
+ * `CreateWorkflowVersionRequest` is sent as given.
20
+ */
21
+ put<I extends InputType, O extends OutputType>(workflow: CreateWorkflowVersionRequest | WorkflowDefinition | BaseWorkflowDeclaration<I, O>): Promise<CreateWorkflowVersionResponse>;
22
+ }
@@ -0,0 +1,46 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.WorkflowsClient = void 0;
16
+ const hatchet_error_1 = __importDefault(require("../../util/errors/hatchet-error"));
17
+ const retrier_1 = require("../../util/retrier");
18
+ const workflow_proto_1 = require("../../v1/client/worker/workflow-proto");
19
+ /** Registers workflow definitions with the engine. */
20
+ class WorkflowsClient {
21
+ constructor(deps) {
22
+ this.deps = deps;
23
+ }
24
+ /**
25
+ * Creates or updates a workflow. A declaration from `/edge` (or its definition) is
26
+ * converted with the client's namespace the way a worker registers it; a
27
+ * `CreateWorkflowVersionRequest` is sent as given.
28
+ */
29
+ put(workflow) {
30
+ return __awaiter(this, void 0, void 0, function* () {
31
+ const request = isWireRequest(workflow)
32
+ ? workflow
33
+ : (0, workflow_proto_1.workflowToProto)(workflow, { namespace: this.deps.namespace });
34
+ try {
35
+ return yield (0, retrier_1.retrier)(() => this.deps.rpc.putWorkflow(request), this.deps.logger, this.deps.retrier);
36
+ }
37
+ catch (e) {
38
+ throw new hatchet_error_1.default(e instanceof Error ? e.message : String(e));
39
+ }
40
+ });
41
+ }
42
+ }
43
+ exports.WorkflowsClient = WorkflowsClient;
44
+ function isWireRequest(workflow) {
45
+ return 'tasks' in workflow && Array.isArray(workflow.tasks);
46
+ }
package/core/index.d.ts CHANGED
@@ -1,9 +1,47 @@
1
1
  /**
2
- * The core entry point: the application client for runtimes without gRPC, built on the
3
- * Connect transport seam. The entry resolves today so that `@hatchet-dev/typescript-sdk/core`
4
- * is a stable import path; the client it exports is added on top.
2
+ * The core entry point: the application client for runtimes without gRPC. It triggers runs,
3
+ * pushes events, waits for results by polling and manages workflows over unary Connect calls
4
+ * on a fetch transport, and it is configured from an explicit object only.
5
5
  *
6
+ * Nothing exported here imports from Node. `scripts/check-edge-entry.mjs` bundles this module
7
+ * for a browser-like target and fails the build if a Node builtin, `axios` or a gRPC package
8
+ * sneaks in.
9
+ *
10
+ * ```typescript
11
+ * import { Hatchet } from './';
12
+ *
13
+ * const hatchet = new Hatchet({ token: env.HATCHET_CLIENT_TOKEN });
14
+ * const ref = await hatchet.runNoWait('greet', { name: 'world' });
15
+ * const output = await ref.result({ timeoutMs: 30_000 });
16
+ * ```
6
17
  * @module Core
7
18
  */
8
19
  /** Bumped whenever the surface exported from this entry changes incompatibly. */
9
- export declare const CORE_ENTRY_VERSION = 0;
20
+ export declare const CORE_ENTRY_VERSION = 1;
21
+ export { HatchetCore, HatchetCore as Hatchet } from './client';
22
+ export type { ResolvedCoreConfig, WorkflowRef } from './client';
23
+ export { WorkflowRunRef, INITIAL_POLL_INTERVAL_MS, MAX_POLL_INTERVAL_MS } from './run-ref';
24
+ export type { RunRefClient } from './run-ref';
25
+ export { toRunDetail, parseTaskOutput, runStatusToJSON } from './run-detail';
26
+ export { ConsoleLogger, consoleLogger } from './logger';
27
+ export type { CallOptions, CancelRunOpts, CoreClientConfig, CreateRateLimitOpts, DesiredWorkerLabelOpt, EventWithMetadata, LogConstructor, PushEventOptions, ReplayRunOpts, ResultOptions, RunDetail, RunFilter, RunFilterBase, TaskRunDetail, TriggerRun, TriggerRunOptions, } from './types';
28
+ export { EventsClient } from './features/events';
29
+ export { RunsClient } from './features/runs';
30
+ export { WorkflowsClient } from './features/workflows';
31
+ export { RateLimitsClient } from './features/rate-limits';
32
+ export { LogsClient, MAX_LOG_LINE_CHARS } from './features/logs';
33
+ export type { PutLogOptions } from './features/logs';
34
+ export { StreamsClient } from './features/streams';
35
+ export { createFetchTransport, limitMessageSizes, resolveServerUrl, type FetchTlsConfig, type FetchTransportOptions, type MessageSizeLimits, } from '../clients/transport/fetch-transport';
36
+ export { createAuthInterceptor, DEFAULT_MAX_MESSAGE_BYTES, type Transport, } from '../clients/transport/transport';
37
+ export { LogLevel } from '../clients/event/rpc';
38
+ export { Priority } from '../v1/declaration';
39
+ export type { RunManyOpt, RunOpts } from '../v1/declaration';
40
+ export { RateLimitDuration } from '../protoc/workflows/workflows';
41
+ export { WorkerLabelComparator } from '../protoc/v1/shared/trigger';
42
+ export { V1TaskStatus } from '../clients/rest/generated/data-contracts';
43
+ export { default as HatchetError, getErrorMessage, toHatchetError, } from '../util/errors/hatchet-error';
44
+ export { IdempotencyCollisionError } from '../util/errors/idempotency-collision-error';
45
+ export { BulkTriggerIdempotencyCollisionError } from '../util/errors/bulk-trigger-idempotency-collision-error';
46
+ export { BulkTriggerPartialError } from '../util/errors/bulk-trigger-partial-error';
47
+ export { AbortError, isAbortError } from '../util/abort-error';
package/core/index.js CHANGED
@@ -1,12 +1,86 @@
1
1
  "use strict";
2
2
  /**
3
- * The core entry point: the application client for runtimes without gRPC, built on the
4
- * Connect transport seam. The entry resolves today so that `@hatchet-dev/typescript-sdk/core`
5
- * is a stable import path; the client it exports is added on top.
3
+ * The core entry point: the application client for runtimes without gRPC. It triggers runs,
4
+ * pushes events, waits for results by polling and manages workflows over unary Connect calls
5
+ * on a fetch transport, and it is configured from an explicit object only.
6
6
  *
7
+ * Nothing exported here imports from Node. `scripts/check-edge-entry.mjs` bundles this module
8
+ * for a browser-like target and fails the build if a Node builtin, `axios` or a gRPC package
9
+ * sneaks in.
10
+ *
11
+ * ```typescript
12
+ * import { Hatchet } from './index.js';
13
+ *
14
+ * const hatchet = new Hatchet({ token: env.HATCHET_CLIENT_TOKEN });
15
+ * const ref = await hatchet.runNoWait('greet', { name: 'world' });
16
+ * const output = await ref.result({ timeoutMs: 30_000 });
17
+ * ```
7
18
  * @module Core
8
19
  */
20
+ var __importDefault = (this && this.__importDefault) || function (mod) {
21
+ return (mod && mod.__esModule) ? mod : { "default": mod };
22
+ };
9
23
  Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.CORE_ENTRY_VERSION = void 0;
24
+ exports.isAbortError = exports.AbortError = exports.BulkTriggerPartialError = exports.BulkTriggerIdempotencyCollisionError = exports.IdempotencyCollisionError = exports.toHatchetError = exports.getErrorMessage = exports.HatchetError = exports.V1TaskStatus = exports.WorkerLabelComparator = exports.RateLimitDuration = exports.Priority = exports.LogLevel = exports.DEFAULT_MAX_MESSAGE_BYTES = exports.createAuthInterceptor = exports.resolveServerUrl = exports.limitMessageSizes = exports.createFetchTransport = exports.StreamsClient = exports.MAX_LOG_LINE_CHARS = exports.LogsClient = exports.RateLimitsClient = exports.WorkflowsClient = exports.RunsClient = exports.EventsClient = exports.consoleLogger = exports.ConsoleLogger = exports.runStatusToJSON = exports.parseTaskOutput = exports.toRunDetail = exports.MAX_POLL_INTERVAL_MS = exports.INITIAL_POLL_INTERVAL_MS = exports.WorkflowRunRef = exports.Hatchet = exports.HatchetCore = exports.CORE_ENTRY_VERSION = void 0;
11
25
  /** Bumped whenever the surface exported from this entry changes incompatibly. */
12
- exports.CORE_ENTRY_VERSION = 0;
26
+ exports.CORE_ENTRY_VERSION = 1;
27
+ var client_1 = require("./client");
28
+ Object.defineProperty(exports, "HatchetCore", { enumerable: true, get: function () { return client_1.HatchetCore; } });
29
+ Object.defineProperty(exports, "Hatchet", { enumerable: true, get: function () { return client_1.HatchetCore; } });
30
+ var run_ref_1 = require("./run-ref");
31
+ Object.defineProperty(exports, "WorkflowRunRef", { enumerable: true, get: function () { return run_ref_1.WorkflowRunRef; } });
32
+ Object.defineProperty(exports, "INITIAL_POLL_INTERVAL_MS", { enumerable: true, get: function () { return run_ref_1.INITIAL_POLL_INTERVAL_MS; } });
33
+ Object.defineProperty(exports, "MAX_POLL_INTERVAL_MS", { enumerable: true, get: function () { return run_ref_1.MAX_POLL_INTERVAL_MS; } });
34
+ var run_detail_1 = require("./run-detail");
35
+ Object.defineProperty(exports, "toRunDetail", { enumerable: true, get: function () { return run_detail_1.toRunDetail; } });
36
+ Object.defineProperty(exports, "parseTaskOutput", { enumerable: true, get: function () { return run_detail_1.parseTaskOutput; } });
37
+ Object.defineProperty(exports, "runStatusToJSON", { enumerable: true, get: function () { return run_detail_1.runStatusToJSON; } });
38
+ var logger_1 = require("./logger");
39
+ Object.defineProperty(exports, "ConsoleLogger", { enumerable: true, get: function () { return logger_1.ConsoleLogger; } });
40
+ Object.defineProperty(exports, "consoleLogger", { enumerable: true, get: function () { return logger_1.consoleLogger; } });
41
+ // Feature clients
42
+ var events_1 = require("./features/events");
43
+ Object.defineProperty(exports, "EventsClient", { enumerable: true, get: function () { return events_1.EventsClient; } });
44
+ var runs_1 = require("./features/runs");
45
+ Object.defineProperty(exports, "RunsClient", { enumerable: true, get: function () { return runs_1.RunsClient; } });
46
+ var workflows_1 = require("./features/workflows");
47
+ Object.defineProperty(exports, "WorkflowsClient", { enumerable: true, get: function () { return workflows_1.WorkflowsClient; } });
48
+ var rate_limits_1 = require("./features/rate-limits");
49
+ Object.defineProperty(exports, "RateLimitsClient", { enumerable: true, get: function () { return rate_limits_1.RateLimitsClient; } });
50
+ var logs_1 = require("./features/logs");
51
+ Object.defineProperty(exports, "LogsClient", { enumerable: true, get: function () { return logs_1.LogsClient; } });
52
+ Object.defineProperty(exports, "MAX_LOG_LINE_CHARS", { enumerable: true, get: function () { return logs_1.MAX_LOG_LINE_CHARS; } });
53
+ var streams_1 = require("./features/streams");
54
+ Object.defineProperty(exports, "StreamsClient", { enumerable: true, get: function () { return streams_1.StreamsClient; } });
55
+ // Transport
56
+ var fetch_transport_1 = require("../clients/transport/fetch-transport");
57
+ Object.defineProperty(exports, "createFetchTransport", { enumerable: true, get: function () { return fetch_transport_1.createFetchTransport; } });
58
+ Object.defineProperty(exports, "limitMessageSizes", { enumerable: true, get: function () { return fetch_transport_1.limitMessageSizes; } });
59
+ Object.defineProperty(exports, "resolveServerUrl", { enumerable: true, get: function () { return fetch_transport_1.resolveServerUrl; } });
60
+ var transport_1 = require("../clients/transport/transport");
61
+ Object.defineProperty(exports, "createAuthInterceptor", { enumerable: true, get: function () { return transport_1.createAuthInterceptor; } });
62
+ Object.defineProperty(exports, "DEFAULT_MAX_MESSAGE_BYTES", { enumerable: true, get: function () { return transport_1.DEFAULT_MAX_MESSAGE_BYTES; } });
63
+ // Wire enums and errors callers switch on
64
+ var rpc_1 = require("../clients/event/rpc");
65
+ Object.defineProperty(exports, "LogLevel", { enumerable: true, get: function () { return rpc_1.LogLevel; } });
66
+ var declaration_1 = require("../v1/declaration");
67
+ Object.defineProperty(exports, "Priority", { enumerable: true, get: function () { return declaration_1.Priority; } });
68
+ var workflows_2 = require("../protoc/workflows/workflows");
69
+ Object.defineProperty(exports, "RateLimitDuration", { enumerable: true, get: function () { return workflows_2.RateLimitDuration; } });
70
+ var trigger_1 = require("../protoc/v1/shared/trigger");
71
+ Object.defineProperty(exports, "WorkerLabelComparator", { enumerable: true, get: function () { return trigger_1.WorkerLabelComparator; } });
72
+ var data_contracts_1 = require("../clients/rest/generated/data-contracts");
73
+ Object.defineProperty(exports, "V1TaskStatus", { enumerable: true, get: function () { return data_contracts_1.V1TaskStatus; } });
74
+ var hatchet_error_1 = require("../util/errors/hatchet-error");
75
+ Object.defineProperty(exports, "HatchetError", { enumerable: true, get: function () { return __importDefault(hatchet_error_1).default; } });
76
+ Object.defineProperty(exports, "getErrorMessage", { enumerable: true, get: function () { return hatchet_error_1.getErrorMessage; } });
77
+ Object.defineProperty(exports, "toHatchetError", { enumerable: true, get: function () { return hatchet_error_1.toHatchetError; } });
78
+ var idempotency_collision_error_1 = require("../util/errors/idempotency-collision-error");
79
+ Object.defineProperty(exports, "IdempotencyCollisionError", { enumerable: true, get: function () { return idempotency_collision_error_1.IdempotencyCollisionError; } });
80
+ var bulk_trigger_idempotency_collision_error_1 = require("../util/errors/bulk-trigger-idempotency-collision-error");
81
+ Object.defineProperty(exports, "BulkTriggerIdempotencyCollisionError", { enumerable: true, get: function () { return bulk_trigger_idempotency_collision_error_1.BulkTriggerIdempotencyCollisionError; } });
82
+ var bulk_trigger_partial_error_1 = require("../util/errors/bulk-trigger-partial-error");
83
+ Object.defineProperty(exports, "BulkTriggerPartialError", { enumerable: true, get: function () { return bulk_trigger_partial_error_1.BulkTriggerPartialError; } });
84
+ var abort_error_1 = require("../util/abort-error");
85
+ Object.defineProperty(exports, "AbortError", { enumerable: true, get: function () { return abort_error_1.AbortError; } });
86
+ Object.defineProperty(exports, "isAbortError", { enumerable: true, get: function () { return abort_error_1.isAbortError; } });
@@ -0,0 +1,19 @@
1
+ import { Logger, LogLevel } from '../util/logger/logger';
2
+ /**
3
+ * The logger the core client uses when none is configured: level-filtered `console` output
4
+ * with the context in brackets. It reads nothing from the process, so it runs anywhere the
5
+ * client does.
6
+ */
7
+ export declare class ConsoleLogger implements Logger {
8
+ private readonly context;
9
+ /** The lowest level written; `OFF` sets it above every level, so nothing is. */
10
+ private readonly threshold;
11
+ constructor(context: string, logLevel?: LogLevel);
12
+ private log;
13
+ debug(message: string): void;
14
+ info(message: string): void;
15
+ green(message: string): void;
16
+ warn(message: string, error?: Error): void;
17
+ error(message: string, error?: Error): void;
18
+ }
19
+ export declare const consoleLogger: (context: string, logLevel?: LogLevel) => Logger;
package/core/logger.js ADDED
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.consoleLogger = exports.ConsoleLogger = void 0;
4
+ const logger_1 = require("../util/logger/logger");
5
+ /**
6
+ * The logger the core client uses when none is configured: level-filtered `console` output
7
+ * with the context in brackets. It reads nothing from the process, so it runs anywhere the
8
+ * client does.
9
+ */
10
+ class ConsoleLogger {
11
+ constructor(context, logLevel = 'INFO') {
12
+ this.context = context;
13
+ this.threshold = logLevel === 'OFF' ? Number.POSITIVE_INFINITY : logger_1.LogLevelEnum[logLevel];
14
+ }
15
+ log(level, message, error) {
16
+ if (logger_1.LogLevelEnum[level] < this.threshold)
17
+ return;
18
+ const write = level === 'ERROR'
19
+ ? console.error
20
+ : level === 'WARN'
21
+ ? console.warn
22
+ : level === 'DEBUG'
23
+ ? console.debug
24
+ : console.info;
25
+ write(`[${level}/${this.context}] ${error ? `${message} ${error}` : message}`);
26
+ }
27
+ debug(message) {
28
+ this.log('DEBUG', message);
29
+ }
30
+ info(message) {
31
+ this.log('INFO', message);
32
+ }
33
+ green(message) {
34
+ this.log('INFO', message);
35
+ }
36
+ warn(message, error) {
37
+ this.log('WARN', message, error);
38
+ }
39
+ error(message, error) {
40
+ this.log('ERROR', message, error);
41
+ }
42
+ }
43
+ exports.ConsoleLogger = ConsoleLogger;
44
+ const consoleLogger = (context, logLevel) => new ConsoleLogger(context, logLevel);
45
+ exports.consoleLogger = consoleLogger;
@@ -0,0 +1,14 @@
1
+ import { GetRunDetailsResponse, runStatusToJSON } from '../protoc/v1/workflows';
2
+ import type { RunDetail, TaskRunDetail } from './types';
3
+ /**
4
+ * A task's output the way the Node client's `result()` reads it (`JSON.parse(output || '{}')`):
5
+ * nothing stored is `{}`, a stored `null` is `null`, and stored text that is not JSON throws
6
+ * the `SyntaxError`, so a corrupt output is never mistaken for an empty one.
7
+ */
8
+ export declare function parseTaskOutput(task: TaskRunDetail): unknown;
9
+ /**
10
+ * Converts a `GetRunDetails` response into the `RunDetail` both clients return: statuses
11
+ * become `V1TaskStatus` values and the JSON payloads are decoded.
12
+ */
13
+ export declare function toRunDetail(raw: GetRunDetailsResponse): RunDetail;
14
+ export { runStatusToJSON };
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runStatusToJSON = void 0;
4
+ exports.parseTaskOutput = parseTaskOutput;
5
+ exports.toRunDetail = toRunDetail;
6
+ const data_contracts_1 = require("../clients/rest/generated/data-contracts");
7
+ const workflows_1 = require("../protoc/v1/workflows");
8
+ Object.defineProperty(exports, "runStatusToJSON", { enumerable: true, get: function () { return workflows_1.runStatusToJSON; } });
9
+ // EVICTED is not in V1TaskStatus; treat as RUNNING per the proto comment.
10
+ const PROTO_STATUS_MAP = {
11
+ [workflows_1.RunStatus.QUEUED]: data_contracts_1.V1TaskStatus.QUEUED,
12
+ [workflows_1.RunStatus.RUNNING]: data_contracts_1.V1TaskStatus.RUNNING,
13
+ [workflows_1.RunStatus.COMPLETED]: data_contracts_1.V1TaskStatus.COMPLETED,
14
+ [workflows_1.RunStatus.FAILED]: data_contracts_1.V1TaskStatus.FAILED,
15
+ [workflows_1.RunStatus.CANCELLED]: data_contracts_1.V1TaskStatus.CANCELLED,
16
+ [workflows_1.RunStatus.EVICTED]: data_contracts_1.V1TaskStatus.RUNNING,
17
+ [workflows_1.RunStatus.UNRECOGNIZED]: data_contracts_1.V1TaskStatus.RUNNING,
18
+ };
19
+ function decodeText(b) {
20
+ return (b === null || b === void 0 ? void 0 : b.length) ? new TextDecoder().decode(b) : undefined;
21
+ }
22
+ /**
23
+ * The forgiving decode `getDetails` shapes payloads with: absent, `null` and malformed JSON
24
+ * all read as `null`, so inspecting a run never throws.
25
+ */
26
+ function decodeJson(text) {
27
+ if (text === undefined)
28
+ return null;
29
+ try {
30
+ return JSON.parse(text);
31
+ }
32
+ catch (_a) {
33
+ return null;
34
+ }
35
+ }
36
+ /**
37
+ * A task's output the way the Node client's `result()` reads it (`JSON.parse(output || '{}')`):
38
+ * nothing stored is `{}`, a stored `null` is `null`, and stored text that is not JSON throws
39
+ * the `SyntaxError`, so a corrupt output is never mistaken for an empty one.
40
+ */
41
+ function parseTaskOutput(task) {
42
+ var _a;
43
+ if (task.rawOutput === undefined) {
44
+ return (_a = task.output) !== null && _a !== void 0 ? _a : {};
45
+ }
46
+ // The forgiving decode already parsed valid JSON; only a `null` result needs the strict
47
+ // parse to tell a stored `null` from text that failed to parse.
48
+ return task.output !== null ? task.output : JSON.parse(task.rawOutput);
49
+ }
50
+ /**
51
+ * Converts a `GetRunDetails` response into the `RunDetail` both clients return: statuses
52
+ * become `V1TaskStatus` values and the JSON payloads are decoded.
53
+ */
54
+ function toRunDetail(raw) {
55
+ var _a;
56
+ return {
57
+ status: (_a = PROTO_STATUS_MAP[raw.status]) !== null && _a !== void 0 ? _a : data_contracts_1.V1TaskStatus.RUNNING,
58
+ done: raw.done,
59
+ input: decodeJson(decodeText(raw.input)),
60
+ additionalMetadata: decodeJson(decodeText(raw.additionalMetadata)),
61
+ isEvicted: raw.isEvicted,
62
+ taskRuns: Object.fromEntries(Object.entries(raw.taskRuns).map(([id, tr]) => {
63
+ var _a;
64
+ const rawOutput = decodeText(tr.output);
65
+ return [
66
+ id,
67
+ {
68
+ externalId: tr.externalId,
69
+ readableId: tr.readableId,
70
+ status: (_a = PROTO_STATUS_MAP[tr.status]) !== null && _a !== void 0 ? _a : data_contracts_1.V1TaskStatus.RUNNING,
71
+ output: decodeJson(rawOutput),
72
+ rawOutput,
73
+ error: tr.error,
74
+ isEvicted: tr.isEvicted,
75
+ },
76
+ ];
77
+ })),
78
+ };
79
+ }
@@ -0,0 +1,63 @@
1
+ import type { CallOptions, ResultOptions, RunDetail } from './types';
2
+ /** What a run reference needs from the client that created it. */
3
+ export interface RunRefClient {
4
+ getDetails(runId: string, options?: CallOptions): Promise<RunDetail>;
5
+ cancel(opts: {
6
+ ids: string[];
7
+ }): Promise<unknown>;
8
+ replay(opts: {
9
+ ids: string[];
10
+ }): Promise<unknown>;
11
+ }
12
+ /** The first wait between two `GetRunDetails` polls. */
13
+ export declare const INITIAL_POLL_INTERVAL_MS = 250;
14
+ /** The longest wait between two polls; the interval doubles until it gets here. */
15
+ export declare const MAX_POLL_INTERVAL_MS = 5000;
16
+ /**
17
+ * A reference to a triggered run. `result()` polls `GetRunDetails` until the run is done,
18
+ * which is the one way to wait for a run that works on every platform the core client runs
19
+ * on: no stream is held open, so a Worker request or a browser tab can wait on it.
20
+ */
21
+ export declare class WorkflowRunRef<T> {
22
+ private readonly runs;
23
+ readonly workflowRunId: string;
24
+ parentWorkflowRunId?: string;
25
+ _standaloneTaskName?: string;
26
+ /**
27
+ * The signal `result()` waits with when none is passed, so a run spawned from inside a task
28
+ * stops being awaited when the task is cancelled.
29
+ */
30
+ defaultSignal?: AbortSignal;
31
+ constructor(workflowRunId: string, runs: RunRefClient, parentWorkflowRunId?: string, standaloneTaskName?: string, defaultSignal?: AbortSignal);
32
+ get runId(): Promise<string>;
33
+ getWorkflowRunId(): Promise<string>;
34
+ /** The run's result; the same as `result()` with no options. */
35
+ get output(): Promise<T>;
36
+ /** The run's current state. */
37
+ details(): Promise<RunDetail>;
38
+ /**
39
+ * Waits for the run to finish and returns its output: the standalone task's output for a
40
+ * task, or the outputs keyed by task name for a workflow.
41
+ *
42
+ * The wait polls with backoff, starting at 250 ms and capped at 5 s with jitter. It is
43
+ * unbounded unless `timeoutMs` is set (rejects with a `HatchetError`) or `signal` fires
44
+ * (rejects with an `AbortError`). Both bound the poll in flight as well as the waits
45
+ * between polls, so a stalled `GetRunDetails` cannot hold the result past the deadline.
46
+ *
47
+ * A failed or cancelled run rejects the way the Node client's `result()` does: with the
48
+ * array of the tasks' error messages when any task reported one. When no task reported an
49
+ * error the run resolves with the tasks' outputs whatever its status, as it does on the
50
+ * Node client, since that is the shape an explicit cancellation leaves. A run with no
51
+ * tasks at all rejects with an `Error` naming the run's status.
52
+ */
53
+ result(options?: ResultOptions): Promise<T>;
54
+ private resolveResult;
55
+ /**
56
+ * The outputs keyed by task name, or the standalone task's own output, each read the way
57
+ * the Node client reads them; a task output that is not JSON throws its `SyntaxError`.
58
+ */
59
+ private outputs;
60
+ toJSON(): Promise<string>;
61
+ cancel(): Promise<void>;
62
+ replay(): Promise<void>;
63
+ }