@major-tech/workflows-client 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @major-tech/workflows-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Start Major workflow runs from a deployed Major app or sandbox preview.
4
+
5
+ ```ts
6
+ import { leadEnrichmentWorkflowClient } from "./clients";
7
+
8
+ const { runId } = await leadEnrichmentWorkflowClient.run({ input: { leadId } });
9
+ ```
10
+
11
+ - `run({ input? })` runs the workflow's published version. From a sandbox preview, the run's calls back to this
12
+ app go to that preview.
13
+ - Generate a client per workflow: `npx @major-tech/workflows-client add <workflow_id> <name> --framework nextjs`.
14
+ Deploy grants the app permission to start the workflows its generated clients name.
15
+ - For a Vite app with a Hono backend, run the generator in the backend package with `--framework hono`. The backend must install Hono’s `contextStorage()` middleware to forward the viewer JWT.
@@ -0,0 +1,296 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI tool to generate singleton workflow clients
4
+ * Part of @major-tech/workflows-client
5
+ *
6
+ * Usage:
7
+ * npx @major-tech/workflows-client add <workflow_id> <name> [description] --framework <nextjs|hono>
8
+ * npx @major-tech/workflows-client remove <name> --framework <nextjs|hono>
9
+ * npx @major-tech/workflows-client list
10
+ *
11
+ * Each workflow is recorded in `workflows.json` and gets a generated client in
12
+ * `src/clients/` (or `clients/`) with its id baked in. Deploy grants the app
13
+ * permission to start exactly the workflows its generated clients name.
14
+ */
15
+
16
+ import * as fs from 'fs';
17
+ import * as path from 'path';
18
+
19
+ const projectRoot = process.cwd();
20
+ const workflowsConfigPath = path.join(projectRoot, 'workflows.json');
21
+
22
+ const RESOURCE_MARKER = 'Auto-generated by @major-tech/resource-client';
23
+ const AGENT_MARKER = 'Auto-generated by @major-tech/agents-client';
24
+ const WORKFLOW_MARKER = 'Auto-generated by @major-tech/workflows-client';
25
+
26
+ function getClientsDir() {
27
+ const srcDir = path.join(projectRoot, 'src');
28
+
29
+ if (fs.existsSync(srcDir)) {
30
+ return path.join(srcDir, 'clients');
31
+ }
32
+
33
+ return path.join(projectRoot, 'clients');
34
+ }
35
+
36
+ function toCamelCase(str) {
37
+ return str
38
+ .toLowerCase()
39
+ .replace(/[^a-z0-9]+(.)/g, (_, char) => char.toUpperCase())
40
+ .replace(/[^a-z0-9]+$/, '')
41
+ .replace(/^[^a-z]+/, '');
42
+ }
43
+
44
+ const clientName = (name) => toCamelCase(name) + 'WorkflowClient';
45
+ const fileBase = (name) => toCamelCase(name) + 'Workflow';
46
+
47
+ // The clients index is shared with the resource and agents generators: keep
48
+ // every generated client, whichever package wrote it.
49
+ function collectGeneratedClientExports(clientsDir) {
50
+ if (!fs.existsSync(clientsDir)) {
51
+ return [];
52
+ }
53
+
54
+ const exports = [];
55
+
56
+ for (const f of fs.readdirSync(clientsDir)) {
57
+ if (!f.endsWith('.ts') || f === 'index.ts' || f === 'bindings.ts') {
58
+ continue;
59
+ }
60
+
61
+ const p = path.join(clientsDir, f);
62
+
63
+ if (!fs.statSync(p).isFile()) {
64
+ continue;
65
+ }
66
+
67
+ const content = fs.readFileSync(p, 'utf-8');
68
+
69
+ if (!content.includes(RESOURCE_MARKER) && !content.includes(AGENT_MARKER) && !content.includes(WORKFLOW_MARKER)) {
70
+ continue;
71
+ }
72
+
73
+ const match = content.match(/export (?:const|function) (\w+)/);
74
+
75
+ if (!match) {
76
+ continue;
77
+ }
78
+
79
+ exports.push({ name: match[1], base: f.replace(/\.ts$/, '') });
80
+ }
81
+
82
+ exports.sort((a, b) => a.name.localeCompare(b.name));
83
+
84
+ return exports.map((e) => `export { ${e.name} } from './${e.base}';`);
85
+ }
86
+
87
+ function writeMergedIndex(clientsDir) {
88
+ const clientExports = collectGeneratedClientExports(clientsDir);
89
+ const hasBindings = fs.existsSync(path.join(clientsDir, 'bindings.ts'));
90
+
91
+ let body;
92
+
93
+ if (hasBindings) {
94
+ body = `// DO NOT EDIT - Auto-generated by @major-tech/resource-client
95
+ export { getResourceId, getAgentId, getApplicationId, type ResourceSlot, type AgentSlot } from './bindings';
96
+
97
+ ${clientExports.join('\n')}
98
+ `;
99
+ } else if (clientExports.length === 0) {
100
+ body = `// No clients configured\n`;
101
+ } else {
102
+ body = `/**
103
+ * Auto-generated client exports
104
+ * DO NOT EDIT
105
+ */
106
+
107
+ ${clientExports.join('\n')}
108
+ `;
109
+ }
110
+
111
+ fs.writeFileSync(path.join(clientsDir, 'index.ts'), body, 'utf-8');
112
+ }
113
+
114
+ function deleteMarkedFiles(clientsDir) {
115
+ if (!fs.existsSync(clientsDir)) {
116
+ return;
117
+ }
118
+
119
+ for (const f of fs.readdirSync(clientsDir)) {
120
+ const p = path.join(clientsDir, f);
121
+
122
+ if (fs.statSync(p).isFile() && fs.readFileSync(p, 'utf-8').includes(WORKFLOW_MARKER)) {
123
+ fs.unlinkSync(p);
124
+ }
125
+ }
126
+ }
127
+
128
+ function clientTemplate(workflow, framework) {
129
+ const isNextJs = framework === 'nextjs';
130
+ const isHono = framework === 'hono';
131
+ const entry = isNextJs ? '@major-tech/workflows-client/next' : '@major-tech/workflows-client';
132
+ const serverOnly = isNextJs ? "import 'server-only';\n" : '';
133
+ const headerImport = isHono ? "\nimport { tryGetContext } from 'hono/context-storage';" : '';
134
+ const getHeadersConfig = isHono ? `
135
+ getHeaders: (): Record<string, string> => {
136
+ const userJwt = tryGetContext()?.req.header('x-major-user-jwt');
137
+ return userJwt ? { 'x-major-user-jwt': userJwt } : {};
138
+ },` : '';
139
+
140
+ return `${serverOnly}import { createWorkflowsClient } from '${entry}';${headerImport}
141
+
142
+ /**
143
+ * ${workflow.description || workflow.name}
144
+ *
145
+ * Workflow ID: ${workflow.id}
146
+ *
147
+ * DO NOT EDIT - ${WORKFLOW_MARKER}
148
+ */
149
+ export const ${clientName(workflow.name)} = createWorkflowsClient({
150
+ baseUrl: process.env.MAJOR_API_BASE_URL || 'https://go-api.prod.major.build',
151
+ majorJwtToken: process.env.MAJOR_JWT_TOKEN,
152
+ workflowId: '${workflow.id}',
153
+ fetch: (...args) => fetch(...args),${getHeadersConfig}
154
+ });
155
+ `;
156
+ }
157
+
158
+ function loadWorkflows() {
159
+ if (!fs.existsSync(workflowsConfigPath)) {
160
+ return [];
161
+ }
162
+
163
+ return JSON.parse(fs.readFileSync(workflowsConfigPath, 'utf-8'));
164
+ }
165
+
166
+ function saveWorkflows(workflows) {
167
+ fs.writeFileSync(workflowsConfigPath, JSON.stringify(workflows, null, 2) + '\n', 'utf-8');
168
+ }
169
+
170
+ function regenerateClients(workflows, framework) {
171
+ const clientsDir = getClientsDir();
172
+
173
+ if (!fs.existsSync(clientsDir)) {
174
+ fs.mkdirSync(clientsDir, { recursive: true });
175
+ }
176
+
177
+ deleteMarkedFiles(clientsDir);
178
+
179
+ for (const workflow of workflows) {
180
+ fs.writeFileSync(path.join(clientsDir, fileBase(workflow.name) + '.ts'), clientTemplate(workflow, framework), 'utf-8');
181
+ }
182
+
183
+ writeMergedIndex(clientsDir);
184
+
185
+ console.log(`✅ Generated ${workflows.length} workflow client(s) in ${clientsDir}`);
186
+ }
187
+
188
+ function addWorkflow(workflowId, name, description, framework) {
189
+ const workflows = loadWorkflows();
190
+
191
+ if (workflows.some((w) => w.name === name)) {
192
+ console.error(`❌ Workflow with name "${name}" already exists`);
193
+ process.exit(1);
194
+ }
195
+
196
+ workflows.push({ id: workflowId, name, description: description || name });
197
+ saveWorkflows(workflows);
198
+
199
+ console.log(`✅ Added workflow: ${name}`);
200
+ console.log(` ID: ${workflowId}`);
201
+ console.log(` import { ${clientName(name)} } from './clients';`);
202
+
203
+ regenerateClients(workflows, framework);
204
+ }
205
+
206
+ function removeWorkflow(name, framework) {
207
+ const workflows = loadWorkflows();
208
+ const index = workflows.findIndex((w) => w.name === name);
209
+
210
+ if (index === -1) {
211
+ console.error(`❌ Workflow "${name}" not found`);
212
+ process.exit(1);
213
+ }
214
+
215
+ const [removed] = workflows.splice(index, 1);
216
+ saveWorkflows(workflows);
217
+
218
+ console.log(`✅ Removed workflow: ${removed.name}`);
219
+
220
+ regenerateClients(workflows, framework);
221
+ }
222
+
223
+ function listWorkflows() {
224
+ const workflows = loadWorkflows();
225
+
226
+ if (workflows.length === 0) {
227
+ console.log('No workflows configured');
228
+ return;
229
+ }
230
+
231
+ console.log(`Workflows (${workflows.length}):\n`);
232
+ for (const w of workflows) {
233
+ console.log(`- ${w.name}`);
234
+ console.log(` ID: ${w.id}`);
235
+ console.log(` Client: ${clientName(w.name)}`);
236
+ }
237
+ }
238
+
239
+ function main() {
240
+ const args = process.argv.slice(2);
241
+ const frameworkIndex = args.indexOf('--framework');
242
+ let framework;
243
+
244
+ if (frameworkIndex !== -1 && args[frameworkIndex + 1]) {
245
+ framework = args[frameworkIndex + 1];
246
+ args.splice(frameworkIndex, 2);
247
+ }
248
+
249
+ const [command, ...rest] = args;
250
+
251
+ if ((command === 'add' || command === 'remove') && framework !== 'nextjs' && framework !== 'hono') {
252
+ console.error('Workflow clients run on the server. Pass --framework nextjs or --framework hono. For Vite apps, run this command in the Hono backend with --framework hono.');
253
+ process.exit(1);
254
+ }
255
+
256
+ switch (command) {
257
+ case 'add': {
258
+ const [workflowId, name, description] = rest;
259
+
260
+ if (!workflowId || !name) {
261
+ console.error('Usage: add <workflow_id> <name> [description] --framework <nextjs|hono>');
262
+ process.exit(1);
263
+ }
264
+
265
+ addWorkflow(workflowId, name, description, framework);
266
+ break;
267
+ }
268
+
269
+ case 'remove': {
270
+ const [name] = rest;
271
+
272
+ if (!name) {
273
+ console.error('Usage: remove <name> --framework <nextjs|hono>');
274
+ process.exit(1);
275
+ }
276
+
277
+ removeWorkflow(name, framework);
278
+ break;
279
+ }
280
+
281
+ case 'list': {
282
+ listWorkflows();
283
+ break;
284
+ }
285
+
286
+ default: {
287
+ console.log('Usage:');
288
+ console.log(' npx @major-tech/workflows-client add <workflow_id> <name> [description] --framework <nextjs|hono>');
289
+ console.log(' npx @major-tech/workflows-client remove <name> --framework <nextjs|hono>');
290
+ console.log(' npx @major-tech/workflows-client list');
291
+ process.exit(command ? 1 : 0);
292
+ }
293
+ }
294
+ }
295
+
296
+ main();
@@ -0,0 +1,32 @@
1
+ import type { WorkflowsClientConfig, RunWorkflowRequest, RunWorkflowResponse } from "./types";
2
+ /**
3
+ * Client for starting Major workflow runs from a deployed app or sandbox preview.
4
+ *
5
+ * Prefer the `createWorkflowsClient()` factory — it reads platform-managed env
6
+ * vars and (when imported from `@major-tech/workflows-client/next`) wires up
7
+ * auto-forwarding of the inbound viewer JWT.
8
+ */
9
+ export declare class WorkflowsClient {
10
+ private readonly baseUrl;
11
+ private readonly majorJwtToken;
12
+ private readonly workflowId;
13
+ private readonly getHeaders;
14
+ private readonly fetchImpl;
15
+ constructor(config?: WorkflowsClientConfig);
16
+ /**
17
+ * Start a run. Returns as soon as the run is accepted; the workflow runs
18
+ * asynchronously. It runs the workflow's published version; from a sandbox
19
+ * preview, the run's calls back to this app go to that preview.
20
+ */
21
+ run(request?: RunWorkflowRequest): Promise<RunWorkflowResponse>;
22
+ private request;
23
+ }
24
+ /**
25
+ * Factory equivalent to `new WorkflowsClient(config)`.
26
+ *
27
+ * In Next.js apps, prefer `createWorkflowsClient` from
28
+ * `@major-tech/workflows-client/next` — it auto-forwards `x-major-user-jwt` from
29
+ * the inbound request headers.
30
+ */
31
+ export declare function createWorkflowsClient(config?: WorkflowsClientConfig): WorkflowsClient;
32
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAS9F;;;;;;GAMG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAqB;IACnD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAqB;IAChD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAiE;IAC5F,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAe;gBAE7B,MAAM,GAAE,qBAA0B;IAiB9C;;;;OAIG;IACG,GAAG,CAAC,OAAO,GAAE,kBAAuB,GAAG,OAAO,CAAC,mBAAmB,CAAC;YAa3D,OAAO;CAmCtB;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,GAAE,qBAA0B,GAAG,eAAe,CAEzF"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Error hierarchy for the Major workflows client. Every error extends
3
+ * {@link WorkflowsClientError}, which carries the HTTP status (when the failure
4
+ * came from a response) and the server's `x-request-id` for support/debugging.
5
+ */
6
+ export declare class WorkflowsClientError extends Error {
7
+ readonly httpStatus?: number;
8
+ readonly requestId?: string;
9
+ constructor(message: string, httpStatus?: number, requestId?: string);
10
+ }
11
+ /** The request was rejected as invalid, e.g. input failing the workflow's `input_schema` (HTTP 400). */
12
+ export declare class WorkflowsValidationError extends WorkflowsClientError {
13
+ constructor(message: string, requestId?: string);
14
+ }
15
+ /**
16
+ * Authentication or authorization failed (HTTP 401/403): no caller token, or
17
+ * the app or its deployer may not use this workflow.
18
+ */
19
+ export declare class WorkflowsAuthError extends WorkflowsClientError {
20
+ constructor(message: string, httpStatus?: number, requestId?: string);
21
+ }
22
+ /** The workflow or version could not be found (HTTP 404). */
23
+ export declare class WorkflowNotFoundError extends WorkflowsClientError {
24
+ constructor(message: string, requestId?: string);
25
+ }
26
+ /**
27
+ * The run could not be started: the workflow is not published (HTTP 409), or a
28
+ * transport error prevented the request.
29
+ */
30
+ export declare class WorkflowRunNotStartedError extends WorkflowsClientError {
31
+ constructor(message: string, httpStatus?: number, requestId?: string);
32
+ }
33
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,qBAAa,oBAAqB,SAAQ,KAAK;IAC7C,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;gBAEhB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM;CAMrE;AAED,wGAAwG;AACxG,qBAAa,wBAAyB,SAAQ,oBAAoB;gBACpD,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM;CAIhD;AAED;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,oBAAoB;gBAC9C,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM;CAIrE;AAED,6DAA6D;AAC7D,qBAAa,qBAAsB,SAAQ,oBAAoB;gBACjD,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM;CAIhD;AAED;;;GAGG;AACH,qBAAa,0BAA2B,SAAQ,oBAAoB;gBACtD,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM;CAIrE"}
package/dist/index.cjs ADDED
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ WorkflowNotFoundError: () => WorkflowNotFoundError,
24
+ WorkflowRunNotStartedError: () => WorkflowRunNotStartedError,
25
+ WorkflowsAuthError: () => WorkflowsAuthError,
26
+ WorkflowsClient: () => WorkflowsClient,
27
+ WorkflowsClientError: () => WorkflowsClientError,
28
+ WorkflowsValidationError: () => WorkflowsValidationError,
29
+ createWorkflowsClient: () => createWorkflowsClient
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+
33
+ // src/errors.ts
34
+ var WorkflowsClientError = class extends Error {
35
+ httpStatus;
36
+ requestId;
37
+ constructor(message, httpStatus, requestId) {
38
+ super(message);
39
+ this.name = "WorkflowsClientError";
40
+ this.httpStatus = httpStatus;
41
+ this.requestId = requestId;
42
+ }
43
+ };
44
+ var WorkflowsValidationError = class extends WorkflowsClientError {
45
+ constructor(message, requestId) {
46
+ super(message, 400, requestId);
47
+ this.name = "WorkflowsValidationError";
48
+ }
49
+ };
50
+ var WorkflowsAuthError = class extends WorkflowsClientError {
51
+ constructor(message, httpStatus, requestId) {
52
+ super(message, httpStatus, requestId);
53
+ this.name = "WorkflowsAuthError";
54
+ }
55
+ };
56
+ var WorkflowNotFoundError = class extends WorkflowsClientError {
57
+ constructor(message, requestId) {
58
+ super(message, 404, requestId);
59
+ this.name = "WorkflowNotFoundError";
60
+ }
61
+ };
62
+ var WorkflowRunNotStartedError = class extends WorkflowsClientError {
63
+ constructor(message, httpStatus, requestId) {
64
+ super(message, httpStatus, requestId);
65
+ this.name = "WorkflowRunNotStartedError";
66
+ }
67
+ };
68
+
69
+ // src/client.ts
70
+ var WorkflowsClient = class {
71
+ baseUrl;
72
+ majorJwtToken;
73
+ workflowId;
74
+ getHeaders;
75
+ fetchImpl;
76
+ constructor(config = {}) {
77
+ const baseUrl = config.baseUrl ?? process.env.MAJOR_API_BASE_URL;
78
+ if (!baseUrl) {
79
+ throw new WorkflowsClientError(
80
+ "WorkflowsClient: baseUrl is required (set MAJOR_API_BASE_URL or pass baseUrl explicitly)."
81
+ );
82
+ }
83
+ this.baseUrl = baseUrl.replace(/\/$/, "");
84
+ this.majorJwtToken = config.majorJwtToken;
85
+ this.workflowId = config.workflowId;
86
+ this.getHeaders = config.getHeaders ?? (() => ({}));
87
+ this.fetchImpl = config.fetch ?? globalThis.fetch;
88
+ }
89
+ /**
90
+ * Start a run. Returns as soon as the run is accepted; the workflow runs
91
+ * asynchronously. It runs the workflow's published version; from a sandbox
92
+ * preview, the run's calls back to this app go to that preview.
93
+ */
94
+ async run(request = {}) {
95
+ const workflowId = request.workflowId ?? this.workflowId;
96
+ if (!workflowId) {
97
+ throw new WorkflowsValidationError(
98
+ "WorkflowsClient.run: workflowId is required (pass it in the request or bind it on the client)."
99
+ );
100
+ }
101
+ return this.request("POST", `/workflows/${encodeURIComponent(workflowId)}/runs`, {
102
+ input: request.input
103
+ });
104
+ }
105
+ async request(method, path, body) {
106
+ const headers = { "Content-Type": "application/json" };
107
+ const majorJwtToken = this.majorJwtToken ?? process.env.MAJOR_JWT_TOKEN;
108
+ if (majorJwtToken) {
109
+ headers["x-major-jwt"] = majorJwtToken;
110
+ }
111
+ Object.assign(headers, await this.getHeaders());
112
+ if (!headers["x-major-jwt"] && !headers["x-major-user-jwt"]) {
113
+ throw new WorkflowsAuthError(
114
+ "WorkflowsClient: no credentials (set MAJOR_JWT_TOKEN, or call from a request that carries x-major-user-jwt)."
115
+ );
116
+ }
117
+ let response;
118
+ try {
119
+ response = await this.fetchImpl(`${this.baseUrl}${path}`, {
120
+ method,
121
+ headers,
122
+ body: body === void 0 ? void 0 : JSON.stringify(body)
123
+ });
124
+ } catch (error) {
125
+ const message = error instanceof Error ? error.message : String(error);
126
+ throw new WorkflowRunNotStartedError(`Failed to reach Major API: ${message}`);
127
+ }
128
+ const requestId = response.headers.get("x-request-id") ?? void 0;
129
+ if (response.ok) {
130
+ return await response.json();
131
+ }
132
+ const errorMessage = await readErrorMessage(response);
133
+ throw toWorkflowsError(response.status, errorMessage, requestId);
134
+ }
135
+ };
136
+ function createWorkflowsClient(config = {}) {
137
+ return new WorkflowsClient(config);
138
+ }
139
+ function toWorkflowsError(status, message, requestId) {
140
+ if (status === 400) {
141
+ return new WorkflowsValidationError(message, requestId);
142
+ }
143
+ if (status === 401 || status === 403) {
144
+ return new WorkflowsAuthError(message, status, requestId);
145
+ }
146
+ if (status === 404) {
147
+ return new WorkflowNotFoundError(message, requestId);
148
+ }
149
+ return new WorkflowRunNotStartedError(message, status, requestId);
150
+ }
151
+ async function readErrorMessage(response) {
152
+ try {
153
+ const data = await response.json();
154
+ if (typeof data.error === "string") {
155
+ return data.error;
156
+ }
157
+ if (typeof data.message === "string") {
158
+ return data.message;
159
+ }
160
+ } catch {
161
+ }
162
+ return `HTTP ${response.status} ${response.statusText}`;
163
+ }
164
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/errors.ts", "../src/client.ts"],
4
+ "sourcesContent": ["export { WorkflowsClient, createWorkflowsClient } from \"./client\";\nexport type { WorkflowsClientConfig, RunWorkflowRequest, RunWorkflowResponse } from \"./types\";\nexport {\n WorkflowsClientError,\n WorkflowsValidationError,\n WorkflowsAuthError,\n WorkflowNotFoundError,\n WorkflowRunNotStartedError,\n} from \"./errors\";\n", "/**\n * Error hierarchy for the Major workflows client. Every error extends\n * {@link WorkflowsClientError}, which carries the HTTP status (when the failure\n * came from a response) and the server's `x-request-id` for support/debugging.\n */\nexport class WorkflowsClientError extends Error {\n readonly httpStatus?: number;\n readonly requestId?: string;\n\n constructor(message: string, httpStatus?: number, requestId?: string) {\n super(message);\n this.name = \"WorkflowsClientError\";\n this.httpStatus = httpStatus;\n this.requestId = requestId;\n }\n}\n\n/** The request was rejected as invalid, e.g. input failing the workflow's `input_schema` (HTTP 400). */\nexport class WorkflowsValidationError extends WorkflowsClientError {\n constructor(message: string, requestId?: string) {\n super(message, 400, requestId);\n this.name = \"WorkflowsValidationError\";\n }\n}\n\n/**\n * Authentication or authorization failed (HTTP 401/403): no caller token, or\n * the app or its deployer may not use this workflow.\n */\nexport class WorkflowsAuthError extends WorkflowsClientError {\n constructor(message: string, httpStatus?: number, requestId?: string) {\n super(message, httpStatus, requestId);\n this.name = \"WorkflowsAuthError\";\n }\n}\n\n/** The workflow or version could not be found (HTTP 404). */\nexport class WorkflowNotFoundError extends WorkflowsClientError {\n constructor(message: string, requestId?: string) {\n super(message, 404, requestId);\n this.name = \"WorkflowNotFoundError\";\n }\n}\n\n/**\n * The run could not be started: the workflow is not published (HTTP 409), or a\n * transport error prevented the request.\n */\nexport class WorkflowRunNotStartedError extends WorkflowsClientError {\n constructor(message: string, httpStatus?: number, requestId?: string) {\n super(message, httpStatus, requestId);\n this.name = \"WorkflowRunNotStartedError\";\n }\n}\n", "import type { WorkflowsClientConfig, RunWorkflowRequest, RunWorkflowResponse } from \"./types\";\nimport {\n WorkflowsClientError,\n WorkflowsValidationError,\n WorkflowsAuthError,\n WorkflowNotFoundError,\n WorkflowRunNotStartedError,\n} from \"./errors\";\n\n/**\n * Client for starting Major workflow runs from a deployed app or sandbox preview.\n *\n * Prefer the `createWorkflowsClient()` factory \u2014 it reads platform-managed env\n * vars and (when imported from `@major-tech/workflows-client/next`) wires up\n * auto-forwarding of the inbound viewer JWT.\n */\nexport class WorkflowsClient {\n private readonly baseUrl: string;\n private readonly majorJwtToken: string | undefined;\n private readonly workflowId: string | undefined;\n private readonly getHeaders: () => Promise<Record<string, string>> | Record<string, string>;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: WorkflowsClientConfig = {}) {\n const baseUrl = config.baseUrl ?? process.env.MAJOR_API_BASE_URL;\n if (!baseUrl) {\n throw new WorkflowsClientError(\n \"WorkflowsClient: baseUrl is required (set MAJOR_API_BASE_URL or pass baseUrl explicitly).\",\n );\n }\n\n // The JWT is read lazily so generated module-scope singletons can load during\n // `next build` page-data collection (MAJOR_JWT_TOKEN is injected at runtime).\n this.baseUrl = baseUrl.replace(/\\/$/, \"\");\n this.majorJwtToken = config.majorJwtToken;\n this.workflowId = config.workflowId;\n this.getHeaders = config.getHeaders ?? (() => ({}));\n this.fetchImpl = config.fetch ?? globalThis.fetch;\n }\n\n /**\n * Start a run. Returns as soon as the run is accepted; the workflow runs\n * asynchronously. It runs the workflow's published version; from a sandbox\n * preview, the run's calls back to this app go to that preview.\n */\n async run(request: RunWorkflowRequest = {}): Promise<RunWorkflowResponse> {\n const workflowId = request.workflowId ?? this.workflowId;\n if (!workflowId) {\n throw new WorkflowsValidationError(\n \"WorkflowsClient.run: workflowId is required (pass it in the request or bind it on the client).\",\n );\n }\n\n return this.request<RunWorkflowResponse>(\"POST\", `/workflows/${encodeURIComponent(workflowId)}/runs`, {\n input: request.input,\n });\n }\n\n private async request<T>(method: string, path: string, body: unknown): Promise<T> {\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n const majorJwtToken = this.majorJwtToken ?? process.env.MAJOR_JWT_TOKEN;\n if (majorJwtToken) {\n headers[\"x-major-jwt\"] = majorJwtToken;\n }\n Object.assign(headers, await this.getHeaders());\n\n if (!headers[\"x-major-jwt\"] && !headers[\"x-major-user-jwt\"]) {\n throw new WorkflowsAuthError(\n \"WorkflowsClient: no credentials (set MAJOR_JWT_TOKEN, or call from a request that carries x-major-user-jwt).\",\n );\n }\n\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new WorkflowRunNotStartedError(`Failed to reach Major API: ${message}`);\n }\n\n const requestId = response.headers.get(\"x-request-id\") ?? undefined;\n\n if (response.ok) {\n return (await response.json()) as T;\n }\n\n const errorMessage = await readErrorMessage(response);\n throw toWorkflowsError(response.status, errorMessage, requestId);\n }\n}\n\n/**\n * Factory equivalent to `new WorkflowsClient(config)`.\n *\n * In Next.js apps, prefer `createWorkflowsClient` from\n * `@major-tech/workflows-client/next` \u2014 it auto-forwards `x-major-user-jwt` from\n * the inbound request headers.\n */\nexport function createWorkflowsClient(config: WorkflowsClientConfig = {}): WorkflowsClient {\n return new WorkflowsClient(config);\n}\n\nfunction toWorkflowsError(status: number, message: string, requestId?: string): WorkflowsClientError {\n if (status === 400) {\n return new WorkflowsValidationError(message, requestId);\n }\n if (status === 401 || status === 403) {\n return new WorkflowsAuthError(message, status, requestId);\n }\n if (status === 404) {\n return new WorkflowNotFoundError(message, requestId);\n }\n return new WorkflowRunNotStartedError(message, status, requestId);\n}\n\nasync function readErrorMessage(response: Response): Promise<string> {\n try {\n const data = (await response.json()) as { error?: unknown; message?: unknown };\n if (typeof data.error === \"string\") {\n return data.error;\n }\n if (typeof data.message === \"string\") {\n return data.message;\n }\n } catch {\n // Non-JSON body: fall through to the status text.\n }\n return `HTTP ${response.status} ${response.statusText}`;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EACrC;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,YAAqB,WAAoB;AACpE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,YAAY;AAAA,EACnB;AACF;AAGO,IAAM,2BAAN,cAAuC,qBAAqB;AAAA,EACjE,YAAY,SAAiB,WAAoB;AAC/C,UAAM,SAAS,KAAK,SAAS;AAC7B,SAAK,OAAO;AAAA,EACd;AACF;AAMO,IAAM,qBAAN,cAAiC,qBAAqB;AAAA,EAC3D,YAAY,SAAiB,YAAqB,WAAoB;AACpE,UAAM,SAAS,YAAY,SAAS;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UAAU;AAClC,aAAO,KAAK;AAAA,IACd;AACA,QAAI,OAAO,KAAK,YAAY,UAAU;AACpC,aAAO,KAAK;AAAA,IACd;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO,QAAQ,SAAS,MAAM,IAAI,SAAS,UAAU;AACvD;",
6
+ "names": []
7
+ }
@@ -0,0 +1,4 @@
1
+ export { WorkflowsClient, createWorkflowsClient } from "./client";
2
+ export type { WorkflowsClientConfig, RunWorkflowRequest, RunWorkflowResponse } from "./types";
3
+ export { WorkflowsClientError, WorkflowsValidationError, WorkflowsAuthError, WorkflowNotFoundError, WorkflowRunNotStartedError, } from "./errors";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAClE,YAAY,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9F,OAAO,EACL,oBAAoB,EACpB,wBAAwB,EACxB,kBAAkB,EAClB,qBAAqB,EACrB,0BAA0B,GAC3B,MAAM,UAAU,CAAC"}