@inferencebureau/apps-sdk 0.6.0 → 0.8.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/dist/index.d.ts +61 -8
- package/dist/index.js +38 -6
- package/dist/runtime.d.ts +5 -3
- package/dist/runtime.js +48 -5
- package/dist/test.js +55 -15
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
* metadata files (`schema.ib.ts`, `permissions.ib.ts`, `settings.ib.ts`), the helpers an action's `run` uses
|
|
4
4
|
* (`applyParams`, `save`, `deleteRecord`), and `createClient`, the API for reading and writing the app's records.
|
|
5
5
|
*
|
|
6
|
-
* Actions run inside the app's own deployment (runtime.ts). Their writes to the action's record
|
|
7
|
-
* sent: when `run` returns, Inference Bureau applies them in one transaction,
|
|
6
|
+
* Actions run inside the app's own deployment (runtime.ts). Their writes to the action's record, and to records its
|
|
7
|
+
* `api` read or built, are collected, not sent: when `run` returns, Inference Bureau applies them in one transaction,
|
|
8
|
+
* then calls `onSuccess`. The code uses
|
|
8
9
|
* only fetch and Web Crypto, so it runs on any JavaScript runtime the app is hosted on.
|
|
9
10
|
*/
|
|
10
11
|
export type FieldType = "string" | "richText" | "email" | "url" | "color" | "number" | "dateTime" | "enum" | "boolean" | "roleList" | "json" | "vector" | "file" | "belongsTo" | "hasOne" | "hasMany" | "hasManyThrough" | "password" | "encryptedString" | "computed";
|
|
@@ -103,8 +104,26 @@ export interface AppSettings {
|
|
|
103
104
|
schedules?: ScheduleSetting[];
|
|
104
105
|
/** How the Shopify app installs, and the scopes it asks for later. */
|
|
105
106
|
shopify?: ShopifyInstallSettings;
|
|
107
|
+
/** Other sites' pages that may call the app's routes from the browser. */
|
|
108
|
+
cors?: CorsSetting;
|
|
106
109
|
[key: string]: unknown;
|
|
107
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* Which other sites' pages may call the app's routes from the browser. Inference Bureau answers for the app: it
|
|
113
|
+
* answers preflights itself and puts the CORS headers on every response, including the page shown while a development
|
|
114
|
+
* server wakes, so a route needs no OPTIONS handler. A route that sets its own `Access-Control-Allow-Origin` keeps it.
|
|
115
|
+
* Shopify's extensions (https://extensions.shopifycdn.com, where Sidekick tools run) are always allowed.
|
|
116
|
+
*/
|
|
117
|
+
export interface CorsSetting {
|
|
118
|
+
/** `https://shop.example.com`, `https://*.example.com` for its subdomains, `http://localhost:3000`, or `*`. */
|
|
119
|
+
origins?: string[];
|
|
120
|
+
/** The paths it covers, e.g. `/api/*` for everything under /api. Every path unless named. */
|
|
121
|
+
paths?: string[];
|
|
122
|
+
/** Send cookies along (`credentials: "include"`). Not with the origin `*`. */
|
|
123
|
+
credentials?: boolean;
|
|
124
|
+
/** Response headers the calling page may read besides the basic ones, e.g. `x-total-count`. */
|
|
125
|
+
exposeHeaders?: string[];
|
|
126
|
+
}
|
|
108
127
|
export interface ShopifyInstallSettings {
|
|
109
128
|
/**
|
|
110
129
|
* `managed` (the default): Shopify installs the app with the scopes from the dashboard, and the app's first load in
|
|
@@ -178,8 +197,8 @@ export interface RecordPage<T = AppRecord> {
|
|
|
178
197
|
}
|
|
179
198
|
/** A record being worked on in an action: its fields, plus what the action has asked to happen to it. */
|
|
180
199
|
export type ActionRecord = AppRecord;
|
|
181
|
-
/** Marks a plain object as the action's
|
|
182
|
-
export declare function trackRecord<T extends object>(record: T, model?: string | null): T;
|
|
200
|
+
/** Marks a plain object as a record `save` can write: the action's own (the runtime does this before `run`), or one its `api` read or built. */
|
|
201
|
+
export declare function trackRecord<T extends object>(record: T, model?: string | null, isNew?: boolean): T;
|
|
183
202
|
/** Copies the action's params onto the record: `params.<model>` when the caller nested them, else params themselves. */
|
|
184
203
|
export declare function applyParams(params: Record<string, unknown>, record: ActionRecord): void;
|
|
185
204
|
/** Saves the record when `run` returns, with everything else the action does to it, in one transaction. */
|
|
@@ -193,6 +212,26 @@ export declare function pendingWrite(record: ActionRecord, isNew: boolean): {
|
|
|
193
212
|
} | {
|
|
194
213
|
op: "delete";
|
|
195
214
|
} | null;
|
|
215
|
+
/** A write to a record other than the action's own, sent with it so all of them are made in one transaction. */
|
|
216
|
+
export type StagedWrite = {
|
|
217
|
+
model: string;
|
|
218
|
+
op: "create";
|
|
219
|
+
id: string;
|
|
220
|
+
values: Record<string, unknown>;
|
|
221
|
+
} | {
|
|
222
|
+
model: string;
|
|
223
|
+
op: "update";
|
|
224
|
+
id: string;
|
|
225
|
+
values: Record<string, unknown>;
|
|
226
|
+
} | {
|
|
227
|
+
model: string;
|
|
228
|
+
op: "delete";
|
|
229
|
+
id: string;
|
|
230
|
+
};
|
|
231
|
+
/** What `run` asked of the other records it was handed (read or built through its `api`), in the order it saved them. */
|
|
232
|
+
export declare function stagedWrites(records: Iterable<object>): StagedWrite[];
|
|
233
|
+
/** A new record's id, made here so other records can point at it before it's written. Inference Bureau's own form. */
|
|
234
|
+
export declare function newRecordId(): string;
|
|
196
235
|
export declare class ApiError extends Error {
|
|
197
236
|
readonly status: number;
|
|
198
237
|
readonly code: string | null;
|
|
@@ -253,9 +292,15 @@ export interface ModelClient {
|
|
|
253
292
|
search(field: string, near: string | number[], o?: Omit<FindManyOptions, "sort" | "search">): Promise<RecordPage<AppRecord & {
|
|
254
293
|
_distance: number;
|
|
255
294
|
}>>;
|
|
295
|
+
/** Writes at once. In an action, that's outside its transaction: to write with the run, `build` and `save` instead. */
|
|
256
296
|
create(values: Record<string, unknown>): Promise<AppRecord>;
|
|
257
297
|
update(id: string, values: Record<string, unknown>): Promise<AppRecord>;
|
|
258
298
|
delete(id: string): Promise<void>;
|
|
299
|
+
/**
|
|
300
|
+
* A new record for an action's `run` to `save()`, written with the action's own record in one transaction. It has
|
|
301
|
+
* its id already, so other records can point at it. Only an action's `api` builds records.
|
|
302
|
+
*/
|
|
303
|
+
build(values?: Record<string, unknown>): AppRecord;
|
|
259
304
|
/**
|
|
260
305
|
* Whether `password` is the one stored in the record's password field (`password` unless named). Hashes are never
|
|
261
306
|
* returned. Failures are counted per `email` (the record without one) and per visitor `ip`; past the limit it throws
|
|
@@ -297,7 +342,8 @@ export type Api = {
|
|
|
297
342
|
}>;
|
|
298
343
|
/**
|
|
299
344
|
* Queues an action as a background job and returns at once: a global action's name, or `<model>.<action>` (with
|
|
300
|
-
* `id` for the record). It gets up to
|
|
345
|
+
* `id` for the record). It gets five minutes unless the action's `timeoutMS` says (up to 15), and is retried when
|
|
346
|
+
* it fails.
|
|
301
347
|
*/
|
|
302
348
|
enqueue(action: string, params?: Record<string, unknown>, options?: EnqueueOptions): Promise<Job>;
|
|
303
349
|
/**
|
|
@@ -395,7 +441,7 @@ export interface EnqueueOptions {
|
|
|
395
441
|
export interface Job {
|
|
396
442
|
id: string;
|
|
397
443
|
action: string;
|
|
398
|
-
state: "queued" | "running" | "succeeded" | "failed" | "canceled";
|
|
444
|
+
state: "queued" | "running" | "canceling" | "succeeded" | "failed" | "canceled";
|
|
399
445
|
run_at: string;
|
|
400
446
|
attempts: number;
|
|
401
447
|
max_attempts: number;
|
|
@@ -762,7 +808,11 @@ export interface ActionContext {
|
|
|
762
808
|
params: Record<string, unknown>;
|
|
763
809
|
/** The record the action works on: the stored one, or a new, empty one for a create. Null in a global action. */
|
|
764
810
|
record: ActionRecord;
|
|
765
|
-
/**
|
|
811
|
+
/**
|
|
812
|
+
* The app's API, as the environment. Records it reads, and ones `build` makes, are written with the action's own when
|
|
813
|
+
* `run` calls `save()` (or `deleteRecord()`) on them, all in one transaction. Its `create`, `update` and `delete`
|
|
814
|
+
* write at once, outside it.
|
|
815
|
+
*/
|
|
766
816
|
api: Api;
|
|
767
817
|
/** Lines written here appear on the action's run in Logs. */
|
|
768
818
|
logger: Logger;
|
|
@@ -800,7 +850,10 @@ export interface ActionOptions {
|
|
|
800
850
|
actionType?: "create" | "update" | "delete" | "custom";
|
|
801
851
|
/** Whether what `run` returns goes back to the caller (it's dropped otherwise). */
|
|
802
852
|
returnType?: boolean;
|
|
803
|
-
/**
|
|
853
|
+
/**
|
|
854
|
+
* How long `run` and `onSuccess` may take together: at most 15 minutes. Unless it says, 30 seconds when called and 5
|
|
855
|
+
* minutes as a background job.
|
|
856
|
+
*/
|
|
804
857
|
timeoutMS?: number;
|
|
805
858
|
}
|
|
806
859
|
export interface ActionModule {
|
package/dist/index.js
CHANGED
|
@@ -3,21 +3,24 @@
|
|
|
3
3
|
* metadata files (`schema.ib.ts`, `permissions.ib.ts`, `settings.ib.ts`), the helpers an action's `run` uses
|
|
4
4
|
* (`applyParams`, `save`, `deleteRecord`), and `createClient`, the API for reading and writing the app's records.
|
|
5
5
|
*
|
|
6
|
-
* Actions run inside the app's own deployment (runtime.ts). Their writes to the action's record
|
|
7
|
-
* sent: when `run` returns, Inference Bureau applies them in one transaction,
|
|
6
|
+
* Actions run inside the app's own deployment (runtime.ts). Their writes to the action's record, and to records its
|
|
7
|
+
* `api` read or built, are collected, not sent: when `run` returns, Inference Bureau applies them in one transaction,
|
|
8
|
+
* then calls `onSuccess`. The code uses
|
|
8
9
|
* only fetch and Web Crypto, so it runs on any JavaScript runtime the app is hosted on.
|
|
9
10
|
*/
|
|
10
11
|
/** Shared by every copy of this module that loads, so `save` works whichever copy an action imported. */
|
|
11
12
|
const STATE = Symbol.for("inferencebureau.apps.record");
|
|
12
|
-
/**
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
/** The order records were saved in, across copies too: they're written in that order. */
|
|
14
|
+
const SEQ = (globalThis[Symbol.for("inferencebureau.apps.seq")] ??= { n: 0 });
|
|
15
|
+
/** Marks a plain object as a record `save` can write: the action's own (the runtime does this before `run`), or one its `api` read or built. */
|
|
16
|
+
export function trackRecord(record, model = null, isNew = false) {
|
|
17
|
+
Object.defineProperty(record, STATE, { value: { original: JSON.stringify(record), model, isNew, save: false, delete: false, seq: 0 }, enumerable: false, configurable: true });
|
|
15
18
|
return record;
|
|
16
19
|
}
|
|
17
20
|
function stateOf(record) {
|
|
18
21
|
const s = record[STATE];
|
|
19
22
|
if (!s)
|
|
20
|
-
throw new Error("save() and deleteRecord() take the record
|
|
23
|
+
throw new Error("save() and deleteRecord() take the action's record, or one its api read or built.");
|
|
21
24
|
return s;
|
|
22
25
|
}
|
|
23
26
|
/** Copies the action's params onto the record: `params.<model>` when the caller nested them, else params themselves. */
|
|
@@ -33,12 +36,14 @@ export async function save(record) {
|
|
|
33
36
|
const s = stateOf(record);
|
|
34
37
|
s.save = true;
|
|
35
38
|
s.delete = false;
|
|
39
|
+
s.seq = ++SEQ.n;
|
|
36
40
|
}
|
|
37
41
|
/** Deletes the record when `run` returns. */
|
|
38
42
|
export async function deleteRecord(record) {
|
|
39
43
|
const s = stateOf(record);
|
|
40
44
|
s.delete = true;
|
|
41
45
|
s.save = false;
|
|
46
|
+
s.seq = ++SEQ.n;
|
|
42
47
|
}
|
|
43
48
|
/** What `run` asked for: the changed fields to save (all set fields for a new record), a delete, or nothing. */
|
|
44
49
|
export function pendingWrite(record, isNew) {
|
|
@@ -57,6 +62,32 @@ export function pendingWrite(record, isNew) {
|
|
|
57
62
|
}
|
|
58
63
|
return { op: "save", values };
|
|
59
64
|
}
|
|
65
|
+
/** What `run` asked of the other records it was handed (read or built through its `api`), in the order it saved them. */
|
|
66
|
+
export function stagedWrites(records) {
|
|
67
|
+
const out = [];
|
|
68
|
+
for (const record of new Set(records)) {
|
|
69
|
+
const s = record[STATE];
|
|
70
|
+
const id = record.id;
|
|
71
|
+
if (!s?.model || typeof id !== "string" || (!s.save && !s.delete))
|
|
72
|
+
continue;
|
|
73
|
+
if (s.delete) {
|
|
74
|
+
if (!s.isNew)
|
|
75
|
+
out.push({ seq: s.seq, write: { model: s.model, op: "delete", id } });
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const w = pendingWrite(record, s.isNew);
|
|
79
|
+
if (w?.op !== "save" || (!s.isNew && !Object.keys(w.values).length))
|
|
80
|
+
continue;
|
|
81
|
+
out.push({ seq: s.seq, write: { model: s.model, op: s.isNew ? "create" : "update", id, values: w.values } });
|
|
82
|
+
}
|
|
83
|
+
return out.sort((a, b) => a.seq - b.seq).map((x) => x.write);
|
|
84
|
+
}
|
|
85
|
+
const ID_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
86
|
+
/** A new record's id, made here so other records can point at it before it's written. Inference Bureau's own form. */
|
|
87
|
+
export function newRecordId() {
|
|
88
|
+
const bytes = crypto.getRandomValues(new Uint8Array(20));
|
|
89
|
+
return `rec_${Date.now().toString(36)}${Array.from(bytes, (b) => ID_CHARS[b % 36]).join("")}`;
|
|
90
|
+
}
|
|
60
91
|
// ---- the API ----
|
|
61
92
|
export class ApiError extends Error {
|
|
62
93
|
status;
|
|
@@ -120,6 +151,7 @@ export function createClient(o = {}) {
|
|
|
120
151
|
create: (values) => call("POST", `${m}/records`, values),
|
|
121
152
|
update: (id, values) => call("PATCH", `${m}/records/${encodeURIComponent(id)}`, values),
|
|
122
153
|
delete: (id) => call("DELETE", `${m}/records/${encodeURIComponent(id)}`),
|
|
154
|
+
build: () => { throw new Error("build() makes a record for an action's run to save(); outside an action, use create()."); },
|
|
123
155
|
checkPassword: async (id, password, field) => {
|
|
124
156
|
const o = typeof field === "string" ? { field } : field ?? {};
|
|
125
157
|
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;
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Runs an app's actions inside its own deployment. Inference Bureau calls the app's `/_ib/actions` route (added to
|
|
3
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
|
|
5
|
-
* applies
|
|
4
|
+
* signature, runs the action file, and answers with what `run` asked to happen to the record, and to the records its
|
|
5
|
+
* `api` read or built. Inference Bureau applies all of it in one transaction, then calls again for `onSuccess` with
|
|
6
|
+
* the saved record.
|
|
6
7
|
*/
|
|
7
|
-
import { type ActionCaller, type ActionModule, type Api, type AppRecord, type LogLine, type ShopifyClient } from "./index.js";
|
|
8
|
+
import { type ActionCaller, type ActionModule, type Api, type AppRecord, type LogLine, type ShopifyClient, type StagedWrite } from "./index.js";
|
|
8
9
|
/** Action modules by key: `<model>/<action>` for model actions, `$global/<action>` for global ones. */
|
|
9
10
|
export type ActionRegistry = Record<string, () => Promise<ActionModule>>;
|
|
10
11
|
export interface ActionRequest {
|
|
@@ -31,6 +32,7 @@ export type ActionResponse = {
|
|
|
31
32
|
} | {
|
|
32
33
|
op: "delete";
|
|
33
34
|
} | null;
|
|
35
|
+
writes?: StagedWrite[];
|
|
34
36
|
result?: unknown;
|
|
35
37
|
logs: LogLine[];
|
|
36
38
|
} | {
|
package/dist/runtime.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Runs an app's actions inside its own deployment. Inference Bureau calls the app's `/_ib/actions` route (added to
|
|
3
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
|
|
5
|
-
* applies
|
|
4
|
+
* signature, runs the action file, and answers with what `run` asked to happen to the record, and to the records its
|
|
5
|
+
* `api` read or built. Inference Bureau applies all of it in one transaction, then calls again for `onSuccess` with
|
|
6
|
+
* the saved record.
|
|
6
7
|
*/
|
|
7
|
-
import { createClient, createShopifyClient, pendingWrite, trackRecord } from "./index.js";
|
|
8
|
+
import { createClient, createShopifyClient, newRecordId, pendingWrite, stagedWrites, trackRecord } from "./index.js";
|
|
8
9
|
const SKEW_MS = 5 * 60_000;
|
|
9
10
|
const encoder = new TextEncoder();
|
|
10
11
|
const envVar = (name) => globalThis.process?.env?.[name];
|
|
@@ -32,6 +33,42 @@ function collector(lines, echo) {
|
|
|
32
33
|
}
|
|
33
34
|
/** An action's `api`: its run's store's records only, when the run is for a store (`createClient()` reaches every store). */
|
|
34
35
|
const scopedApi = (api, shop) => (shop && typeof api.forShop === "function" ? api.forShop(shop) : api);
|
|
36
|
+
const SYSTEM_FIELDS = new Set(["id", "createdAt", "updatedAt"]);
|
|
37
|
+
/**
|
|
38
|
+
* The action's `api`, handing out records `save()` can write with the run: each one it reads, and each one `build`
|
|
39
|
+
* makes, is tracked and kept in `handed`, and what `run` asked of them goes back with its own record's write.
|
|
40
|
+
*/
|
|
41
|
+
function stagingApi(api, handed) {
|
|
42
|
+
const models = new Map();
|
|
43
|
+
const keep = (model, r) => { if (r)
|
|
44
|
+
handed.push(trackRecord(r, model)); return r; };
|
|
45
|
+
const page = (model, p) => { for (const r of p.records)
|
|
46
|
+
keep(model, r); return p; };
|
|
47
|
+
const wrap = (name, m) => ({
|
|
48
|
+
...m,
|
|
49
|
+
findOne: async (id) => keep(name, await m.findOne(id)),
|
|
50
|
+
findFirst: async (o) => keep(name, await m.findFirst(o)),
|
|
51
|
+
findMany: async (o) => page(name, await m.findMany(o)),
|
|
52
|
+
search: async (field, near, o) => page(name, await m.search(field, near, o)),
|
|
53
|
+
build(values = {}) {
|
|
54
|
+
const r = trackRecord({ id: newRecordId(), ...Object.fromEntries(Object.entries(values).filter(([k]) => !SYSTEM_FIELDS.has(k))) }, name, true);
|
|
55
|
+
handed.push(r);
|
|
56
|
+
return r;
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
return new Proxy(api, {
|
|
60
|
+
get(target, prop, receiver) {
|
|
61
|
+
const v = Reflect.get(target, prop, receiver);
|
|
62
|
+
if (prop === "forShop" || prop === "asRole")
|
|
63
|
+
return (...args) => stagingApi(v.apply(target, args), handed);
|
|
64
|
+
if (typeof prop !== "string" || prop.startsWith("$") || prop === "then" || prop === "enqueue" || prop === "shopifySync" || !v || typeof v !== "object")
|
|
65
|
+
return v;
|
|
66
|
+
if (!models.has(prop))
|
|
67
|
+
models.set(prop, wrap(prop, v));
|
|
68
|
+
return models.get(prop);
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
}
|
|
35
72
|
/**
|
|
36
73
|
* Runs one phase of an action, without checking where the request came from (handleAction does). `api` and
|
|
37
74
|
* `shopify` stand in for the environment's clients (the test app's in-memory ones); `echo: false` keeps the logger's
|
|
@@ -46,20 +83,26 @@ export async function runAction(req, registry, o = {}) {
|
|
|
46
83
|
throw new Error(`The deployment has no action ${key}. Deploy again if it was added since.`);
|
|
47
84
|
const mod = await load();
|
|
48
85
|
const record = req.record ? trackRecord({ ...req.record }, req.model) : null;
|
|
86
|
+
const handed = [];
|
|
87
|
+
const logger = collector(logs, o.echo ?? true);
|
|
49
88
|
const ctx = {
|
|
50
|
-
params: req.params ?? {}, record, api: scopedApi(o.api ?? createClient(o.token ? { token: o.token } : {}), req.shop),
|
|
89
|
+
params: req.params ?? {}, record, api: stagingApi(scopedApi(o.api ?? createClient(o.token ? { token: o.token } : {}), req.shop), handed), logger,
|
|
51
90
|
model: req.model, action: req.action, environment: req.environment, signal: o.signal ?? new AbortController().signal,
|
|
52
91
|
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
92
|
};
|
|
54
93
|
if (req.phase === "onSuccess") {
|
|
55
94
|
await mod.onSuccess?.(ctx);
|
|
95
|
+
if (stagedWrites(handed).length || (record && pendingWrite(record, false))) {
|
|
96
|
+
logger.warn("save() and deleteRecord() write nothing in onSuccess: the run's changes have already committed. Use api.<model>.update() here, or save in run.");
|
|
97
|
+
}
|
|
56
98
|
return { ok: true, write: null, logs };
|
|
57
99
|
}
|
|
58
100
|
if (typeof mod.run !== "function")
|
|
59
101
|
throw new Error(`${key} doesn't export a run function.`);
|
|
60
102
|
const result = await mod.run(ctx);
|
|
61
103
|
const write = record ? pendingWrite(record, req.isNew) : null;
|
|
62
|
-
|
|
104
|
+
const writes = stagedWrites(handed);
|
|
105
|
+
return { ok: true, write, ...(writes.length ? { writes } : {}), ...(mod.options?.returnType && result !== undefined ? { result } : {}), logs };
|
|
63
106
|
}
|
|
64
107
|
catch (e) {
|
|
65
108
|
const err = e instanceof Error ? e : new Error(String(e));
|
package/dist/test.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
* File fields keep their files in memory: `base64` reads back as a `data:` URL, `copyURL` as the URL itself (not
|
|
19
19
|
* fetched, size 0), and `upload`/`createUpload` tokens as the upload (a `createUpload` needs no PUT here).
|
|
20
20
|
*/
|
|
21
|
-
import { ApiError, ShopifyError } from "./index.js";
|
|
21
|
+
import { ApiError, ShopifyError, newRecordId } from "./index.js";
|
|
22
22
|
import { runAction as runPhase } from "./runtime.js";
|
|
23
23
|
/** Kept in `data`; the rest are a vector, the other side of a relationship, or worked out (computed). */
|
|
24
24
|
const STORED = new Set(["string", "richText", "email", "url", "color", "number", "dateTime", "enum", "boolean", "roleList", "json", "belongsTo", "password", "encryptedString", "file"]);
|
|
@@ -521,6 +521,11 @@ class Records {
|
|
|
521
521
|
return this.rows.get(m.name);
|
|
522
522
|
}
|
|
523
523
|
clear() { this.rows.clear(); }
|
|
524
|
+
/** The records as they are, for putting back when a run's writes don't all go through (they're made together). */
|
|
525
|
+
snapshot() {
|
|
526
|
+
return new Map([...this.rows].map(([m, t]) => [m, new Map([...t].map(([id, r]) => [id, { ...r, vectors: new Map(r.vectors) }]))]));
|
|
527
|
+
}
|
|
528
|
+
restore(rows) { this.rows = rows; }
|
|
524
529
|
present(m, row, vectors) {
|
|
525
530
|
const out = { id: row.id, createdAt: row.createdAt, updatedAt: row.updatedAt };
|
|
526
531
|
for (const f of m.fields) {
|
|
@@ -1059,11 +1064,14 @@ class Records {
|
|
|
1059
1064
|
this.last = t;
|
|
1060
1065
|
return new Date(t).toISOString();
|
|
1061
1066
|
}
|
|
1062
|
-
|
|
1067
|
+
/** `id` is one an action's run made for the record (`build`, or its own new record), so others could point at it. */
|
|
1068
|
+
async create(model, values, id) {
|
|
1063
1069
|
const m = this.model(model);
|
|
1070
|
+
if (id !== undefined && (!/^rec_[0-9a-z]{20,40}$/.test(id) || this.table(m).has(id)))
|
|
1071
|
+
throw invalid([{ field: "id", message: this.table(m).has(id) ? `${id} is already a record` : `${id} isn't a record id` }]);
|
|
1064
1072
|
const p = this.prepare(m, values, null);
|
|
1065
1073
|
const at = this.stamp();
|
|
1066
|
-
const row = { id: `rec_${String(++this.seq).padStart(6, "0")}`, createdAt: at, updatedAt: at, data: p.data, vectors: new Map() };
|
|
1074
|
+
const row = { id: id ?? `rec_${String(++this.seq).padStart(6, "0")}`, createdAt: at, updatedAt: at, data: p.data, vectors: new Map() };
|
|
1067
1075
|
await this.vectorize(m, row, p.vectors, null);
|
|
1068
1076
|
this.table(m).set(row.id, row);
|
|
1069
1077
|
return this.present(m, row, true);
|
|
@@ -1679,10 +1687,13 @@ const filterFields = (node) => "all" in node ? node.all.flatMap(filterFields) :
|
|
|
1679
1687
|
export function matchesWebhookFilter(filter, payload) {
|
|
1680
1688
|
return holds(parseWebhookFilter(filter), payload);
|
|
1681
1689
|
}
|
|
1682
|
-
/**
|
|
1683
|
-
const
|
|
1690
|
+
/** How long an action may take, run and onSuccess together: 15 minutes at most; 30 seconds unless it says, five minutes as a background job. */
|
|
1691
|
+
const MAX_TIMEOUT_MS = 900_000;
|
|
1684
1692
|
const DEFAULT_CALL_TIMEOUT_MS = 30_000;
|
|
1685
1693
|
const JOB_TIMEOUT_MS = 300_000;
|
|
1694
|
+
const ON_SUCCESS_MIN_MS = 1_000;
|
|
1695
|
+
/** The most other records one run may write with its own. */
|
|
1696
|
+
const MAX_RUN_WRITES = 500;
|
|
1686
1697
|
/** An action's `run` threw: nothing it asked for was applied. The API answers the same 422. */
|
|
1687
1698
|
export class ActionFailedError extends ApiError {
|
|
1688
1699
|
logs;
|
|
@@ -1724,8 +1735,9 @@ export function createTestApp(o = {}) {
|
|
|
1724
1735
|
let record = null;
|
|
1725
1736
|
if (model) {
|
|
1726
1737
|
store.model(model);
|
|
1738
|
+
// A new record has its id from the start, so records `run` builds can point at it.
|
|
1727
1739
|
if (type === "create")
|
|
1728
|
-
record = {};
|
|
1740
|
+
record = { id: newRecordId() };
|
|
1729
1741
|
else {
|
|
1730
1742
|
if (!input.id)
|
|
1731
1743
|
throw new ApiError(`${name} works on a record: pass its id.`, 400, "invalid_request");
|
|
@@ -1736,11 +1748,13 @@ export function createTestApp(o = {}) {
|
|
|
1736
1748
|
}
|
|
1737
1749
|
const params = wire(input.params ?? {});
|
|
1738
1750
|
const shop = input.shop ?? null;
|
|
1739
|
-
const max = how.background ? JOB_TIMEOUT_MS : CALL_TIMEOUT_MS;
|
|
1740
1751
|
const given = mod.options?.timeoutMS;
|
|
1741
|
-
const
|
|
1752
|
+
const total = Math.min(MAX_TIMEOUT_MS, Math.max(1000, typeof given === "number" ? given : how.background ? JOB_TIMEOUT_MS : DEFAULT_CALL_TIMEOUT_MS));
|
|
1753
|
+
const started = Date.now();
|
|
1742
1754
|
// A phase that runs out of time is answered as the API answers it; the run itself is left to finish unheard.
|
|
1755
|
+
// onSuccess gets what run left of the time, and at least a second.
|
|
1743
1756
|
const phase = async (p, rec, isNew) => {
|
|
1757
|
+
const timeout = p === "run" ? total : Math.max(ON_SUCCESS_MIN_MS, total - (Date.now() - started));
|
|
1744
1758
|
let timer;
|
|
1745
1759
|
const late = new Promise((_, reject) => {
|
|
1746
1760
|
timer = setTimeout(() => reject(new ApiError(`The action took longer than ${Math.round(timeout / 1000)} seconds.`, 503, "dependency_unavailable")), timeout);
|
|
@@ -1759,15 +1773,40 @@ export function createTestApp(o = {}) {
|
|
|
1759
1773
|
keep(reply.logs);
|
|
1760
1774
|
if (!reply.ok)
|
|
1761
1775
|
throw new ActionFailedError(`${name} failed: ${reply.error.message}`, reply.logs, reply.error.stack);
|
|
1776
|
+
// The record's write, then the others run saved, in order: all of them, or none when one is refused.
|
|
1762
1777
|
let saved = record;
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1778
|
+
const others = reply.writes ?? [];
|
|
1779
|
+
if (others.length > MAX_RUN_WRITES)
|
|
1780
|
+
throw new ApiError(`A run can write at most ${MAX_RUN_WRITES} other records with its own; it wrote ${others.length}. Queue the rest as jobs.`, 400, "invalid_request");
|
|
1781
|
+
const before = store.snapshot();
|
|
1782
|
+
try {
|
|
1783
|
+
if (model && reply.write) {
|
|
1784
|
+
if (reply.write.op === "delete") {
|
|
1785
|
+
if (input.id)
|
|
1786
|
+
store.delete(model, input.id);
|
|
1787
|
+
saved = null;
|
|
1788
|
+
}
|
|
1789
|
+
else
|
|
1790
|
+
saved = type === "create" ? await store.create(model, reply.write.values, String(record.id)) : await store.update(model, input.id, reply.write.values);
|
|
1768
1791
|
}
|
|
1769
|
-
|
|
1770
|
-
|
|
1792
|
+
for (const w of others) {
|
|
1793
|
+
const m = store.model(w.model);
|
|
1794
|
+
// A run about one store writes that store's records of a store-owned model, as through the API.
|
|
1795
|
+
const f = shop ? storeField(m) : null;
|
|
1796
|
+
const own = { shop, role: null, session: { userId: null, customerId: null, customerRecordId: null } };
|
|
1797
|
+
if (w.op !== "create" && f && !(await findVisible(m.name, w.id, { [f]: { equals: shop } })))
|
|
1798
|
+
throw notFound(`There's no ${m.name} with id ${w.id}.`);
|
|
1799
|
+
if (w.op === "delete")
|
|
1800
|
+
store.delete(m.name, w.id);
|
|
1801
|
+
else if (w.op === "update")
|
|
1802
|
+
await store.update(m.name, w.id, f ? scopedUpdate(own, m, wire(w.values)) : wire(w.values));
|
|
1803
|
+
else
|
|
1804
|
+
await store.create(m.name, f ? scopedValues(own, m, wire(w.values)) : wire(w.values), w.id);
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
catch (e) {
|
|
1808
|
+
store.restore(before);
|
|
1809
|
+
throw e;
|
|
1771
1810
|
}
|
|
1772
1811
|
const after = await phase("onSuccess", saved ?? record, false).catch((e) => ({ ok: false, error: { message: e.message }, logs: [] }));
|
|
1773
1812
|
keep(after.logs);
|
|
@@ -1817,6 +1856,7 @@ export function createTestApp(o = {}) {
|
|
|
1817
1856
|
}
|
|
1818
1857
|
};
|
|
1819
1858
|
return {
|
|
1859
|
+
build: () => { throw new Error("build() makes a record for an action's run to save(); outside an action, use create()."); },
|
|
1820
1860
|
findOne: async (id) => findVisible(name, id, readOf()),
|
|
1821
1861
|
findMany: async (q = {}) => store.findMany(name, narrow(wire(q))),
|
|
1822
1862
|
findFirst: async (q = {}) => (await store.findMany(name, { ...narrow(wire(q)), first: 1 })).records[0] ?? null,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inferencebureau/apps-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types, the records API client and a test harness for its actions.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"keywords": [
|