@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 +84 -2
- package/dist/browser.d.ts +17 -0
- package/dist/browser.js +95 -0
- package/dist/index.d.ts +349 -0
- package/dist/index.js +211 -0
- package/dist/runtime.d.ts +57 -0
- package/dist/runtime.js +85 -0
- package/dist/test.d.ts +250 -0
- package/dist/test.js +1017 -0
- package/package.json +64 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
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
|
+
/** Shared by every copy of this module that loads, so `save` works whichever copy an action imported. */
|
|
11
|
+
const STATE = Symbol.for("inferencebureau.apps.record");
|
|
12
|
+
/** Marks a plain object as the action's record (the runtime does this before `run`). */
|
|
13
|
+
export function trackRecord(record, model = null) {
|
|
14
|
+
Object.defineProperty(record, STATE, { value: { original: JSON.stringify(record), model, save: false, delete: false }, enumerable: false });
|
|
15
|
+
return record;
|
|
16
|
+
}
|
|
17
|
+
function stateOf(record) {
|
|
18
|
+
const s = record[STATE];
|
|
19
|
+
if (!s)
|
|
20
|
+
throw new Error("save() and deleteRecord() take the record an action was given.");
|
|
21
|
+
return s;
|
|
22
|
+
}
|
|
23
|
+
/** Copies the action's params onto the record: `params.<model>` when the caller nested them, else params themselves. */
|
|
24
|
+
export function applyParams(params, record) {
|
|
25
|
+
const model = record[STATE]?.model;
|
|
26
|
+
const nested = model && params[model] && typeof params[model] === "object" && !Array.isArray(params[model]) ? params[model] : params;
|
|
27
|
+
for (const [k, v] of Object.entries(nested))
|
|
28
|
+
if (k !== "id" && k !== "createdAt" && k !== "updatedAt")
|
|
29
|
+
record[k] = v;
|
|
30
|
+
}
|
|
31
|
+
/** Saves the record when `run` returns, with everything else the action does to it, in one transaction. */
|
|
32
|
+
export async function save(record) {
|
|
33
|
+
const s = stateOf(record);
|
|
34
|
+
s.save = true;
|
|
35
|
+
s.delete = false;
|
|
36
|
+
}
|
|
37
|
+
/** Deletes the record when `run` returns. */
|
|
38
|
+
export async function deleteRecord(record) {
|
|
39
|
+
const s = stateOf(record);
|
|
40
|
+
s.delete = true;
|
|
41
|
+
s.save = false;
|
|
42
|
+
}
|
|
43
|
+
/** What `run` asked for: the changed fields to save (all set fields for a new record), a delete, or nothing. */
|
|
44
|
+
export function pendingWrite(record, isNew) {
|
|
45
|
+
const s = stateOf(record);
|
|
46
|
+
if (s.delete)
|
|
47
|
+
return { op: "delete" };
|
|
48
|
+
if (!s.save)
|
|
49
|
+
return null;
|
|
50
|
+
const before = JSON.parse(s.original);
|
|
51
|
+
const values = {};
|
|
52
|
+
for (const [k, v] of Object.entries(record)) {
|
|
53
|
+
if (k === "id" || k === "createdAt" || k === "updatedAt" || v === undefined)
|
|
54
|
+
continue;
|
|
55
|
+
if (isNew ? v !== null : JSON.stringify(v) !== JSON.stringify(before[k]))
|
|
56
|
+
values[k] = v;
|
|
57
|
+
}
|
|
58
|
+
return { op: "save", values };
|
|
59
|
+
}
|
|
60
|
+
// ---- the API ----
|
|
61
|
+
export class ApiError extends Error {
|
|
62
|
+
status;
|
|
63
|
+
code;
|
|
64
|
+
problems;
|
|
65
|
+
constructor(message, status, code, problems = []) {
|
|
66
|
+
super(message);
|
|
67
|
+
this.status = status;
|
|
68
|
+
this.code = code;
|
|
69
|
+
this.problems = problems;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const envVar = (name) => globalThis.process?.env?.[name];
|
|
73
|
+
/** The app's API. In an app's deployment every option comes from its environment variables. */
|
|
74
|
+
export function createClient(o = {}) {
|
|
75
|
+
const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
|
|
76
|
+
const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
|
|
77
|
+
const app = o.app ?? envVar("IB_APP") ?? "";
|
|
78
|
+
const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
|
|
79
|
+
const f = o.fetch ?? fetch;
|
|
80
|
+
const base = `${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}`;
|
|
81
|
+
async function call(method, path, body) {
|
|
82
|
+
const res = await f(`${base}${path}`, {
|
|
83
|
+
method, headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "content-type": "application/json" }) },
|
|
84
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
85
|
+
});
|
|
86
|
+
if (res.status === 204)
|
|
87
|
+
return undefined;
|
|
88
|
+
const text = await res.text();
|
|
89
|
+
let json = {};
|
|
90
|
+
try {
|
|
91
|
+
json = text ? JSON.parse(text) : {};
|
|
92
|
+
}
|
|
93
|
+
catch { /* reported below */ }
|
|
94
|
+
if (!res.ok)
|
|
95
|
+
throw new ApiError(json.error?.message ?? `The API answered ${res.status}.`, res.status, json.error?.code ?? null, json.error?.problems ?? []);
|
|
96
|
+
return json;
|
|
97
|
+
}
|
|
98
|
+
const model = (name) => {
|
|
99
|
+
const m = `/models/${encodeURIComponent(name)}`;
|
|
100
|
+
const query = (o) => call("POST", `${m}/records/query`, o);
|
|
101
|
+
return {
|
|
102
|
+
async findOne(id) {
|
|
103
|
+
try {
|
|
104
|
+
return await call("GET", `${m}/records/${encodeURIComponent(id)}`);
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
if (e instanceof ApiError && e.status === 404)
|
|
108
|
+
return null;
|
|
109
|
+
throw e;
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
findMany: (o = {}) => query({ ...o }),
|
|
113
|
+
findFirst: async (o = {}) => (await query({ ...o, first: 1 })).records[0] ?? null,
|
|
114
|
+
search: (field, near, o = {}) => query({ ...o, search: { field, near } }),
|
|
115
|
+
create: (values) => call("POST", `${m}/records`, values),
|
|
116
|
+
update: (id, values) => call("PATCH", `${m}/records/${encodeURIComponent(id)}`, values),
|
|
117
|
+
delete: (id) => call("DELETE", `${m}/records/${encodeURIComponent(id)}`),
|
|
118
|
+
checkPassword: async (id, password, field) => (await call("POST", `${m}/records/${encodeURIComponent(id)}/check-password`, { password, ...(field ? { field } : {}) })).valid,
|
|
119
|
+
run: (action, o = {}) => call("POST", `${m}/actions/${encodeURIComponent(action)}`, { ...(o.id ? { id: o.id } : {}), params: o.params ?? {}, ...(o.shop ? { shop: o.shop } : {}) }),
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
const cache = new Map();
|
|
123
|
+
const $global = (action, params = {}) => call("POST", `/actions/${encodeURIComponent(action)}`, { params });
|
|
124
|
+
const enqueue = (action, params = {}, o = {}) => call("POST", "/jobs", { action, params, ...o, ...(o.runAt instanceof Date ? { runAt: o.runAt.toISOString() } : {}) });
|
|
125
|
+
return new Proxy({}, {
|
|
126
|
+
get(_t, prop) {
|
|
127
|
+
if (prop === "$global")
|
|
128
|
+
return $global;
|
|
129
|
+
if (prop === "enqueue")
|
|
130
|
+
return enqueue;
|
|
131
|
+
if (typeof prop !== "string" || prop === "then")
|
|
132
|
+
return undefined;
|
|
133
|
+
if (!cache.has(prop))
|
|
134
|
+
cache.set(prop, model(prop));
|
|
135
|
+
return cache.get(prop);
|
|
136
|
+
},
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
export class ShopifyError extends Error {
|
|
140
|
+
errors;
|
|
141
|
+
constructor(message, errors) {
|
|
142
|
+
super(message);
|
|
143
|
+
this.errors = errors;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** The Admin API for `shop`, as the environment (the same options as createClient). */
|
|
147
|
+
export function createShopifyClient(shop, o = {}) {
|
|
148
|
+
const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
|
|
149
|
+
const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
|
|
150
|
+
const app = o.app ?? envVar("IB_APP") ?? "";
|
|
151
|
+
const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
|
|
152
|
+
const f = o.fetch ?? fetch;
|
|
153
|
+
return {
|
|
154
|
+
shop,
|
|
155
|
+
async graphql(query, variables = {}) {
|
|
156
|
+
const res = await f(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/graphql`, {
|
|
157
|
+
method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ shop, query, variables }),
|
|
158
|
+
});
|
|
159
|
+
const json = (await res.json().catch(() => ({})));
|
|
160
|
+
if (!res.ok)
|
|
161
|
+
throw new ShopifyError(json.error?.message ?? `Shopify answered ${res.status}.`, json.errors ?? []);
|
|
162
|
+
if (json.errors?.length)
|
|
163
|
+
throw new ShopifyError(json.errors.map((e) => e.message ?? String(e)).join("; "), json.errors);
|
|
164
|
+
return json.data;
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* The store and staff member behind a request from one of the app's pages in the Shopify admin, or null when it
|
|
170
|
+
* carries no valid session token. App Bridge's `shopify.idToken()` gives the page its token; send it as
|
|
171
|
+
* `Authorization: Bearer <token>` (or pass the token itself). Shopify signs it with the app's client secret, which
|
|
172
|
+
* Inference Bureau holds, so the check happens there; never trust a shop named any other way.
|
|
173
|
+
*/
|
|
174
|
+
export async function verifyShopifySession(request, o = {}) {
|
|
175
|
+
const token = typeof request === "string" ? request : (request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
|
|
176
|
+
if (!token || token.split(".").length !== 3)
|
|
177
|
+
return null;
|
|
178
|
+
const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
|
|
179
|
+
const app = o.app ?? envVar("IB_APP") ?? "";
|
|
180
|
+
const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
|
|
181
|
+
const res = await (o.fetch ?? fetch)(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/session`, {
|
|
182
|
+
method: "POST", headers: { authorization: `Bearer ${o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? ""}`, "content-type": "application/json" }, body: JSON.stringify({ token }),
|
|
183
|
+
});
|
|
184
|
+
const json = (await res.json().catch(() => ({})));
|
|
185
|
+
// A refused session token is an answer (null); anything else, like the app's own token being refused, is an error.
|
|
186
|
+
if (res.status === 401 && json.error?.code === "invalid_session")
|
|
187
|
+
return null;
|
|
188
|
+
if (!res.ok)
|
|
189
|
+
throw new ApiError(json.error?.message ?? `Checking the session failed (${res.status}).`, res.status, json.error?.code ?? null);
|
|
190
|
+
return { shop: json.shop, userId: json.userId, sessionId: json.sessionId, ...(json.preview ? { preview: json.preview } : {}) };
|
|
191
|
+
}
|
|
192
|
+
const hex = (b) => Array.from(new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
|
|
193
|
+
/**
|
|
194
|
+
* A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or null for
|
|
195
|
+
* anything else. Shopify's own signature was checked before it was passed on; this checks ours, so only a real
|
|
196
|
+
* storefront request is trusted with a shop and customer.
|
|
197
|
+
*/
|
|
198
|
+
export async function verifyProxyRequest(request, o = {}) {
|
|
199
|
+
const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
|
|
200
|
+
const h = request.headers;
|
|
201
|
+
const shop = h.get("x-ib-shop") ?? "", customer = h.get("x-ib-customer-id") ?? "", prefix = h.get("x-ib-path-prefix") ?? "", ts = h.get("x-ib-timestamp") ?? "";
|
|
202
|
+
if (!token || !shop || Math.abs((o.now ?? Date.now)() - Number(ts)) > 5 * 60_000)
|
|
203
|
+
return null;
|
|
204
|
+
const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(token), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
205
|
+
const want = hex(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${ts}.${shop}.${customer}.${prefix}`)));
|
|
206
|
+
const got = h.get("x-ib-proxy-signature") ?? "";
|
|
207
|
+
let d = got.length ^ want.length;
|
|
208
|
+
for (let i = 0; i < Math.min(got.length, want.length); i++)
|
|
209
|
+
d |= got.charCodeAt(i) ^ want.charCodeAt(i);
|
|
210
|
+
return d === 0 ? { shop, customerId: customer || null, pathPrefix: prefix } : null;
|
|
211
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs an app's actions inside its own deployment. Inference Bureau calls the app's `/_ib/actions` route (added to
|
|
3
|
+
* every build) with the action, its params and its record, signed with the environment's token; this verifies the
|
|
4
|
+
* signature, runs the action file, and answers with what `run` asked to happen to the record. Inference Bureau
|
|
5
|
+
* applies that in one transaction, then calls again for `onSuccess` with the saved record.
|
|
6
|
+
*/
|
|
7
|
+
import { type ActionModule, type Api, type AppRecord, type LogLine, type ShopifyClient } from "./index.js";
|
|
8
|
+
/** Action modules by key: `<model>/<action>` for model actions, `$global/<action>` for global ones. */
|
|
9
|
+
export type ActionRegistry = Record<string, () => Promise<ActionModule>>;
|
|
10
|
+
export interface ActionRequest {
|
|
11
|
+
phase: "run" | "onSuccess";
|
|
12
|
+
model: string | null;
|
|
13
|
+
action: string;
|
|
14
|
+
params: Record<string, unknown>;
|
|
15
|
+
/** The stored record (update, delete, custom), a new one's starting values (create), or null (global). */
|
|
16
|
+
record: AppRecord | Record<string, unknown> | null;
|
|
17
|
+
isNew: boolean;
|
|
18
|
+
environment: "development" | "production";
|
|
19
|
+
/** The store the run is about, when there is one. */
|
|
20
|
+
shop?: string | null;
|
|
21
|
+
}
|
|
22
|
+
export type ActionResponse = {
|
|
23
|
+
ok: true;
|
|
24
|
+
write: {
|
|
25
|
+
op: "save";
|
|
26
|
+
values: Record<string, unknown>;
|
|
27
|
+
} | {
|
|
28
|
+
op: "delete";
|
|
29
|
+
} | null;
|
|
30
|
+
result?: unknown;
|
|
31
|
+
logs: LogLine[];
|
|
32
|
+
} | {
|
|
33
|
+
ok: false;
|
|
34
|
+
error: {
|
|
35
|
+
message: string;
|
|
36
|
+
stack?: string;
|
|
37
|
+
};
|
|
38
|
+
logs: LogLine[];
|
|
39
|
+
};
|
|
40
|
+
/** The signature Inference Bureau sends: HMAC-SHA256 of `<timestamp>.<body>` with the environment's token, hex. */
|
|
41
|
+
export declare function sign(token: string, timestamp: string, body: string): Promise<string>;
|
|
42
|
+
/**
|
|
43
|
+
* Runs one phase of an action, without checking where the request came from (handleAction does). `api` and
|
|
44
|
+
* `shopify` stand in for the environment's clients (the test app's in-memory ones); `echo: false` keeps the logger's
|
|
45
|
+
* lines off the console.
|
|
46
|
+
*/
|
|
47
|
+
export declare function runAction(req: ActionRequest, registry: ActionRegistry, o?: {
|
|
48
|
+
token?: string;
|
|
49
|
+
api?: Api;
|
|
50
|
+
shopify?: (shop: string) => ShopifyClient;
|
|
51
|
+
echo?: boolean;
|
|
52
|
+
}): Promise<ActionResponse>;
|
|
53
|
+
/** The `/_ib/actions` route: a signed request from Inference Bureau, or 404 for anyone else. */
|
|
54
|
+
export declare function handleAction(request: Request, registry: ActionRegistry, o?: {
|
|
55
|
+
token?: string;
|
|
56
|
+
now?: () => number;
|
|
57
|
+
}): Promise<Response>;
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs an app's actions inside its own deployment. Inference Bureau calls the app's `/_ib/actions` route (added to
|
|
3
|
+
* every build) with the action, its params and its record, signed with the environment's token; this verifies the
|
|
4
|
+
* signature, runs the action file, and answers with what `run` asked to happen to the record. Inference Bureau
|
|
5
|
+
* applies that in one transaction, then calls again for `onSuccess` with the saved record.
|
|
6
|
+
*/
|
|
7
|
+
import { createClient, createShopifyClient, pendingWrite, trackRecord } from "./index.js";
|
|
8
|
+
const SKEW_MS = 5 * 60_000;
|
|
9
|
+
const encoder = new TextEncoder();
|
|
10
|
+
const envVar = (name) => globalThis.process?.env?.[name];
|
|
11
|
+
/** The signature Inference Bureau sends: HMAC-SHA256 of `<timestamp>.<body>` with the environment's token, hex. */
|
|
12
|
+
export async function sign(token, timestamp, body) {
|
|
13
|
+
const key = await crypto.subtle.importKey("raw", encoder.encode(token), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
14
|
+
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(`${timestamp}.${body}`)));
|
|
15
|
+
return Array.from(mac, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
16
|
+
}
|
|
17
|
+
function sameText(a, b) {
|
|
18
|
+
if (a.length !== b.length)
|
|
19
|
+
return false;
|
|
20
|
+
let d = 0;
|
|
21
|
+
for (let i = 0; i < a.length; i++)
|
|
22
|
+
d |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
23
|
+
return d === 0;
|
|
24
|
+
}
|
|
25
|
+
function collector(lines, echo) {
|
|
26
|
+
const at = (level) => (message, data) => {
|
|
27
|
+
lines.push({ level, message: String(message).slice(0, 2000), ...(data === undefined ? {} : { data }), at: new Date().toISOString() });
|
|
28
|
+
if (echo)
|
|
29
|
+
(level === "error" ? console.error : level === "warn" ? console.warn : console.log)(`[action] ${message}`, ...(data === undefined ? [] : [data]));
|
|
30
|
+
};
|
|
31
|
+
return { debug: at("debug"), info: at("info"), warn: at("warn"), error: at("error") };
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Runs one phase of an action, without checking where the request came from (handleAction does). `api` and
|
|
35
|
+
* `shopify` stand in for the environment's clients (the test app's in-memory ones); `echo: false` keeps the logger's
|
|
36
|
+
* lines off the console.
|
|
37
|
+
*/
|
|
38
|
+
export async function runAction(req, registry, o = {}) {
|
|
39
|
+
const logs = [];
|
|
40
|
+
try {
|
|
41
|
+
const key = req.model ? `${req.model}/${req.action}` : `$global/${req.action}`;
|
|
42
|
+
const load = registry[key];
|
|
43
|
+
if (!load)
|
|
44
|
+
throw new Error(`The deployment has no action ${key}. Deploy again if it was added since.`);
|
|
45
|
+
const mod = await load();
|
|
46
|
+
const record = req.record ? trackRecord({ ...req.record }, req.model) : null;
|
|
47
|
+
const ctx = {
|
|
48
|
+
params: req.params ?? {}, record, api: o.api ?? createClient(o.token ? { token: o.token } : {}), logger: collector(logs, o.echo ?? true),
|
|
49
|
+
model: req.model, action: req.action, environment: req.environment,
|
|
50
|
+
shop: req.shop ?? null, shopify: req.shop ? (o.shopify?.(req.shop) ?? createShopifyClient(req.shop, o.token ? { token: o.token } : {})) : null,
|
|
51
|
+
};
|
|
52
|
+
if (req.phase === "onSuccess") {
|
|
53
|
+
await mod.onSuccess?.(ctx);
|
|
54
|
+
return { ok: true, write: null, logs };
|
|
55
|
+
}
|
|
56
|
+
if (typeof mod.run !== "function")
|
|
57
|
+
throw new Error(`${key} doesn't export a run function.`);
|
|
58
|
+
const result = await mod.run(ctx);
|
|
59
|
+
const write = record ? pendingWrite(record, req.isNew) : null;
|
|
60
|
+
return { ok: true, write, ...(mod.options?.returnType && result !== undefined ? { result } : {}), logs };
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
64
|
+
return { ok: false, error: { message: err.message, ...(err.stack ? { stack: err.stack.split("\n").slice(0, 8).join("\n") } : {}) }, logs };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** The `/_ib/actions` route: a signed request from Inference Bureau, or 404 for anyone else. */
|
|
68
|
+
export async function handleAction(request, registry, o = {}) {
|
|
69
|
+
const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
|
|
70
|
+
const body = await request.text();
|
|
71
|
+
const ts = request.headers.get("x-ib-timestamp") ?? "";
|
|
72
|
+
const sig = request.headers.get("x-ib-signature") ?? "";
|
|
73
|
+
const fresh = Math.abs((o.now ?? Date.now)() - Number(ts)) < SKEW_MS;
|
|
74
|
+
if (!token || !fresh || !sameText(sig, await sign(token, ts, body)))
|
|
75
|
+
return new Response("Not found", { status: 404 });
|
|
76
|
+
let req;
|
|
77
|
+
try {
|
|
78
|
+
req = JSON.parse(body);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return new Response("Bad request", { status: 400 });
|
|
82
|
+
}
|
|
83
|
+
const res = await runAction(req, registry, { token });
|
|
84
|
+
return new Response(JSON.stringify(res), { status: 200, headers: { "content-type": "application/json", "cache-control": "no-store" } });
|
|
85
|
+
}
|
package/dist/test.d.ts
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @inferencebureau/apps-sdk/test: an app's actions run in the test process against an in-memory copy of its records,
|
|
3
|
+
* so they can be tested without an environment. `loadApp()` reads the app's folder (its schemas, actions and
|
|
4
|
+
* settings) and gives back a TestApp: `run` an action as Inference Bureau would, read and write records through
|
|
5
|
+
* `api` as the action's own `api` does, deliver Shopify webhooks, install a store, run queued jobs, and answer the
|
|
6
|
+
* action's Shopify Admin calls with mocks.
|
|
7
|
+
*
|
|
8
|
+
* The records follow the records engine's rules (packages/apps/src/records.ts): field types and conversions,
|
|
9
|
+
* defaults, validations, uniqueness, belongsTo, filters, sorting and pages, and the errors the API answers with, as
|
|
10
|
+
* ApiError. An action's run goes through the same runner as a deployment (runtime.ts): its params and record arrive
|
|
11
|
+
* as JSON, its writes are applied when `run` returns, then `onSuccess` runs with the saved record. Not covered:
|
|
12
|
+
* permissions (actions run as the system), `timeoutMS`, webhook `filter`s (Shopify applies them), schedules' timing
|
|
13
|
+
* and computed or relationship fields other than belongsTo.
|
|
14
|
+
*/
|
|
15
|
+
import { ApiError, type ActionModule, type Api, type AppRecord, type AppSettings, type Job, type LogLine, type ModelSchema } from "./index.js";
|
|
16
|
+
type Embed = (model: string, input: string[]) => Promise<number[][]>;
|
|
17
|
+
/** The store a test app installs on and runs as, unless a test names another. */
|
|
18
|
+
export declare const TEST_SHOP = "test-shop.myshopify.com";
|
|
19
|
+
export interface ShopifyCall {
|
|
20
|
+
shop: string;
|
|
21
|
+
query: string;
|
|
22
|
+
variables: Record<string, unknown>;
|
|
23
|
+
}
|
|
24
|
+
export type ShopifyAnswer = unknown | ((variables: Record<string, unknown>, call: ShopifyCall) => unknown);
|
|
25
|
+
/** Answers for the Admin API calls an action makes, and the calls it made. */
|
|
26
|
+
export interface ShopifyMock {
|
|
27
|
+
/**
|
|
28
|
+
* Answers queries containing `match` (text, like an operation name, or a RegExp) with `data`, or what a function
|
|
29
|
+
* returns for the call; a function that throws ShopifyError fails the call as Shopify would. The latest match wins.
|
|
30
|
+
*/
|
|
31
|
+
on(match: string | RegExp, answer: ShopifyAnswer): ShopifyMock;
|
|
32
|
+
calls: ShopifyCall[];
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Shopify's webhook payloads (REST-shaped, as deliveries arrive), filled with believable values. Pass what the test
|
|
36
|
+
* cares about; the rest is made up. Ids are unique within the test run.
|
|
37
|
+
*/
|
|
38
|
+
export declare const fixtures: {
|
|
39
|
+
shop(o?: Record<string, unknown>): {
|
|
40
|
+
id: number;
|
|
41
|
+
name: string;
|
|
42
|
+
email: string;
|
|
43
|
+
domain: string;
|
|
44
|
+
myshopify_domain: string;
|
|
45
|
+
currency: string;
|
|
46
|
+
plan_display_name: string;
|
|
47
|
+
country_code: string;
|
|
48
|
+
timezone: string;
|
|
49
|
+
};
|
|
50
|
+
variant(o?: Record<string, unknown>): {
|
|
51
|
+
id: number;
|
|
52
|
+
admin_graphql_api_id: string;
|
|
53
|
+
title: string;
|
|
54
|
+
sku: string;
|
|
55
|
+
price: string;
|
|
56
|
+
compare_at_price: null;
|
|
57
|
+
inventory_quantity: number;
|
|
58
|
+
position: number;
|
|
59
|
+
updated_at: string;
|
|
60
|
+
};
|
|
61
|
+
product(o?: Record<string, unknown>): {
|
|
62
|
+
id: number;
|
|
63
|
+
admin_graphql_api_id: string;
|
|
64
|
+
title: string;
|
|
65
|
+
handle: string;
|
|
66
|
+
status: string;
|
|
67
|
+
vendor: string;
|
|
68
|
+
product_type: string;
|
|
69
|
+
tags: string;
|
|
70
|
+
body_html: string;
|
|
71
|
+
published_at: string;
|
|
72
|
+
created_at: string;
|
|
73
|
+
updated_at: string;
|
|
74
|
+
variants: {
|
|
75
|
+
id: number;
|
|
76
|
+
admin_graphql_api_id: string;
|
|
77
|
+
title: string;
|
|
78
|
+
sku: string;
|
|
79
|
+
price: string;
|
|
80
|
+
compare_at_price: null;
|
|
81
|
+
inventory_quantity: number;
|
|
82
|
+
position: number;
|
|
83
|
+
updated_at: string;
|
|
84
|
+
}[];
|
|
85
|
+
};
|
|
86
|
+
collection(o?: Record<string, unknown>): {
|
|
87
|
+
id: number;
|
|
88
|
+
admin_graphql_api_id: string;
|
|
89
|
+
title: string;
|
|
90
|
+
handle: string;
|
|
91
|
+
body_html: string;
|
|
92
|
+
sort_order: string;
|
|
93
|
+
updated_at: string;
|
|
94
|
+
};
|
|
95
|
+
customer(o?: Record<string, unknown>): {
|
|
96
|
+
id: number;
|
|
97
|
+
admin_graphql_api_id: string;
|
|
98
|
+
email: string;
|
|
99
|
+
first_name: string;
|
|
100
|
+
last_name: string;
|
|
101
|
+
phone: null;
|
|
102
|
+
state: string;
|
|
103
|
+
created_at: string;
|
|
104
|
+
updated_at: string;
|
|
105
|
+
};
|
|
106
|
+
order(o?: Record<string, unknown>): {
|
|
107
|
+
id: number;
|
|
108
|
+
admin_graphql_api_id: string;
|
|
109
|
+
name: string;
|
|
110
|
+
order_number: number;
|
|
111
|
+
email: string;
|
|
112
|
+
currency: string;
|
|
113
|
+
total_price: string;
|
|
114
|
+
subtotal_price: string;
|
|
115
|
+
total_tax: string;
|
|
116
|
+
financial_status: string;
|
|
117
|
+
fulfillment_status: null;
|
|
118
|
+
customer: {
|
|
119
|
+
id: number;
|
|
120
|
+
admin_graphql_api_id: string;
|
|
121
|
+
email: string;
|
|
122
|
+
first_name: string;
|
|
123
|
+
last_name: string;
|
|
124
|
+
phone: null;
|
|
125
|
+
state: string;
|
|
126
|
+
created_at: string;
|
|
127
|
+
updated_at: string;
|
|
128
|
+
};
|
|
129
|
+
line_items: {
|
|
130
|
+
id: number;
|
|
131
|
+
product_id: number;
|
|
132
|
+
variant_id: number;
|
|
133
|
+
title: string;
|
|
134
|
+
quantity: number;
|
|
135
|
+
price: string;
|
|
136
|
+
sku: string;
|
|
137
|
+
}[];
|
|
138
|
+
created_at: string;
|
|
139
|
+
updated_at: string;
|
|
140
|
+
};
|
|
141
|
+
/** customers/redact, customers/data_request and shop/redact, for the shopify* privacy actions. */
|
|
142
|
+
customersRedact(o?: Record<string, unknown>): {
|
|
143
|
+
shop_id: number;
|
|
144
|
+
shop_domain: string;
|
|
145
|
+
customer: {
|
|
146
|
+
id: number;
|
|
147
|
+
email: string;
|
|
148
|
+
phone: null;
|
|
149
|
+
};
|
|
150
|
+
orders_to_redact: never[];
|
|
151
|
+
};
|
|
152
|
+
customersDataRequest(o?: Record<string, unknown>): {
|
|
153
|
+
shop_id: number;
|
|
154
|
+
shop_domain: string;
|
|
155
|
+
customer: {
|
|
156
|
+
id: number;
|
|
157
|
+
email: string;
|
|
158
|
+
phone: null;
|
|
159
|
+
};
|
|
160
|
+
orders_requested: never[];
|
|
161
|
+
data_request: {
|
|
162
|
+
id: number;
|
|
163
|
+
};
|
|
164
|
+
};
|
|
165
|
+
shopRedact(o?: Record<string, unknown>): {
|
|
166
|
+
shop_id: number;
|
|
167
|
+
shop_domain: string;
|
|
168
|
+
};
|
|
169
|
+
};
|
|
170
|
+
export type ActionModules = Record<string, ActionModule | (() => Promise<ActionModule>)>;
|
|
171
|
+
export interface TestAppOptions {
|
|
172
|
+
/** Each model's `schema` (from its schema.ib.ts), by model name. */
|
|
173
|
+
models?: Record<string, ModelSchema>;
|
|
174
|
+
/** Action modules (or loaders) by `<model>/<action>`, and `$global/<action>` for global ones. */
|
|
175
|
+
actions?: ActionModules;
|
|
176
|
+
/** settings.ib.ts's `settings`: which webhooks run which actions. */
|
|
177
|
+
settings?: AppSettings;
|
|
178
|
+
environment?: "development" | "production";
|
|
179
|
+
/** The clock records are stamped with. */
|
|
180
|
+
now?: () => number;
|
|
181
|
+
/** Embeds text for vector fields and text searches; without one, a sourced vector is dropped when its text changes. */
|
|
182
|
+
embed?: Embed;
|
|
183
|
+
/** Prints what actions log to the console as well (it's always in `logs`). */
|
|
184
|
+
echo?: boolean;
|
|
185
|
+
}
|
|
186
|
+
export interface RunOptions {
|
|
187
|
+
id?: string;
|
|
188
|
+
params?: Record<string, unknown>;
|
|
189
|
+
shop?: string;
|
|
190
|
+
}
|
|
191
|
+
export interface TestRun {
|
|
192
|
+
/** `<model>.<action>`, or the global action's name. */
|
|
193
|
+
action: string;
|
|
194
|
+
/** The record after the run: saved, or null when deleted (and in a global action). */
|
|
195
|
+
record: AppRecord | null;
|
|
196
|
+
/** What `run` returned, when the action's options have `returnType: true`. */
|
|
197
|
+
result?: unknown;
|
|
198
|
+
logs: LogLine[];
|
|
199
|
+
/** onSuccess threw: the run's changes stand, as they do in a deployment, and this says why. */
|
|
200
|
+
onSuccessError: string | null;
|
|
201
|
+
}
|
|
202
|
+
/** An action's `run` threw: nothing it asked for was applied. The API answers the same 422. */
|
|
203
|
+
export declare class ActionFailedError extends ApiError {
|
|
204
|
+
readonly logs: LogLine[];
|
|
205
|
+
constructor(message: string, logs: LogLine[], actionStack?: string);
|
|
206
|
+
}
|
|
207
|
+
export interface TestApp {
|
|
208
|
+
/**
|
|
209
|
+
* The app's records and actions, as an action's own `api` sees them: `create`, `update` and `delete` run the
|
|
210
|
+
* model's action of that name when it has one, as through the API.
|
|
211
|
+
*/
|
|
212
|
+
api: Api;
|
|
213
|
+
/** Writes a record directly, without its actions (still validated): data for a test to start from. */
|
|
214
|
+
seed(model: string, values: Record<string, unknown>): Promise<AppRecord>;
|
|
215
|
+
/** Runs an action (`<model>.<action>` or a global one's name) as a call through the API would. */
|
|
216
|
+
run(action: string, o?: RunOptions): Promise<TestRun>;
|
|
217
|
+
/** A model's records, oldest first. */
|
|
218
|
+
records(model: string): AppRecord[];
|
|
219
|
+
/** A store installs the app: the shopifyShop model's install (or reinstall) runs, as on a real install. */
|
|
220
|
+
install(shop?: string, o?: {
|
|
221
|
+
scopes?: string;
|
|
222
|
+
}): Promise<AppRecord | null>;
|
|
223
|
+
uninstall(shop?: string): Promise<AppRecord | null>;
|
|
224
|
+
/**
|
|
225
|
+
* A Shopify webhook arrives from `shop` (TEST_SHOP unless named): synced Shopify models are written (and their
|
|
226
|
+
* create, update or delete actions run), and the actions settings.ib.ts names for the topic run with the payload.
|
|
227
|
+
*/
|
|
228
|
+
webhook(topic: string, payload: Record<string, unknown>, o?: {
|
|
229
|
+
shop?: string;
|
|
230
|
+
}): Promise<TestRun[]>;
|
|
231
|
+
/** Jobs `api.enqueue` queued, in order. */
|
|
232
|
+
jobs: Job[];
|
|
233
|
+
/** Runs every queued job once (and the ones they queue), whatever its delay. A failed job stays queued while it has tries left. */
|
|
234
|
+
runJobs(): Promise<Job[]>;
|
|
235
|
+
shopify: ShopifyMock;
|
|
236
|
+
/** Everything every action logged, in order. */
|
|
237
|
+
logs: (LogLine & {
|
|
238
|
+
action: string;
|
|
239
|
+
})[];
|
|
240
|
+
/** Empties the records, jobs, logs and Shopify calls (mocks stay), e.g. in beforeEach. */
|
|
241
|
+
reset(): void;
|
|
242
|
+
}
|
|
243
|
+
export declare function createTestApp(o?: TestAppOptions): TestApp;
|
|
244
|
+
/**
|
|
245
|
+
* A TestApp from an app's folder (the working directory unless named): every model's schema.ib.ts, every action
|
|
246
|
+
* file (loaded when first run, as a deployment does) and settings.ib.ts. Runs under a test runner that loads
|
|
247
|
+
* TypeScript, like Vitest (`ib-apps test`).
|
|
248
|
+
*/
|
|
249
|
+
export declare function loadApp(dir?: string, o?: Omit<TestAppOptions, "models" | "actions" | "settings">): Promise<TestApp>;
|
|
250
|
+
export {};
|