@colixsystems/actions-client 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,9 @@ An Action is a server-side script the workspace owns. The app may run one only w
10
10
 
11
11
  ## Status
12
12
 
13
- `v0.3.0` — adds `createConnectorsClient`, which calls a workspace's REST connectors through the operations it listed for apps.
13
+ `v0.4.1` — the factory option checks, URL joining and request headers now come from the transport the clients share. Two small changes: a `getRequestHeaders` value of `null` or `undefined` is no longer sent as the text "null", and a `multipartFetchImpl` option that is not a function is now refused with a `TypeError`, as in the other clients. No export or request shape changed.
14
+
15
+ `v0.4.0` — adds `enqueue`, which queues an Action run instead of waiting for it. `v0.3.0` added `createConnectorsClient`, which calls a workspace's REST connectors through the operations it listed for apps.
14
16
 
15
17
  ## Public API
16
18
 
@@ -43,6 +45,8 @@ const { available, reason } = await actions.status(actionId); // reason: "ACTION
43
45
 
44
46
  The request is `POST {baseUrl}/app-actions/:actionId/run` with `Authorization: Bearer <token>` and `x-tenant-id`. The body is `{ input }`; when `input` is omitted or `null` no body is sent. It answers `{ ok, result }`, where `result` is the value the script passed to `respond()`, or `null`.
45
47
 
48
+ `enqueue(actionId, input)` sends the same request to `POST {baseUrl}/app-actions/:actionId/enqueue` and resolves `{ queued: true }` once the server accepts it (202). It meets the same refusals as `run`, but nothing waits on the script: it runs later, away from the request, with the Action's normal limits instead of the 500 ms an app run gets, and its `respond()` value is not returned. Use it to start work the app does not need an answer from. Beyond `run`'s refusals it answers 409 `ACTION_DISABLED` / `ACTION_PAUSED` for an Action that would not run, 429 `RATE_LIMITED` when the workspace already has 10 queued runs, and 503 `ACTION_QUEUE_UNREACHABLE` when the broker did not confirm the run was queued (the outcome is then unknown). The client never retries it, but the server may run a queued run twice if it restarts mid-run, so the Action must be safe to repeat.
49
+
46
50
  An empty, `.` or `..` `actionId` rejects with a `TypeError` before any request. A run is **never retried**: an Action can have side effects.
47
51
 
48
52
  ## Errors
package/dist/client.js CHANGED
@@ -9,15 +9,10 @@
9
9
  // opt-in of the Action for apps. This client only carries the id and input.
10
10
 
11
11
  import { ActionError, errorFromResponse } from "./errors.js";
12
+ import { buildHeaders, joinUrl, readClientOptions } from "./transport.js";
12
13
 
13
14
  const NAMESPACE = "actions";
14
15
 
15
- function joinUrl(base, path) {
16
- const b = base.endsWith("/") ? base.slice(0, -1) : base;
17
- const p = path.startsWith("/") ? path : `/${path}`;
18
- return `${b}${p}`;
19
- }
20
-
21
16
  /**
22
17
  * @param {object} opts
23
18
  * @param {string} opts.baseUrl
@@ -32,43 +27,16 @@ function joinUrl(base, path) {
32
27
  * @returns the `send(method, path, body, operation)` both clients use.
33
28
  */
34
29
  export function createSender(opts, factory, namespace, toError) {
35
- if (!opts || typeof opts !== "object") {
36
- throw new TypeError(`${factory}: opts is required`);
37
- }
38
- const { baseUrl, getToken, getTenantId, getRequestHeaders } = opts;
39
- if (typeof baseUrl !== "string" || baseUrl.length === 0) {
40
- throw new TypeError(`${factory}: baseUrl is required`);
41
- }
42
- if (typeof getToken !== "function") {
43
- throw new TypeError(`${factory}: getToken must be a function`);
44
- }
45
- if (typeof getTenantId !== "function") {
46
- throw new TypeError(`${factory}: getTenantId must be a function`);
47
- }
48
- if (getRequestHeaders !== undefined && typeof getRequestHeaders !== "function") {
49
- throw new TypeError(
50
- `${factory}: getRequestHeaders must be a function when provided`,
51
- );
52
- }
53
- const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
54
- if (typeof fetchImpl !== "function") {
55
- throw new TypeError(
56
- `${factory}: no fetch available. Pass fetchImpl or run in an environment with global fetch.`,
57
- );
58
- }
30
+ const { baseUrl, getToken, getTenantId, getRequestHeaders, fetchImpl } = readClientOptions(
31
+ factory,
32
+ opts,
33
+ );
59
34
 
60
35
  async function send(method, path, body, operation) {
61
- const token = await getToken();
62
- const tenantId = await getTenantId();
63
- const headers = { accept: "application/json" };
64
- if (token)
65
- headers.authorization = token.startsWith("Bearer ") ? token : `Bearer ${token}`;
66
- if (tenantId) headers["x-tenant-id"] = tenantId;
67
- if (body !== undefined) headers["content-type"] = "application/json";
68
- if (getRequestHeaders) {
69
- const extra = await getRequestHeaders({ namespace, operation });
70
- if (extra && typeof extra === "object") Object.assign(headers, extra);
71
- }
36
+ const headers = await buildHeaders(
37
+ { getToken, getTenantId, getRequestHeaders },
38
+ { json: body !== undefined, namespace, operation },
39
+ );
72
40
 
73
41
  const res = await fetchImpl(joinUrl(baseUrl, path), {
74
42
  method,
@@ -106,6 +74,26 @@ export function createActionsClient(opts) {
106
74
  }
107
75
  }
108
76
 
77
+ async function post(actionId, operation, input) {
78
+ assertActionId(actionId, operation);
79
+ try {
80
+ return await send(
81
+ "POST",
82
+ `/app-actions/${encodeURIComponent(actionId)}/${operation}`,
83
+ input == null ? undefined : { input },
84
+ operation,
85
+ );
86
+ } catch (err) {
87
+ if (err instanceof ActionError) throw err;
88
+ // No HTTP answer (offline, or no session to send) keeps the generic code.
89
+ throw new ActionError(`Action request failed: ${err?.message || err}`, {
90
+ code: "ACTION_FAILED",
91
+ status: 0,
92
+ cause: err,
93
+ });
94
+ }
95
+ }
96
+
109
97
  return {
110
98
  /**
111
99
  * Whether this caller's run would reach the Action's script. Resolves
@@ -139,26 +127,19 @@ export function createActionsClient(opts) {
139
127
  * pass null) to send no body. Never retried: a run can have side effects.
140
128
  */
141
129
  async run(actionId, input) {
142
- assertActionId(actionId, "run");
143
- let body;
144
- try {
145
- body = await send(
146
- "POST",
147
- `/app-actions/${encodeURIComponent(actionId)}/run`,
148
- input == null ? undefined : { input },
149
- "run",
150
- );
151
- } catch (err) {
152
- if (err instanceof ActionError) throw err;
153
- // No HTTP answer (offline, or no session to send) keeps the generic code.
154
- throw new ActionError(`Action request failed: ${err?.message || err}`, {
155
- code: "ACTION_FAILED",
156
- status: 0,
157
- cause: err,
158
- });
159
- }
130
+ const body = await post(actionId, "run", input);
160
131
  const src = body && typeof body === "object" ? body : {};
161
132
  return { ok: src.ok === true, result: src.result === undefined ? null : src.result };
162
133
  },
134
+
135
+ /**
136
+ * Queue one Action and resolve to `{ queued: true }` as soon as the server
137
+ * accepted it — the same refusals as `run`, but nothing waits on the
138
+ * script, which runs later with the Action's normal limits. Never retried.
139
+ */
140
+ async enqueue(actionId, input) {
141
+ await post(actionId, "enqueue", input);
142
+ return { queued: true };
143
+ },
163
144
  };
164
145
  }
@@ -234,3 +234,35 @@ test("status rejects when no answer came, so the caller keeps what it knew", asy
234
234
  await assert.rejects(makeClient(makeFetch({ status: 500 }).fetchImpl).status("a"), { status: 500 });
235
235
  await assert.rejects(makeClient(makeFetch({ status: 200 }).fetchImpl).status(".."), TypeError);
236
236
  });
237
+
238
+ // sc-15876 — a queued run: same request shape on its own path, answered at once.
239
+ test("enqueue posts { input } to the enqueue path and resolves { queued: true }", async () => {
240
+ const { fetchImpl, calls } = makeFetch({ status: 202, body: { queued: true } });
241
+ const out = await makeClient(fetchImpl).enqueue("act-1", { batch: 7 });
242
+
243
+ assert.deepEqual(out, { queued: true });
244
+ assert.equal(calls.length, 1);
245
+ assert.equal(calls[0].url, "https://api.example.test/api/v1/app-actions/act-1/enqueue");
246
+ assert.equal(calls[0].init.method, "POST");
247
+ assert.deepEqual(JSON.parse(calls[0].init.body), { input: { batch: 7 } });
248
+ assert.equal(calls[0].init.headers["x-tenant-id"], "tenant-abc");
249
+ });
250
+
251
+ test("enqueue meets the same refusals as run and is never retried", async () => {
252
+ const { fetchImpl, calls } = makeFetch({ status: 403, body: { code: "ACTION_NOT_APP_INVOKABLE" } });
253
+ await assert.rejects(
254
+ () => makeClient(fetchImpl).enqueue("act-1"),
255
+ (err) => err instanceof ForbiddenError && err.code === "ACTION_NOT_APP_INVOKABLE",
256
+ );
257
+ assert.equal(calls.length, 1);
258
+ assert.equal(calls[0].init.body, undefined);
259
+ await assert.rejects(() => makeClient(fetchImpl).enqueue(".."), TypeError);
260
+ });
261
+
262
+ test("enqueue with no answer rejects ACTION_FAILED", async () => {
263
+ const { fetchImpl } = makeFetch({ throws: new Error("offline") });
264
+ await assert.rejects(
265
+ () => makeClient(fetchImpl).enqueue("act-1"),
266
+ (err) => err instanceof ActionError && err.code === "ACTION_FAILED" && err.status === 0,
267
+ );
268
+ });
package/dist/index.d.ts CHANGED
@@ -25,6 +25,11 @@ export interface ActionsClient {
25
25
  * An empty, ".", or ".." id rejects with a TypeError before any request.
26
26
  */
27
27
  run(actionId: string, input?: Record<string, unknown> | null): Promise<ActionRunResult>;
28
+ /**
29
+ * POST /app-actions/:actionId/enqueue. Resolves once the run is queued; the
30
+ * script runs later with the Action's normal limits and returns nothing here.
31
+ */
32
+ enqueue(actionId: string, input?: Record<string, unknown> | null): Promise<{ queued: true }>;
28
33
  }
29
34
 
30
35
  export interface RequestHeaderContext {
@@ -0,0 +1,245 @@
1
+ // The one HTTP transport of the @colixsystems/*-client packages.
2
+ //
3
+ // Each client imports it through a one-line shim, `src/transport.js`, and
4
+ // its build copies this file over `dist/transport.js`. A published client
5
+ // therefore still ships with zero runtime dependencies, and the transport it
6
+ // carries is the one it was tested with. This file must import nothing; the
7
+ // build asserts that.
8
+ //
9
+ // Error classes stay in each client (`errors.js`): they are its published
10
+ // contract. A client declares its policy once, in its `retry.js`.
11
+
12
+ const DEFAULT_TIMEOUT_MS = 10_000;
13
+ // An upload lasts as long as the file takes to cross a mobile link.
14
+ const MULTIPART_TIMEOUT_MS = 5 * 60_000;
15
+ const BACKOFF_MS = [200, 400, 800];
16
+ const RETRY_VERBS = new Set(["GET", "HEAD"]);
17
+ // A longer server hint surfaces the 429 at once instead of hanging a widget.
18
+ const MAX_RETRY_AFTER_MS = DEFAULT_TIMEOUT_MS;
19
+
20
+ // Kept off the error object, so no client's errors gain a public field.
21
+ const retryAfterMsByError = new WeakMap();
22
+
23
+ export function joinUrl(base, path) {
24
+ const b = base.endsWith("/") ? base.slice(0, -1) : base;
25
+ const p = path.startsWith("/") ? path : `/${path}`;
26
+ return `${b}${p}`;
27
+ }
28
+
29
+ /**
30
+ * Today's `createXClient` option checks, each message prefixed `${factory}: `.
31
+ * `multipartFetchImpl` defaults to `fetchImpl` and is checked only when given.
32
+ */
33
+ export function readClientOptions(factory, opts) {
34
+ if (!opts || typeof opts !== "object") {
35
+ throw new TypeError(`${factory}: opts is required`);
36
+ }
37
+ const { baseUrl, getToken, getTenantId, getRequestHeaders } = opts;
38
+ if (typeof baseUrl !== "string" || baseUrl.length === 0) {
39
+ throw new TypeError(`${factory}: baseUrl is required`);
40
+ }
41
+ if (typeof getToken !== "function") {
42
+ throw new TypeError(`${factory}: getToken must be a function`);
43
+ }
44
+ if (typeof getTenantId !== "function") {
45
+ throw new TypeError(`${factory}: getTenantId must be a function`);
46
+ }
47
+ if (getRequestHeaders !== undefined && typeof getRequestHeaders !== "function") {
48
+ throw new TypeError(`${factory}: getRequestHeaders must be a function when provided`);
49
+ }
50
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
51
+ if (typeof fetchImpl !== "function") {
52
+ throw new TypeError(
53
+ `${factory}: no fetch available. Pass fetchImpl or run in an environment with global fetch.`,
54
+ );
55
+ }
56
+ const multipartFetchImpl = opts.multipartFetchImpl ?? fetchImpl;
57
+ if (typeof multipartFetchImpl !== "function") {
58
+ throw new TypeError(`${factory}: multipartFetchImpl must be a function when provided`);
59
+ }
60
+ return { baseUrl, getToken, getTenantId, getRequestHeaders, fetchImpl, multipartFetchImpl };
61
+ }
62
+
63
+ function sleep(ms) {
64
+ return new Promise((resolve) => setTimeout(resolve, ms));
65
+ }
66
+
67
+ function secondsToMs(value) {
68
+ const seconds = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
69
+ return typeof seconds === "number" && Number.isFinite(seconds) && seconds >= 0
70
+ ? seconds * 1000
71
+ : null;
72
+ }
73
+
74
+ // Body first: a cross-origin web Player cannot read the header, native can.
75
+ function retryAfterMs(body, header) {
76
+ const fromBody = secondsToMs(body?.retry_after);
77
+ if (fromBody != null) return fromBody;
78
+ if (typeof header !== "string" || header.trim() === "") return null;
79
+ const fromSeconds = secondsToMs(header);
80
+ if (fromSeconds != null) return fromSeconds;
81
+ const at = Date.parse(header);
82
+ return Number.isNaN(at) ? null : Math.max(0, at - Date.now());
83
+ }
84
+
85
+ function isRetryable(err) {
86
+ if (!err) return false;
87
+ if (err.code === "NETWORK" || err.status === 429 || err.status >= 500) return true;
88
+ // A caller's own `withRetry` attempt may reject with fetch's raw TypeError.
89
+ // A raw AbortError is a caller's cancel, which must stay final.
90
+ return err.name === "TypeError";
91
+ }
92
+
93
+ /**
94
+ * The headers a client request carries, in order: accept, the Bearer token and
95
+ * the tenant when there are any, JSON content-type, the call's own headers,
96
+ * then the host's `getRequestHeaders` result without null or undefined values.
97
+ */
98
+ export async function buildHeaders(
99
+ { getToken, getTenantId, getRequestHeaders },
100
+ { json = false, headers: callHeaders, namespace, operation } = {},
101
+ ) {
102
+ const token = await getToken();
103
+ const tenantId = await getTenantId();
104
+ const headers = { accept: "application/json" };
105
+ if (token) headers.authorization = token.startsWith("Bearer ") ? token : `Bearer ${token}`;
106
+ if (tenantId) headers["x-tenant-id"] = tenantId;
107
+ if (json) headers["content-type"] = "application/json";
108
+ Object.assign(headers, callHeaders);
109
+ // The host's headers win: they carry the widget's capability token.
110
+ const extra = getRequestHeaders ? await getRequestHeaders({ namespace, operation }) : null;
111
+ if (extra && typeof extra === "object") {
112
+ for (const [key, value] of Object.entries(extra)) {
113
+ if (value != null) headers[key] = value;
114
+ }
115
+ }
116
+ return headers;
117
+ }
118
+
119
+ // One attempt under its own timer. `timedOut` says the timer, not the
120
+ // attempt, ended it.
121
+ async function timedAttempt(attempt, timeoutMs) {
122
+ const controller = new AbortController();
123
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
124
+ try {
125
+ return { ok: true, value: await attempt(controller.signal) };
126
+ } catch (error) {
127
+ return { ok: false, error, timedOut: controller.signal.aborted };
128
+ } finally {
129
+ clearTimeout(timer);
130
+ }
131
+ }
132
+
133
+ function parseBody(text) {
134
+ if (text.length === 0) return null;
135
+ try {
136
+ return JSON.parse(text);
137
+ } catch {
138
+ return { raw: text };
139
+ }
140
+ }
141
+
142
+ /**
143
+ * One client's retry contract.
144
+ *
145
+ * @param {{ BaseError: new (message: string, init: { code: string, status: number }) => Error,
146
+ * fromResponse: (status: number, body: unknown) => Error }} policy
147
+ * @returns {{ BaseError, fromResponse, withRetry }} `withRetry` is the client's public export.
148
+ */
149
+ export function defineTransportPolicy({ BaseError, fromResponse }) {
150
+ /**
151
+ * Run `attempt` with retries: GET and HEAD up to 3 more times on a network
152
+ * failure, a 429 or a 5xx; other verbs once. Each attempt gets its own
153
+ * AbortSignal, aborted after `timeoutMs` (default 10 s); an attempt that
154
+ * timed out is not resent.
155
+ *
156
+ * @param {{ method?: string, timeoutMs?: number }} opts
157
+ * @param {(signal: AbortSignal) => Promise<any>} attempt
158
+ */
159
+ async function withRetry(opts, attempt) {
160
+ const method = (opts?.method || "GET").toUpperCase();
161
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
162
+ const maxAttempts = RETRY_VERBS.has(method) ? BACKOFF_MS.length + 1 : 1;
163
+ for (let i = 0; ; i++) {
164
+ const outcome = await timedAttempt(attempt, timeoutMs);
165
+ if (outcome.ok) return outcome.value;
166
+ const { error } = outcome;
167
+ const hintMs = retryAfterMsByError.get(error) ?? 0;
168
+ // The server may still be working on a request we timed out.
169
+ const final = i === maxAttempts - 1 || outcome.timedOut || hintMs > MAX_RETRY_AFTER_MS;
170
+ if (final || !isRetryable(error)) throw error;
171
+ await sleep(Math.max(BACKOFF_MS[i], hintMs));
172
+ }
173
+ }
174
+ return { BaseError, fromResponse, withRetry };
175
+ }
176
+
177
+ /**
178
+ * Validate a client factory's options and build the request its methods call.
179
+ *
180
+ * @param {string} factory The factory name, prefixed to every option error.
181
+ * @param {object} opts The factory's options.
182
+ * @param {ReturnType<typeof defineTransportPolicy>} policy
183
+ * @param {{ namespace?: string }} [defaults] The namespace a call without one reports.
184
+ */
185
+ export function createRequester(factory, opts, policy, { namespace: defaultNamespace } = {}) {
186
+ const options = readClientOptions(factory, opts);
187
+ const { baseUrl, fetchImpl, multipartFetchImpl } = options;
188
+ const { BaseError, fromResponse, withRetry } = policy;
189
+
190
+ /**
191
+ * `body` is sent as JSON; `formData` verbatim over `multipartFetchImpl`, with
192
+ * no content-type so the runtime sets the multipart boundary.
193
+ */
194
+ async function request(
195
+ method,
196
+ path,
197
+ {
198
+ body,
199
+ formData,
200
+ headers: callHeaders,
201
+ namespace = defaultNamespace,
202
+ operation,
203
+ timeoutMs,
204
+ onResponse,
205
+ } = {},
206
+ ) {
207
+ const url = joinUrl(baseUrl, path);
208
+ const headers = await buildHeaders(options, {
209
+ json: body !== undefined,
210
+ headers: callHeaders,
211
+ namespace,
212
+ operation,
213
+ });
214
+
215
+ const isMultipart = formData !== undefined;
216
+ const send = isMultipart ? multipartFetchImpl : fetchImpl;
217
+ const payload = isMultipart ? formData : body === undefined ? undefined : JSON.stringify(body);
218
+ const deadline = timeoutMs ?? (isMultipart ? MULTIPART_TIMEOUT_MS : undefined);
219
+
220
+ return withRetry({ method, timeoutMs: deadline }, async (signal) => {
221
+ let res;
222
+ let text;
223
+ // The body read can fail like the fetch, so both are classified here.
224
+ try {
225
+ res = await send(url, { method, headers, body: payload, signal });
226
+ text = await res.text();
227
+ } catch (err) {
228
+ const reason = signal.aborted ? "request timed out" : err?.message;
229
+ throw new BaseError(`Network failure: ${reason}`, { code: "NETWORK", status: 0 });
230
+ }
231
+ const parsed = parseBody(text);
232
+ if (!res.ok) {
233
+ const err = fromResponse(res.status, parsed);
234
+ const hintMs =
235
+ res.status === 429 ? retryAfterMs(parsed, res.headers?.get?.("retry-after")) : null;
236
+ if (hintMs != null) retryAfterMsByError.set(err, hintMs);
237
+ throw err;
238
+ }
239
+ onResponse?.(res);
240
+ return parsed;
241
+ });
242
+ }
243
+
244
+ return { request, ...options };
245
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colixsystems/actions-client",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Scoped clients for running a workspace's Actions and calling its REST connectors from an AppStudio app. Used by widgets through the injected WidgetContext.actions and WidgetContext.connectors.",
5
5
  "homepage": "https://github.com/Colix-AB/AppStudio",
6
6
  "type": "module",