@colixsystems/actions-client 0.2.0 → 0.3.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
@@ -10,7 +10,7 @@ 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.2.0` — adds `status(actionId)`, which says whether a run would reach the script.
13
+ `v0.3.0` — adds `createConnectorsClient`, which calls a workspace's REST connectors through the operations it listed for apps.
14
14
 
15
15
  ## Public API
16
16
 
@@ -59,6 +59,25 @@ Every failed run rejects with an `ActionError` (or a subclass) carrying `code`,
59
59
  | `ServerError` | 5xx | `ACTION_FAILED` — the script failed or the server is unavailable |
60
60
  | `ActionError` | 0 | `ACTION_FAILED` — offline, or no session to send; the original error is `cause` |
61
61
 
62
+ ## Connectors (v0.3.0)
63
+
64
+ A REST connector is a workspace's configured outside API: a base URL and its credentials. A workspace can let its app call a connector, but only through the **operations** it lists on it, each a method and a path template such as `GET /products/{id}`. The app names an operation and passes its arguments; the server builds the request from the listing, adds the credential and returns the answer. The credential never reaches the app.
65
+
66
+ ```js
67
+ import { createConnectorsClient, ConnectorError } from "@colixsystems/actions-client";
68
+
69
+ // Same providers as createActionsClient; getRequestHeaders sees
70
+ // { namespace: "connectors", operation: "call" }.
71
+ const connectors = createConnectorsClient(providers);
72
+
73
+ const { status, content_type, body } = await connectors.call(connectorId, "getProduct", {
74
+ params: { id: "42" },
75
+ query: { fields: "name,price" },
76
+ });
77
+ ```
78
+
79
+ `call` resolves with the outside API's status, even when it is not 2xx, and its parsed JSON (or text) body. It rejects with a `ConnectorError` when the platform refused the call or no answer came. `code` is the server's code when it sends one, else the status's: `INVALID_CONNECTOR_PARAMS` (400), `AUTH_REQUIRED` (401), `OPERATION_NOT_ALLOWED` (403), `CONNECTOR_NOT_FOUND` (404), `CONNECTOR_SETUP_INCOMPLETE` (409), `RATE_LIMITED` (429), `UPSTREAM_ERROR` (502), `UPSTREAM_TIMEOUT` (504), else `CONNECTOR_FAILED` with `status` 0. A call is never retried, because an operation can change data upstream.
80
+
62
81
  ## License
63
82
 
64
83
  MIT
package/dist/client.js CHANGED
@@ -26,30 +26,34 @@ function joinUrl(base, path) {
26
26
  * @param {(ctx: { namespace: string, operation: string }) => object | Promise<object>} [opts.getRequestHeaders]
27
27
  * Optional extra headers merged per request.
28
28
  * @param {typeof fetch} [opts.fetchImpl] Defaults to globalThis.fetch.
29
+ * @param {string} factory the public factory's name, for its error messages.
30
+ * @param {string} namespace passed to getRequestHeaders.
31
+ * @param {(status: number, body: unknown) => Error} toError maps a refusal.
32
+ * @returns the `send(method, path, body, operation)` both clients use.
29
33
  */
30
- export function createActionsClient(opts) {
34
+ export function createSender(opts, factory, namespace, toError) {
31
35
  if (!opts || typeof opts !== "object") {
32
- throw new TypeError("createActionsClient: opts is required");
36
+ throw new TypeError(`${factory}: opts is required`);
33
37
  }
34
38
  const { baseUrl, getToken, getTenantId, getRequestHeaders } = opts;
35
39
  if (typeof baseUrl !== "string" || baseUrl.length === 0) {
36
- throw new TypeError("createActionsClient: baseUrl is required");
40
+ throw new TypeError(`${factory}: baseUrl is required`);
37
41
  }
38
42
  if (typeof getToken !== "function") {
39
- throw new TypeError("createActionsClient: getToken must be a function");
43
+ throw new TypeError(`${factory}: getToken must be a function`);
40
44
  }
41
45
  if (typeof getTenantId !== "function") {
42
- throw new TypeError("createActionsClient: getTenantId must be a function");
46
+ throw new TypeError(`${factory}: getTenantId must be a function`);
43
47
  }
44
48
  if (getRequestHeaders !== undefined && typeof getRequestHeaders !== "function") {
45
49
  throw new TypeError(
46
- "createActionsClient: getRequestHeaders must be a function when provided",
50
+ `${factory}: getRequestHeaders must be a function when provided`,
47
51
  );
48
52
  }
49
53
  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
50
54
  if (typeof fetchImpl !== "function") {
51
55
  throw new TypeError(
52
- "createActionsClient: no fetch available. Pass fetchImpl or run in an environment with global fetch.",
56
+ `${factory}: no fetch available. Pass fetchImpl or run in an environment with global fetch.`,
53
57
  );
54
58
  }
55
59
 
@@ -62,7 +66,7 @@ export function createActionsClient(opts) {
62
66
  if (tenantId) headers["x-tenant-id"] = tenantId;
63
67
  if (body !== undefined) headers["content-type"] = "application/json";
64
68
  if (getRequestHeaders) {
65
- const extra = await getRequestHeaders({ namespace: NAMESPACE, operation });
69
+ const extra = await getRequestHeaders({ namespace, operation });
66
70
  if (extra && typeof extra === "object") Object.assign(headers, extra);
67
71
  }
68
72
 
@@ -80,9 +84,15 @@ export function createActionsClient(opts) {
80
84
  parsed = { raw: text };
81
85
  }
82
86
  }
83
- if (!res.ok) throw errorFromResponse(res.status, parsed);
87
+ if (!res.ok) throw toError(res.status, parsed);
84
88
  return parsed;
85
89
  }
90
+ return send;
91
+ }
92
+
93
+ /** Takes the providers createSender documents. */
94
+ export function createActionsClient(opts) {
95
+ const send = createSender(opts, "createActionsClient", NAMESPACE, errorFromResponse);
86
96
 
87
97
  function assertActionId(actionId, operation) {
88
98
  // "." and ".." survive encodeURIComponent and fetch would resolve them.
@@ -0,0 +1,51 @@
1
+ // sc-15659 — connectors client factory. Widgets never touch it directly; they
2
+ // receive a built client through WidgetContext.connectors.
3
+ //
4
+ // The server decides what may be called: the app-user JWT, the workspace's
5
+ // opt-in of the connector for apps, and the operations it listed. This client
6
+ // only carries the connector id, the operation's name and its arguments; the
7
+ // connector's credential is added on the server and never reaches the app.
8
+
9
+ import { ConnectorError, connectorErrorFromResponse } from "./errors.js";
10
+ import { createSender } from "./client.js";
11
+
12
+ /** Takes the same providers as createActionsClient. */
13
+ export function createConnectorsClient(opts) {
14
+ const send = createSender(opts, "createConnectorsClient", "connectors", connectorErrorFromResponse);
15
+
16
+ return {
17
+ /**
18
+ * Call one operation the workspace listed on an app-callable connector.
19
+ * Resolves `{ status, content_type, body }`: the upstream's status (a
20
+ * non-2xx upstream answer still resolves) and its parsed body. Rejects
21
+ * with a ConnectorError when the platform refused the call or no answer
22
+ * came. Never retried: an operation can change data upstream.
23
+ */
24
+ async call(connectorId, operation, { params, query, body } = {}) {
25
+ for (const [label, value] of [["connectorId", connectorId], ["operation", operation]]) {
26
+ // "." and ".." survive encodeURIComponent and fetch would resolve them.
27
+ if (typeof value !== "string" || !value.trim() || value === "." || value === "..") {
28
+ throw new TypeError(`call(connectorId, operation): ${label} must be a non-empty string`);
29
+ }
30
+ }
31
+ let answer;
32
+ try {
33
+ answer = await send(
34
+ "POST",
35
+ `/app-connectors/${encodeURIComponent(connectorId)}/call`,
36
+ { operation, params: params ?? {}, query: query ?? {}, body: body ?? null },
37
+ "call",
38
+ );
39
+ } catch (err) {
40
+ if (err instanceof ConnectorError) throw err;
41
+ throw new ConnectorError(`Connector request failed: ${err?.message || err}`, { cause: err });
42
+ }
43
+ const src = answer && typeof answer === "object" ? answer : {};
44
+ return {
45
+ status: typeof src.status === "number" ? src.status : 0,
46
+ content_type: typeof src.content_type === "string" ? src.content_type : null,
47
+ body: src.body === undefined ? null : src.body,
48
+ };
49
+ },
50
+ };
51
+ }
@@ -0,0 +1,64 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { createConnectorsClient, ConnectorError } from "./index.js";
4
+
5
+ function stubFetch(status, body) {
6
+ const calls = [];
7
+ const fetchImpl = async (url, init) => {
8
+ calls.push({ url, init });
9
+ return { ok: status >= 200 && status < 300, status, text: async () => (body === undefined ? "" : JSON.stringify(body)) };
10
+ };
11
+ return { calls, fetchImpl };
12
+ }
13
+
14
+ const base = (fetchImpl) =>
15
+ createConnectorsClient({ baseUrl: "https://api.example/api/v1/", getToken: () => "tok", getTenantId: () => "t1", fetchImpl });
16
+
17
+ test("call posts the operation and its arguments, never a method or a path", async () => {
18
+ const { calls, fetchImpl } = stubFetch(200, { status: 200, content_type: "application/json", body: { a: 1 } });
19
+ const out = await base(fetchImpl).call("c 1", "getProduct", { params: { id: "7" }, query: { q: "x" } });
20
+ assert.deepEqual(out, { status: 200, content_type: "application/json", body: { a: 1 } });
21
+ assert.equal(calls[0].url, "https://api.example/api/v1/app-connectors/c%201/call");
22
+ assert.equal(calls[0].init.method, "POST");
23
+ assert.equal(calls[0].init.headers.authorization, "Bearer tok");
24
+ assert.equal(calls[0].init.headers["x-tenant-id"], "t1");
25
+ assert.deepEqual(JSON.parse(calls[0].init.body), {
26
+ operation: "getProduct",
27
+ params: { id: "7" },
28
+ query: { q: "x" },
29
+ body: null,
30
+ });
31
+ });
32
+
33
+ test("an upstream error status still resolves", async () => {
34
+ const { fetchImpl } = stubFetch(200, { status: 404, content_type: null, body: "nope" });
35
+ assert.equal((await base(fetchImpl).call("c1", "getProduct")).status, 404);
36
+ });
37
+
38
+ for (const [status, envelope, code] of [
39
+ [403, { code: "OPERATION_NOT_ALLOWED" }, "OPERATION_NOT_ALLOWED"],
40
+ [404, { message: "Not found" }, "CONNECTOR_NOT_FOUND"],
41
+ [409, {}, "CONNECTOR_SETUP_INCOMPLETE"],
42
+ [429, {}, "RATE_LIMITED"],
43
+ [401, { message: "Unauthorized" }, "AUTH_REQUIRED"],
44
+ [500, {}, "CONNECTOR_FAILED"],
45
+ ]) {
46
+ test(`a ${status} rejects with ${code}`, async () => {
47
+ const { fetchImpl } = stubFetch(status, envelope);
48
+ await assert.rejects(base(fetchImpl).call("c1", "op"), (err) => err instanceof ConnectorError && err.code === code);
49
+ });
50
+ }
51
+
52
+ test("no answer rejects with CONNECTOR_FAILED and status 0", async () => {
53
+ const client = base(async () => {
54
+ throw new Error("offline");
55
+ });
56
+ await assert.rejects(client.call("c1", "op"), (err) => err.code === "CONNECTOR_FAILED" && err.status === 0);
57
+ });
58
+
59
+ test("a dot id or an empty operation is refused before any request", async () => {
60
+ const { calls, fetchImpl } = stubFetch(200, {});
61
+ await assert.rejects(base(fetchImpl).call("..", "op"), TypeError);
62
+ await assert.rejects(base(fetchImpl).call("c1", ""), TypeError);
63
+ assert.equal(calls.length, 0);
64
+ });
package/dist/errors.js CHANGED
@@ -59,6 +59,19 @@ export class ServerError extends ActionError {
59
59
 
60
60
  const CODE_SHAPED = /^[A-Z][A-Z0-9_]+$/;
61
61
 
62
+ /**
63
+ * The stable code for a refusal: the envelope's `code` when CODE-shaped, else
64
+ * the status's code, else the fallback. A bare `{ message: "Unauthorized" }`
65
+ * must not become a widget's code.
66
+ */
67
+ function refusal(status, body, codeByStatus, fallback) {
68
+ const details = body && typeof body === "object" ? body : null;
69
+ const envelopeCode = details && typeof details.code === "string" ? details.code : "";
70
+ const code = CODE_SHAPED.test(envelopeCode) ? envelopeCode : codeByStatus[status] || fallback;
71
+ const message = (details && typeof details.message === "string" && details.message) || code;
72
+ return { code, message, details };
73
+ }
74
+
62
75
  const CODE_BY_STATUS = {
63
76
  400: "INVALID_ACTION_INPUT",
64
77
  401: "AUTH_REQUIRED",
@@ -72,13 +85,7 @@ const CODE_BY_STATUS = {
72
85
  * to the matching ActionError subclass.
73
86
  */
74
87
  export function errorFromResponse(status, body) {
75
- const details = body && typeof body === "object" ? body : null;
76
- const envelopeCode = details && typeof details.code === "string" ? details.code : "";
77
- // A bare `{ message: "Unauthorized" }` must not become a widget's code.
78
- const code = CODE_SHAPED.test(envelopeCode)
79
- ? envelopeCode
80
- : CODE_BY_STATUS[status] || "ACTION_FAILED";
81
- const message = (details && typeof details.message === "string" && details.message) || code;
88
+ const { code, message, details } = refusal(status, body, CODE_BY_STATUS, "ACTION_FAILED");
82
89
  switch (status) {
83
90
  case 400:
84
91
  return new ValidationError(message, code, details);
@@ -93,3 +100,31 @@ export function errorFromResponse(status, body) {
93
100
  return new ActionError(message, { code, status, details });
94
101
  }
95
102
  }
103
+
104
+ // sc-15659 — what a connector call rejects with. Same shape as ActionError.
105
+ export class ConnectorError extends Error {
106
+ constructor(message, { code = "CONNECTOR_FAILED", status = 0, details = null, cause = undefined } = {}) {
107
+ super(message);
108
+ this.name = "ConnectorError";
109
+ this.code = code;
110
+ this.status = status;
111
+ this.details = details;
112
+ if (cause !== undefined) this.cause = cause;
113
+ }
114
+ }
115
+
116
+ const CONNECTOR_CODE_BY_STATUS = {
117
+ 400: "INVALID_CONNECTOR_PARAMS",
118
+ 401: "AUTH_REQUIRED",
119
+ 403: "OPERATION_NOT_ALLOWED",
120
+ 404: "CONNECTOR_NOT_FOUND",
121
+ 409: "CONNECTOR_SETUP_INCOMPLETE",
122
+ 429: "RATE_LIMITED",
123
+ 502: "UPSTREAM_ERROR",
124
+ 504: "UPSTREAM_TIMEOUT",
125
+ };
126
+
127
+ export function connectorErrorFromResponse(status, body) {
128
+ const { code, message, details } = refusal(status, body, CONNECTOR_CODE_BY_STATUS, "CONNECTOR_FAILED");
129
+ return new ConnectorError(message, { code, status, details });
130
+ }
package/dist/index.d.ts CHANGED
@@ -66,3 +66,45 @@ export class RateLimitedError extends ActionError {}
66
66
  export class ServerError extends ActionError {}
67
67
 
68
68
  export function errorFromResponse(status: number, body: unknown): ActionError;
69
+
70
+ // sc-15659 — calling a workspace REST connector's listed operations.
71
+
72
+ /** What one call answers: the upstream's status and parsed body. */
73
+ export interface ConnectorCallResult {
74
+ status: number;
75
+ content_type: string | null;
76
+ body: unknown;
77
+ }
78
+
79
+ export interface ConnectorCallArgs {
80
+ /** Values for the operation's `{name}` path segments. */
81
+ params?: Record<string, string | number>;
82
+ /** Only the query names the operation lists. */
83
+ query?: Record<string, string | number | boolean | Array<string | number | boolean>>;
84
+ /** A JSON body, only for an operation that takes one. */
85
+ body?: unknown;
86
+ }
87
+
88
+ export interface ConnectorsClient {
89
+ /** POST /app-connectors/:connectorId/call. Never retried. */
90
+ call(connectorId: string, operation: string, args?: ConnectorCallArgs): Promise<ConnectorCallResult>;
91
+ }
92
+
93
+ /** sc-15659 — takes the same providers as createActionsClient. */
94
+ export function createConnectorsClient(opts: CreateActionsClientOptions): ConnectorsClient;
95
+
96
+ export class ConnectorError extends Error {
97
+ /**
98
+ * The server's `code` when CODE-shaped, else the status's code (400
99
+ * INVALID_CONNECTOR_PARAMS, 401 AUTH_REQUIRED, 403 OPERATION_NOT_ALLOWED,
100
+ * 404 CONNECTOR_NOT_FOUND, 409 CONNECTOR_SETUP_INCOMPLETE, 429 RATE_LIMITED,
101
+ * 502 UPSTREAM_ERROR, 504 UPSTREAM_TIMEOUT), else "CONNECTOR_FAILED".
102
+ */
103
+ code: string;
104
+ /** The HTTP status; 0 when no HTTP answer arrived. */
105
+ status: number;
106
+ details: unknown;
107
+ constructor(message: string, init?: { code?: string; status?: number; details?: unknown; cause?: unknown });
108
+ }
109
+
110
+ export function connectorErrorFromResponse(status: number, body: unknown): ConnectorError;
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Public entry for @colixsystems/actions-client.
2
2
 
3
3
  export { createActionsClient } from "./client.js";
4
+ export { createConnectorsClient } from "./connectors.js";
4
5
  export {
5
6
  ActionError,
6
7
  ValidationError,
@@ -9,4 +10,6 @@ export {
9
10
  RateLimitedError,
10
11
  ServerError,
11
12
  errorFromResponse,
13
+ ConnectorError,
14
+ connectorErrorFromResponse,
12
15
  } from "./errors.js";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@colixsystems/actions-client",
3
- "version": "0.2.0",
4
- "description": "Scoped client for running a workspace's Actions from an AppStudio app. Used by widgets through the injected WidgetContext.actions.",
3
+ "version": "0.3.0",
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",
7
7
  "main": "./dist/index.js",
@@ -33,6 +33,7 @@
33
33
  "keywords": [
34
34
  "appstudio",
35
35
  "actions",
36
+ "connectors",
36
37
  "client"
37
38
  ],
38
39
  "license": "MIT"