@orbit-app/functions 0.6.0 → 0.8.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
@@ -22,6 +22,8 @@ export default defineFunction({
22
22
  });
23
23
  ```
24
24
 
25
+ A function calls a provider through the store's org connection: `await orbit.connections.call("gitlab", "list_issues", { state: "opened" })` runs one operation that `orbit.json` declares, and `orbit.defineConnections<OrbitOperations>()` gives the same call with the types of `orbit types --ts` (0.7.0 and later). A failure is an `OrbitConnectionError`.
26
+
25
27
  A function can also map a provider account to the store member who connected it, such as the reviewers of a GitLab event: `await orbit.connections.members("gitlab", { accountIds })` gives `{ userId, accountId, username, team }` for each match, and `team` keeps only one Slack workspace or Grid org (0.6.0 and later).
26
28
 
27
29
  Declare each function under `functions` in `orbit.json`. `orbit publish` and `orbit pack` bundle each entry with esbuild and `serve()`, the wrapper of this package. Do not call `serve()` yourself.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { type ObjectsApi, type ObjectsClient, type ObjectsOptions } from "@orbit-app/web";
2
- export { OrbitObjectError, type ObjectsApi, type ObjectsClient, type ObjectsOptions, type RetryOptions } from "@orbit-app/web";
1
+ import { type OperationTypes, type ObjectsApi, type ObjectsClient, type ObjectsOptions } from "@orbit-app/web";
2
+ export { OrbitConnectionError, OrbitObjectError, type ObjectsApi, type ObjectsClient, type ObjectsOptions, type OperationTypes, type OrbitConnectionErrorCode, type RetryOptions, } from "@orbit-app/web";
3
3
  export type ActionTrigger = {
4
4
  type: "action";
5
5
  };
@@ -97,13 +97,16 @@ export type OrbitOrg = {
97
97
  };
98
98
  export type OrgConnection = {
99
99
  provider: string;
100
- scopes: readonly string[];
101
- missingScopes: readonly string[];
102
- fetch(path: string, init?: {
103
- method?: string;
104
- headers?: Record<string, string>;
105
- body?: string | Uint8Array | null;
106
- }): Promise<Response>;
100
+ missingOperations: readonly string[];
101
+ };
102
+ type CallArgs<Input> = {} extends Input ? [input?: Input] : [input: Input];
103
+ export type OrgConnections<Ops extends OperationTypes = OperationTypes> = {
104
+ get(provider: string): Promise<OrgConnection | null>;
105
+ call<P extends keyof Ops & string, O extends keyof Ops[P] & string>(provider: P, operation: O, ...args: CallArgs<Ops[P][O]["input"]>): Promise<Ops[P][O]["output"]>;
106
+ members(provider: string, opts?: {
107
+ accountIds?: readonly string[];
108
+ team?: string;
109
+ }): Promise<ConnectionMember[]>;
107
110
  };
108
111
  export type ConnectionMember = {
109
112
  userId: string;
@@ -119,13 +122,8 @@ export type FunctionOrbit = {
119
122
  defineObjects<Types extends Record<string, Record<string, unknown>>, Required extends {
120
123
  [K in keyof Types]?: keyof Types[K];
121
124
  } = {}>(options?: ObjectsOptions): ObjectsClient<Types, Required>;
122
- connections: {
123
- get(provider: string): Promise<OrgConnection | null>;
124
- members(provider: string, opts?: {
125
- accountIds?: readonly string[];
126
- team?: string;
127
- }): Promise<ConnectionMember[]>;
128
- };
125
+ connections: OrgConnections;
126
+ defineConnections<Ops extends OperationTypes>(): OrgConnections<Ops>;
129
127
  defineDelegates<M extends Record<string, DelegateTypes> = Record<string, DelegateTypes>>(): Delegates<M>;
130
128
  org(): OrbitOrg;
131
129
  secret(name: OrbitSecretName): string;
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Orbit Functions: publisher code that runs in Orbit's sandbox, never on a member's Mac. A function
2
2
  // acts as the store's org. It reaches only the Orbit API, with the token of its run.
3
- import { OrbitObjectError, typedObjects, withRetry, } from "@orbit-app/web";
4
- export { OrbitObjectError } from "@orbit-app/web";
3
+ import { OrbitConnectionError, OrbitObjectError, typedObjects, withRetry, } from "@orbit-app/web";
4
+ export { OrbitConnectionError, OrbitObjectError, } from "@orbit-app/web";
5
5
  const DELEGATE_CODES = [
6
6
  "invalid",
7
7
  "invalid_allow_from",
@@ -128,6 +128,17 @@ const OBJECT_CODES = ["not_found", "forbidden", "invalid", "conflict", "limit",
128
128
  function createOrbit(req) {
129
129
  const base = req.apiBase.replace(/\/+$/, "");
130
130
  const objectError = (code, message, extra) => new OrbitObjectError(OBJECT_CODES.includes(code) ? code : "unavailable", message, extra);
131
+ const CONNECTION_CODES = [
132
+ "not_declared",
133
+ "not_connected",
134
+ "invalid",
135
+ "not_found",
136
+ "provider_error",
137
+ "limit",
138
+ "rate_limited",
139
+ "unavailable",
140
+ ];
141
+ const connectionError = (code, message, extra) => new OrbitConnectionError(CONNECTION_CODES.includes(code) ? code : "unavailable", message, extra);
131
142
  const delegateError = (code, message, extra) => new OrbitDelegateError(DELEGATE_CODES.includes(code) ? code : "unavailable", message, extra);
132
143
  async function call(method, path, body, fail = objectError) {
133
144
  let res;
@@ -171,49 +182,35 @@ function createOrbit(req) {
171
182
  function connection(c) {
172
183
  return Object.freeze({
173
184
  provider: c.provider,
174
- scopes: Object.freeze([...c.scopes]),
175
- missingScopes: Object.freeze([...c.missingScopes]),
176
- async fetch(rawPath, init = {}) {
177
- const { path, query } = splitPath(rawPath);
178
- const method = (init.method ?? "GET").toUpperCase();
179
- const body = init.body === undefined || init.body === null
180
- ? null
181
- : typeof init.body === "string"
182
- ? init.body
183
- : { base64: toBase64(init.body) };
184
- const reply = (await call("POST", `/v1/connections/${enc(c.provider)}/proxy`, {
185
- method,
186
- path,
187
- ...(query && { query }),
188
- headers: init.headers ?? {},
189
- body,
190
- owner: "org",
191
- }));
192
- const bytes = typeof reply.body === "string" ? reply.body : fromBase64(reply.body.base64);
193
- const empty = [204, 205, 304].includes(reply.status) || method === "HEAD";
194
- return new Response(empty ? null : bytes, { status: reply.status, headers: reply.headers });
195
- },
185
+ missingOperations: Object.freeze([...(c.missingOperations ?? [])]),
196
186
  });
197
187
  }
188
+ const connections = {
189
+ async get(provider) {
190
+ const list = (await call("GET", "/v1/connections?owner=org"));
191
+ const c = list.connections.find((x) => x.provider === provider && x.status === "active");
192
+ return c ? connection(c) : null;
193
+ },
194
+ async call(provider, operation, input) {
195
+ const body = { operation, input: input ?? {}, owner: "org" };
196
+ const reply = (await call("POST", `/v1/connections/${enc(provider)}/call`, body, connectionError));
197
+ return reply.output;
198
+ },
199
+ async members(provider, opts = {}) {
200
+ const ids = opts.accountIds ? [...opts.accountIds] : undefined;
201
+ if (ids?.length === 0)
202
+ return [];
203
+ const params = [...(ids ?? []).map((id) => `accountId=${enc(String(id))}`), ...(opts.team ? [`team=${enc(opts.team)}`] : [])];
204
+ const query = params.length ? `?${params.join("&")}` : "";
205
+ const reply = (await call("GET", `/v1/connections/${enc(provider)}/members${query}`));
206
+ return reply.members.map((m) => Object.freeze({ userId: m.userId, accountId: m.accountId, username: m.username ?? null, team: m.team ?? null }));
207
+ },
208
+ };
198
209
  return {
199
210
  objects,
200
211
  defineObjects: (options) => typedObjects(options ? withRetry(once, options.retry) : objects),
201
- connections: {
202
- async get(provider) {
203
- const list = (await call("GET", "/v1/connections?owner=org"));
204
- const c = list.connections.find((x) => x.provider === provider && x.status === "active");
205
- return c ? connection(c) : null;
206
- },
207
- async members(provider, opts = {}) {
208
- const ids = opts.accountIds ? [...opts.accountIds] : undefined;
209
- if (ids?.length === 0)
210
- return [];
211
- const params = [...(ids ?? []).map((id) => `accountId=${enc(String(id))}`), ...(opts.team ? [`team=${enc(opts.team)}`] : [])];
212
- const query = params.length ? `?${params.join("&")}` : "";
213
- const reply = (await call("GET", `/v1/connections/${enc(provider)}/members${query}`));
214
- return reply.members.map((m) => Object.freeze({ userId: m.userId, accountId: m.accountId, username: m.username ?? null, team: m.team ?? null }));
215
- },
216
- },
212
+ connections,
213
+ defineConnections: () => connections,
217
214
  defineDelegates: () => ({
218
215
  sign: (name, opts) => call("POST", "/v1/delegates", { name, ...opts }, delegateError),
219
216
  revoke: async (id) => {
@@ -232,26 +229,3 @@ function createOrbit(req) {
232
229
  },
233
230
  };
234
231
  }
235
- // "/users.info?user=U1" → the path and a query map, as the proxy takes them.
236
- function splitPath(raw) {
237
- const q = raw.indexOf("?");
238
- if (q < 0)
239
- return { path: raw };
240
- const query = {};
241
- for (const [k, v] of new URLSearchParams(raw.slice(q + 1)))
242
- query[k] = v;
243
- return { path: raw.slice(0, q), query };
244
- }
245
- function toBase64(bytes) {
246
- let s = "";
247
- for (const b of bytes)
248
- s += String.fromCharCode(b);
249
- return btoa(s);
250
- }
251
- function fromBase64(b64) {
252
- const s = atob(b64);
253
- const out = new Uint8Array(s.length);
254
- for (let i = 0; i < s.length; i++)
255
- out[i] = s.charCodeAt(i);
256
- return out;
257
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orbit-app/functions",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Write Orbit Functions: publisher code that runs in Orbit's sandbox as the store's org.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -19,7 +19,7 @@
19
19
  "prepack": "pnpm build"
20
20
  },
21
21
  "dependencies": {
22
- "@orbit-app/web": "^0.1.1"
22
+ "@orbit-app/web": "^0.3.0"
23
23
  },
24
24
  "devDependencies": {
25
25
  "typescript": "^7.0.2",