@inferencebureau/apps-sdk 0.15.2 → 0.16.1
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 +67 -15
- package/dist/index.js +20 -15
- package/dist/runtime.d.ts +1 -0
- package/dist/test.d.ts +7 -1
- package/dist/test.js +95 -25
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -56,6 +56,13 @@ export interface FieldDef {
|
|
|
56
56
|
* record's webhook. A reference metafield goes in a belongsTo to the synced model it names, a list in a json field.
|
|
57
57
|
*/
|
|
58
58
|
metafield?: string;
|
|
59
|
+
/**
|
|
60
|
+
* On the same synced models: a GraphQL selection on the record's type that the field holds, `"seo { title }"` or
|
|
61
|
+
* `"variantsCount { count }"`, read when its metafields are (with `fetch: "onWebhook"`, on the record's webhook too)
|
|
62
|
+
* and checked against the app's API version. Objects of one field unwrap to their value, a list's item by item; a
|
|
63
|
+
* json field takes the rest as Shopify answers it. A list of connected records (`first:`) isn't read.
|
|
64
|
+
*/
|
|
65
|
+
shopify?: string;
|
|
59
66
|
/**
|
|
60
67
|
* Computed fields, worked out when a record is read: an expression over the record's own fields (`"price * quantity"`,
|
|
61
68
|
* `"concat(firstName, ' ', lastName)"`), or an aggregate over a hasMany's records. They filter and sort like stored ones.
|
|
@@ -557,18 +564,32 @@ export interface ActionRecord {
|
|
|
557
564
|
updatedAt: string;
|
|
558
565
|
[field: string]: any;
|
|
559
566
|
}
|
|
567
|
+
/** Options for `save`. */
|
|
568
|
+
export interface SaveOptions {
|
|
569
|
+
/**
|
|
570
|
+
* The record's `updatedAt` as it was read (`record.updatedAt`): the save is made only while that still stands, so a
|
|
571
|
+
* write that landed meanwhile isn't lost; otherwise the run fails with 409 `version_conflict` and nothing is written.
|
|
572
|
+
*/
|
|
573
|
+
ifUpdatedAt?: string;
|
|
574
|
+
}
|
|
575
|
+
/** A number field's value written as an increment: `{ hits: increment(1) }` adds to the stored value under the record's lock, so two at once both count. */
|
|
576
|
+
export interface Increment {
|
|
577
|
+
_increment: number;
|
|
578
|
+
}
|
|
579
|
+
export declare const increment: (by?: number) => Increment;
|
|
560
580
|
/** 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. */
|
|
561
581
|
export declare function trackRecord<T extends object>(record: T, model?: string | null, isNew?: boolean): T;
|
|
562
582
|
/** Copies the action's params onto the record: `params.<model>` when the caller nested them, else params themselves. */
|
|
563
583
|
export declare function applyParams(params: Record<string, unknown>, record: ActionRecord): void;
|
|
564
584
|
/** Saves the record when `run` returns, with everything else the action does to it, in one transaction. */
|
|
565
|
-
export declare function save(record: ActionRecord): Promise<void>;
|
|
585
|
+
export declare function save(record: ActionRecord, o?: SaveOptions): Promise<void>;
|
|
566
586
|
/** Deletes the record when `run` returns. */
|
|
567
587
|
export declare function deleteRecord(record: ActionRecord): Promise<void>;
|
|
568
588
|
/** What `run` asked for: the changed fields to save (all set fields for a new record), a delete, or nothing. */
|
|
569
589
|
export declare function pendingWrite(record: ActionRecord, isNew: boolean): {
|
|
570
590
|
op: "save";
|
|
571
591
|
values: Record<string, unknown>;
|
|
592
|
+
ifUpdatedAt?: string;
|
|
572
593
|
} | {
|
|
573
594
|
op: "delete";
|
|
574
595
|
} | null;
|
|
@@ -583,6 +604,7 @@ export type StagedWrite = {
|
|
|
583
604
|
op: "update";
|
|
584
605
|
id: string;
|
|
585
606
|
values: Record<string, unknown>;
|
|
607
|
+
ifUpdatedAt?: string;
|
|
586
608
|
} | {
|
|
587
609
|
model: string;
|
|
588
610
|
op: "delete";
|
|
@@ -680,6 +702,14 @@ export interface BulkDeleteResult {
|
|
|
680
702
|
}
|
|
681
703
|
/** The field (or fields) an upsert finds its record by: a stored field with a value in `values`, or `id`. */
|
|
682
704
|
export type UpsertOn<M extends ModelTypes = UntypedModel> = (keyof M["input"] & string) | "id";
|
|
705
|
+
/** A creating or running call's `Idempotency-Key`: a retry with the same key and body within a day answers the first call instead of running again. */
|
|
706
|
+
export interface IdempotentOptions {
|
|
707
|
+
idempotencyKey?: string;
|
|
708
|
+
}
|
|
709
|
+
/** An update's precondition: the record's `updatedAt` as it was read. */
|
|
710
|
+
export interface UpdateOptions {
|
|
711
|
+
ifUpdatedAt?: string;
|
|
712
|
+
}
|
|
683
713
|
export interface ModelClient<M extends ModelTypes = UntypedModel> {
|
|
684
714
|
/** The model's fields as the API describes them (ModelDescription): what AutoTable and AutoForm draw from. */
|
|
685
715
|
describe(): Promise<ModelDescription>;
|
|
@@ -696,9 +726,18 @@ export interface ModelClient<M extends ModelTypes = UntypedModel> {
|
|
|
696
726
|
search<S extends SelectOf<M> | undefined = undefined>(field: M["vectors"], near: string | number[], o?: Omit<FindManyOptions<M, S>, "sort" | "search">): Promise<RecordPage<ReadOf<M, S> & {
|
|
697
727
|
_distance: number;
|
|
698
728
|
}>>;
|
|
699
|
-
/**
|
|
700
|
-
|
|
701
|
-
|
|
729
|
+
/**
|
|
730
|
+
* Writes at once. In an action, that's outside its transaction: to write with the run, `build` and `save` instead.
|
|
731
|
+
* With an `idempotencyKey`, a retried call (the same key and values within a day) makes nothing twice: it answers
|
|
732
|
+
* the first call's record.
|
|
733
|
+
*/
|
|
734
|
+
create(values: M["input"], o?: IdempotentOptions): Promise<M["record"]>;
|
|
735
|
+
/**
|
|
736
|
+
* Changes the given fields. With `ifUpdatedAt` (the record's `updatedAt` as read), the update is made only while
|
|
737
|
+
* that still stands; otherwise it throws a 409 `version_conflict` ApiError, and nothing is written. A number field
|
|
738
|
+
* takes `increment(n)` to add to the stored value under the record's lock.
|
|
739
|
+
*/
|
|
740
|
+
update(id: string, values: M["input"], o?: UpdateOptions): Promise<M["record"]>;
|
|
702
741
|
delete(id: string): Promise<void>;
|
|
703
742
|
/**
|
|
704
743
|
* Updates the record whose `on` field (or fields) hold the values' values, or creates one when there's none, the
|
|
@@ -707,25 +746,27 @@ export interface ModelClient<M extends ModelTypes = UntypedModel> {
|
|
|
707
746
|
upsert(o: {
|
|
708
747
|
on: UpsertOn<M> | UpsertOn<M>[];
|
|
709
748
|
values: M["input"];
|
|
710
|
-
}): Promise<{
|
|
749
|
+
} & IdempotentOptions): Promise<{
|
|
711
750
|
record: M["record"];
|
|
712
751
|
created: boolean;
|
|
713
752
|
}>;
|
|
714
753
|
/**
|
|
715
754
|
* Up to 250 records in one call, each the way a single write goes (the model's action when it has one). Direct
|
|
716
755
|
* writes share one transaction, each rolled back alone when refused; the answer names which failed and why, and
|
|
717
|
-
* the rest are saved.
|
|
756
|
+
* the rest are saved. An update's `ifUpdatedAt` holds for that record alone: a changed one fails with
|
|
757
|
+
* `version_conflict` and the rest land. Each takes an `idempotencyKey` for the whole batch.
|
|
718
758
|
*/
|
|
719
|
-
bulkCreate(values: M["input"][]): Promise<BulkResult<M["record"]>>;
|
|
759
|
+
bulkCreate(values: M["input"][], o?: IdempotentOptions): Promise<BulkResult<M["record"]>>;
|
|
720
760
|
bulkUpdate(records: {
|
|
721
761
|
id: string;
|
|
722
762
|
values: M["input"];
|
|
723
|
-
|
|
724
|
-
|
|
763
|
+
ifUpdatedAt?: string;
|
|
764
|
+
}[], o?: IdempotentOptions): Promise<BulkResult<M["record"]>>;
|
|
765
|
+
bulkDelete(ids: string[], o?: IdempotentOptions): Promise<BulkDeleteResult>;
|
|
725
766
|
bulkUpsert(o: {
|
|
726
767
|
on: UpsertOn<M> | UpsertOn<M>[];
|
|
727
768
|
records: M["input"][];
|
|
728
|
-
}): Promise<BulkResult<M["record"]>>;
|
|
769
|
+
} & IdempotentOptions): Promise<BulkResult<M["record"]>>;
|
|
729
770
|
/**
|
|
730
771
|
* A new record for an action's `run` to `save()`, written with the action's own record in one transaction. It has
|
|
731
772
|
* its id already, so other records can point at it. Only an action's `api` builds records.
|
|
@@ -739,12 +780,16 @@ export interface ModelClient<M extends ModelTypes = UntypedModel> {
|
|
|
739
780
|
checkPassword(id: string, password: string, field?: M["passwords"] | (CheckPasswordOptions & {
|
|
740
781
|
field?: M["passwords"];
|
|
741
782
|
})): Promise<boolean>;
|
|
742
|
-
/**
|
|
783
|
+
/**
|
|
784
|
+
* Runs one of the model's actions: on a record when `id` is given, else as a new one; `shop` gives it `shopify`.
|
|
785
|
+
* With `ifUpdatedAt`, the run happens only while the record still has that `updatedAt` (409 `version_conflict`
|
|
786
|
+
* otherwise); with an `idempotencyKey`, a retried call answers the first run instead of running again.
|
|
787
|
+
*/
|
|
743
788
|
run<A extends keyof M["actions"] & string>(action: A, o?: {
|
|
744
789
|
id?: string;
|
|
745
790
|
params?: M["actions"][A]["params"];
|
|
746
791
|
shop?: string;
|
|
747
|
-
}): Promise<{
|
|
792
|
+
} & UpdateOptions & IdempotentOptions): Promise<{
|
|
748
793
|
record: M["record"] | null;
|
|
749
794
|
result?: M["actions"][A]["result"];
|
|
750
795
|
}>;
|
|
@@ -777,8 +822,8 @@ export type Api = ModelClients & {
|
|
|
777
822
|
* Held to the client's store and role as reads are: a store's client hears only of its records.
|
|
778
823
|
*/
|
|
779
824
|
$changes(o: ChangesOptions): Promise<Changes>;
|
|
780
|
-
/** Runs a global action (`api/actions/<name>.ts`). */
|
|
781
|
-
$global<A extends GlobalName>(action: A, params?: GlobalOf<A>["params"]): Promise<{
|
|
825
|
+
/** Runs a global action (`api/actions/<name>.ts`). With an `idempotencyKey`, a retried call answers the first run. */
|
|
826
|
+
$global<A extends GlobalName>(action: A, params?: GlobalOf<A>["params"], o?: IdempotentOptions): Promise<{
|
|
782
827
|
result?: GlobalOf<A>["result"];
|
|
783
828
|
}>;
|
|
784
829
|
/**
|
|
@@ -795,7 +840,8 @@ export type Api = ModelClients & {
|
|
|
795
840
|
enqueueMany<A extends ActionName>(action: A, jobs: {
|
|
796
841
|
id?: string;
|
|
797
842
|
params?: ParamsOf<A>;
|
|
798
|
-
|
|
843
|
+
dedupeKey?: string;
|
|
844
|
+
}[], options?: Omit<EnqueueOptions, "id" | "dedupeKey">): Promise<Job[]>;
|
|
799
845
|
/**
|
|
800
846
|
* The same API for one store: store-owned models (Shopify's, and any with a text field named `shop`) show only that
|
|
801
847
|
* store's records, new ones are made as its, and actions run for it. An action's `api` is already its run's store's.
|
|
@@ -955,6 +1001,11 @@ export interface EnqueueOptions {
|
|
|
955
1001
|
/** Jobs with the same key run at most `concurrency` (1 by default) at a time. */
|
|
956
1002
|
concurrencyKey?: string;
|
|
957
1003
|
concurrency?: number;
|
|
1004
|
+
/**
|
|
1005
|
+
* Queues nothing new while the environment has a job with this key (300 characters at most): the job it named is
|
|
1006
|
+
* returned instead. A webhook delivery's id, or `<action>:<record>:<day>`, so a retry or a second delivery runs once.
|
|
1007
|
+
*/
|
|
1008
|
+
dedupeKey?: string;
|
|
958
1009
|
}
|
|
959
1010
|
export interface Job {
|
|
960
1011
|
id: string;
|
|
@@ -1011,6 +1062,7 @@ export type RecordsRequest = {
|
|
|
1011
1062
|
model: string;
|
|
1012
1063
|
id: string;
|
|
1013
1064
|
values: Record<string, unknown>;
|
|
1065
|
+
ifUpdatedAt?: string;
|
|
1014
1066
|
} | {
|
|
1015
1067
|
op: "delete";
|
|
1016
1068
|
model: string;
|
package/dist/index.js
CHANGED
|
@@ -35,6 +35,7 @@ export function describeSchema(name, schema) {
|
|
|
35
35
|
],
|
|
36
36
|
};
|
|
37
37
|
}
|
|
38
|
+
export const increment = (by = 1) => ({ _increment: by });
|
|
38
39
|
/** Shared by every copy of this module that loads, so `save` works whichever copy an action imported. */
|
|
39
40
|
const STATE = Symbol.for("inferencebureau.apps.record");
|
|
40
41
|
/** The order records were saved in, across copies too: they're written in that order. */
|
|
@@ -59,11 +60,13 @@ export function applyParams(params, record) {
|
|
|
59
60
|
record[k] = v;
|
|
60
61
|
}
|
|
61
62
|
/** Saves the record when `run` returns, with everything else the action does to it, in one transaction. */
|
|
62
|
-
export async function save(record) {
|
|
63
|
+
export async function save(record, o = {}) {
|
|
63
64
|
const s = stateOf(record);
|
|
64
65
|
s.save = true;
|
|
65
66
|
s.delete = false;
|
|
66
67
|
s.seq = ++SEQ.n;
|
|
68
|
+
if (o.ifUpdatedAt !== undefined)
|
|
69
|
+
s.ifUpdatedAt = o.ifUpdatedAt;
|
|
67
70
|
}
|
|
68
71
|
/** Deletes the record when `run` returns. */
|
|
69
72
|
export async function deleteRecord(record) {
|
|
@@ -87,7 +90,7 @@ export function pendingWrite(record, isNew) {
|
|
|
87
90
|
if (isNew ? v !== null : JSON.stringify(v) !== JSON.stringify(before[k]))
|
|
88
91
|
values[k] = v;
|
|
89
92
|
}
|
|
90
|
-
return { op: "save", values };
|
|
93
|
+
return { op: "save", values, ...(!isNew && s.ifUpdatedAt !== undefined ? { ifUpdatedAt: s.ifUpdatedAt } : {}) };
|
|
91
94
|
}
|
|
92
95
|
/** What `run` asked of the other records it was handed (read or built through its `api`), in the order it saved them. */
|
|
93
96
|
export function stagedWrites(records) {
|
|
@@ -105,7 +108,7 @@ export function stagedWrites(records) {
|
|
|
105
108
|
const w = pendingWrite(record, s.isNew);
|
|
106
109
|
if (w?.op !== "save" || (!s.isNew && !Object.keys(w.values).length))
|
|
107
110
|
continue;
|
|
108
|
-
out.push({ seq: s.seq, write: { model: s.model, op:
|
|
111
|
+
out.push({ seq: s.seq, write: s.isNew ? { model: s.model, op: "create", id, values: w.values } : { model: s.model, op: "update", id, values: w.values, ...(w.ifUpdatedAt !== undefined ? { ifUpdatedAt: w.ifUpdatedAt } : {}) } });
|
|
109
112
|
}
|
|
110
113
|
return out.sort((a, b) => a.seq - b.seq).map((x) => x.write);
|
|
111
114
|
}
|
|
@@ -153,11 +156,11 @@ export function createClient(o = {}) {
|
|
|
153
156
|
* before it did anything is tried again, up to CALL_RETRIES times after Retry-After: the environment's calls all
|
|
154
157
|
* running (429 concurrency_limit_exceeded), or, for a read, the database's connections busy (503 reason busy).
|
|
155
158
|
*/
|
|
156
|
-
async function call(method, path, body, raw) {
|
|
159
|
+
async function call(method, path, body, raw, headers = {}) {
|
|
157
160
|
const read = method === "GET" || /\/records\/(query|aggregate)$/.test(path);
|
|
158
161
|
for (let tries = 0;; tries++) {
|
|
159
162
|
const res = await f(`${base}${path}`, {
|
|
160
|
-
method, headers: { authorization: `Bearer ${token}`, ...scope, ...(raw ? (raw.type ? { "content-type": raw.type } : {}) : body === undefined ? {} : { "content-type": "application/json" }) },
|
|
163
|
+
method, headers: { authorization: `Bearer ${token}`, ...scope, ...headers, ...(raw ? (raw.type ? { "content-type": raw.type } : {}) : body === undefined ? {} : { "content-type": "application/json" }) },
|
|
161
164
|
...(raw ? { body: raw.body } : body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
162
165
|
});
|
|
163
166
|
if (res.status === 204)
|
|
@@ -179,6 +182,8 @@ export function createClient(o = {}) {
|
|
|
179
182
|
throw new ApiError(json.error?.message ?? `The API answered ${res.status}.`, res.status, json.error?.code ?? null, json.error?.problems ?? []);
|
|
180
183
|
}
|
|
181
184
|
}
|
|
185
|
+
/** The `Idempotency-Key` header for a creating or running call that asked for one. */
|
|
186
|
+
const idem = (o) => (o.idempotencyKey ? { "idempotency-key": o.idempotencyKey } : {});
|
|
182
187
|
const model = (name) => {
|
|
183
188
|
const m = `/models/${encodeURIComponent(name)}`;
|
|
184
189
|
const query = (o) => call("POST", `${m}/records/query`, o);
|
|
@@ -201,20 +206,20 @@ export function createClient(o = {}) {
|
|
|
201
206
|
findFirst: async (o = {}) => (await query({ ...o, first: 1 })).records[0] ?? null,
|
|
202
207
|
search: (field, near, o = {}) => query({ ...o, search: { field, near } }),
|
|
203
208
|
aggregate: (o) => call("POST", `${m}/records/aggregate`, o),
|
|
204
|
-
create: (values) => call("POST", `${m}/records`, values),
|
|
205
|
-
update: (id, values) => call("PATCH", `${m}/records/${encodeURIComponent(id)}`, values),
|
|
209
|
+
create: (values, o = {}) => call("POST", `${m}/records`, values, undefined, idem(o)),
|
|
210
|
+
update: (id, values, o = {}) => call("PATCH", `${m}/records/${encodeURIComponent(id)}`, values, undefined, o.ifUpdatedAt ? { "x-ib-if-updated-at": o.ifUpdatedAt } : {}),
|
|
206
211
|
delete: (id) => call("DELETE", `${m}/records/${encodeURIComponent(id)}`),
|
|
207
|
-
upsert: (o) => call("POST", `${m}/records/upsert`, { on: o.on, values: o.values }),
|
|
208
|
-
bulkCreate: (values) => call("POST", `${m}/bulk`, { op: "create", records: values }),
|
|
209
|
-
bulkUpdate: (records) => call("POST", `${m}/bulk`, { op: "update", records }),
|
|
210
|
-
bulkDelete: (ids) => call("POST", `${m}/bulk`, { op: "delete", ids }),
|
|
211
|
-
bulkUpsert: (o) => call("POST", `${m}/bulk`, { op: "upsert", on: o.on, records: o.records }),
|
|
212
|
+
upsert: (o) => call("POST", `${m}/records/upsert`, { on: o.on, values: o.values }, undefined, idem(o)),
|
|
213
|
+
bulkCreate: (values, o = {}) => call("POST", `${m}/bulk`, { op: "create", records: values }, undefined, idem(o)),
|
|
214
|
+
bulkUpdate: (records, o = {}) => call("POST", `${m}/bulk`, { op: "update", records }, undefined, idem(o)),
|
|
215
|
+
bulkDelete: (ids, o = {}) => call("POST", `${m}/bulk`, { op: "delete", ids }, undefined, idem(o)),
|
|
216
|
+
bulkUpsert: (o) => call("POST", `${m}/bulk`, { op: "upsert", on: o.on, records: o.records }, undefined, idem(o)),
|
|
212
217
|
build: () => { throw new Error("build() makes a record for an action's run to save(); outside an action, use create()."); },
|
|
213
218
|
checkPassword: async (id, password, field) => {
|
|
214
219
|
const o = typeof field === "string" ? { field } : field ?? {};
|
|
215
220
|
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;
|
|
216
221
|
},
|
|
217
|
-
run: (action, o = {}) => call("POST", `${m}/actions/${encodeURIComponent(action)}`, { ...(o.id ? { id: o.id } : {}), params: o.params ?? {}, ...(o.shop ? { shop: o.shop } : {}) }),
|
|
222
|
+
run: (action, o = {}) => call("POST", `${m}/actions/${encodeURIComponent(action)}`, { ...(o.id ? { id: o.id } : {}), params: o.params ?? {}, ...(o.shop ? { shop: o.shop } : {}), ...(o.ifUpdatedAt ? { ifUpdatedAt: o.ifUpdatedAt } : {}) }, undefined, idem(o)),
|
|
218
223
|
createUpload: (field, o = {}) => call("POST", `${m}/uploads`, { field, ...o }),
|
|
219
224
|
async upload(field, body, o = {}) {
|
|
220
225
|
const blob = body instanceof Blob ? body : new Blob([body]);
|
|
@@ -231,7 +236,7 @@ export function createClient(o = {}) {
|
|
|
231
236
|
const cache = new Map();
|
|
232
237
|
const modelNamed = (name) => { if (!cache.has(name))
|
|
233
238
|
cache.set(name, model(name)); return cache.get(name); };
|
|
234
|
-
const $global = (action, params = {}) => call("POST", `/actions/${encodeURIComponent(action)}`, { params });
|
|
239
|
+
const $global = (action, params = {}, o = {}) => call("POST", `/actions/${encodeURIComponent(action)}`, { params }, undefined, idem(o));
|
|
235
240
|
const $changes = (q) => call("POST", "/changes", { models: q.models, ...(q.cursor ? { cursor: q.cursor } : {}), ...(q.wait !== undefined ? { wait: q.wait } : {}) });
|
|
236
241
|
const enqueue = (action, params = {}, o = {}) => call("POST", "/jobs", { action, params, ...o, ...(o.runAt instanceof Date ? { runAt: o.runAt.toISOString() } : {}) });
|
|
237
242
|
const enqueueMany = async (action, jobs, o = {}) => (await call("POST", "/jobs/bulk", { action, jobs, ...o, ...(o.runAt instanceof Date ? { runAt: o.runAt.toISOString() } : {}) })).jobs;
|
|
@@ -390,7 +395,7 @@ export async function serveRecords(request, api, o = {}) {
|
|
|
390
395
|
case "update":
|
|
391
396
|
if (!str(b.id))
|
|
392
397
|
break;
|
|
393
|
-
return Response.json(await m.update(b.id, obj(b.values)));
|
|
398
|
+
return Response.json(await m.update(b.id, obj(b.values), str(b.ifUpdatedAt) ? { ifUpdatedAt: b.ifUpdatedAt } : {}));
|
|
394
399
|
case "delete":
|
|
395
400
|
if (!str(b.id))
|
|
396
401
|
break;
|
package/dist/runtime.d.ts
CHANGED
package/dist/test.d.ts
CHANGED
|
@@ -20,6 +20,11 @@
|
|
|
20
20
|
* storage (`api.files`) is in memory too: a file reads back as a `data:` URL, and `reset()` empties it.
|
|
21
21
|
*/
|
|
22
22
|
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";
|
|
23
|
+
/** An update whose `ifUpdatedAt` no longer stands, as the API answers it: 409 `version_conflict` with the record's updatedAt now. */
|
|
24
|
+
export declare class ConflictError extends ApiError {
|
|
25
|
+
readonly updatedAt: string;
|
|
26
|
+
constructor(model: string, id: string, updatedAt: string);
|
|
27
|
+
}
|
|
23
28
|
type Embed = (model: string, input: string[]) => Promise<number[][]>;
|
|
24
29
|
/** The store a test app installs on and runs as, unless a test names another. */
|
|
25
30
|
export declare const TEST_SHOP = "test-shop.myshopify.com";
|
|
@@ -233,7 +238,8 @@ export interface TestAppOptions {
|
|
|
233
238
|
export interface RunOptions {
|
|
234
239
|
id?: string;
|
|
235
240
|
params?: Record<string, unknown>;
|
|
236
|
-
shop?: string;
|
|
241
|
+
shop?: string; /** The record's updatedAt as read: the run happens only while it still stands. */
|
|
242
|
+
ifUpdatedAt?: string;
|
|
237
243
|
}
|
|
238
244
|
/**
|
|
239
245
|
* Who a call is for: a role in permissions.ib.ts and the caller's session (what `{ $session: … }` in a grant's filter
|
package/dist/test.js
CHANGED
|
@@ -40,6 +40,24 @@ function under(at, f) {
|
|
|
40
40
|
}
|
|
41
41
|
}
|
|
42
42
|
const notFound = (message) => new ApiError(message, 404, "not_found");
|
|
43
|
+
/** An update whose `ifUpdatedAt` no longer stands, as the API answers it: 409 `version_conflict` with the record's updatedAt now. */
|
|
44
|
+
export class ConflictError extends ApiError {
|
|
45
|
+
updatedAt;
|
|
46
|
+
constructor(model, id, updatedAt) {
|
|
47
|
+
super(`${model} ${id} was changed at ${updatedAt}, after it was read. Read it again and retry.`, 409, "version_conflict");
|
|
48
|
+
this.updatedAt = updatedAt;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const sameInstant = (a, b) => new Date(a).getTime() === new Date(b).getTime();
|
|
52
|
+
const ifUpdatedAtOf = (v) => {
|
|
53
|
+
if (v === undefined || v === null)
|
|
54
|
+
return undefined;
|
|
55
|
+
if (typeof v !== "string" || Number.isNaN(Date.parse(v)))
|
|
56
|
+
throw invalid([{ field: "ifUpdatedAt", message: "must be the updatedAt the record was read with" }]);
|
|
57
|
+
return v;
|
|
58
|
+
};
|
|
59
|
+
/** A number field written as `{ _increment: n }` (the SDK's `increment`): added to the stored value. */
|
|
60
|
+
const incrementOf = (v) => (isObj(v) && typeof v._increment === "number" && Number.isFinite(v._increment) && Object.keys(v).length === 1 ? v._increment : null);
|
|
43
61
|
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
44
62
|
/** What crosses the wire between Inference Bureau and the app: JSON (a Date arrives as its ISO string). */
|
|
45
63
|
const wire = (v) => (v === undefined ? v : JSON.parse(JSON.stringify(v)));
|
|
@@ -1428,7 +1446,13 @@ class Records {
|
|
|
1428
1446
|
problems.push({ field: name, message: `is embedded from ${f.def.source.map(String).join(", ")}; it can't be written` });
|
|
1429
1447
|
continue;
|
|
1430
1448
|
}
|
|
1431
|
-
const
|
|
1449
|
+
const by = incrementOf(value);
|
|
1450
|
+
if (by !== null && f.type !== "number") {
|
|
1451
|
+
problems.push({ field: name, message: `only a number field takes { _increment }; ${name} is ${f.type}` });
|
|
1452
|
+
continue;
|
|
1453
|
+
}
|
|
1454
|
+
const stored = current ? current.data[f.key] : defaultOf(f);
|
|
1455
|
+
const c = convert(f, by === null ? value : (typeof stored === "number" ? stored : Number(stored) || 0) + by, "write");
|
|
1432
1456
|
if (!c.ok) {
|
|
1433
1457
|
problems.push({ field: name, message: c.message });
|
|
1434
1458
|
continue;
|
|
@@ -1558,11 +1582,15 @@ class Records {
|
|
|
1558
1582
|
this.log(m, row.data);
|
|
1559
1583
|
return this.present(m, row, true);
|
|
1560
1584
|
}
|
|
1561
|
-
|
|
1585
|
+
/** `ifUpdatedAt`: the update is made only while the record's updatedAt is still that, else ConflictError (409 version_conflict). */
|
|
1586
|
+
async update(model, id, values, o = {}) {
|
|
1562
1587
|
const m = this.model(model);
|
|
1563
1588
|
const row = this.table(m).get(id);
|
|
1564
1589
|
if (!row)
|
|
1565
1590
|
throw notFound(`There's no ${m.name} with id ${id}.`);
|
|
1591
|
+
const since = ifUpdatedAtOf(o.ifUpdatedAt);
|
|
1592
|
+
if (since !== undefined && !sameInstant(row.updatedAt, since))
|
|
1593
|
+
throw new ConflictError(m.name, id, row.updatedAt);
|
|
1566
1594
|
const p = this.prepare(m, values, row);
|
|
1567
1595
|
const before = row.data;
|
|
1568
1596
|
row.data = p.data;
|
|
@@ -2337,6 +2365,10 @@ export function createTestApp(o = {}) {
|
|
|
2337
2365
|
record = store.findOne(model, input.id);
|
|
2338
2366
|
if (!record)
|
|
2339
2367
|
throw notFound(`There's no ${model} with id ${input.id}.`);
|
|
2368
|
+
// Refused before the action runs when the record has moved on, as the API does; checked again at the write.
|
|
2369
|
+
const since = ifUpdatedAtOf(input.ifUpdatedAt);
|
|
2370
|
+
if (since !== undefined && !sameInstant(String(record.updatedAt), since))
|
|
2371
|
+
throw new ConflictError(model, input.id, String(record.updatedAt));
|
|
2340
2372
|
}
|
|
2341
2373
|
}
|
|
2342
2374
|
const params = wire(input.params ?? {});
|
|
@@ -2380,7 +2412,7 @@ export function createTestApp(o = {}) {
|
|
|
2380
2412
|
saved = null;
|
|
2381
2413
|
}
|
|
2382
2414
|
else
|
|
2383
|
-
saved = type === "create" ? await store.create(model, reply.write.values, String(record.id)) : await store.update(model, input.id, reply.write.values);
|
|
2415
|
+
saved = type === "create" ? await store.create(model, reply.write.values, String(record.id)) : await store.update(model, input.id, reply.write.values, { ifUpdatedAt: ifUpdatedAtOf(reply.write.ifUpdatedAt ?? input.ifUpdatedAt) });
|
|
2384
2416
|
}
|
|
2385
2417
|
for (const w of others) {
|
|
2386
2418
|
const m = store.model(w.model);
|
|
@@ -2392,7 +2424,7 @@ export function createTestApp(o = {}) {
|
|
|
2392
2424
|
if (w.op === "delete")
|
|
2393
2425
|
store.delete(m.name, w.id);
|
|
2394
2426
|
else if (w.op === "update")
|
|
2395
|
-
await store.update(m.name, w.id, f ? scopedUpdate(own, m, wire(w.values)) : wire(w.values));
|
|
2427
|
+
await store.update(m.name, w.id, f ? scopedUpdate(own, m, wire(w.values)) : wire(w.values), { ifUpdatedAt: ifUpdatedAtOf(w.ifUpdatedAt) });
|
|
2396
2428
|
else
|
|
2397
2429
|
await store.create(m.name, f ? scopedValues(own, m, wire(w.values)) : wire(w.values), w.id);
|
|
2398
2430
|
}
|
|
@@ -2501,7 +2533,7 @@ export function createTestApp(o = {}) {
|
|
|
2501
2533
|
throw e;
|
|
2502
2534
|
records.push(null);
|
|
2503
2535
|
counts.failed++;
|
|
2504
|
-
failed.push({ index, ...(it.id ? { id: it.id } : {}), error: { code: e.code ?? "invalid_request", message: e.message, ...(e.problems.length ? { problems: e.problems } : {}), ...(e instanceof ActionFailedError ? { logs: e.logs } : {}) } });
|
|
2536
|
+
failed.push({ index, ...(it.id ? { id: it.id } : {}), error: { code: e.code ?? "invalid_request", message: e.message, ...(e.problems.length ? { problems: e.problems } : {}), ...(e instanceof ActionFailedError ? { logs: e.logs } : {}), ...(e instanceof ConflictError ? { updatedAt: e.updatedAt } : {}) } });
|
|
2505
2537
|
}
|
|
2506
2538
|
}
|
|
2507
2539
|
return { records, failed, counts };
|
|
@@ -2515,19 +2547,19 @@ export function createTestApp(o = {}) {
|
|
|
2515
2547
|
aggregate: async (q) => store.aggregate(name, narrow(wire(q))),
|
|
2516
2548
|
search: async (field, near, q = {}) => (await store.findMany(name, { ...narrow(wire(q)), search: { field, near } })),
|
|
2517
2549
|
// As through the API: the model's create, update or delete action when it has one, else a direct write.
|
|
2518
|
-
create: async (values) => {
|
|
2550
|
+
create: async (values, q = {}) => once(`create ${name}`, q, values, async () => {
|
|
2519
2551
|
const v = scoped ? scopedValues(scope, store.model(name), wire(values)) : wire(values);
|
|
2520
2552
|
if (registry[`${name}/create`])
|
|
2521
2553
|
return (await runFor(scope, name, "create", { params: v })).record;
|
|
2522
2554
|
await canRun(scope, name, "create", null);
|
|
2523
2555
|
return store.create(name, v);
|
|
2524
|
-
},
|
|
2525
|
-
update: async (id, values) => {
|
|
2556
|
+
}),
|
|
2557
|
+
update: async (id, values, q = {}) => {
|
|
2526
2558
|
const v = scoped ? scopedUpdate(scope, store.model(name), wire(values)) : wire(values);
|
|
2527
2559
|
if (registry[`${name}/update`])
|
|
2528
|
-
return (await runFor(scope, name, "update", { id, params: v })).record;
|
|
2560
|
+
return (await runFor(scope, name, "update", { id, params: v, ...(q.ifUpdatedAt ? { ifUpdatedAt: q.ifUpdatedAt } : {}) })).record;
|
|
2529
2561
|
await canRun(scope, name, "update", id);
|
|
2530
|
-
return store.update(name, id, v);
|
|
2562
|
+
return store.update(name, id, v, { ifUpdatedAt: q.ifUpdatedAt });
|
|
2531
2563
|
},
|
|
2532
2564
|
delete: async (id) => {
|
|
2533
2565
|
if (registry[`${name}/delete`]) {
|
|
@@ -2538,7 +2570,7 @@ export function createTestApp(o = {}) {
|
|
|
2538
2570
|
store.delete(name, id);
|
|
2539
2571
|
},
|
|
2540
2572
|
// As through the API: the record the on fields find (one the call's update grant reaches) is updated, else one is created.
|
|
2541
|
-
upsert: async ({ on, values }) => {
|
|
2573
|
+
upsert: async ({ on, values, ...q }) => once(`upsert ${name}`, q, { on, values }, async () => {
|
|
2542
2574
|
const m = store.model(name);
|
|
2543
2575
|
const v = scoped ? scopedValues(scope, m, wire(values)) : wire(values);
|
|
2544
2576
|
const by = upsertBy(m, Array.isArray(on) ? on : [on], v);
|
|
@@ -2549,21 +2581,22 @@ export function createTestApp(o = {}) {
|
|
|
2549
2581
|
if (found)
|
|
2550
2582
|
return { record: registry[`${name}/update`] ? (await runFor(scope, name, "update", { id: found.id, params: v })).record : await store.update(name, found.id, v), created: false };
|
|
2551
2583
|
return { record: registry[`${name}/create`] ? (await runFor(scope, name, "create", { params: v })).record : await store.create(name, v), created: true };
|
|
2552
|
-
},
|
|
2553
|
-
bulkCreate: (values) => batch(values.map((v) => ({ work: async () => ({ record: await client.create(v) }) }))),
|
|
2554
|
-
bulkUpdate: (records) => batch(records.map((r) => ({ id: r.id, work: async () => ({ record: await client.update(r.id, r.values) }) }))),
|
|
2555
|
-
bulkDelete: async (
|
|
2584
|
+
}),
|
|
2585
|
+
bulkCreate: (values, q = {}) => once(`bulk ${name}`, q, { op: "create", values }, () => batch(values.map((v) => ({ work: async () => ({ record: await client.create(v) }) })))),
|
|
2586
|
+
bulkUpdate: (records, q = {}) => once(`bulk ${name}`, q, { op: "update", records }, () => batch(records.map((r) => ({ id: r.id, work: async () => ({ record: await client.update(r.id, r.values, r.ifUpdatedAt ? { ifUpdatedAt: r.ifUpdatedAt } : {}) }) })))),
|
|
2587
|
+
bulkDelete: (ids, q = {}) => once(`bulk ${name}`, q, { op: "delete", ids }, async () => {
|
|
2556
2588
|
const r = await batch(ids.map((id) => ({ id, work: async () => { await client.delete(id); return { record: null }; } })));
|
|
2557
2589
|
const lost = new Set(r.failed.map((f) => f.index));
|
|
2558
2590
|
return { deleted: ids.filter((_id, i) => !lost.has(i)), failed: r.failed, counts: r.counts };
|
|
2559
|
-
},
|
|
2560
|
-
bulkUpsert: (q) =>
|
|
2591
|
+
}),
|
|
2592
|
+
bulkUpsert: ({ on, records, ...q }) => once(`bulk ${name}`, q, { op: "upsert", on, records }, () => batch(records.map((v) => ({ work: () => client.upsert({ on, values: v }) })), true)),
|
|
2561
2593
|
// A record the call can't read answers false, as a missing one does.
|
|
2562
2594
|
checkPassword: async (id, password, field) => (scoped && !(await findVisible(name, id, readOf())) ? false : store.checkPassword(name, id, password, typeof field === "string" ? field : field?.field)),
|
|
2563
|
-
run: async (action, q = {}) => {
|
|
2564
|
-
const
|
|
2595
|
+
run: async (action, q = {}) => once(`run ${name}.${action}`, q, { id: q.id, params: q.params, shop: q.shop, ifUpdatedAt: q.ifUpdatedAt }, async () => {
|
|
2596
|
+
const { idempotencyKey: _k, ...rest } = q;
|
|
2597
|
+
const r = await runFor(scope, name, action, rest);
|
|
2565
2598
|
return { record: r.record, ...(r.result !== undefined ? { result: r.result } : {}) };
|
|
2566
|
-
},
|
|
2599
|
+
}),
|
|
2567
2600
|
createUpload: async (field, q = {}) => {
|
|
2568
2601
|
fileFieldOf(store.model(name), field);
|
|
2569
2602
|
uploadable();
|
|
@@ -2590,13 +2623,50 @@ export function createTestApp(o = {}) {
|
|
|
2590
2623
|
const enqueue = async (action, params = {}, q = {}) => {
|
|
2591
2624
|
const t = (o.now ?? Date.now)();
|
|
2592
2625
|
const runAt = q.runAt !== undefined ? new Date(q.runAt) : new Date(t + (q.delay ?? 0));
|
|
2626
|
+
// As the API does: a dedupeKey the environment already has a job for queues nothing new, and answers that job.
|
|
2627
|
+
if (q.dedupeKey !== undefined && q.dedupeKey !== "") {
|
|
2628
|
+
if (q.dedupeKey.length > 300)
|
|
2629
|
+
throw new ApiError("dedupeKey is at most 300 characters", 400, "invalid_request");
|
|
2630
|
+
const had = jobs.find((j) => j.dedupe_key === q.dedupeKey);
|
|
2631
|
+
if (had)
|
|
2632
|
+
return wire(had);
|
|
2633
|
+
}
|
|
2593
2634
|
const job = {
|
|
2594
2635
|
id: `job_${String(++jobSeq).padStart(6, "0")}`, action, state: "queued", run_at: runAt.toISOString(), attempts: 0, max_attempts: Math.min(20, q.retries ?? 6) + 1, last_error: null,
|
|
2595
|
-
params: wire(params), record_id: q.id ?? null, shop: q.shop ?? null, priority: q.priority ?? "default",
|
|
2636
|
+
params: wire(params), record_id: q.id ?? null, shop: q.shop ?? null, priority: q.priority ?? "default", dedupe_key: q.dedupeKey || null,
|
|
2596
2637
|
};
|
|
2597
2638
|
jobs.push(job);
|
|
2598
2639
|
return wire(job);
|
|
2599
2640
|
};
|
|
2641
|
+
/**
|
|
2642
|
+
* A creating or running call made once per `idempotencyKey`, as the API makes it: the first call's answer (or its
|
|
2643
|
+
* refusal) is kept and a retry with the same key and input gets it back; a different input is a 409.
|
|
2644
|
+
*/
|
|
2645
|
+
const kept = new Map();
|
|
2646
|
+
const once = async (route, q, input, work) => {
|
|
2647
|
+
if (!q.idempotencyKey)
|
|
2648
|
+
return work();
|
|
2649
|
+
const k = `${route}:${q.idempotencyKey}`;
|
|
2650
|
+
const fingerprint = JSON.stringify(wire(input) ?? null);
|
|
2651
|
+
const had = kept.get(k);
|
|
2652
|
+
if (had) {
|
|
2653
|
+
if (had.fingerprint !== fingerprint)
|
|
2654
|
+
throw new ApiError("Idempotency-Key was already used with a different request body", 409, "idempotency_conflict");
|
|
2655
|
+
if (had.error)
|
|
2656
|
+
throw had.error;
|
|
2657
|
+
return wire(had.value);
|
|
2658
|
+
}
|
|
2659
|
+
try {
|
|
2660
|
+
const value = await work();
|
|
2661
|
+
kept.set(k, { fingerprint, value: wire(value) });
|
|
2662
|
+
return value;
|
|
2663
|
+
}
|
|
2664
|
+
catch (e) {
|
|
2665
|
+
if (e instanceof ApiError && e.status < 500)
|
|
2666
|
+
kept.set(k, { fingerprint, error: e });
|
|
2667
|
+
throw e;
|
|
2668
|
+
}
|
|
2669
|
+
};
|
|
2600
2670
|
// Runs succeed at once and write nothing: a test sees what was asked for in `syncRuns`.
|
|
2601
2671
|
const shopifySync = ({ shop, role }) => {
|
|
2602
2672
|
const allowed = () => { if (role)
|
|
@@ -2639,10 +2709,10 @@ export function createTestApp(o = {}) {
|
|
|
2639
2709
|
if (apis.has(key))
|
|
2640
2710
|
return apis.get(key);
|
|
2641
2711
|
const clients = new Map();
|
|
2642
|
-
const $global = async (action, params = {}) => {
|
|
2712
|
+
const $global = async (action, params = {}, q = {}) => once(`global ${action}`, q, params, async () => {
|
|
2643
2713
|
const r = await runFor(scope, null, action, { params });
|
|
2644
2714
|
return r.result !== undefined ? { result: r.result } : {};
|
|
2645
|
-
};
|
|
2715
|
+
});
|
|
2646
2716
|
const queue = async (action, params = {}, q = {}) => {
|
|
2647
2717
|
const n = parseName(action);
|
|
2648
2718
|
await canRun(scope, n.model, n.action, q.id ?? null);
|
|
@@ -2658,7 +2728,7 @@ export function createTestApp(o = {}) {
|
|
|
2658
2728
|
await canRun(scope, n.model, n.action, e.id ?? null);
|
|
2659
2729
|
const out = [];
|
|
2660
2730
|
for (const e of entries)
|
|
2661
|
-
out.push(await queue(action, e.params, { ...q, ...(e.id ? { id: e.id } : {}) }));
|
|
2731
|
+
out.push(await queue(action, e.params, { ...q, ...(e.id ? { id: e.id } : {}), ...(e.dedupeKey ? { dedupeKey: e.dedupeKey } : {}) }));
|
|
2662
2732
|
return out;
|
|
2663
2733
|
};
|
|
2664
2734
|
// What changed since a cursor, as the API answers it: waiting up to `wait` seconds for a write when none has.
|
|
@@ -2911,7 +2981,7 @@ export function createTestApp(o = {}) {
|
|
|
2911
2981
|
shopify,
|
|
2912
2982
|
ai,
|
|
2913
2983
|
logs,
|
|
2914
|
-
reset() { store.clear(); storage.clear(); jobs.length = 0; scheduled.clear(); syncRuns.length = 0; logs.length = 0; shopify.calls.length = 0; ai.calls.length = 0; },
|
|
2984
|
+
reset() { store.clear(); storage.clear(); jobs.length = 0; kept.clear(); scheduled.clear(); syncRuns.length = 0; logs.length = 0; shopify.calls.length = 0; ai.calls.length = 0; },
|
|
2915
2985
|
};
|
|
2916
2986
|
}
|
|
2917
2987
|
// ---- loading an app's folder ----
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inferencebureau/apps-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.1",
|
|
4
4
|
"description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types, the records API client, React hooks with AutoTable and AutoForm, and a test harness for its actions.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"keywords": [
|