@inferencebureau/apps-sdk 0.0.0-stage → 0.1.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 +44 -2
- package/dist/browser.d.ts +17 -0
- package/dist/browser.js +95 -0
- package/dist/index.d.ts +261 -0
- package/dist/index.js +207 -0
- package/dist/runtime.d.ts +50 -0
- package/dist/runtime.js +80 -0
- package/package.json +59 -4
package/README.md
CHANGED
|
@@ -1,3 +1,45 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @inferencebureau/apps-sdk
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
and request checks for Shopify session tokens and app proxies. Apps are operator-only for now.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @inferencebureau/apps-sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Apps built on Inference Bureau get the SDK in every build already; install it to have the types in your editor, or to
|
|
12
|
+
use the client from your own code. It's ESM, uses only `fetch` and Web Crypto, and runs on Node 20+, edge runtimes and
|
|
13
|
+
Next.js without `transpilePackages`.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
// api/models/review/actions/approve.ts
|
|
17
|
+
import { save, type ActionRun, type ActionOptions } from "@inferencebureau/apps-sdk";
|
|
18
|
+
|
|
19
|
+
export const run: ActionRun = async ({ record }) => {
|
|
20
|
+
record.status = "approved";
|
|
21
|
+
await save(record);
|
|
22
|
+
};
|
|
23
|
+
export const options: ActionOptions = { actionType: "update" };
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
// web/app/proxy/route.ts: a storefront app proxy route
|
|
28
|
+
import { verifyProxyRequest } from "@inferencebureau/apps-sdk";
|
|
29
|
+
|
|
30
|
+
export async function GET(request: Request) {
|
|
31
|
+
const proxy = await verifyProxyRequest(request);
|
|
32
|
+
if (!proxy) return new Response("Not found", { status: 404 });
|
|
33
|
+
return new Response("<h1>Hello {{ shop.name }}</h1>", { headers: { "content-type": "application/liquid" } });
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Entry points:
|
|
38
|
+
|
|
39
|
+
- `@inferencebureau/apps-sdk`: metadata types, action helpers, `createClient`, `createShopifyClient`,
|
|
40
|
+
`verifyShopifySession`, `verifyProxyRequest`.
|
|
41
|
+
- `@inferencebureau/apps-sdk/runtime`: `handleAction`, the signed `/_ib/actions` route every build adds.
|
|
42
|
+
- `@inferencebureau/apps-sdk/browser`: for an embedded admin page's client code: `sessionFetch`,
|
|
43
|
+
`shopifySessionToken`, `isPreview`.
|
|
44
|
+
|
|
45
|
+
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>;
|
package/dist/browser.js
ADDED
|
@@ -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
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
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
|
+
export interface AppSettings {
|
|
62
|
+
type: "ib/settings/v1";
|
|
63
|
+
platform: "shopify" | "web";
|
|
64
|
+
[key: string]: unknown;
|
|
65
|
+
}
|
|
66
|
+
export interface AppPermissions {
|
|
67
|
+
type: "ib/permissions/v1";
|
|
68
|
+
roles: Record<string, unknown>;
|
|
69
|
+
}
|
|
70
|
+
export interface AppRecord {
|
|
71
|
+
id: string;
|
|
72
|
+
createdAt: string;
|
|
73
|
+
updatedAt: string;
|
|
74
|
+
[field: string]: unknown;
|
|
75
|
+
}
|
|
76
|
+
/** Which records a list returns: `{ field: { equals: x } }`, with AND, OR and NOT lists. */
|
|
77
|
+
export type Filter = {
|
|
78
|
+
AND?: Filter[];
|
|
79
|
+
OR?: Filter[];
|
|
80
|
+
NOT?: Filter[];
|
|
81
|
+
} & {
|
|
82
|
+
[field: string]: unknown;
|
|
83
|
+
};
|
|
84
|
+
export type Sort = Record<string, "Ascending" | "Descending">;
|
|
85
|
+
export interface FindManyOptions {
|
|
86
|
+
filter?: Filter;
|
|
87
|
+
sort?: Sort | Sort[];
|
|
88
|
+
first?: number;
|
|
89
|
+
after?: string | null;
|
|
90
|
+
}
|
|
91
|
+
export interface RecordPage<T = AppRecord> {
|
|
92
|
+
records: T[];
|
|
93
|
+
hasNextPage: boolean;
|
|
94
|
+
endCursor: string | null;
|
|
95
|
+
}
|
|
96
|
+
/** A record being worked on in an action: its fields, plus what the action has asked to happen to it. */
|
|
97
|
+
export type ActionRecord = AppRecord;
|
|
98
|
+
/** Marks a plain object as the action's record (the runtime does this before `run`). */
|
|
99
|
+
export declare function trackRecord<T extends object>(record: T, model?: string | null): T;
|
|
100
|
+
/** Copies the action's params onto the record: `params.<model>` when the caller nested them, else params themselves. */
|
|
101
|
+
export declare function applyParams(params: Record<string, unknown>, record: ActionRecord): void;
|
|
102
|
+
/** Saves the record when `run` returns, with everything else the action does to it, in one transaction. */
|
|
103
|
+
export declare function save(record: ActionRecord): Promise<void>;
|
|
104
|
+
/** Deletes the record when `run` returns. */
|
|
105
|
+
export declare function deleteRecord(record: ActionRecord): Promise<void>;
|
|
106
|
+
/** What `run` asked for: the changed fields to save (all set fields for a new record), a delete, or nothing. */
|
|
107
|
+
export declare function pendingWrite(record: ActionRecord, isNew: boolean): {
|
|
108
|
+
op: "save";
|
|
109
|
+
values: Record<string, unknown>;
|
|
110
|
+
} | {
|
|
111
|
+
op: "delete";
|
|
112
|
+
} | null;
|
|
113
|
+
export declare class ApiError extends Error {
|
|
114
|
+
readonly status: number;
|
|
115
|
+
readonly code: string | null;
|
|
116
|
+
readonly problems: {
|
|
117
|
+
field: string;
|
|
118
|
+
message: string;
|
|
119
|
+
}[];
|
|
120
|
+
constructor(message: string, status: number, code: string | null, problems?: {
|
|
121
|
+
field: string;
|
|
122
|
+
message: string;
|
|
123
|
+
}[]);
|
|
124
|
+
}
|
|
125
|
+
export interface ModelClient {
|
|
126
|
+
findOne(id: string): Promise<AppRecord | null>;
|
|
127
|
+
findMany(o?: FindManyOptions): Promise<RecordPage>;
|
|
128
|
+
findFirst(o?: Omit<FindManyOptions, "first" | "after">): Promise<AppRecord | null>;
|
|
129
|
+
/** Nearest records to text (embedded with the field's model) or a vector, nearest first, with `_distance`. */
|
|
130
|
+
search(field: string, near: string | number[], o?: Omit<FindManyOptions, "sort">): Promise<RecordPage<AppRecord & {
|
|
131
|
+
_distance: number;
|
|
132
|
+
}>>;
|
|
133
|
+
create(values: Record<string, unknown>): Promise<AppRecord>;
|
|
134
|
+
update(id: string, values: Record<string, unknown>): Promise<AppRecord>;
|
|
135
|
+
delete(id: string): Promise<void>;
|
|
136
|
+
/** Runs one of the model's actions: on a record when `id` is given, else as a new one; `shop` gives it `shopify`. */
|
|
137
|
+
run(action: string, o?: {
|
|
138
|
+
id?: string;
|
|
139
|
+
params?: Record<string, unknown>;
|
|
140
|
+
shop?: string;
|
|
141
|
+
}): Promise<{
|
|
142
|
+
record: AppRecord | null;
|
|
143
|
+
result?: unknown;
|
|
144
|
+
}>;
|
|
145
|
+
}
|
|
146
|
+
export type Api = {
|
|
147
|
+
[model: string]: ModelClient;
|
|
148
|
+
} & {
|
|
149
|
+
/** Runs a global action (`api/actions/<name>.ts`). */
|
|
150
|
+
$global(action: string, params?: Record<string, unknown>): Promise<{
|
|
151
|
+
result?: unknown;
|
|
152
|
+
}>;
|
|
153
|
+
};
|
|
154
|
+
export interface ClientOptions {
|
|
155
|
+
/** Inference Bureau's API; IB_API_URL in an app's deployment. */
|
|
156
|
+
url?: string;
|
|
157
|
+
/** The environment's token (IB_ENVIRONMENT_TOKEN), or an API key linked to the app. */
|
|
158
|
+
token?: string;
|
|
159
|
+
/** The app (IB_APP) and environment (IB_ENVIRONMENT). */
|
|
160
|
+
app?: string;
|
|
161
|
+
environment?: string;
|
|
162
|
+
fetch?: typeof fetch;
|
|
163
|
+
}
|
|
164
|
+
/** The app's API. In an app's deployment every option comes from its environment variables. */
|
|
165
|
+
export declare function createClient(o?: ClientOptions): Api;
|
|
166
|
+
/**
|
|
167
|
+
* The Shopify Admin API for one store the app is installed on, through Inference Bureau: the store's token stays
|
|
168
|
+
* with us, and each call is checked against the environment's install.
|
|
169
|
+
*/
|
|
170
|
+
export interface ShopifyClient {
|
|
171
|
+
shop: string;
|
|
172
|
+
/** Runs an Admin GraphQL query or mutation and returns its `data`; GraphQL errors throw ShopifyError. */
|
|
173
|
+
graphql<T = any>(query: string, variables?: Record<string, unknown>): Promise<T>;
|
|
174
|
+
}
|
|
175
|
+
export declare class ShopifyError extends Error {
|
|
176
|
+
readonly errors: unknown[];
|
|
177
|
+
constructor(message: string, errors: unknown[]);
|
|
178
|
+
}
|
|
179
|
+
/** The Admin API for `shop`, as the environment (the same options as createClient). */
|
|
180
|
+
export declare function createShopifyClient(shop: string, o?: ClientOptions): ShopifyClient;
|
|
181
|
+
export interface ShopifySession {
|
|
182
|
+
/** The store the admin page is open in (x.myshopify.com). */
|
|
183
|
+
shop: string;
|
|
184
|
+
/** The staff member's Shopify user id, when Shopify includes it. */
|
|
185
|
+
userId: string | null;
|
|
186
|
+
sessionId: string | null;
|
|
187
|
+
/** Set when the page is open in Inference Bureau's preview, not the Shopify admin: who's previewing. */
|
|
188
|
+
preview?: {
|
|
189
|
+
actor: string;
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* The store and staff member behind a request from one of the app's pages in the Shopify admin, or null when it
|
|
194
|
+
* carries no valid session token. App Bridge's `shopify.idToken()` gives the page its token; send it as
|
|
195
|
+
* `Authorization: Bearer <token>` (or pass the token itself). Shopify signs it with the app's client secret, which
|
|
196
|
+
* Inference Bureau holds, so the check happens there; never trust a shop named any other way.
|
|
197
|
+
*/
|
|
198
|
+
export declare function verifyShopifySession(request: Request | string, o?: ClientOptions): Promise<ShopifySession | null>;
|
|
199
|
+
export interface ProxyRequest {
|
|
200
|
+
/** The store whose storefront made the request (x.myshopify.com). */
|
|
201
|
+
shop: string;
|
|
202
|
+
/** The signed-in customer's id, or null for a guest. */
|
|
203
|
+
customerId: string | null;
|
|
204
|
+
/** Where the storefront reached the app, e.g. /apps/wholesale. */
|
|
205
|
+
pathPrefix: string;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or null for
|
|
209
|
+
* anything else. Shopify's own signature was checked before it was passed on; this checks ours, so only a real
|
|
210
|
+
* storefront request is trusted with a shop and customer.
|
|
211
|
+
*/
|
|
212
|
+
export declare function verifyProxyRequest(request: Request, o?: {
|
|
213
|
+
token?: string;
|
|
214
|
+
now?: () => number;
|
|
215
|
+
}): Promise<ProxyRequest | null>;
|
|
216
|
+
export interface LogLine {
|
|
217
|
+
level: "debug" | "info" | "warn" | "error";
|
|
218
|
+
message: string;
|
|
219
|
+
data?: unknown;
|
|
220
|
+
at: string;
|
|
221
|
+
}
|
|
222
|
+
export interface Logger {
|
|
223
|
+
debug(message: string, data?: unknown): void;
|
|
224
|
+
info(message: string, data?: unknown): void;
|
|
225
|
+
warn(message: string, data?: unknown): void;
|
|
226
|
+
error(message: string, data?: unknown): void;
|
|
227
|
+
}
|
|
228
|
+
export interface ActionContext {
|
|
229
|
+
/** What the caller passed. A model action's fields may be at the top level or under the model's name. */
|
|
230
|
+
params: Record<string, unknown>;
|
|
231
|
+
/** The record the action works on: the stored one, or a new, empty one for a create. Null in a global action. */
|
|
232
|
+
record: ActionRecord;
|
|
233
|
+
/** The app's API, as the environment. Writes through it happen at once, outside this action's transaction. */
|
|
234
|
+
api: Api;
|
|
235
|
+
/** Lines written here appear on the action's run in Logs. */
|
|
236
|
+
logger: Logger;
|
|
237
|
+
model: string | null;
|
|
238
|
+
action: string;
|
|
239
|
+
environment: "development" | "production";
|
|
240
|
+
/** The store this run is about (an install, a webhook, or the caller's `shop`), and the Admin API for it. */
|
|
241
|
+
shop: string | null;
|
|
242
|
+
shopify: ShopifyClient | null;
|
|
243
|
+
}
|
|
244
|
+
export type ActionRun = (ctx: ActionContext) => unknown | Promise<unknown>;
|
|
245
|
+
export type ActionOnSuccess = (ctx: ActionContext) => void | Promise<void>;
|
|
246
|
+
export type GlobalActionRun = (ctx: Omit<ActionContext, "record"> & {
|
|
247
|
+
record: null;
|
|
248
|
+
}) => unknown | Promise<unknown>;
|
|
249
|
+
export interface ActionOptions {
|
|
250
|
+
/** create: works on a new record; update and custom: on the record named by id; delete: removes it. */
|
|
251
|
+
actionType?: "create" | "update" | "delete" | "custom";
|
|
252
|
+
/** Whether what `run` returns goes back to the caller (it's dropped otherwise). */
|
|
253
|
+
returnType?: boolean;
|
|
254
|
+
/** How long `run` may take, at most 60 seconds (30 by default). */
|
|
255
|
+
timeoutMS?: number;
|
|
256
|
+
}
|
|
257
|
+
export interface ActionModule {
|
|
258
|
+
run?: ActionRun;
|
|
259
|
+
onSuccess?: ActionOnSuccess;
|
|
260
|
+
options?: ActionOptions;
|
|
261
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
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
|
+
run: (action, o = {}) => call("POST", `${m}/actions/${encodeURIComponent(action)}`, { ...(o.id ? { id: o.id } : {}), params: o.params ?? {}, ...(o.shop ? { shop: o.shop } : {}) }),
|
|
119
|
+
};
|
|
120
|
+
};
|
|
121
|
+
const cache = new Map();
|
|
122
|
+
const $global = (action, params = {}) => call("POST", `/actions/${encodeURIComponent(action)}`, { params });
|
|
123
|
+
return new Proxy({}, {
|
|
124
|
+
get(_t, prop) {
|
|
125
|
+
if (prop === "$global")
|
|
126
|
+
return $global;
|
|
127
|
+
if (typeof prop !== "string" || prop === "then")
|
|
128
|
+
return undefined;
|
|
129
|
+
if (!cache.has(prop))
|
|
130
|
+
cache.set(prop, model(prop));
|
|
131
|
+
return cache.get(prop);
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
export class ShopifyError extends Error {
|
|
136
|
+
errors;
|
|
137
|
+
constructor(message, errors) {
|
|
138
|
+
super(message);
|
|
139
|
+
this.errors = errors;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/** The Admin API for `shop`, as the environment (the same options as createClient). */
|
|
143
|
+
export function createShopifyClient(shop, o = {}) {
|
|
144
|
+
const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
|
|
145
|
+
const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
|
|
146
|
+
const app = o.app ?? envVar("IB_APP") ?? "";
|
|
147
|
+
const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
|
|
148
|
+
const f = o.fetch ?? fetch;
|
|
149
|
+
return {
|
|
150
|
+
shop,
|
|
151
|
+
async graphql(query, variables = {}) {
|
|
152
|
+
const res = await f(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/graphql`, {
|
|
153
|
+
method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ shop, query, variables }),
|
|
154
|
+
});
|
|
155
|
+
const json = (await res.json().catch(() => ({})));
|
|
156
|
+
if (!res.ok)
|
|
157
|
+
throw new ShopifyError(json.error?.message ?? `Shopify answered ${res.status}.`, json.errors ?? []);
|
|
158
|
+
if (json.errors?.length)
|
|
159
|
+
throw new ShopifyError(json.errors.map((e) => e.message ?? String(e)).join("; "), json.errors);
|
|
160
|
+
return json.data;
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The store and staff member behind a request from one of the app's pages in the Shopify admin, or null when it
|
|
166
|
+
* carries no valid session token. App Bridge's `shopify.idToken()` gives the page its token; send it as
|
|
167
|
+
* `Authorization: Bearer <token>` (or pass the token itself). Shopify signs it with the app's client secret, which
|
|
168
|
+
* Inference Bureau holds, so the check happens there; never trust a shop named any other way.
|
|
169
|
+
*/
|
|
170
|
+
export async function verifyShopifySession(request, o = {}) {
|
|
171
|
+
const token = typeof request === "string" ? request : (request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
|
|
172
|
+
if (!token || token.split(".").length !== 3)
|
|
173
|
+
return null;
|
|
174
|
+
const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
|
|
175
|
+
const app = o.app ?? envVar("IB_APP") ?? "";
|
|
176
|
+
const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
|
|
177
|
+
const res = await (o.fetch ?? fetch)(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/session`, {
|
|
178
|
+
method: "POST", headers: { authorization: `Bearer ${o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? ""}`, "content-type": "application/json" }, body: JSON.stringify({ token }),
|
|
179
|
+
});
|
|
180
|
+
const json = (await res.json().catch(() => ({})));
|
|
181
|
+
// A refused session token is an answer (null); anything else, like the app's own token being refused, is an error.
|
|
182
|
+
if (res.status === 401 && json.error?.code === "invalid_session")
|
|
183
|
+
return null;
|
|
184
|
+
if (!res.ok)
|
|
185
|
+
throw new ApiError(json.error?.message ?? `Checking the session failed (${res.status}).`, res.status, json.error?.code ?? null);
|
|
186
|
+
return { shop: json.shop, userId: json.userId, sessionId: json.sessionId, ...(json.preview ? { preview: json.preview } : {}) };
|
|
187
|
+
}
|
|
188
|
+
const hex = (b) => Array.from(new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
|
|
189
|
+
/**
|
|
190
|
+
* A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or null for
|
|
191
|
+
* anything else. Shopify's own signature was checked before it was passed on; this checks ours, so only a real
|
|
192
|
+
* storefront request is trusted with a shop and customer.
|
|
193
|
+
*/
|
|
194
|
+
export async function verifyProxyRequest(request, o = {}) {
|
|
195
|
+
const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
|
|
196
|
+
const h = request.headers;
|
|
197
|
+
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") ?? "";
|
|
198
|
+
if (!token || !shop || Math.abs((o.now ?? Date.now)() - Number(ts)) > 5 * 60_000)
|
|
199
|
+
return null;
|
|
200
|
+
const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(token), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
201
|
+
const want = hex(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${ts}.${shop}.${customer}.${prefix}`)));
|
|
202
|
+
const got = h.get("x-ib-proxy-signature") ?? "";
|
|
203
|
+
let d = got.length ^ want.length;
|
|
204
|
+
for (let i = 0; i < Math.min(got.length, want.length); i++)
|
|
205
|
+
d |= got.charCodeAt(i) ^ want.charCodeAt(i);
|
|
206
|
+
return d === 0 ? { shop, customerId: customer || null, pathPrefix: prefix } : null;
|
|
207
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
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 AppRecord, type LogLine } 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
|
+
/** Runs one phase of an action, without checking where the request came from (handleAction does). */
|
|
43
|
+
export declare function runAction(req: ActionRequest, registry: ActionRegistry, o?: {
|
|
44
|
+
token?: string;
|
|
45
|
+
}): Promise<ActionResponse>;
|
|
46
|
+
/** The `/_ib/actions` route: a signed request from Inference Bureau, or 404 for anyone else. */
|
|
47
|
+
export declare function handleAction(request: Request, registry: ActionRegistry, o?: {
|
|
48
|
+
token?: string;
|
|
49
|
+
now?: () => number;
|
|
50
|
+
}): Promise<Response>;
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
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) {
|
|
26
|
+
const at = (level) => (message, data) => {
|
|
27
|
+
lines.push({ level, message: String(message).slice(0, 2000), ...(data === undefined ? {} : { data }), at: new Date().toISOString() });
|
|
28
|
+
(level === "error" ? console.error : level === "warn" ? console.warn : console.log)(`[action] ${message}`, ...(data === undefined ? [] : [data]));
|
|
29
|
+
};
|
|
30
|
+
return { debug: at("debug"), info: at("info"), warn: at("warn"), error: at("error") };
|
|
31
|
+
}
|
|
32
|
+
/** Runs one phase of an action, without checking where the request came from (handleAction does). */
|
|
33
|
+
export async function runAction(req, registry, o = {}) {
|
|
34
|
+
const logs = [];
|
|
35
|
+
try {
|
|
36
|
+
const key = req.model ? `${req.model}/${req.action}` : `$global/${req.action}`;
|
|
37
|
+
const load = registry[key];
|
|
38
|
+
if (!load)
|
|
39
|
+
throw new Error(`The deployment has no action ${key}. Deploy again if it was added since.`);
|
|
40
|
+
const mod = await load();
|
|
41
|
+
const record = req.record ? trackRecord({ ...req.record }, req.model) : null;
|
|
42
|
+
const ctx = {
|
|
43
|
+
params: req.params ?? {}, record, api: createClient(o.token ? { token: o.token } : {}), logger: collector(logs),
|
|
44
|
+
model: req.model, action: req.action, environment: req.environment,
|
|
45
|
+
shop: req.shop ?? null, shopify: req.shop ? createShopifyClient(req.shop, o.token ? { token: o.token } : {}) : null,
|
|
46
|
+
};
|
|
47
|
+
if (req.phase === "onSuccess") {
|
|
48
|
+
await mod.onSuccess?.(ctx);
|
|
49
|
+
return { ok: true, write: null, logs };
|
|
50
|
+
}
|
|
51
|
+
if (typeof mod.run !== "function")
|
|
52
|
+
throw new Error(`${key} doesn't export a run function.`);
|
|
53
|
+
const result = await mod.run(ctx);
|
|
54
|
+
const write = record ? pendingWrite(record, req.isNew) : null;
|
|
55
|
+
return { ok: true, write, ...(mod.options?.returnType && result !== undefined ? { result } : {}), logs };
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
59
|
+
return { ok: false, error: { message: err.message, ...(err.stack ? { stack: err.stack.split("\n").slice(0, 8).join("\n") } : {}) }, logs };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** The `/_ib/actions` route: a signed request from Inference Bureau, or 404 for anyone else. */
|
|
63
|
+
export async function handleAction(request, registry, o = {}) {
|
|
64
|
+
const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
|
|
65
|
+
const body = await request.text();
|
|
66
|
+
const ts = request.headers.get("x-ib-timestamp") ?? "";
|
|
67
|
+
const sig = request.headers.get("x-ib-signature") ?? "";
|
|
68
|
+
const fresh = Math.abs((o.now ?? Date.now)() - Number(ts)) < SKEW_MS;
|
|
69
|
+
if (!token || !fresh || !sameText(sig, await sign(token, ts, body)))
|
|
70
|
+
return new Response("Not found", { status: 404 });
|
|
71
|
+
let req;
|
|
72
|
+
try {
|
|
73
|
+
req = JSON.parse(body);
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return new Response("Bad request", { status: 400 });
|
|
77
|
+
}
|
|
78
|
+
const res = await runAction(req, registry, { token });
|
|
79
|
+
return new Response(JSON.stringify(res), { status: 200, headers: { "content-type": "application/json", "cache-control": "no-store" } });
|
|
80
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inferencebureau/apps-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types and the records API client.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"inferencebureau",
|
|
8
|
+
"shopify",
|
|
9
|
+
"apps",
|
|
10
|
+
"sdk"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://inferencebureau.com",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/Inference-Bureau/inferencebureau.git",
|
|
16
|
+
"directory": "packages/apps-sdk"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"import": "./dist/index.js",
|
|
24
|
+
"default": "./dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./runtime": {
|
|
27
|
+
"types": "./dist/runtime.d.ts",
|
|
28
|
+
"import": "./dist/runtime.js",
|
|
29
|
+
"default": "./dist/runtime.js"
|
|
30
|
+
},
|
|
31
|
+
"./browser": {
|
|
32
|
+
"types": "./dist/browser.d.ts",
|
|
33
|
+
"import": "./dist/browser.js",
|
|
34
|
+
"default": "./dist/browser.js"
|
|
35
|
+
},
|
|
36
|
+
"./package.json": "./package.json"
|
|
37
|
+
},
|
|
38
|
+
"main": "./dist/index.js",
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"files": [
|
|
41
|
+
"dist",
|
|
42
|
+
"README.md"
|
|
43
|
+
],
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=20"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && node scripts/fix-dist.mjs",
|
|
52
|
+
"prepublishOnly": "npm run build",
|
|
53
|
+
"typecheck": "tsc --noEmit",
|
|
54
|
+
"test": "vitest run",
|
|
55
|
+
"embed": "node scripts/embed.mjs"
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"typescript": "^5.8.0",
|
|
59
|
+
"vitest": "^3.2.0"
|
|
60
|
+
}
|
|
61
|
+
}
|