@inferencebureau/apps-sdk 0.0.0-stage → 0.2.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,85 @@
1
- # Temporary Holding Version
1
+ # @inferencebureau/apps-sdk
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
+ What an Inference Bureau app's code imports: types for the metadata files (`schema.ib.ts`, `permissions.ib.ts`,
4
+ `settings.ib.ts`), the helpers an action's `run` uses (`applyParams`, `save`, `deleteRecord`), the records API client,
5
+ request checks for Shopify session tokens and app proxies, and a harness for testing actions. Apps are operator-only for
6
+ now.
7
+
8
+ ```sh
9
+ npm install @inferencebureau/apps-sdk
10
+ ```
11
+
12
+ Apps built on Inference Bureau get the SDK in every build already; install it to have the types in your editor, or to
13
+ use the client from your own code. It's ESM, uses only `fetch` and Web Crypto, and runs on Node 20+, edge runtimes and
14
+ Next.js without `transpilePackages`.
15
+
16
+ ```ts
17
+ // api/models/review/actions/approve.ts
18
+ import { save, type ActionRun, type ActionOptions } from "@inferencebureau/apps-sdk";
19
+
20
+ export const run: ActionRun = async ({ record }) => {
21
+ record.status = "approved";
22
+ await save(record);
23
+ };
24
+ export const options: ActionOptions = { actionType: "update" };
25
+ ```
26
+
27
+ ```ts
28
+ // web/app/proxy/route.ts: a storefront app proxy route
29
+ import { verifyProxyRequest } from "@inferencebureau/apps-sdk";
30
+
31
+ export async function GET(request: Request) {
32
+ const proxy = await verifyProxyRequest(request);
33
+ if (!proxy) return new Response("Not found", { status: 404 });
34
+ return new Response("<h1>Hello {{ shop.name }}</h1>", { headers: { "content-type": "application/liquid" } });
35
+ }
36
+ ```
37
+
38
+ ```ts
39
+ // Anywhere in the app's server code: the environment's records and actions, no options needed.
40
+ import { ApiError, createClient } from "@inferencebureau/apps-sdk";
41
+
42
+ const api = createClient();
43
+ const page = await api.review.findMany({
44
+ filter: { shop: { equals: "inference-bureau.myshopify.com" }, status: { equals: "pending" } },
45
+ sort: { createdAt: "Ascending" },
46
+ first: 50,
47
+ });
48
+ try {
49
+ await api.review.run("approve", { id: page.records[0].id, shop: "inference-bureau.myshopify.com" });
50
+ } catch (e) {
51
+ if (e instanceof ApiError) console.error(e.status, e.code, e.problems);
52
+ }
53
+ ```
54
+
55
+ ```ts
56
+ // tests/approve.test.ts: the app's actions against in-memory records, run with `ib-apps test` (Vitest)
57
+ import { expect, it } from "vitest";
58
+ import { TEST_SHOP, loadApp } from "@inferencebureau/apps-sdk/test";
59
+
60
+ const app = await loadApp(); // the folder's schemas, actions and settings.ib.ts
61
+
62
+ it("approves a review", async () => {
63
+ app.shopify.on("PublishReviews", { metafieldsSet: { userErrors: [] } }); // the Admin API, mocked
64
+ const review = await app.seed("review", { shop: TEST_SHOP, rating: 5, body: "Fits well, washes well." });
65
+ const run = await app.run("review.approve", { id: review.id, shop: TEST_SHOP });
66
+ expect(run.record).toMatchObject({ status: "approved" });
67
+ });
68
+ ```
69
+
70
+ Inside an app, `createClient()` reads `IB_API_URL`, `IB_ENVIRONMENT_TOKEN`, `IB_APP` and `IB_ENVIRONMENT`, which
71
+ Inference Bureau sets. From a script or another service, pass `{ token: process.env.IB_API_KEY, app, environment }`
72
+ with a key linked to the app.
73
+
74
+ Entry points:
75
+
76
+ - `@inferencebureau/apps-sdk`: metadata types, action helpers, `createClient`, `createShopifyClient`,
77
+ `verifyShopifySession`, `verifyProxyRequest`, and the errors they throw (`ApiError`, `ShopifyError`).
78
+ - `@inferencebureau/apps-sdk/runtime`: `handleAction`, the signed `/_ib/actions` route every build adds.
79
+ - `@inferencebureau/apps-sdk/browser`: for an embedded admin page's client code: `sessionFetch`,
80
+ `shopifySessionToken`, `isPreview`, `previewSession`.
81
+ - `@inferencebureau/apps-sdk/test`: for the app's tests: `loadApp` (or `createTestApp`) runs actions against
82
+ in-memory records with the records engine's rules, mocks the Shopify Admin API, delivers webhooks and installs,
83
+ and runs queued jobs; `fixtures` has Shopify's webhook payloads. Node only.
84
+
85
+ Docs: https://app.inferencebureau.com/docs/apps
@@ -0,0 +1,17 @@
1
+ /**
2
+ * For an embedded Shopify admin page's own scripts (client components): the session token its requests carry, which
3
+ * the app's routes check with `verifyShopifySession`.
4
+ *
5
+ * In the Shopify admin it's App Bridge's (`shopify.idToken()`). In Inference Bureau's preview, where there's no admin
6
+ * around the page, the dashboard hands the page a preview session instead (`#ib_preview=…` on its first URL): signed
7
+ * by us for the team member previewing, one environment and one store it's installed on, for an hour. It's kept for
8
+ * the tab (sessionStorage) so the page's own navigation keeps it, and taken off the address bar.
9
+ */
10
+ /** The preview session from the page's URL (moved into sessionStorage) or from earlier in the tab, or null. */
11
+ export declare function previewSession(): string | null;
12
+ /** Whether the page is open in Inference Bureau's preview rather than the Shopify admin. */
13
+ export declare const isPreview: () => boolean;
14
+ /** The session token for the page's requests: the preview's, else App Bridge's, else null (not in the admin). */
15
+ export declare function shopifySessionToken(): Promise<string | null>;
16
+ /** `fetch` with the session token as `Authorization: Bearer …`, for the app's own routes. */
17
+ export declare function sessionFetch(input: string | URL, init?: RequestInit): Promise<Response>;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * For an embedded Shopify admin page's own scripts (client components): the session token its requests carry, which
3
+ * the app's routes check with `verifyShopifySession`.
4
+ *
5
+ * In the Shopify admin it's App Bridge's (`shopify.idToken()`). In Inference Bureau's preview, where there's no admin
6
+ * around the page, the dashboard hands the page a preview session instead (`#ib_preview=…` on its first URL): signed
7
+ * by us for the team member previewing, one environment and one store it's installed on, for an hour. It's kept for
8
+ * the tab (sessionStorage) so the page's own navigation keeps it, and taken off the address bar.
9
+ */
10
+ const KEY = "ib_preview";
11
+ function storage() {
12
+ try {
13
+ return window.sessionStorage;
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ /** The preview session from the page's URL (moved into sessionStorage) or from earlier in the tab, or null. */
20
+ export function previewSession() {
21
+ if (typeof window === "undefined")
22
+ return null;
23
+ const hash = new URLSearchParams(window.location.hash.slice(1));
24
+ const fromUrl = hash.get(KEY);
25
+ if (fromUrl) {
26
+ storage()?.setItem(KEY, fromUrl);
27
+ hash.delete(KEY);
28
+ const rest = hash.toString();
29
+ history.replaceState(history.state, "", `${window.location.pathname}${window.location.search}${rest ? `#${rest}` : ""}`);
30
+ return fromUrl;
31
+ }
32
+ const kept = storage()?.getItem(KEY) ?? null;
33
+ if (!kept)
34
+ return null;
35
+ // The token's own expiry (it's a JWT); an expired one is dropped so App Bridge's is used, or none.
36
+ try {
37
+ const { exp } = JSON.parse(atob(kept.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")));
38
+ if (typeof exp === "number" && exp * 1000 < Date.now()) {
39
+ storage()?.removeItem(KEY);
40
+ return null;
41
+ }
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ return kept;
47
+ }
48
+ /** Whether the page is open in Inference Bureau's preview rather than the Shopify admin. */
49
+ export const isPreview = () => previewSession() !== null;
50
+ /** The session token for the page's requests: the preview's, else App Bridge's, else null (not in the admin). */
51
+ export async function shopifySessionToken() {
52
+ const preview = previewSession();
53
+ if (preview)
54
+ return preview;
55
+ const bridge = globalThis.shopify;
56
+ if (!bridge?.idToken)
57
+ return null;
58
+ // Outside the admin App Bridge may never answer; a page shouldn't hang waiting for it.
59
+ return Promise.race([bridge.idToken().catch(() => null), new Promise((r) => setTimeout(() => r(null), 5000))]);
60
+ }
61
+ /**
62
+ * The request without App Bridge's `fetch`. App Bridge wraps `fetch` to add its own token, and waits for the admin to
63
+ * hand one over; in the preview there's no admin, so a page App Bridge set itself up in (it remembers a store for the
64
+ * tab) would wait forever. XMLHttpRequest isn't wrapped.
65
+ */
66
+ function plainRequest(input, init, headers) {
67
+ return new Promise((resolve, reject) => {
68
+ const xhr = new XMLHttpRequest();
69
+ xhr.open(init.method ?? "GET", String(input));
70
+ xhr.responseType = "blob";
71
+ headers.forEach((v, k) => xhr.setRequestHeader(k, v));
72
+ xhr.onload = () => {
73
+ const out = new Headers();
74
+ for (const line of xhr.getAllResponseHeaders().trim().split(/[\r\n]+/)) {
75
+ const at = line.indexOf(":");
76
+ if (at > 0)
77
+ out.append(line.slice(0, at).trim(), line.slice(at + 1).trim());
78
+ }
79
+ resolve(new Response(xhr.status === 204 || xhr.status === 304 ? null : xhr.response, { status: xhr.status, statusText: xhr.statusText, headers: out }));
80
+ };
81
+ xhr.onerror = () => reject(new TypeError("Failed to fetch"));
82
+ xhr.onabort = () => reject(new DOMException("Aborted", "AbortError"));
83
+ init.signal?.addEventListener("abort", () => xhr.abort());
84
+ xhr.send((init.body ?? null));
85
+ });
86
+ }
87
+ /** `fetch` with the session token as `Authorization: Bearer …`, for the app's own routes. */
88
+ export async function sessionFetch(input, init = {}) {
89
+ const preview = previewSession();
90
+ const token = preview ?? (await shopifySessionToken());
91
+ const headers = new Headers(init.headers);
92
+ if (token)
93
+ headers.set("authorization", `Bearer ${token}`);
94
+ return preview ? plainRequest(input, init, headers) : fetch(input, { ...init, headers });
95
+ }
@@ -0,0 +1,349 @@
1
+ /**
2
+ * @inferencebureau/apps-sdk: what an Inference Bureau app's code imports (docs/apps-plan.md §4). Types for the
3
+ * metadata files (`schema.ib.ts`, `permissions.ib.ts`, `settings.ib.ts`), the helpers an action's `run` uses
4
+ * (`applyParams`, `save`, `deleteRecord`), and `createClient`, the API for reading and writing the app's records.
5
+ *
6
+ * Actions run inside the app's own deployment (runtime.ts). Their writes to the action's record are collected, not
7
+ * sent: when `run` returns, Inference Bureau applies them in one transaction, then calls `onSuccess`. The code uses
8
+ * only fetch and Web Crypto, so it runs on any JavaScript runtime the app is hosted on.
9
+ */
10
+ export type FieldType = "string" | "richText" | "email" | "url" | "color" | "number" | "dateTime" | "enum" | "boolean" | "roleList" | "json" | "vector" | "file" | "belongsTo" | "hasOne" | "hasMany" | "hasManyThrough" | "password" | "encryptedString" | "computed";
11
+ export interface FieldValidations {
12
+ required?: boolean;
13
+ unique?: boolean | {
14
+ caseSensitive?: boolean;
15
+ };
16
+ range?: {
17
+ min?: number;
18
+ max?: number;
19
+ };
20
+ stringLength?: {
21
+ min?: number;
22
+ max?: number;
23
+ };
24
+ regex?: {
25
+ pattern: string;
26
+ };
27
+ }
28
+ export interface FieldDef {
29
+ type: FieldType;
30
+ /** Where the field's values are kept. The schema editor sets it; keep it when renaming the field so its values follow. */
31
+ storageKey?: string;
32
+ default?: unknown;
33
+ validations?: FieldValidations;
34
+ options?: string[];
35
+ allowMultiple?: boolean;
36
+ /** Vector fields: the fields embedded into it, and the embedding model (openai/text-embedding-3-small by default). */
37
+ source?: string[];
38
+ embeddingModel?: string;
39
+ dimensions?: number;
40
+ parent?: {
41
+ model: string;
42
+ };
43
+ child?: {
44
+ model: string;
45
+ belongsToField?: string;
46
+ };
47
+ children?: {
48
+ model: string;
49
+ belongsToField?: string;
50
+ };
51
+ through?: {
52
+ model: string;
53
+ };
54
+ [key: string]: unknown;
55
+ }
56
+ export interface ModelSchema {
57
+ type: "ib/model-schema/v1";
58
+ storageKey?: string;
59
+ fields: Record<string, FieldDef>;
60
+ }
61
+ /**
62
+ * `settings.ib.ts`. Keep it a plain object literal: Inference Bureau reads `webhooks` and `schedules` from the file.
63
+ * Both run global actions (`api/actions/<name>.ts`) as background jobs, retried when they fail.
64
+ */
65
+ export interface AppSettings {
66
+ type: "ib/settings/v1";
67
+ platform: "shopify" | "web";
68
+ /** Shopify webhook topics that queue an action, with Shopify's payload as `params` and the store as `shop`. */
69
+ webhooks?: WebhookSetting[];
70
+ /** Actions queued on a cron schedule, `params.scheduledAt` the time it was due. */
71
+ schedules?: ScheduleSetting[];
72
+ [key: string]: unknown;
73
+ }
74
+ export interface WebhookSetting {
75
+ /** A Shopify webhook topic, e.g. orders/create. The app's scopes must allow it. */
76
+ topic: string;
77
+ /** The global action to queue. */
78
+ action: string;
79
+ /** Only deliveries matching this, in Shopify's search syntax (e.g. "total_price:>100"). */
80
+ filter?: string;
81
+ /** Only these fields of the payload. */
82
+ includeFields?: string[];
83
+ }
84
+ export interface ScheduleSetting {
85
+ /** The global action to queue. */
86
+ action: string;
87
+ /** Five fields: minute hour day-of-month month day-of-week, e.g. "0 3 * * *" for 03:00 every day. */
88
+ cron: string;
89
+ /** An IANA timezone, UTC unless named. */
90
+ timezone?: string;
91
+ /** Where it runs: production only unless development is named too. */
92
+ environments?: ("development" | "production")[];
93
+ }
94
+ export interface AppPermissions {
95
+ type: "ib/permissions/v1";
96
+ roles: Record<string, unknown>;
97
+ }
98
+ export interface AppRecord {
99
+ id: string;
100
+ createdAt: string;
101
+ updatedAt: string;
102
+ [field: string]: unknown;
103
+ }
104
+ /** Which records a list returns: `{ field: { equals: x } }`, with AND, OR and NOT lists. */
105
+ export type Filter = {
106
+ AND?: Filter[];
107
+ OR?: Filter[];
108
+ NOT?: Filter[];
109
+ } & {
110
+ [field: string]: unknown;
111
+ };
112
+ export type Sort = Record<string, "Ascending" | "Descending">;
113
+ export interface FindManyOptions {
114
+ filter?: Filter;
115
+ sort?: Sort | Sort[];
116
+ first?: number;
117
+ after?: string | null;
118
+ }
119
+ export interface RecordPage<T = AppRecord> {
120
+ records: T[];
121
+ hasNextPage: boolean;
122
+ endCursor: string | null;
123
+ }
124
+ /** A record being worked on in an action: its fields, plus what the action has asked to happen to it. */
125
+ export type ActionRecord = AppRecord;
126
+ /** Marks a plain object as the action's record (the runtime does this before `run`). */
127
+ export declare function trackRecord<T extends object>(record: T, model?: string | null): T;
128
+ /** Copies the action's params onto the record: `params.<model>` when the caller nested them, else params themselves. */
129
+ export declare function applyParams(params: Record<string, unknown>, record: ActionRecord): void;
130
+ /** Saves the record when `run` returns, with everything else the action does to it, in one transaction. */
131
+ export declare function save(record: ActionRecord): Promise<void>;
132
+ /** Deletes the record when `run` returns. */
133
+ export declare function deleteRecord(record: ActionRecord): Promise<void>;
134
+ /** What `run` asked for: the changed fields to save (all set fields for a new record), a delete, or nothing. */
135
+ export declare function pendingWrite(record: ActionRecord, isNew: boolean): {
136
+ op: "save";
137
+ values: Record<string, unknown>;
138
+ } | {
139
+ op: "delete";
140
+ } | null;
141
+ export declare class ApiError extends Error {
142
+ readonly status: number;
143
+ readonly code: string | null;
144
+ readonly problems: {
145
+ field: string;
146
+ message: string;
147
+ }[];
148
+ constructor(message: string, status: number, code: string | null, problems?: {
149
+ field: string;
150
+ message: string;
151
+ }[]);
152
+ }
153
+ export interface ModelClient {
154
+ findOne(id: string): Promise<AppRecord | null>;
155
+ findMany(o?: FindManyOptions): Promise<RecordPage>;
156
+ findFirst(o?: Omit<FindManyOptions, "first" | "after">): Promise<AppRecord | null>;
157
+ /** Nearest records to text (embedded with the field's model) or a vector, nearest first, with `_distance`. */
158
+ search(field: string, near: string | number[], o?: Omit<FindManyOptions, "sort">): Promise<RecordPage<AppRecord & {
159
+ _distance: number;
160
+ }>>;
161
+ create(values: Record<string, unknown>): Promise<AppRecord>;
162
+ update(id: string, values: Record<string, unknown>): Promise<AppRecord>;
163
+ delete(id: string): Promise<void>;
164
+ /** Whether `password` is the one stored in the record's password field (`password` unless named). Hashes are never returned. */
165
+ checkPassword(id: string, password: string, field?: string): Promise<boolean>;
166
+ /** Runs one of the model's actions: on a record when `id` is given, else as a new one; `shop` gives it `shopify`. */
167
+ run(action: string, o?: {
168
+ id?: string;
169
+ params?: Record<string, unknown>;
170
+ shop?: string;
171
+ }): Promise<{
172
+ record: AppRecord | null;
173
+ result?: unknown;
174
+ }>;
175
+ }
176
+ export type Api = {
177
+ [model: string]: ModelClient;
178
+ } & {
179
+ /** Runs a global action (`api/actions/<name>.ts`). */
180
+ $global(action: string, params?: Record<string, unknown>): Promise<{
181
+ result?: unknown;
182
+ }>;
183
+ /**
184
+ * Queues an action as a background job and returns at once: a global action's name, or `<model>.<action>` (with
185
+ * `id` for the record). It gets up to five minutes, and is retried when it fails.
186
+ */
187
+ enqueue(action: string, params?: Record<string, unknown>, options?: EnqueueOptions): Promise<Job>;
188
+ };
189
+ export interface EnqueueOptions {
190
+ /** The record a model's action works on. */
191
+ id?: string;
192
+ /** Gives the action its `shopify` client for this store. */
193
+ shop?: string;
194
+ /** Milliseconds to wait before running it (at most 30 days); or `runAt`. */
195
+ delay?: number;
196
+ runAt?: string | Date;
197
+ /** Tries after the first, when it fails (6 by default, up to 20), backing off from 15 seconds to an hour. */
198
+ retries?: number;
199
+ /** high runs before default before low. */
200
+ priority?: "low" | "default" | "high";
201
+ /** Jobs with the same key run at most `concurrency` (1 by default) at a time. */
202
+ concurrencyKey?: string;
203
+ concurrency?: number;
204
+ }
205
+ export interface Job {
206
+ id: string;
207
+ action: string;
208
+ state: "queued" | "running" | "succeeded" | "failed" | "canceled";
209
+ run_at: string;
210
+ attempts: number;
211
+ max_attempts: number;
212
+ last_error: string | null;
213
+ [key: string]: unknown;
214
+ }
215
+ export interface ClientOptions {
216
+ /** Inference Bureau's API; IB_API_URL in an app's deployment. */
217
+ url?: string;
218
+ /** The environment's token (IB_ENVIRONMENT_TOKEN), or an API key linked to the app. */
219
+ token?: string;
220
+ /** The app (IB_APP) and environment (IB_ENVIRONMENT). */
221
+ app?: string;
222
+ environment?: string;
223
+ fetch?: typeof fetch;
224
+ }
225
+ /** The app's API. In an app's deployment every option comes from its environment variables. */
226
+ export declare function createClient(o?: ClientOptions): Api;
227
+ /**
228
+ * The Shopify Admin API for one store the app is installed on, through Inference Bureau: the store's token stays
229
+ * with us, and each call is checked against the environment's install.
230
+ */
231
+ export interface ShopifyClient {
232
+ shop: string;
233
+ /** Runs an Admin GraphQL query or mutation and returns its `data`; GraphQL errors throw ShopifyError. */
234
+ graphql<T = any>(query: string, variables?: Record<string, unknown>): Promise<T>;
235
+ }
236
+ export declare class ShopifyError extends Error {
237
+ readonly errors: unknown[];
238
+ constructor(message: string, errors: unknown[]);
239
+ }
240
+ /** The Admin API for `shop`, as the environment (the same options as createClient). */
241
+ export declare function createShopifyClient(shop: string, o?: ClientOptions): ShopifyClient;
242
+ export interface ShopifySession {
243
+ /** The store the admin page is open in (x.myshopify.com). */
244
+ shop: string;
245
+ /** The staff member's Shopify user id, when Shopify includes it. */
246
+ userId: string | null;
247
+ sessionId: string | null;
248
+ /** Set when the page is open in Inference Bureau's preview, not the Shopify admin: who's previewing. */
249
+ preview?: {
250
+ actor: string;
251
+ };
252
+ }
253
+ /**
254
+ * The store and staff member behind a request from one of the app's pages in the Shopify admin, or null when it
255
+ * carries no valid session token. App Bridge's `shopify.idToken()` gives the page its token; send it as
256
+ * `Authorization: Bearer <token>` (or pass the token itself). Shopify signs it with the app's client secret, which
257
+ * Inference Bureau holds, so the check happens there; never trust a shop named any other way.
258
+ */
259
+ export declare function verifyShopifySession(request: Request | string, o?: ClientOptions): Promise<ShopifySession | null>;
260
+ export interface ProxyRequest {
261
+ /** The store whose storefront made the request (x.myshopify.com). */
262
+ shop: string;
263
+ /** The signed-in customer's id, or null for a guest. */
264
+ customerId: string | null;
265
+ /** Where the storefront reached the app, e.g. /apps/wholesale. */
266
+ pathPrefix: string;
267
+ }
268
+ /**
269
+ * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or null for
270
+ * anything else. Shopify's own signature was checked before it was passed on; this checks ours, so only a real
271
+ * storefront request is trusted with a shop and customer.
272
+ */
273
+ export declare function verifyProxyRequest(request: Request, o?: {
274
+ token?: string;
275
+ now?: () => number;
276
+ }): Promise<ProxyRequest | null>;
277
+ export interface LogLine {
278
+ level: "debug" | "info" | "warn" | "error";
279
+ message: string;
280
+ data?: unknown;
281
+ at: string;
282
+ }
283
+ export interface Logger {
284
+ debug(message: string, data?: unknown): void;
285
+ info(message: string, data?: unknown): void;
286
+ warn(message: string, data?: unknown): void;
287
+ error(message: string, data?: unknown): void;
288
+ }
289
+ export interface ActionContext {
290
+ /** What the caller passed. A model action's fields may be at the top level or under the model's name. */
291
+ params: Record<string, unknown>;
292
+ /** The record the action works on: the stored one, or a new, empty one for a create. Null in a global action. */
293
+ record: ActionRecord;
294
+ /** The app's API, as the environment. Writes through it happen at once, outside this action's transaction. */
295
+ api: Api;
296
+ /** Lines written here appear on the action's run in Logs. */
297
+ logger: Logger;
298
+ model: string | null;
299
+ action: string;
300
+ environment: "development" | "production";
301
+ /** The store this run is about (an install, a webhook, or the caller's `shop`), and the Admin API for it. */
302
+ shop: string | null;
303
+ shopify: ShopifyClient | null;
304
+ }
305
+ export type ActionRun = (ctx: ActionContext) => unknown | Promise<unknown>;
306
+ export type ActionOnSuccess = (ctx: ActionContext) => void | Promise<void>;
307
+ export type GlobalActionRun = (ctx: Omit<ActionContext, "record"> & {
308
+ record: null;
309
+ }) => unknown | Promise<unknown>;
310
+ export interface ActionOptions {
311
+ /** create: works on a new record; update and custom: on the record named by id; delete: removes it. */
312
+ actionType?: "create" | "update" | "delete" | "custom";
313
+ /** Whether what `run` returns goes back to the caller (it's dropped otherwise). */
314
+ returnType?: boolean;
315
+ /** How long `run` may take: at most 60 seconds (30 by default), or 5 minutes (the default) as a background job. */
316
+ timeoutMS?: number;
317
+ }
318
+ export interface ActionModule {
319
+ run?: ActionRun;
320
+ onSuccess?: ActionOnSuccess;
321
+ options?: ActionOptions;
322
+ }
323
+ export interface ShopifyPrivacyCustomer {
324
+ id: number;
325
+ email?: string | null;
326
+ phone?: string | null;
327
+ }
328
+ /** `api/actions/shopifyCustomersRedact.ts`: erase what the app holds on this customer (and these orders). */
329
+ export interface ShopifyCustomersRedactParams {
330
+ shop_id: number;
331
+ shop_domain: string;
332
+ customer: ShopifyPrivacyCustomer;
333
+ orders_to_redact: number[];
334
+ }
335
+ /** `api/actions/shopifyCustomersDataRequest.ts`: send the store what the app holds on this customer, within 30 days. */
336
+ export interface ShopifyCustomersDataRequestParams {
337
+ shop_id: number;
338
+ shop_domain: string;
339
+ customer: ShopifyPrivacyCustomer;
340
+ orders_requested: number[];
341
+ data_request: {
342
+ id: number;
343
+ };
344
+ }
345
+ /** `api/actions/shopifyShopRedact.ts`: 48 hours after an uninstall, erase the store's data the app keeps elsewhere. */
346
+ export interface ShopifyShopRedactParams {
347
+ shop_id: number;
348
+ shop_domain: string;
349
+ }