@inferencebureau/apps-sdk 0.4.1 → 0.6.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 +4 -2
- package/dist/index.d.ts +56 -3
- package/dist/index.js +4 -1
- package/dist/runtime.d.ts +1 -0
- package/dist/runtime.js +3 -2
- package/dist/test.d.ts +56 -7
- package/dist/test.js +1107 -77
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -81,8 +81,10 @@ Entry points:
|
|
|
81
81
|
- `@inferencebureau/apps-sdk/browser`: for an embedded admin page's client code: `sessionFetch`,
|
|
82
82
|
`shopifySessionToken`, `isPreview`, `previewSession`, `requestScopes`.
|
|
83
83
|
- `@inferencebureau/apps-sdk/test`: for the app's tests: `loadApp` (or `createTestApp`) runs actions against
|
|
84
|
-
in-memory records with the records engine's rules
|
|
85
|
-
|
|
84
|
+
in-memory records with the records engine's rules and each action's `timeoutMS`, holds calls to a role in
|
|
85
|
+
permissions.ib.ts (`runAs`, `api.asRole`), mocks the Shopify Admin API, delivers webhooks (through their `filter`)
|
|
86
|
+
and installs, queues what schedules owe (`queueSchedules`, `nextRuns`) and runs queued jobs; `fixtures` has
|
|
87
|
+
Shopify's webhook payloads. Node only, under Vitest with this package inlined:
|
|
86
88
|
`test: { server: { deps: { inline: ["@inferencebureau/apps-sdk"] } } }` in vitest.config.ts (new apps have it).
|
|
87
89
|
|
|
88
90
|
Docs: https://app.inferencebureau.com/docs/apps
|
package/dist/index.d.ts
CHANGED
|
@@ -46,6 +46,12 @@ export interface FieldDef {
|
|
|
46
46
|
* webhook writes what its payload carries.
|
|
47
47
|
*/
|
|
48
48
|
fetch?: "onWebhook" | "later";
|
|
49
|
+
/**
|
|
50
|
+
* Computed fields, worked out when a record is read: an expression over the record's own fields (`"price * quantity"`,
|
|
51
|
+
* `"concat(firstName, ' ', lastName)"`), or an aggregate over a hasMany's records. They filter and sort like stored ones.
|
|
52
|
+
*/
|
|
53
|
+
expression?: string;
|
|
54
|
+
aggregate?: ComputedAggregate;
|
|
49
55
|
parent?: {
|
|
50
56
|
model: string;
|
|
51
57
|
};
|
|
@@ -62,6 +68,23 @@ export interface FieldDef {
|
|
|
62
68
|
};
|
|
63
69
|
[key: string]: unknown;
|
|
64
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* One of count, sum, avg, min or max over a hasMany field's records: `{ count: "reviews" }`, or
|
|
73
|
+
* `{ avg: "reviews.rating", filter: { status: { equals: "approved" } } }` for a field of theirs, only those matching.
|
|
74
|
+
*/
|
|
75
|
+
export type ComputedAggregate = ({
|
|
76
|
+
count: string;
|
|
77
|
+
} | {
|
|
78
|
+
sum: string;
|
|
79
|
+
} | {
|
|
80
|
+
avg: string;
|
|
81
|
+
} | {
|
|
82
|
+
min: string;
|
|
83
|
+
} | {
|
|
84
|
+
max: string;
|
|
85
|
+
}) & {
|
|
86
|
+
filter?: Filter;
|
|
87
|
+
};
|
|
65
88
|
export interface ModelSchema {
|
|
66
89
|
type: "ib/model-schema/v1";
|
|
67
90
|
storageKey?: string;
|
|
@@ -90,6 +113,11 @@ export interface ShopifyInstallSettings {
|
|
|
90
113
|
install?: "managed" | "oauth";
|
|
91
114
|
/** Scopes the app asks for once it needs them, in the admin: `requestScopes` from the browser helpers. */
|
|
92
115
|
optionalScopes?: string[];
|
|
116
|
+
/**
|
|
117
|
+
* What the app's Sidekick tools cover, for Sidekick to match merchants' questions to the app, e.g. "Search and
|
|
118
|
+
* compare product bundles and their discounts". Required once an extension defines tools (at most 256 tokens).
|
|
119
|
+
*/
|
|
120
|
+
sidekickSummary?: string;
|
|
93
121
|
}
|
|
94
122
|
export interface WebhookSetting {
|
|
95
123
|
/** A Shopify webhook topic, e.g. orders/create. The app's scopes must allow it. */
|
|
@@ -110,6 +138,11 @@ export interface ScheduleSetting {
|
|
|
110
138
|
timezone?: string;
|
|
111
139
|
/** Where it runs: production only unless development is named too. */
|
|
112
140
|
environments?: ("development" | "production")[];
|
|
141
|
+
/**
|
|
142
|
+
* Replay times it missed by more than a few minutes (an outage, a paused team): the latest 24 from the last day,
|
|
143
|
+
* each with its own `scheduledAt`. Without it they're skipped.
|
|
144
|
+
*/
|
|
145
|
+
catchUp?: boolean;
|
|
113
146
|
}
|
|
114
147
|
export interface AppPermissions {
|
|
115
148
|
type: "ib/permissions/v1";
|
|
@@ -135,6 +168,8 @@ export interface FindManyOptions {
|
|
|
135
168
|
sort?: Sort | Sort[];
|
|
136
169
|
first?: number;
|
|
137
170
|
after?: string | null;
|
|
171
|
+
/** Words to find in the model's text fields: records holding every one (any case, part of a word counts), those holding the whole phrase first unless sorted. */
|
|
172
|
+
search?: string;
|
|
138
173
|
}
|
|
139
174
|
export interface RecordPage<T = AppRecord> {
|
|
140
175
|
records: T[];
|
|
@@ -201,19 +236,32 @@ export interface Upload {
|
|
|
201
236
|
token: string;
|
|
202
237
|
expiresAt: string;
|
|
203
238
|
}
|
|
239
|
+
/**
|
|
240
|
+
* Who a sign-in is for, so failed ones are counted: the email typed (counted the same whether or not it has an
|
|
241
|
+
* account) and the visitor's IP (the `x-ib-client-ip` header on requests to the app).
|
|
242
|
+
*/
|
|
243
|
+
export interface CheckPasswordOptions {
|
|
244
|
+
field?: string;
|
|
245
|
+
email?: string;
|
|
246
|
+
ip?: string;
|
|
247
|
+
}
|
|
204
248
|
export interface ModelClient {
|
|
205
249
|
findOne(id: string): Promise<AppRecord | null>;
|
|
206
250
|
findMany(o?: FindManyOptions): Promise<RecordPage>;
|
|
207
251
|
findFirst(o?: Omit<FindManyOptions, "first" | "after">): Promise<AppRecord | null>;
|
|
208
252
|
/** Nearest records to text (embedded with the field's model) or a vector, nearest first, with `_distance`. */
|
|
209
|
-
search(field: string, near: string | number[], o?: Omit<FindManyOptions, "sort">): Promise<RecordPage<AppRecord & {
|
|
253
|
+
search(field: string, near: string | number[], o?: Omit<FindManyOptions, "sort" | "search">): Promise<RecordPage<AppRecord & {
|
|
210
254
|
_distance: number;
|
|
211
255
|
}>>;
|
|
212
256
|
create(values: Record<string, unknown>): Promise<AppRecord>;
|
|
213
257
|
update(id: string, values: Record<string, unknown>): Promise<AppRecord>;
|
|
214
258
|
delete(id: string): Promise<void>;
|
|
215
|
-
/**
|
|
216
|
-
|
|
259
|
+
/**
|
|
260
|
+
* Whether `password` is the one stored in the record's password field (`password` unless named). Hashes are never
|
|
261
|
+
* returned. Failures are counted per `email` (the record without one) and per visitor `ip`; past the limit it throws
|
|
262
|
+
* an ApiError with status 429 and a message to show, without checking.
|
|
263
|
+
*/
|
|
264
|
+
checkPassword(id: string, password: string, field?: string | CheckPasswordOptions): Promise<boolean>;
|
|
217
265
|
/** Runs one of the model's actions: on a record when `id` is given, else as a new one; `shop` gives it `shopify`. */
|
|
218
266
|
run(action: string, o?: {
|
|
219
267
|
id?: string;
|
|
@@ -729,6 +777,11 @@ export interface ActionContext {
|
|
|
729
777
|
* staff in the store's admin (verifyShopifySession's), a shopper. Null for the app's own calls, webhooks and jobs.
|
|
730
778
|
*/
|
|
731
779
|
caller: ActionCaller | null;
|
|
780
|
+
/**
|
|
781
|
+
* Fires when the run is stopped: its job canceled from the Queue or the API, or its time up. Pass it to `fetch` and
|
|
782
|
+
* check it between steps of a long loop to stop early; what `run` returns after it fires is dropped.
|
|
783
|
+
*/
|
|
784
|
+
signal: AbortSignal;
|
|
732
785
|
}
|
|
733
786
|
export interface ActionCaller {
|
|
734
787
|
role: string;
|
package/dist/index.js
CHANGED
|
@@ -120,7 +120,10 @@ export function createClient(o = {}) {
|
|
|
120
120
|
create: (values) => call("POST", `${m}/records`, values),
|
|
121
121
|
update: (id, values) => call("PATCH", `${m}/records/${encodeURIComponent(id)}`, values),
|
|
122
122
|
delete: (id) => call("DELETE", `${m}/records/${encodeURIComponent(id)}`),
|
|
123
|
-
checkPassword: async (id, password, field) =>
|
|
123
|
+
checkPassword: async (id, password, field) => {
|
|
124
|
+
const o = typeof field === "string" ? { field } : field ?? {};
|
|
125
|
+
return (await call("POST", `${m}/records/${encodeURIComponent(id)}/check-password`, { password, ...(o.field ? { field: o.field } : {}), ...(o.email ? { email: o.email } : {}), ...(o.ip ? { ip: o.ip } : {}) })).valid;
|
|
126
|
+
},
|
|
124
127
|
run: (action, o = {}) => call("POST", `${m}/actions/${encodeURIComponent(action)}`, { ...(o.id ? { id: o.id } : {}), params: o.params ?? {}, ...(o.shop ? { shop: o.shop } : {}) }),
|
|
125
128
|
createUpload: (field, o = {}) => call("POST", `${m}/uploads`, { field, ...o }),
|
|
126
129
|
async upload(field, body, o = {}) {
|
package/dist/runtime.d.ts
CHANGED
|
@@ -53,6 +53,7 @@ export declare function runAction(req: ActionRequest, registry: ActionRegistry,
|
|
|
53
53
|
api?: Api;
|
|
54
54
|
shopify?: (shop: string) => ShopifyClient;
|
|
55
55
|
echo?: boolean;
|
|
56
|
+
signal?: AbortSignal;
|
|
56
57
|
}): Promise<ActionResponse>;
|
|
57
58
|
/** The `/_ib/actions` route: a signed request from Inference Bureau, or 404 for anyone else. */
|
|
58
59
|
export declare function handleAction(request: Request, registry: ActionRegistry, o?: {
|
package/dist/runtime.js
CHANGED
|
@@ -48,7 +48,7 @@ export async function runAction(req, registry, o = {}) {
|
|
|
48
48
|
const record = req.record ? trackRecord({ ...req.record }, req.model) : null;
|
|
49
49
|
const ctx = {
|
|
50
50
|
params: req.params ?? {}, record, api: scopedApi(o.api ?? createClient(o.token ? { token: o.token } : {}), req.shop), logger: collector(logs, o.echo ?? true),
|
|
51
|
-
model: req.model, action: req.action, environment: req.environment,
|
|
51
|
+
model: req.model, action: req.action, environment: req.environment, signal: o.signal ?? new AbortController().signal,
|
|
52
52
|
caller: req.caller ?? null, shop: req.shop ?? null, shopify: req.shop ? (o.shopify?.(req.shop) ?? createShopifyClient(req.shop, { ...(o.token ? { token: o.token } : {}), ...(req.background ? { priority: "background" } : {}) })) : null,
|
|
53
53
|
};
|
|
54
54
|
if (req.phase === "onSuccess") {
|
|
@@ -82,6 +82,7 @@ export async function handleAction(request, registry, o = {}) {
|
|
|
82
82
|
catch {
|
|
83
83
|
return new Response("Bad request", { status: 400 });
|
|
84
84
|
}
|
|
85
|
-
|
|
85
|
+
// The request is aborted when Inference Bureau stops waiting: the job was canceled, or the time ran out.
|
|
86
|
+
const res = await runAction(req, registry, { token, signal: request.signal });
|
|
86
87
|
return new Response(JSON.stringify(res), { status: 200, headers: { "content-type": "application/json", "cache-control": "no-store" } });
|
|
87
88
|
}
|
package/dist/test.d.ts
CHANGED
|
@@ -8,14 +8,17 @@
|
|
|
8
8
|
* The records follow the records engine's rules (packages/apps/src/records.ts): field types and conversions,
|
|
9
9
|
* defaults, validations, uniqueness, belongsTo, filters, sorting and pages, and the errors the API answers with, as
|
|
10
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
|
|
12
|
-
*
|
|
13
|
-
* and
|
|
11
|
+
* as JSON, its writes are applied when `run` returns, then `onSuccess` runs with the saved record, each within its
|
|
12
|
+
* `timeoutMS`. Calls run as the system unless a test says who they're for (`runAs`, `api.asRole`, `api.forShop`), and
|
|
13
|
+
* are then held to accessControl/permissions.ib.ts and the store as the API holds them (packages/apps/src/access.ts).
|
|
14
|
+
* Webhook entries' `filter`s are applied as Shopify applies them, and `queueSchedules` queues what settings.ib.ts's
|
|
15
|
+
* schedules owe in a window of time. Computed fields are worked out as records.ts's SQL works them out. Not covered:
|
|
16
|
+
* relationship fields other than belongsTo, except as the hasMany a computed field aggregates over.
|
|
14
17
|
*
|
|
15
18
|
* File fields keep their files in memory: `base64` reads back as a `data:` URL, `copyURL` as the URL itself (not
|
|
16
19
|
* fetched, size 0), and `upload`/`createUpload` tokens as the upload (a `createUpload` needs no PUT here).
|
|
17
20
|
*/
|
|
18
|
-
import { ApiError, type ActionModule, type Api, type AppRecord, type AppSettings, type Job, type LogLine, type ModelSchema, type SyncRun } from "./index.js";
|
|
21
|
+
import { ApiError, type ActionModule, type Api, type AppPermissions, type AppRecord, type AppSettings, type CallerSession, type ScheduleSetting, type Job, type LogLine, type ModelSchema, type SyncRun } from "./index.js";
|
|
19
22
|
type Embed = (model: string, input: string[]) => Promise<number[][]>;
|
|
20
23
|
/** The store a test app installs on and runs as, unless a test names another. */
|
|
21
24
|
export declare const TEST_SHOP = "test-shop.myshopify.com";
|
|
@@ -170,14 +173,34 @@ export declare const fixtures: {
|
|
|
170
173
|
shop_domain: string;
|
|
171
174
|
};
|
|
172
175
|
};
|
|
176
|
+
type When = Date | string | number;
|
|
177
|
+
/**
|
|
178
|
+
* When a schedule (settings.ib.ts's entry, or a cron) runs next after `after` (now unless named), as ISO times, as
|
|
179
|
+
* Inference Bureau works them out: in its timezone (UTC unless named), minutes a DST change skips not occurring.
|
|
180
|
+
*/
|
|
181
|
+
export declare function nextRuns(schedule: ScheduleSetting | string, o?: {
|
|
182
|
+
after?: When;
|
|
183
|
+
count?: number;
|
|
184
|
+
timezone?: string;
|
|
185
|
+
}): string[];
|
|
186
|
+
/**
|
|
187
|
+
* Whether Shopify delivers a payload to a webhook entry with this `filter`, in Shopify's search syntax:
|
|
188
|
+
* `field:value` (case-sensitive), `field:>=10`, `field:*` (has a value), `field:Prefix*`, dot paths into nested fields
|
|
189
|
+
* (any element of a list), AND (or just a space), OR, NOT or a leading `-`, and parentheses. Throws on a filter
|
|
190
|
+
* Shopify would refuse to subscribe with.
|
|
191
|
+
*/
|
|
192
|
+
export declare function matchesWebhookFilter(filter: string, payload: Record<string, unknown>): boolean;
|
|
173
193
|
export type ActionModules = Record<string, ActionModule | (() => Promise<ActionModule>)>;
|
|
174
194
|
export interface TestAppOptions {
|
|
175
195
|
/** Each model's `schema` (from its schema.ib.ts), by model name. */
|
|
176
196
|
models?: Record<string, ModelSchema>;
|
|
177
197
|
/** Action modules (or loaders) by `<model>/<action>`, and `$global/<action>` for global ones. */
|
|
178
198
|
actions?: ActionModules;
|
|
179
|
-
/** settings.ib.ts's `settings`: which webhooks run which actions. */
|
|
199
|
+
/** settings.ib.ts's `settings`: which webhooks and schedules run which actions. */
|
|
180
200
|
settings?: AppSettings;
|
|
201
|
+
/** accessControl/permissions.ib.ts's `permissions`: what each role may read and run. */
|
|
202
|
+
permissions?: AppPermissions;
|
|
203
|
+
/** Which schedules run (production only, unless one names development). */
|
|
181
204
|
environment?: "development" | "production";
|
|
182
205
|
/** The clock records are stamped with. */
|
|
183
206
|
now?: () => number;
|
|
@@ -191,6 +214,15 @@ export interface RunOptions {
|
|
|
191
214
|
params?: Record<string, unknown>;
|
|
192
215
|
shop?: string;
|
|
193
216
|
}
|
|
217
|
+
/**
|
|
218
|
+
* Who a call is for: a role in permissions.ib.ts and the caller's session (what `{ $session: … }` in a grant's filter
|
|
219
|
+
* stands for), and the store it's held to. Staff in the store's admin are `shopify-app-users` for their store; a
|
|
220
|
+
* signed-in storefront customer is `storefront-customers` with their `customerId` (and `customerRecordId`).
|
|
221
|
+
*/
|
|
222
|
+
export interface TestCaller extends CallerSession {
|
|
223
|
+
role?: string;
|
|
224
|
+
shop?: string;
|
|
225
|
+
}
|
|
194
226
|
export interface TestRun {
|
|
195
227
|
/** `<model>.<action>`, or the global action's name. */
|
|
196
228
|
action: string;
|
|
@@ -217,6 +249,12 @@ export interface TestApp {
|
|
|
217
249
|
seed(model: string, values: Record<string, unknown>): Promise<AppRecord>;
|
|
218
250
|
/** Runs an action (`<model>.<action>` or a global one's name) as a call through the API would. */
|
|
219
251
|
run(action: string, o?: RunOptions): Promise<TestRun>;
|
|
252
|
+
/**
|
|
253
|
+
* Runs an action as a call for `caller` would: refused (403 policy_denied) unless permissions.ib.ts grants the role
|
|
254
|
+
* the action, answered as missing (404) when the grant's filter or the store doesn't reach the record, and with
|
|
255
|
+
* `caller` set in the action. `app.api.forShop(shop).asRole(role, session)` holds record calls the same way.
|
|
256
|
+
*/
|
|
257
|
+
runAs(caller: TestCaller, action: string, o?: RunOptions): Promise<TestRun>;
|
|
220
258
|
/** A model's records, oldest first. */
|
|
221
259
|
records(model: string): AppRecord[];
|
|
222
260
|
/** A store installs the app: the shopifyShop model's install (or reinstall) runs, as on a real install. */
|
|
@@ -226,7 +264,8 @@ export interface TestApp {
|
|
|
226
264
|
uninstall(shop?: string): Promise<AppRecord | null>;
|
|
227
265
|
/**
|
|
228
266
|
* A Shopify webhook arrives from `shop` (TEST_SHOP unless named): synced Shopify models are written (and their
|
|
229
|
-
* create, update or delete actions run), and the actions settings.ib.ts names for the topic run with the payload
|
|
267
|
+
* create, update or delete actions run), and the actions settings.ib.ts names for the topic run with the payload,
|
|
268
|
+
* those whose `filter` it matches (see matchesWebhookFilter), trimmed to their `includeFields`.
|
|
230
269
|
*/
|
|
231
270
|
webhook(topic: string, payload: Record<string, unknown>, o?: {
|
|
232
271
|
shop?: string;
|
|
@@ -237,6 +276,16 @@ export interface TestApp {
|
|
|
237
276
|
syncRuns: SyncRun[];
|
|
238
277
|
/** Runs every queued job once (and the ones they queue), whatever its delay. A failed job stays queued while it has tries left. */
|
|
239
278
|
runJobs(): Promise<Job[]>;
|
|
279
|
+
/**
|
|
280
|
+
* Queues what settings.ib.ts's schedules owe between `from` and `to` (now unless named): a job for each time a
|
|
281
|
+
* schedule's cron matched, in its timezone, with `params.scheduledAt`, each time once however often it's asked.
|
|
282
|
+
* Only schedules that run in the test app's environment (production unless one names development). Run them with
|
|
283
|
+
* `runJobs()`.
|
|
284
|
+
*/
|
|
285
|
+
queueSchedules(window: {
|
|
286
|
+
from: Date | string | number;
|
|
287
|
+
to?: Date | string | number;
|
|
288
|
+
}): Promise<Job[]>;
|
|
240
289
|
shopify: ShopifyMock;
|
|
241
290
|
/** Everything every action logged, in order. */
|
|
242
291
|
logs: (LogLine & {
|
|
@@ -248,7 +297,7 @@ export interface TestApp {
|
|
|
248
297
|
export declare function createTestApp(o?: TestAppOptions): TestApp;
|
|
249
298
|
/**
|
|
250
299
|
* A TestApp from an app's folder (the working directory unless named): every model's schema.ib.ts, every action
|
|
251
|
-
* file (loaded when first run, as a deployment does) and
|
|
300
|
+
* file (loaded when first run, as a deployment does), settings.ib.ts and accessControl/permissions.ib.ts. Runs under Vitest (`ib-apps test`), with
|
|
252
301
|
* this package inlined (`server.deps.inline`, as new apps' vitest.config.ts has it) so it can load TypeScript.
|
|
253
302
|
*/
|
|
254
303
|
export declare function loadApp(dir?: string, o?: Omit<TestAppOptions, "models" | "actions" | "settings">): Promise<TestApp>;
|