@orbit-app/functions 0.8.0 → 0.11.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,6 +1,6 @@
1
1
  # @orbit-app/functions
2
2
 
3
- Write Orbit Functions: TypeScript that runs in Orbit's sandbox for one app, as the store's org. An app calls an action function. A provider event, such as a Slack reaction, runs a webhook function. A cron schedule in `orbit.json` runs a schedule function. A service outside Orbit runs a delegate function through a signed link, which an action, webhook or schedule function makes with `orbit.defineDelegates().sign()`.
3
+ Write Orbit Functions: TypeScript that runs in Orbit's sandbox for one app. An app calls an action function. A provider event, such as a Slack reaction, runs a webhook function. A cron schedule in `orbit.json` runs a schedule function. A service outside Orbit runs a delegate function through a signed link, which an action, webhook or schedule function makes with `orbit.defineDelegates().sign()`.
4
4
 
5
5
  ```bash
6
6
  npm install --save-dev @orbit-app/functions esbuild
@@ -22,13 +22,17 @@ export default defineFunction({
22
22
  });
23
23
  ```
24
24
 
25
+ A run reads and writes objects with the access of its person. An action run acts as its caller, and a delegate run as the member who signed it: it reads only what that person's app can read, and an object that it creates without `owner` belongs to that person. A webhook run, a schedule run and a delegate run that an event or a schedule signed act as the app: they read the objects that the app owns and the objects shared with the whole store. `orbit.app.objects` and `orbit.app.defineObjects()` call as the app, only within the `grants` of the function in `orbit.json`, such as `{ "kudos": ["create"] }`. The approval dialog shows each grant (0.10.0 and later; the doc `migrations/functions-caller-access` gives the move). From 0.11.0, a typed `update` or `delete` as the app needs no `read` grant: Orbit checks the type (the doc `migrations/functions-app-writes`).
26
+
27
+ `orbit.runOrg()` gives the org that the run acts in, in the shape of `getOrg()` of `@orbit-app/web`: the caller's org of an action, the signer's org of a delegate, else the org that owns the app. `orbit.appOrg()` gives the org that owns the app. `orbit.org()` is the same as `appOrg()` and goes in a later release (0.10.0 and later; the doc `migrations/functions-run-org` gives the move).
28
+
25
29
  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
30
 
27
31
  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).
28
32
 
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.
33
+ 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. Keep `orbit` and each client of it inside `run`: its token ends with the run.
30
34
 
31
- The full guide (triggers, limits, org connections, the run log) is `functions.md` of the Orbit MCP server's docs. In this repository it is `api/public-docs/functions.md`.
35
+ The full guide (triggers, limits, org connections, the run log) is the `functions` doc of the Orbit MCP server, and the Functions pages of the docs site. In this repository they are in `docs-site/src/content/docs` (`concepts/functions.md`, `guides/functions/` and `reference/functions/`).
32
36
 
33
37
  ## Develop this package
34
38
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
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";
2
+ export { OrbitConnectionError, OrbitObjectError, type ObjectsApi, type ObjectsClient, type ObjectsOptions, type OperationTypes, type OrbitConnectionErrorCode, type RetryOptions, type WriteOptions, } from "@orbit-app/web";
3
3
  export type ActionTrigger = {
4
4
  type: "action";
5
5
  };
@@ -95,6 +95,13 @@ export type OrbitOrg = {
95
95
  name: string;
96
96
  slug: string;
97
97
  };
98
+ export type OrbitRunOrg = {
99
+ id: string;
100
+ name: string;
101
+ slug: string | null;
102
+ role: string | null;
103
+ appOrgId: string;
104
+ };
98
105
  export type OrgConnection = {
99
106
  provider: string;
100
107
  missingOperations: readonly string[];
@@ -117,7 +124,14 @@ export type ConnectionMember = {
117
124
  export interface OrbitSecretNames {
118
125
  }
119
126
  export type OrbitSecretName = [keyof OrbitSecretNames] extends [never] ? string : Extract<keyof OrbitSecretNames, string>;
127
+ export type FunctionAppOrbit = {
128
+ objects: ObjectsApi;
129
+ defineObjects<Types extends Record<string, Record<string, unknown>>, Required extends {
130
+ [K in keyof Types]?: keyof Types[K];
131
+ } = {}>(options?: ObjectsOptions): ObjectsClient<Types, Required>;
132
+ };
120
133
  export type FunctionOrbit = {
134
+ app: FunctionAppOrbit;
121
135
  objects: ObjectsApi;
122
136
  defineObjects<Types extends Record<string, Record<string, unknown>>, Required extends {
123
137
  [K in keyof Types]?: keyof Types[K];
@@ -125,6 +139,9 @@ export type FunctionOrbit = {
125
139
  connections: OrgConnections;
126
140
  defineConnections<Ops extends OperationTypes>(): OrgConnections<Ops>;
127
141
  defineDelegates<M extends Record<string, DelegateTypes> = Record<string, DelegateTypes>>(): Delegates<M>;
142
+ runOrg(): OrbitRunOrg;
143
+ appOrg(): OrbitOrg;
144
+ /** @deprecated Use appOrg() for the org that owns the app, or runOrg() for the org of the run. */
128
145
  org(): OrbitOrg;
129
146
  secret(name: OrbitSecretName): string;
130
147
  };
@@ -167,6 +184,8 @@ export type DispatchRequest = {
167
184
  attempt?: number;
168
185
  delegate?: DelegateContext["delegate"];
169
186
  org: OrbitOrg;
187
+ appOrg?: OrbitOrg;
188
+ runOrg?: OrbitRunOrg;
170
189
  secretNonce?: string;
171
190
  };
172
191
  };
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
- // Orbit Functions: publisher code that runs in Orbit's sandbox, never on a member's Mac. A function
2
- // acts as the store's org. It reaches only the Orbit API, with the token of its run.
1
+ // Orbit Functions: publisher code that runs in Orbit's sandbox, never on a member's Mac. A run
2
+ // reads objects as its person (the caller of an action, the member who signed a delegate), or as the
3
+ // app with no person. orbit.app acts as the app within the grants of orbit.json. It reaches only the
4
+ // Orbit API, with the token of its run.
3
5
  import { OrbitConnectionError, OrbitObjectError, typedObjects, withRetry, } from "@orbit-app/web";
4
6
  export { OrbitConnectionError, OrbitObjectError, } from "@orbit-app/web";
5
7
  const DELEGATE_CODES = [
@@ -140,13 +142,15 @@ function createOrbit(req) {
140
142
  ];
141
143
  const connectionError = (code, message, extra) => new OrbitConnectionError(CONNECTION_CODES.includes(code) ? code : "unavailable", message, extra);
142
144
  const delegateError = (code, message, extra) => new OrbitDelegateError(DELEGATE_CODES.includes(code) ? code : "unavailable", message, extra);
143
- async function call(method, path, body, fail = objectError) {
145
+ // `asApp` makes the call as the app, within the function's grants (orbit.app, rule 128).
146
+ async function call(method, path, body, fail = objectError, asApp = false) {
144
147
  let res;
145
148
  try {
146
149
  res = await fetch(`${base}${path}`, {
147
150
  method,
148
151
  headers: {
149
152
  authorization: `Bearer ${req.token}`,
153
+ ...(asApp && { "orbit-as": "app" }),
150
154
  ...(body !== undefined && { "content-type": "application/json" }),
151
155
  },
152
156
  body: body === undefined ? undefined : JSON.stringify(body),
@@ -167,18 +171,23 @@ function createOrbit(req) {
167
171
  });
168
172
  }
169
173
  const enc = encodeURIComponent;
170
- const once = {
171
- create: (input) => call("POST", "/v1/objects", input),
172
- get: (id) => call("GET", `/v1/objects/${enc(id)}`),
173
- getByHandle: (type, handle) => call("GET", `/v1/objects/by-handle/${enc(type)}/${enc(handle)}`),
174
- list: (input) => call("POST", "/v1/objects/query", input),
175
- update: (id, input) => call("PATCH", `/v1/objects/${enc(id)}`, input),
176
- upsert: (type, handle, input = {}) => call("PUT", `/v1/objects/by-handle/${enc(type)}/${enc(handle)}`, input),
177
- delete: async (id) => {
178
- await call("DELETE", `/v1/objects/${enc(id)}`);
174
+ const typeQuery = (options) => (options?.type === undefined ? "" : `?type=${enc(options.type)}`);
175
+ const objectsAs = (asApp) => ({
176
+ create: (input) => call("POST", "/v1/objects", input, objectError, asApp),
177
+ get: (id) => call("GET", `/v1/objects/${enc(id)}`, undefined, objectError, asApp),
178
+ getByHandle: (type, handle) => call("GET", `/v1/objects/by-handle/${enc(type)}/${enc(handle)}`, undefined, objectError, asApp),
179
+ list: (input) => call("POST", "/v1/objects/query", input, objectError, asApp),
180
+ // ?type= makes the API check the type, so a typed write needs no read grant.
181
+ update: (id, input, options) => call("PATCH", `/v1/objects/${enc(id)}${typeQuery(options)}`, input, objectError, asApp),
182
+ upsert: (type, handle, input = {}) => call("PUT", `/v1/objects/by-handle/${enc(type)}/${enc(handle)}`, input, objectError, asApp),
183
+ delete: async (id, options) => {
184
+ await call("DELETE", `/v1/objects/${enc(id)}${typeQuery(options)}`, undefined, objectError, asApp);
179
185
  },
180
- };
186
+ });
187
+ const once = objectsAs(false);
181
188
  const objects = withRetry(once);
189
+ const appOnce = objectsAs(true);
190
+ const appObjects = withRetry(appOnce);
182
191
  function connection(c) {
183
192
  return Object.freeze({
184
193
  provider: c.provider,
@@ -209,6 +218,10 @@ function createOrbit(req) {
209
218
  return {
210
219
  objects,
211
220
  defineObjects: (options) => typedObjects(options ? withRetry(once, options.retry) : objects),
221
+ app: Object.freeze({
222
+ objects: appObjects,
223
+ defineObjects: (options) => typedObjects(options ? withRetry(appOnce, options.retry) : appObjects),
224
+ }),
212
225
  connections,
213
226
  defineConnections: () => connections,
214
227
  defineDelegates: () => ({
@@ -217,6 +230,8 @@ function createOrbit(req) {
217
230
  await call("DELETE", `/v1/delegates/${enc(id)}`, undefined, delegateError);
218
231
  },
219
232
  }),
233
+ runOrg: () => ({ ...(req.ctx.runOrg ?? { ...req.ctx.org, role: null, appOrgId: req.ctx.org.id }) }),
234
+ appOrg: () => ({ ...(req.ctx.appOrg ?? req.ctx.org) }),
220
235
  org: () => ({ ...req.ctx.org }),
221
236
  secret: (name) => {
222
237
  if (typeof name !== "string" || !SECRET_NAME.test(name)) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orbit-app/functions",
3
- "version": "0.8.0",
4
- "description": "Write Orbit Functions: publisher code that runs in Orbit's sandbox as the store's org.",
3
+ "version": "0.11.0",
4
+ "description": "Write Orbit Functions: publisher code that runs in Orbit's sandbox as its caller or as the app.",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": {
@@ -19,7 +19,7 @@
19
19
  "prepack": "pnpm build"
20
20
  },
21
21
  "dependencies": {
22
- "@orbit-app/web": "^0.3.0"
22
+ "@orbit-app/web": "^0.6.0"
23
23
  },
24
24
  "devDependencies": {
25
25
  "typescript": "^7.0.2",