@inferencebureau/apps-sdk 0.8.1 → 0.10.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 +13 -0
- package/dist/index.d.ts +310 -33
- package/dist/index.js +70 -6
- package/dist/runtime.d.ts +6 -3
- package/dist/runtime.js +9 -5
- package/dist/test.d.ts +25 -3
- package/dist/test.js +208 -16
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -71,6 +71,19 @@ Inside an app, `createClient()` reads `IB_API_URL`, `IB_ENVIRONMENT_TOKEN`, `IB_
|
|
|
71
71
|
Inference Bureau sets. From a script or another service, pass `{ token: process.env.IB_API_KEY, app, environment }`
|
|
72
72
|
with a key linked to the app.
|
|
73
73
|
|
|
74
|
+
The client is typed from the app's own schemas and actions: Inference Bureau writes `web/ib-client.d.ts` whenever
|
|
75
|
+
one changes (`ib-apps dev` and `ib-apps pull` bring it down), and it fills in this package's `AppModels` and
|
|
76
|
+
`AppGlobalActions`. A misspelled model, field, filter, enum value or action then fails the type check instead of the
|
|
77
|
+
request. `ModelRecord<"review">` and `ModelInput<"review">` name a model's types; `api.$model(name)` reaches a model
|
|
78
|
+
the app may not have. Without the file the client takes any name.
|
|
79
|
+
|
|
80
|
+
Reads take `select` to pick fields and follow relationships in one call, typed to what they pick:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
const { records } = await api.review.findMany({ select: { rating: true, product: { select: { title: true } } } });
|
|
84
|
+
records[0]?.product?.title; // a belongsTo reads as its record; a hasMany as { records, hasNextPage }
|
|
85
|
+
```
|
|
86
|
+
|
|
74
87
|
Entry points:
|
|
75
88
|
|
|
76
89
|
- `@inferencebureau/apps-sdk`: metadata types, action helpers, `createClient`, `createShopifyClient`,
|
package/dist/index.d.ts
CHANGED
|
@@ -71,8 +71,14 @@ export interface FieldDef {
|
|
|
71
71
|
model: string;
|
|
72
72
|
belongsToField?: string;
|
|
73
73
|
};
|
|
74
|
+
/**
|
|
75
|
+
* A hasManyThrough's join model. Its belongsTo to this model and its belongsTo to the records reached are found when
|
|
76
|
+
* there's one of each; name them when there are more.
|
|
77
|
+
*/
|
|
74
78
|
through?: {
|
|
75
79
|
model: string;
|
|
80
|
+
belongsToSelfField?: string;
|
|
81
|
+
belongsToSiblingField?: string;
|
|
76
82
|
};
|
|
77
83
|
[key: string]: unknown;
|
|
78
84
|
}
|
|
@@ -180,30 +186,206 @@ export interface AppRecord {
|
|
|
180
186
|
updatedAt: string;
|
|
181
187
|
[field: string]: unknown;
|
|
182
188
|
}
|
|
183
|
-
/**
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
} & {
|
|
189
|
+
/**
|
|
190
|
+
* Which records a list returns: `{ field: { equals: x } }`, with AND, OR and NOT lists. `F` is a model's fields and
|
|
191
|
+
* their filters, from the app's generated client types (`web/ib-client.d.ts`); any field without them.
|
|
192
|
+
*/
|
|
193
|
+
export type Filter<F extends object = {
|
|
189
194
|
[field: string]: unknown;
|
|
195
|
+
}> = {
|
|
196
|
+
AND?: Filter<F>[];
|
|
197
|
+
OR?: Filter<F>[];
|
|
198
|
+
NOT?: Filter<F>[];
|
|
199
|
+
} & F;
|
|
200
|
+
/** A list's order: the field to sort by, or several in turn. `K` is a model's sortable fields once the client is generated. */
|
|
201
|
+
export type Sort<K extends string = string> = string extends K ? Record<string, SortDirection> : {
|
|
202
|
+
[P in K]?: SortDirection;
|
|
190
203
|
};
|
|
191
|
-
export type
|
|
192
|
-
export interface FindManyOptions {
|
|
193
|
-
filter?: Filter
|
|
194
|
-
sort?: Sort | Sort[];
|
|
204
|
+
export type SortDirection = "Ascending" | "Descending";
|
|
205
|
+
export interface FindManyOptions<M extends ModelTypes = UntypedModel, S extends SelectOf<M> | undefined = undefined> {
|
|
206
|
+
filter?: Filter<M["filter"]>;
|
|
207
|
+
sort?: Sort<M["sortable"]> | Sort<M["sortable"]>[];
|
|
195
208
|
first?: number;
|
|
196
209
|
after?: string | null;
|
|
197
210
|
/** 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. */
|
|
198
211
|
search?: string;
|
|
212
|
+
/** Which fields to read, and which related records with them (SelectOf); every field and no related records when left out. */
|
|
213
|
+
select?: S;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* What a read's `select` names: fields as `true` (the id always comes), and relationships as `true` for their records
|
|
217
|
+
* with every field, or `{ select }` to choose theirs. A hasMany or hasManyThrough also takes `filter`, `sort` and
|
|
218
|
+
* `first` (50 unless given, at most 250 for each record). Up to 3 relationships deep, every related model read
|
|
219
|
+
* through the same store and role as the call itself.
|
|
220
|
+
*
|
|
221
|
+
* const reviews = await api.review.findMany({ select: { rating: true, product: { select: { title: true } } } });
|
|
222
|
+
* reviews.records[0].product?.title;
|
|
223
|
+
*
|
|
224
|
+
* A belongsTo then reads as its record (null when there's none, or the call can't read it) instead of its id; a
|
|
225
|
+
* hasOne as its record or null; a hasMany or hasManyThrough as `{ records, hasNextPage }`, newest first unless sorted.
|
|
226
|
+
*/
|
|
227
|
+
export type SelectOf<M extends ModelTypes = UntypedModel> = string extends keyof RelationsOf<M> ? {
|
|
228
|
+
[field: string]: true | {
|
|
229
|
+
select?: SelectOf;
|
|
230
|
+
filter?: Filter;
|
|
231
|
+
sort?: Sort | Sort[];
|
|
232
|
+
first?: number;
|
|
233
|
+
};
|
|
234
|
+
} : {
|
|
235
|
+
[K in Exclude<keyof M["record"], keyof RelationsOf<M>> & string]?: true;
|
|
236
|
+
} & {
|
|
237
|
+
[R in keyof RelationsOf<M> & string]?: true | RelatedSelectOf<RelationsOf<M>[R]>;
|
|
238
|
+
};
|
|
239
|
+
type RelatedSelectOf<R extends RelationTypes> = {
|
|
240
|
+
select?: SelectOf<ModelOf<R["model"]>>;
|
|
241
|
+
} & (R["many"] extends true ? {
|
|
242
|
+
filter?: Filter<ModelOf<R["model"]>["filter"]>;
|
|
243
|
+
sort?: Sort<ModelOf<R["model"]>["sortable"]> | Sort<ModelOf<R["model"]>["sortable"]>[];
|
|
244
|
+
first?: number;
|
|
245
|
+
} : {});
|
|
246
|
+
type RelationsOf<M extends ModelTypes> = M extends {
|
|
247
|
+
relations: infer R extends {
|
|
248
|
+
[field: string]: RelationTypes;
|
|
249
|
+
};
|
|
250
|
+
} ? R : {
|
|
251
|
+
[field: string]: RelationTypes;
|
|
252
|
+
};
|
|
253
|
+
/** A record as a read with `select` returns it: the fields it names, and the related records it reads. */
|
|
254
|
+
export type Selected<M extends ModelTypes, S> = string extends keyof RelationsOf<M> ? AppRecord : Flat<{
|
|
255
|
+
id: string;
|
|
256
|
+
} & {
|
|
257
|
+
[K in keyof S & Exclude<keyof M["record"], keyof RelationsOf<M>>]: M["record"][K];
|
|
258
|
+
} & {
|
|
259
|
+
[K in keyof S & keyof RelationsOf<M>]: RelatedOf<RelationsOf<M>[K], S[K]>;
|
|
260
|
+
}>;
|
|
261
|
+
type RelatedOf<R extends RelationTypes, V> = (V extends {
|
|
262
|
+
select: infer T;
|
|
263
|
+
} ? Selected<ModelOf<R["model"]>, T> : ModelOf<R["model"]>["record"]) extends infer T ? R["many"] extends true ? {
|
|
264
|
+
records: T[];
|
|
265
|
+
hasNextPage: boolean;
|
|
266
|
+
} : T | null : never;
|
|
267
|
+
type Flat<T> = {
|
|
268
|
+
[K in keyof T]: T[K];
|
|
269
|
+
} & {};
|
|
270
|
+
/** A read's records: the model's record, or what `select` picked of it. */
|
|
271
|
+
export type ReadOf<M extends ModelTypes, S> = [S] extends [undefined] ? M["record"] : Selected<M, S>;
|
|
272
|
+
/** A field's filter: `null` matches records without a value (or holding the field's default when that's null). */
|
|
273
|
+
export interface FieldFilter<V> {
|
|
274
|
+
equals?: V | null;
|
|
275
|
+
notEquals?: V | null;
|
|
276
|
+
in?: (V | null)[];
|
|
277
|
+
notIn?: (V | null)[];
|
|
278
|
+
isSet?: boolean;
|
|
279
|
+
}
|
|
280
|
+
/** Numbers, dates and text compare by value. */
|
|
281
|
+
export interface OrderedFilter<V> extends FieldFilter<V> {
|
|
282
|
+
lessThan?: V;
|
|
283
|
+
lessThanOrEqual?: V;
|
|
284
|
+
greaterThan?: V;
|
|
285
|
+
greaterThanOrEqual?: V;
|
|
286
|
+
}
|
|
287
|
+
/** `startsWith` matches case and all; `contains` ignores case. */
|
|
288
|
+
export interface StringFilter<V extends string = string> extends OrderedFilter<V> {
|
|
289
|
+
startsWith?: string;
|
|
290
|
+
contains?: string;
|
|
291
|
+
}
|
|
292
|
+
/** Dates as ISO 8601 text or a Date. */
|
|
293
|
+
export type DateTimeFilter = OrderedFilter<string | Date>;
|
|
294
|
+
/**
|
|
295
|
+
* The app's models, filled in by `web/ib-client.d.ts`: Inference Bureau writes that file into development whenever a
|
|
296
|
+
* schema or an action changes, `ib-apps dev` and `ib-apps pull` bring it down, and deploys carry it to production.
|
|
297
|
+
* With it, `createClient()`, an action's `api` and a session's `api` know every model, field and action, so a typo
|
|
298
|
+
* fails the type check instead of the request. Without it (an app that has none yet), the API takes any name.
|
|
299
|
+
*/
|
|
300
|
+
export interface AppModels {
|
|
301
|
+
}
|
|
302
|
+
/** The app's global actions (`api/actions/*.ts`), filled in by `web/ib-client.d.ts` like `AppModels`. */
|
|
303
|
+
export interface AppGlobalActions {
|
|
304
|
+
}
|
|
305
|
+
/** What the generated file says of one model. */
|
|
306
|
+
export interface ModelTypes {
|
|
307
|
+
/** A record as reads return it. */
|
|
308
|
+
record: AppRecord;
|
|
309
|
+
/** What `create`, `update` and `build` take: every field optional, the API checks validations. */
|
|
310
|
+
input: Record<string, unknown>;
|
|
311
|
+
/** Each field the model can filter on, with its filter. */
|
|
312
|
+
filter: object;
|
|
313
|
+
/** The fields it can sort on. */
|
|
314
|
+
sortable: string;
|
|
315
|
+
/** Its vector fields (`search`), file fields (`createUpload`, `upload`) and password fields (`checkPassword`). */
|
|
316
|
+
vectors: string;
|
|
317
|
+
files: string;
|
|
318
|
+
passwords: string;
|
|
319
|
+
/** Its actions (api/models/<model>/actions/*.ts). */
|
|
320
|
+
actions: {
|
|
321
|
+
[action: string]: ActionTypes;
|
|
322
|
+
};
|
|
323
|
+
/** Its relationships (belongsTo, hasOne, hasMany, hasManyThrough), for `select`: the model each reads, and whether it's a list. */
|
|
324
|
+
relations?: {
|
|
325
|
+
[field: string]: RelationTypes;
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
export interface RelationTypes {
|
|
329
|
+
model: string;
|
|
330
|
+
many: boolean;
|
|
331
|
+
}
|
|
332
|
+
/** An action's `params` and what it returns: `unknown` when its options say `returnType: true`, else nothing. */
|
|
333
|
+
export interface ActionTypes {
|
|
334
|
+
params: Record<string, unknown>;
|
|
335
|
+
result: unknown;
|
|
199
336
|
}
|
|
337
|
+
/** A model as the API sees it without generated types: any field, any action. */
|
|
338
|
+
export interface UntypedModel {
|
|
339
|
+
record: AppRecord;
|
|
340
|
+
input: Record<string, unknown>;
|
|
341
|
+
filter: {
|
|
342
|
+
[field: string]: unknown;
|
|
343
|
+
};
|
|
344
|
+
sortable: string;
|
|
345
|
+
vectors: string;
|
|
346
|
+
files: string;
|
|
347
|
+
passwords: string;
|
|
348
|
+
actions: {
|
|
349
|
+
[action: string]: ActionTypes;
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
type Typed<T> = keyof T extends never ? false : true;
|
|
353
|
+
/** The model clients: the generated file's models, or any name before there is one. */
|
|
354
|
+
export type ModelClients = Typed<AppModels> extends true ? {
|
|
355
|
+
[K in keyof AppModels]: ModelClient<AppModels[K] extends ModelTypes ? AppModels[K] : UntypedModel>;
|
|
356
|
+
} : {
|
|
357
|
+
[model: string]: ModelClient;
|
|
358
|
+
};
|
|
359
|
+
type Globals = Typed<AppGlobalActions> extends true ? AppGlobalActions : {
|
|
360
|
+
[action: string]: ActionTypes;
|
|
361
|
+
};
|
|
362
|
+
type GlobalName = keyof Globals & string;
|
|
363
|
+
type GlobalOf<A extends string> = A extends keyof Globals ? (Globals[A] extends ActionTypes ? Globals[A] : ActionTypes) : ActionTypes;
|
|
364
|
+
/** What `enqueue` takes: a global action, or `<model>.<action>`. */
|
|
365
|
+
export type ActionName = Typed<AppModels> extends true ? GlobalName | {
|
|
366
|
+
[K in keyof AppModels & string]: AppModels[K] extends ModelTypes ? `${K}.${keyof AppModels[K]["actions"] & string}` : never;
|
|
367
|
+
}[keyof AppModels & string] : string;
|
|
368
|
+
type ModelOf<N extends string> = N extends keyof AppModels ? (AppModels[N] extends ModelTypes ? AppModels[N] : UntypedModel) : UntypedModel;
|
|
369
|
+
/** A model's record as the API reads it, by name: `ModelRecord<"review">`. Any record before the app has generated types. */
|
|
370
|
+
export type ModelRecord<N extends string> = ModelOf<N>["record"];
|
|
371
|
+
/** What creating or updating a model's record takes, by name. */
|
|
372
|
+
export type ModelInput<N extends string> = ModelOf<N>["input"];
|
|
373
|
+
type ParamsOf<A extends string> = A extends `${infer M}.${infer N}` ? M extends keyof AppModels ? AppModels[M] extends ModelTypes ? N extends keyof AppModels[M]["actions"] ? AppModels[M]["actions"][N]["params"] : never : never : GlobalOf<A>["params"] : GlobalOf<A>["params"];
|
|
200
374
|
export interface RecordPage<T = AppRecord> {
|
|
201
375
|
records: T[];
|
|
202
376
|
hasNextPage: boolean;
|
|
203
377
|
endCursor: string | null;
|
|
204
378
|
}
|
|
205
|
-
/**
|
|
206
|
-
|
|
379
|
+
/**
|
|
380
|
+
* A record being worked on in an action: its fields, plus what the action has asked to happen to it. Its fields read
|
|
381
|
+
* as `any`, since one action file doesn't say which model's it is, so they pass to the generated client's typed calls.
|
|
382
|
+
*/
|
|
383
|
+
export interface ActionRecord {
|
|
384
|
+
id: string;
|
|
385
|
+
createdAt: string;
|
|
386
|
+
updatedAt: string;
|
|
387
|
+
[field: string]: any;
|
|
388
|
+
}
|
|
207
389
|
/** 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. */
|
|
208
390
|
export declare function trackRecord<T extends object>(record: T, model?: string | null, isNew?: boolean): T;
|
|
209
391
|
/** Copies the action's params onto the record: `params.<model>` when the caller nested them, else params themselves. */
|
|
@@ -291,68 +473,75 @@ export interface CheckPasswordOptions {
|
|
|
291
473
|
email?: string;
|
|
292
474
|
ip?: string;
|
|
293
475
|
}
|
|
294
|
-
export interface ModelClient {
|
|
295
|
-
findOne(id: string
|
|
296
|
-
|
|
297
|
-
|
|
476
|
+
export interface ModelClient<M extends ModelTypes = UntypedModel> {
|
|
477
|
+
findOne<S extends SelectOf<M> | undefined = undefined>(id: string, o?: {
|
|
478
|
+
select?: S;
|
|
479
|
+
}): Promise<ReadOf<M, S> | null>;
|
|
480
|
+
findMany<S extends SelectOf<M> | undefined = undefined>(o?: FindManyOptions<M, S>): Promise<RecordPage<ReadOf<M, S>>>;
|
|
481
|
+
findFirst<S extends SelectOf<M> | undefined = undefined>(o?: Omit<FindManyOptions<M, S>, "first" | "after">): Promise<ReadOf<M, S> | null>;
|
|
298
482
|
/** Nearest records to text (embedded with the field's model) or a vector, nearest first, with `_distance`. */
|
|
299
|
-
search(field:
|
|
483
|
+
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> & {
|
|
300
484
|
_distance: number;
|
|
301
485
|
}>>;
|
|
302
486
|
/** Writes at once. In an action, that's outside its transaction: to write with the run, `build` and `save` instead. */
|
|
303
|
-
create(values:
|
|
304
|
-
update(id: string, values:
|
|
487
|
+
create(values: M["input"]): Promise<M["record"]>;
|
|
488
|
+
update(id: string, values: M["input"]): Promise<M["record"]>;
|
|
305
489
|
delete(id: string): Promise<void>;
|
|
306
490
|
/**
|
|
307
491
|
* A new record for an action's `run` to `save()`, written with the action's own record in one transaction. It has
|
|
308
492
|
* its id already, so other records can point at it. Only an action's `api` builds records.
|
|
309
493
|
*/
|
|
310
|
-
build(values?:
|
|
494
|
+
build(values?: M["input"]): M["record"];
|
|
311
495
|
/**
|
|
312
496
|
* Whether `password` is the one stored in the record's password field (`password` unless named). Hashes are never
|
|
313
497
|
* returned. Failures are counted per `email` (the record without one) and per visitor `ip`; past the limit it throws
|
|
314
498
|
* an ApiError with status 429 and a message to show, without checking.
|
|
315
499
|
*/
|
|
316
|
-
checkPassword(id: string, password: string, field?:
|
|
500
|
+
checkPassword(id: string, password: string, field?: M["passwords"] | (CheckPasswordOptions & {
|
|
501
|
+
field?: M["passwords"];
|
|
502
|
+
})): Promise<boolean>;
|
|
317
503
|
/** Runs one of the model's actions: on a record when `id` is given, else as a new one; `shop` gives it `shopify`. */
|
|
318
|
-
run(action:
|
|
504
|
+
run<A extends keyof M["actions"] & string>(action: A, o?: {
|
|
319
505
|
id?: string;
|
|
320
|
-
params?:
|
|
506
|
+
params?: M["actions"][A]["params"];
|
|
321
507
|
shop?: string;
|
|
322
508
|
}): Promise<{
|
|
323
|
-
record:
|
|
324
|
-
result?:
|
|
509
|
+
record: M["record"] | null;
|
|
510
|
+
result?: M["actions"][A]["result"];
|
|
325
511
|
}>;
|
|
326
512
|
/**
|
|
327
513
|
* A direct upload for a file field, for a browser to PUT a file to (up to 1 GiB) without it passing through the app.
|
|
328
514
|
* Give `size` and the upload takes at most that many bytes.
|
|
329
515
|
*/
|
|
330
|
-
createUpload(field:
|
|
516
|
+
createUpload(field: M["files"], o?: {
|
|
331
517
|
fileName?: string;
|
|
332
518
|
mimeType?: string;
|
|
333
519
|
size?: number;
|
|
334
520
|
}): Promise<Upload>;
|
|
335
521
|
/** Uploads a file for a file field, straight to storage, and answers the value to write to the field. */
|
|
336
|
-
upload(field:
|
|
522
|
+
upload(field: M["files"], body: Blob | ArrayBuffer | Uint8Array, o?: {
|
|
337
523
|
fileName?: string;
|
|
338
524
|
mimeType?: string;
|
|
339
525
|
}): Promise<{
|
|
340
526
|
directUploadToken: string;
|
|
341
527
|
}>;
|
|
342
528
|
}
|
|
343
|
-
export type Api = {
|
|
344
|
-
|
|
345
|
-
|
|
529
|
+
export type Api = ModelClients & {
|
|
530
|
+
/**
|
|
531
|
+
* A model by name, for one the app may not have: a Shopify model it syncs only once it's chosen. Typed as
|
|
532
|
+
* `api.<model>` is when the generated types list it, any name otherwise; a model that doesn't exist answers 404.
|
|
533
|
+
*/
|
|
534
|
+
$model<N extends string>(name: N): ModelClient<ModelOf<N>>;
|
|
346
535
|
/** Runs a global action (`api/actions/<name>.ts`). */
|
|
347
|
-
$global(action:
|
|
348
|
-
result?:
|
|
536
|
+
$global<A extends GlobalName>(action: A, params?: GlobalOf<A>["params"]): Promise<{
|
|
537
|
+
result?: GlobalOf<A>["result"];
|
|
349
538
|
}>;
|
|
350
539
|
/**
|
|
351
540
|
* Queues an action as a background job and returns at once: a global action's name, or `<model>.<action>` (with
|
|
352
541
|
* `id` for the record). It gets five minutes unless the action's `timeoutMS` says (up to 15), and is retried when
|
|
353
542
|
* it fails.
|
|
354
543
|
*/
|
|
355
|
-
enqueue(action:
|
|
544
|
+
enqueue<A extends ActionName>(action: A, params?: ParamsOf<A>, options?: EnqueueOptions): Promise<Job>;
|
|
356
545
|
/**
|
|
357
546
|
* The same API for one store: store-owned models (Shopify's, and any with a text field named `shop`) show only that
|
|
358
547
|
* 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.
|
|
@@ -520,6 +709,69 @@ export interface ShopifyClientOptions extends ClientOptions {
|
|
|
520
709
|
}
|
|
521
710
|
/** The Admin API for `shop`, as the environment (the same options as createClient). */
|
|
522
711
|
export declare function createShopifyClient(shop: string, o?: ShopifyClientOptions): ShopifyClient;
|
|
712
|
+
/**
|
|
713
|
+
* Models through Inference Bureau's gateway, billed to the team like the app's embeddings: no provider key to manage.
|
|
714
|
+
* Each call is an ordinary gateway request on the team's Apps AI key, so Directives, budgets and the balance apply, it
|
|
715
|
+
* shows in the gateway's Logs, and the app's Logs has it (model, tokens, cost) under the action that made it.
|
|
716
|
+
*
|
|
717
|
+
* The client is also the settings of an OpenAI-compatible provider: `createInferenceBureau(ai)` from
|
|
718
|
+
* `@inferencebureau/ai-sdk-provider` (or `createOpenAI({ baseURL: ai.baseURL, apiKey: ai.apiKey, headers: ai.headers })`)
|
|
719
|
+
* gives the AI SDK's `generateText`, `streamText`, `generateObject` and tools.
|
|
720
|
+
*/
|
|
721
|
+
export interface AiClient {
|
|
722
|
+
/** The gateway for this environment, with chat completions, Anthropic Messages and embeddings under it. */
|
|
723
|
+
baseURL: string;
|
|
724
|
+
/** What to send as the API key: the environment's token. */
|
|
725
|
+
apiKey: string;
|
|
726
|
+
/** Sent with every call: ties the call to the action's run in Logs. */
|
|
727
|
+
headers: Record<string, string>;
|
|
728
|
+
/** fetch with the token and headers added, for a client of your own. */
|
|
729
|
+
fetch: typeof fetch;
|
|
730
|
+
/** One answer from a chat model: `prompt` (with an optional `system`), or `messages`. */
|
|
731
|
+
generateText(o: GenerateTextOptions): Promise<GenerateTextResult>;
|
|
732
|
+
/** Vectors for the texts, in order (openai/text-embedding-3-small unless `model` names another). */
|
|
733
|
+
embed(input: string | string[], o?: {
|
|
734
|
+
model?: string;
|
|
735
|
+
signal?: AbortSignal;
|
|
736
|
+
}): Promise<number[][]>;
|
|
737
|
+
}
|
|
738
|
+
export interface AiMessage {
|
|
739
|
+
role: "system" | "user" | "assistant";
|
|
740
|
+
content: string;
|
|
741
|
+
}
|
|
742
|
+
export interface GenerateTextOptions {
|
|
743
|
+
/** A catalog id (`openai/gpt-5-mini`, `anthropic/claude-sonnet-4.5`) or a team alias, as Directives allow. */
|
|
744
|
+
model: string;
|
|
745
|
+
prompt?: string;
|
|
746
|
+
system?: string;
|
|
747
|
+
messages?: AiMessage[];
|
|
748
|
+
maxTokens?: number;
|
|
749
|
+
temperature?: number;
|
|
750
|
+
/** Answer with a JSON object (say what shape in the prompt); `text` is then the JSON. */
|
|
751
|
+
json?: boolean;
|
|
752
|
+
signal?: AbortSignal;
|
|
753
|
+
}
|
|
754
|
+
export interface GenerateTextResult {
|
|
755
|
+
text: string;
|
|
756
|
+
/** The model that answered (a fallback in Directives may differ from the one asked for). */
|
|
757
|
+
model: string;
|
|
758
|
+
finishReason: string | null;
|
|
759
|
+
usage: {
|
|
760
|
+
inputTokens: number;
|
|
761
|
+
outputTokens: number;
|
|
762
|
+
} | null;
|
|
763
|
+
/** The gateway request's id, as Logs shows it. */
|
|
764
|
+
requestId: string | null;
|
|
765
|
+
}
|
|
766
|
+
export interface AiClientOptions extends ClientOptions {
|
|
767
|
+
/** The action run's event, so its calls sit under it in Logs (an action's `ai` has it). */
|
|
768
|
+
event?: string;
|
|
769
|
+
/** Aborts every call (an action's `ai` stops with its run). */
|
|
770
|
+
signal?: AbortSignal;
|
|
771
|
+
}
|
|
772
|
+
export declare const DEFAULT_EMBEDDING_MODEL = "openai/text-embedding-3-small";
|
|
773
|
+
/** Models for the app's code, as the environment (the same options as createClient). */
|
|
774
|
+
export declare function createAiClient(o?: AiClientOptions): AiClient;
|
|
523
775
|
export interface Money {
|
|
524
776
|
amount: number | string;
|
|
525
777
|
currencyCode: string;
|
|
@@ -834,6 +1086,11 @@ export interface ActionContext {
|
|
|
834
1086
|
* staff in the store's admin (verifyShopifySession's), a shopper. Null for the app's own calls, webhooks and jobs.
|
|
835
1087
|
*/
|
|
836
1088
|
caller: ActionCaller | null;
|
|
1089
|
+
/**
|
|
1090
|
+
* Models through Inference Bureau's gateway, billed to the team: `ai.generateText({ model, prompt })`, `ai.embed`,
|
|
1091
|
+
* or `createInferenceBureau(ai)` for the AI SDK. Its calls appear under the run in Logs, and stop with it.
|
|
1092
|
+
*/
|
|
1093
|
+
ai: AiClient;
|
|
837
1094
|
/**
|
|
838
1095
|
* Fires when the run is stopped: its job canceled from the Queue or the API, or its time up. Pass it to `fetch` and
|
|
839
1096
|
* check it between steps of a long loop to stop early; what `run` returns after it fires is dropped.
|
|
@@ -868,6 +1125,25 @@ export interface ActionModule {
|
|
|
868
1125
|
onSuccess?: ActionOnSuccess;
|
|
869
1126
|
options?: ActionOptions;
|
|
870
1127
|
}
|
|
1128
|
+
/**
|
|
1129
|
+
* `export const params` in an action file: what callers pass it, for the app's generated client types
|
|
1130
|
+
* (`web/ib-client.d.ts`) to check calls by. Keep it a plain object literal: Inference Bureau reads it from the file.
|
|
1131
|
+
* It isn't checked at run time. A create or update action takes the model's fields as well.
|
|
1132
|
+
*
|
|
1133
|
+
* export const params: ActionParams = { note: { type: "string" }, notify: { type: "boolean", required: true } };
|
|
1134
|
+
*/
|
|
1135
|
+
export type ActionParams = Record<string, ParamDef>;
|
|
1136
|
+
export interface ParamDef {
|
|
1137
|
+
type: "string" | "number" | "boolean" | "dateTime" | "enum" | "json" | "object" | "array";
|
|
1138
|
+
/** Callers must pass it. */
|
|
1139
|
+
required?: boolean;
|
|
1140
|
+
/** enum: the values it takes. */
|
|
1141
|
+
options?: string[];
|
|
1142
|
+
/** object: its keys. */
|
|
1143
|
+
properties?: Record<string, ParamDef>;
|
|
1144
|
+
/** array: each item. */
|
|
1145
|
+
items?: ParamDef;
|
|
1146
|
+
}
|
|
871
1147
|
export interface ShopifyPrivacyCustomer {
|
|
872
1148
|
id: number;
|
|
873
1149
|
email?: string | null;
|
|
@@ -895,3 +1171,4 @@ export interface ShopifyShopRedactParams {
|
|
|
895
1171
|
shop_id: number;
|
|
896
1172
|
shop_domain: string;
|
|
897
1173
|
}
|
|
1174
|
+
export {};
|
package/dist/index.js
CHANGED
|
@@ -134,10 +134,12 @@ export function createClient(o = {}) {
|
|
|
134
134
|
const model = (name) => {
|
|
135
135
|
const m = `/models/${encodeURIComponent(name)}`;
|
|
136
136
|
const query = (o) => call("POST", `${m}/records/query`, o);
|
|
137
|
+
// Reads answer what `select` picked; the types say so (ReadOf), the wire doesn't.
|
|
137
138
|
return {
|
|
138
|
-
async findOne(id) {
|
|
139
|
+
async findOne(id, o = {}) {
|
|
140
|
+
const q = o.select ? `?select=${encodeURIComponent(JSON.stringify(o.select))}` : "";
|
|
139
141
|
try {
|
|
140
|
-
return await call("GET", `${m}/records/${encodeURIComponent(id)}`);
|
|
142
|
+
return await call("GET", `${m}/records/${encodeURIComponent(id)}${q}`);
|
|
141
143
|
}
|
|
142
144
|
catch (e) {
|
|
143
145
|
if (e instanceof ApiError && e.status === 404)
|
|
@@ -171,6 +173,8 @@ export function createClient(o = {}) {
|
|
|
171
173
|
};
|
|
172
174
|
};
|
|
173
175
|
const cache = new Map();
|
|
176
|
+
const modelNamed = (name) => { if (!cache.has(name))
|
|
177
|
+
cache.set(name, model(name)); return cache.get(name); };
|
|
174
178
|
const $global = (action, params = {}) => call("POST", `/actions/${encodeURIComponent(action)}`, { params });
|
|
175
179
|
const enqueue = (action, params = {}, o = {}) => call("POST", "/jobs", { action, params, ...o, ...(o.runAt instanceof Date ? { runAt: o.runAt.toISOString() } : {}) });
|
|
176
180
|
const sync = "/shopify/sync";
|
|
@@ -206,6 +210,8 @@ export function createClient(o = {}) {
|
|
|
206
210
|
get(_t, prop) {
|
|
207
211
|
if (prop === "$global")
|
|
208
212
|
return $global;
|
|
213
|
+
if (prop === "$model")
|
|
214
|
+
return modelNamed;
|
|
209
215
|
if (prop === "enqueue")
|
|
210
216
|
return enqueue;
|
|
211
217
|
if (prop === "forShop")
|
|
@@ -216,9 +222,7 @@ export function createClient(o = {}) {
|
|
|
216
222
|
return shopifySync;
|
|
217
223
|
if (typeof prop !== "string" || prop === "then")
|
|
218
224
|
return undefined;
|
|
219
|
-
|
|
220
|
-
cache.set(prop, model(prop));
|
|
221
|
-
return cache.get(prop);
|
|
225
|
+
return modelNamed(prop);
|
|
222
226
|
},
|
|
223
227
|
});
|
|
224
228
|
}
|
|
@@ -266,6 +270,63 @@ export function createShopifyClient(shop, o = {}) {
|
|
|
266
270
|
},
|
|
267
271
|
};
|
|
268
272
|
}
|
|
273
|
+
export const DEFAULT_EMBEDDING_MODEL = "openai/text-embedding-3-small";
|
|
274
|
+
/** Models for the app's code, as the environment (the same options as createClient). */
|
|
275
|
+
export function createAiClient(o = {}) {
|
|
276
|
+
const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
|
|
277
|
+
const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
|
|
278
|
+
const app = o.app ?? envVar("IB_APP") ?? "";
|
|
279
|
+
const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
|
|
280
|
+
const f = o.fetch ?? fetch;
|
|
281
|
+
const baseURL = `${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/ai`;
|
|
282
|
+
const headers = o.event ? { "x-ib-event": o.event } : {};
|
|
283
|
+
const withAuth = (input, init = {}) => {
|
|
284
|
+
const h = new Headers(init.headers);
|
|
285
|
+
if (!h.has("authorization"))
|
|
286
|
+
h.set("authorization", `Bearer ${token}`);
|
|
287
|
+
for (const [k, v] of Object.entries(headers))
|
|
288
|
+
if (!h.has(k))
|
|
289
|
+
h.set(k, v);
|
|
290
|
+
const signal = init.signal ?? o.signal;
|
|
291
|
+
return f(input, { ...init, headers: h, ...(signal ? { signal } : {}) });
|
|
292
|
+
};
|
|
293
|
+
async function post(path, body, signal) {
|
|
294
|
+
const res = await withAuth(`${baseURL}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), ...(signal ? { signal } : {}) });
|
|
295
|
+
const text = await res.text();
|
|
296
|
+
let json = {};
|
|
297
|
+
try {
|
|
298
|
+
json = text ? JSON.parse(text) : {};
|
|
299
|
+
}
|
|
300
|
+
catch { /* reported below */ }
|
|
301
|
+
if (!res.ok)
|
|
302
|
+
throw new ApiError(json.error?.message ?? `The gateway answered ${res.status}.`, res.status, json.error?.code ?? null);
|
|
303
|
+
return { json: json, requestId: res.headers.get("x-request-id") };
|
|
304
|
+
}
|
|
305
|
+
return {
|
|
306
|
+
baseURL, apiKey: token, headers, fetch: withAuth,
|
|
307
|
+
async generateText(g) {
|
|
308
|
+
if (!g.prompt && !g.messages?.length)
|
|
309
|
+
throw new Error("generateText needs a prompt or messages.");
|
|
310
|
+
const messages = [...(g.system ? [{ role: "system", content: g.system }] : []), ...(g.messages ?? []), ...(g.prompt ? [{ role: "user", content: g.prompt }] : [])];
|
|
311
|
+
const { json, requestId } = await post("/chat/completions", {
|
|
312
|
+
model: g.model, messages, ...(g.maxTokens !== undefined ? { max_tokens: g.maxTokens } : {}), ...(g.temperature !== undefined ? { temperature: g.temperature } : {}),
|
|
313
|
+
...(g.json ? { response_format: { type: "json_object" } } : {}),
|
|
314
|
+
}, g.signal);
|
|
315
|
+
const choice = json.choices?.[0];
|
|
316
|
+
return {
|
|
317
|
+
text: typeof choice?.message?.content === "string" ? choice.message.content : "", model: json.model ?? g.model, finishReason: choice?.finish_reason ?? null,
|
|
318
|
+
usage: json.usage ? { inputTokens: json.usage.prompt_tokens ?? 0, outputTokens: json.usage.completion_tokens ?? 0 } : null, requestId,
|
|
319
|
+
};
|
|
320
|
+
},
|
|
321
|
+
async embed(input, e = {}) {
|
|
322
|
+
const texts = typeof input === "string" ? [input] : input;
|
|
323
|
+
if (!texts.length)
|
|
324
|
+
return [];
|
|
325
|
+
const { json } = await post("/embeddings", { model: e.model ?? DEFAULT_EMBEDDING_MODEL, input: texts }, e.signal);
|
|
326
|
+
return [...(json.data ?? [])].sort((a, b) => (a.index ?? 0) - (b.index ?? 0)).map((d) => d.embedding);
|
|
327
|
+
},
|
|
328
|
+
};
|
|
329
|
+
}
|
|
269
330
|
export class ShopifyBillingError extends Error {
|
|
270
331
|
userErrors;
|
|
271
332
|
constructor(message, userErrors = []) {
|
|
@@ -387,7 +448,10 @@ export async function currentPlan(shopify, o = {}) {
|
|
|
387
448
|
let read = false;
|
|
388
449
|
if (o.api) {
|
|
389
450
|
try {
|
|
390
|
-
|
|
451
|
+
// By name: an app that doesn't sync it has no such model in its generated types. An api made by an older copy of
|
|
452
|
+
// the SDK has no $model.
|
|
453
|
+
const subs = typeof o.api.$model === "function" ? o.api.$model("shopifyAppSubscription") : o.api.shopifyAppSubscription;
|
|
454
|
+
const r = await subs.findFirst({ filter: { shop: { equals: shopify.shop }, status: { equals: "active" } }, sort: { shopifyCreatedAt: "Descending" } });
|
|
391
455
|
read = true;
|
|
392
456
|
if (r)
|
|
393
457
|
sub = { name: String(r.name ?? ""), status: "ACTIVE", subscriptionId: String(r.shopifyId), test: r.test === true, currentPeriodEnd: r.currentPeriodEnd ?? null, trialDays: Number(r.trialDays ?? 0), createdAt: String(r.shopifyCreatedAt ?? r.createdAt), source: "synced" };
|
package/dist/runtime.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* `api` read or built. Inference Bureau applies all of it in one transaction, then calls again for `onSuccess` with
|
|
6
6
|
* the saved record.
|
|
7
7
|
*/
|
|
8
|
-
import { type ActionCaller, type ActionModule, type Api, type AppRecord, type LogLine, type ShopifyClient, type StagedWrite } from "./index.js";
|
|
8
|
+
import { type ActionCaller, type AiClient, type ActionModule, type Api, type AppRecord, type LogLine, type ShopifyClient, type StagedWrite } from "./index.js";
|
|
9
9
|
/** Action modules by key: `<model>/<action>` for model actions, `$global/<action>` for global ones. */
|
|
10
10
|
export type ActionRegistry = Record<string, () => Promise<ActionModule>>;
|
|
11
11
|
export interface ActionRequest {
|
|
@@ -23,6 +23,8 @@ export interface ActionRequest {
|
|
|
23
23
|
background?: boolean;
|
|
24
24
|
/** Who called, when the call was held to a role. */
|
|
25
25
|
caller?: ActionCaller | null;
|
|
26
|
+
/** The run's event in Logs: the action's `ai` calls sit under it. */
|
|
27
|
+
event?: string;
|
|
26
28
|
}
|
|
27
29
|
export type ActionResponse = {
|
|
28
30
|
ok: true;
|
|
@@ -46,14 +48,15 @@ export type ActionResponse = {
|
|
|
46
48
|
/** The signature Inference Bureau sends: HMAC-SHA256 of `<timestamp>.<body>` with the environment's token, hex. */
|
|
47
49
|
export declare function sign(token: string, timestamp: string, body: string): Promise<string>;
|
|
48
50
|
/**
|
|
49
|
-
* Runs one phase of an action, without checking where the request came from (handleAction does). `api`
|
|
50
|
-
* `
|
|
51
|
+
* Runs one phase of an action, without checking where the request came from (handleAction does). `api`, `shopify`
|
|
52
|
+
* and `ai` stand in for the environment's clients (the test app's in-memory ones); `echo: false` keeps the logger's
|
|
51
53
|
* lines off the console.
|
|
52
54
|
*/
|
|
53
55
|
export declare function runAction(req: ActionRequest, registry: ActionRegistry, o?: {
|
|
54
56
|
token?: string;
|
|
55
57
|
api?: Api;
|
|
56
58
|
shopify?: (shop: string) => ShopifyClient;
|
|
59
|
+
ai?: AiClient;
|
|
57
60
|
echo?: boolean;
|
|
58
61
|
signal?: AbortSignal;
|
|
59
62
|
}): Promise<ActionResponse>;
|
package/dist/runtime.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* `api` read or built. Inference Bureau applies all of it in one transaction, then calls again for `onSuccess` with
|
|
6
6
|
* the saved record.
|
|
7
7
|
*/
|
|
8
|
-
import { createClient, createShopifyClient, newRecordId, pendingWrite, stagedWrites, trackRecord } from "./index.js";
|
|
8
|
+
import { createAiClient, createClient, createShopifyClient, newRecordId, pendingWrite, stagedWrites, trackRecord } from "./index.js";
|
|
9
9
|
const SKEW_MS = 5 * 60_000;
|
|
10
10
|
const encoder = new TextEncoder();
|
|
11
11
|
const envVar = (name) => globalThis.process?.env?.[name];
|
|
@@ -46,7 +46,7 @@ function stagingApi(api, handed) {
|
|
|
46
46
|
keep(model, r); return p; };
|
|
47
47
|
const wrap = (name, m) => ({
|
|
48
48
|
...m,
|
|
49
|
-
findOne: async (id) => keep(name, await m.findOne(id)),
|
|
49
|
+
findOne: async (id, o) => keep(name, await m.findOne(id, o)),
|
|
50
50
|
findFirst: async (o) => keep(name, await m.findFirst(o)),
|
|
51
51
|
findMany: async (o) => page(name, await m.findMany(o)),
|
|
52
52
|
search: async (field, near, o) => page(name, await m.search(field, near, o)),
|
|
@@ -61,6 +61,8 @@ function stagingApi(api, handed) {
|
|
|
61
61
|
const v = Reflect.get(target, prop, receiver);
|
|
62
62
|
if (prop === "forShop" || prop === "asRole")
|
|
63
63
|
return (...args) => stagingApi(v.apply(target, args), handed);
|
|
64
|
+
if (prop === "$model")
|
|
65
|
+
return (name) => receiver[name];
|
|
64
66
|
if (typeof prop !== "string" || prop.startsWith("$") || prop === "then" || prop === "enqueue" || prop === "shopifySync" || !v || typeof v !== "object")
|
|
65
67
|
return v;
|
|
66
68
|
if (!models.has(prop))
|
|
@@ -70,8 +72,8 @@ function stagingApi(api, handed) {
|
|
|
70
72
|
});
|
|
71
73
|
}
|
|
72
74
|
/**
|
|
73
|
-
* Runs one phase of an action, without checking where the request came from (handleAction does). `api`
|
|
74
|
-
* `
|
|
75
|
+
* Runs one phase of an action, without checking where the request came from (handleAction does). `api`, `shopify`
|
|
76
|
+
* and `ai` stand in for the environment's clients (the test app's in-memory ones); `echo: false` keeps the logger's
|
|
75
77
|
* lines off the console.
|
|
76
78
|
*/
|
|
77
79
|
export async function runAction(req, registry, o = {}) {
|
|
@@ -85,10 +87,12 @@ export async function runAction(req, registry, o = {}) {
|
|
|
85
87
|
const record = req.record ? trackRecord({ ...req.record }, req.model) : null;
|
|
86
88
|
const handed = [];
|
|
87
89
|
const logger = collector(logs, o.echo ?? true);
|
|
90
|
+
const signal = o.signal ?? new AbortController().signal;
|
|
88
91
|
const ctx = {
|
|
89
92
|
params: req.params ?? {}, record, api: stagingApi(scopedApi(o.api ?? createClient(o.token ? { token: o.token } : {}), req.shop), handed), logger,
|
|
90
|
-
model: req.model, action: req.action, environment: req.environment, signal
|
|
93
|
+
model: req.model, action: req.action, environment: req.environment, signal,
|
|
91
94
|
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,
|
|
95
|
+
ai: o.ai ?? createAiClient({ ...(o.token ? { token: o.token } : {}), ...(req.event ? { event: req.event } : {}), signal }),
|
|
92
96
|
};
|
|
93
97
|
if (req.phase === "onSuccess") {
|
|
94
98
|
await mod.onSuccess?.(ctx);
|
package/dist/test.d.ts
CHANGED
|
@@ -12,8 +12,8 @@
|
|
|
12
12
|
* `timeoutMS`. Calls run as the system unless a test says who they're for (`runAs`, `api.asRole`, `api.forShop`), and
|
|
13
13
|
* are then held to accessControl/permissions.ib.ts and the store as the API holds them (packages/apps/src/access.ts).
|
|
14
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
|
|
16
|
-
*
|
|
15
|
+
* schedules owe in a window of time. Computed fields are worked out as records.ts's SQL works them out, and a read's
|
|
16
|
+
* `select` follows belongsTo, hasOne, hasMany and hasManyThrough as the API's does.
|
|
17
17
|
*
|
|
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).
|
|
@@ -37,6 +37,26 @@ export interface ShopifyMock {
|
|
|
37
37
|
on(match: string | RegExp, answer: ShopifyAnswer): ShopifyMock;
|
|
38
38
|
calls: ShopifyCall[];
|
|
39
39
|
}
|
|
40
|
+
/** A chat call an action made through its `ai` client: the model, the messages, and the last user message's text. */
|
|
41
|
+
export interface AiCall {
|
|
42
|
+
model: string;
|
|
43
|
+
messages: {
|
|
44
|
+
role: string;
|
|
45
|
+
content: unknown;
|
|
46
|
+
}[];
|
|
47
|
+
prompt: string;
|
|
48
|
+
body: Record<string, unknown>;
|
|
49
|
+
}
|
|
50
|
+
/** The reply's text, or a function of the call returning it; a function that throws fails the call. */
|
|
51
|
+
export type AiAnswer = string | ((call: AiCall) => string | Promise<string>);
|
|
52
|
+
export interface AiMock {
|
|
53
|
+
/**
|
|
54
|
+
* Answers chat calls whose last user message contains `match` (or matches the RegExp) with `answer`, through
|
|
55
|
+
* `ai.generateText` and the AI SDK alike, streamed or not. The latest match wins. `ai.embed` uses the test app's `embed`.
|
|
56
|
+
*/
|
|
57
|
+
on(match: string | RegExp, answer: AiAnswer): AiMock;
|
|
58
|
+
calls: AiCall[];
|
|
59
|
+
}
|
|
40
60
|
/**
|
|
41
61
|
* Shopify's webhook payloads (REST-shaped, as deliveries arrive), filled with believable values. Pass what the test
|
|
42
62
|
* cares about; the rest is made up. Ids are unique within the test run.
|
|
@@ -287,11 +307,13 @@ export interface TestApp {
|
|
|
287
307
|
to?: Date | string | number;
|
|
288
308
|
}): Promise<Job[]>;
|
|
289
309
|
shopify: ShopifyMock;
|
|
310
|
+
/** The gateway, mocked: what an action's `ai` answers. */
|
|
311
|
+
ai: AiMock;
|
|
290
312
|
/** Everything every action logged, in order. */
|
|
291
313
|
logs: (LogLine & {
|
|
292
314
|
action: string;
|
|
293
315
|
})[];
|
|
294
|
-
/** Empties the records, jobs, logs and
|
|
316
|
+
/** Empties the records, jobs, logs, Shopify and AI calls (mocks stay), e.g. in beforeEach. */
|
|
295
317
|
reset(): void;
|
|
296
318
|
}
|
|
297
319
|
export declare function createTestApp(o?: TestAppOptions): TestApp;
|
package/dist/test.js
CHANGED
|
@@ -12,13 +12,13 @@
|
|
|
12
12
|
* `timeoutMS`. Calls run as the system unless a test says who they're for (`runAs`, `api.asRole`, `api.forShop`), and
|
|
13
13
|
* are then held to accessControl/permissions.ib.ts and the store as the API holds them (packages/apps/src/access.ts).
|
|
14
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
|
|
16
|
-
*
|
|
15
|
+
* schedules owe in a window of time. Computed fields are worked out as records.ts's SQL works them out, and a read's
|
|
16
|
+
* `select` follows belongsTo, hasOne, hasMany and hasManyThrough as the API's does.
|
|
17
17
|
*
|
|
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, newRecordId } from "./index.js";
|
|
21
|
+
import { ApiError, ShopifyError, createAiClient, 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"]);
|
|
@@ -37,6 +37,8 @@ function modelOf(name, schema) {
|
|
|
37
37
|
throw new Error(`${name}: two fields store their values under ${dup.key}; give ${dup.name} its own storageKey`);
|
|
38
38
|
return { name, fields, byName: new Map(fields.map((f) => [f.name, f])) };
|
|
39
39
|
}
|
|
40
|
+
const RELATIONSHIPS = new Set(["belongsTo", "hasOne", "hasMany", "hasManyThrough"]);
|
|
41
|
+
const both = (a, b) => (a && b ? { AND: [a, b] } : a ?? b);
|
|
40
42
|
const ok = (value) => ({ ok: true, value });
|
|
41
43
|
const bad = (message) => ({ ok: false, message });
|
|
42
44
|
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
@@ -526,10 +528,14 @@ class Records {
|
|
|
526
528
|
return new Map([...this.rows].map(([m, t]) => [m, new Map([...t].map(([id, r]) => [id, { ...r, vectors: new Map(r.vectors) }]))]));
|
|
527
529
|
}
|
|
528
530
|
restore(rows) { this.rows = rows; }
|
|
529
|
-
present(m, row, vectors) {
|
|
530
|
-
const out = { id: row.id
|
|
531
|
+
present(m, row, vectors, only = null) {
|
|
532
|
+
const out = { id: row.id };
|
|
533
|
+
if (!only || only.has("createdAt"))
|
|
534
|
+
out.createdAt = row.createdAt;
|
|
535
|
+
if (!only || only.has("updatedAt"))
|
|
536
|
+
out.updatedAt = row.updatedAt;
|
|
531
537
|
for (const f of m.fields) {
|
|
532
|
-
if (f.type === "password")
|
|
538
|
+
if (f.type === "password" || (only && !only.has(f.name)))
|
|
533
539
|
continue;
|
|
534
540
|
if (f.type === "vector") {
|
|
535
541
|
const v = row.vectors.get(f.key);
|
|
@@ -554,10 +560,13 @@ class Records {
|
|
|
554
560
|
}
|
|
555
561
|
return out;
|
|
556
562
|
}
|
|
557
|
-
findOne(model, id) {
|
|
563
|
+
findOne(model, id, o = {}) {
|
|
558
564
|
const m = this.model(model);
|
|
565
|
+
const plan = this.plan(m, o.select);
|
|
559
566
|
const row = this.table(m).get(id);
|
|
560
|
-
|
|
567
|
+
if (!row)
|
|
568
|
+
return null;
|
|
569
|
+
return plan ? this.selected(m, row, plan, o.readable, { left: 5000 }, false) : this.present(m, row, true);
|
|
561
570
|
}
|
|
562
571
|
/** Every record, oldest first. */
|
|
563
572
|
all(model) {
|
|
@@ -618,7 +627,9 @@ class Records {
|
|
|
618
627
|
};
|
|
619
628
|
}
|
|
620
629
|
childrenOf(m, rel) {
|
|
621
|
-
const
|
|
630
|
+
const at = rel.type === "hasOne" ? "child" : "children";
|
|
631
|
+
const v = rel.def[at];
|
|
632
|
+
const to = isObj(v) ? v : {};
|
|
622
633
|
const cm = typeof to.model === "string" ? this.models.get(to.model) : undefined;
|
|
623
634
|
if (!cm)
|
|
624
635
|
throw new Error(`${rel.name} points at ${typeof to.model === "string" ? to.model : "no model"}, which doesn't exist`);
|
|
@@ -627,7 +638,7 @@ class Records {
|
|
|
627
638
|
const named = typeof to.belongsToField === "string" && to.belongsToField ? cm.byName.get(to.belongsToField) : undefined;
|
|
628
639
|
const link = named ?? (links.length === 1 ? links[0] : undefined);
|
|
629
640
|
if (!link || link.type !== "belongsTo") {
|
|
630
|
-
throw new Error(typeof to.belongsToField === "string" && to.belongsToField ? `${cm.name} has no belongsTo field named ${to.belongsToField}` : `${rel.name} needs
|
|
641
|
+
throw new Error(typeof to.belongsToField === "string" && to.belongsToField ? `${cm.name} has no belongsTo field named ${to.belongsToField}` : `${rel.name} needs ${at}.belongsToField: the field on ${cm.name} that points back`);
|
|
631
642
|
}
|
|
632
643
|
return { model: cm, link };
|
|
633
644
|
}
|
|
@@ -889,6 +900,7 @@ class Records {
|
|
|
889
900
|
}
|
|
890
901
|
async findMany(model, o = {}) {
|
|
891
902
|
const m = this.model(model);
|
|
903
|
+
const plan = this.plan(m, o.select);
|
|
892
904
|
const first = Math.min(Math.max(1, Math.floor(o.first ?? 50)), MAX_PAGE);
|
|
893
905
|
const offset = offsetOf(o.after);
|
|
894
906
|
let rows = [...this.table(m).values()].filter((r) => this.matches(m, r, o.filter));
|
|
@@ -925,8 +937,10 @@ class Records {
|
|
|
925
937
|
else
|
|
926
938
|
rows = this.sorted(m, rows, o.sort);
|
|
927
939
|
const page = rows.slice(offset, offset + first);
|
|
940
|
+
const budget = { left: 5000 };
|
|
941
|
+
const read = (r) => (plan ? this.selected(m, r, plan, o.readable, budget, false) : this.present(m, r, false));
|
|
928
942
|
return {
|
|
929
|
-
records: page.map((r) => (distances ? { ...
|
|
943
|
+
records: page.map((r) => (distances ? { ...read(r), _distance: distances.get(r.id) } : read(r))),
|
|
930
944
|
hasNextPage: rows.length > offset + first,
|
|
931
945
|
endCursor: page.length ? cursorOf(offset + page.length) : null,
|
|
932
946
|
};
|
|
@@ -935,6 +949,128 @@ class Records {
|
|
|
935
949
|
const m = this.model(model);
|
|
936
950
|
return [...this.table(m).values()].filter((r) => this.matches(m, r, filter)).length;
|
|
937
951
|
}
|
|
952
|
+
// ---- select (records.ts: planOf, attach) ----
|
|
953
|
+
/** A select checked against the model, as records.ts's planOf checks it; null when unset. */
|
|
954
|
+
plan(m, select, path = "select", depth = 0) {
|
|
955
|
+
if (select === undefined || select === null)
|
|
956
|
+
return null;
|
|
957
|
+
const wrong = (field, message) => invalid([{ field, message }]);
|
|
958
|
+
if (!isObj(select))
|
|
959
|
+
throw wrong(path, "must be an object of field names, like { title: true }");
|
|
960
|
+
const fields = new Set();
|
|
961
|
+
const relations = [];
|
|
962
|
+
for (const [name, v] of Object.entries(select)) {
|
|
963
|
+
const at = `${path}.${name}`;
|
|
964
|
+
const f = m.byName.get(name);
|
|
965
|
+
if (!f && !SYSTEM.includes(name))
|
|
966
|
+
throw wrong(at, `${m.name} has no field named ${name}`);
|
|
967
|
+
if (f?.type === "password")
|
|
968
|
+
throw wrong(at, "password fields are never read");
|
|
969
|
+
if (!f || !RELATIONSHIPS.has(f.type)) {
|
|
970
|
+
if (v !== true)
|
|
971
|
+
throw wrong(at, "takes true");
|
|
972
|
+
fields.add(name);
|
|
973
|
+
continue;
|
|
974
|
+
}
|
|
975
|
+
if (v !== true && !isObj(v))
|
|
976
|
+
throw wrong(at, "takes true, or { select } to choose its records' fields");
|
|
977
|
+
if (depth >= 3)
|
|
978
|
+
throw wrong(at, "related records can be read at most 3 relationships deep");
|
|
979
|
+
const o = v === true ? {} : v;
|
|
980
|
+
const many = f.type === "hasMany" || f.type === "hasManyThrough";
|
|
981
|
+
for (const k of Object.keys(o)) {
|
|
982
|
+
if (k === "select" || (many && (k === "filter" || k === "sort" || k === "first")))
|
|
983
|
+
continue;
|
|
984
|
+
throw wrong(`${at}.${k}`, many ? "isn't an option; use select, filter, sort or first" : `isn't an option; a ${f.type} takes select`);
|
|
985
|
+
}
|
|
986
|
+
if (o.first !== undefined && (typeof o.first !== "number" || !Number.isInteger(o.first) || o.first < 1 || o.first > MAX_PAGE))
|
|
987
|
+
throw wrong(`${at}.first`, `must be 1 to ${MAX_PAGE}`);
|
|
988
|
+
let rel;
|
|
989
|
+
try {
|
|
990
|
+
rel = this.relatedOf(m, f);
|
|
991
|
+
}
|
|
992
|
+
catch (e) {
|
|
993
|
+
throw wrong(at, e.message);
|
|
994
|
+
}
|
|
995
|
+
if (f.type === "belongsTo")
|
|
996
|
+
fields.add(name);
|
|
997
|
+
const probe = { id: "", createdAt: "", updatedAt: "", data: {}, vectors: new Map() };
|
|
998
|
+
try {
|
|
999
|
+
this.matches(rel.target, probe, o.filter);
|
|
1000
|
+
this.sorted(rel.target, [], o.sort);
|
|
1001
|
+
}
|
|
1002
|
+
catch (e) {
|
|
1003
|
+
if (e instanceof ApiError)
|
|
1004
|
+
throw invalid(e.problems.map((p) => ({ field: `${at}.${p.field}`, message: p.message })));
|
|
1005
|
+
throw e;
|
|
1006
|
+
}
|
|
1007
|
+
relations.push({
|
|
1008
|
+
field: f, ...rel, filter: o.filter, sort: o.sort,
|
|
1009
|
+
first: f.type === "hasOne" ? 1 : (o.first ?? 50), plan: this.plan(rel.target, o.select ?? undefined, `${at}.select`, depth + 1),
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
return { fields, relations };
|
|
1013
|
+
}
|
|
1014
|
+
relatedOf(m, f) {
|
|
1015
|
+
const parentOf = (x) => (isObj(x.def.parent) && typeof x.def.parent.model === "string" ? x.def.parent.model : null);
|
|
1016
|
+
if (f.type === "belongsTo") {
|
|
1017
|
+
const target = this.models.get(parentOf(f) ?? "");
|
|
1018
|
+
if (!target)
|
|
1019
|
+
throw new Error(`${f.name} points at ${parentOf(f) ?? "no model"}, which doesn't exist`);
|
|
1020
|
+
return { target, link: null, join: null };
|
|
1021
|
+
}
|
|
1022
|
+
if (f.type === "hasOne" || f.type === "hasMany") {
|
|
1023
|
+
const c = this.childrenOf(m, f);
|
|
1024
|
+
return { target: c.model, link: c.link, join: null };
|
|
1025
|
+
}
|
|
1026
|
+
const t = isObj(f.def.through) ? f.def.through : {};
|
|
1027
|
+
const jm = typeof t.model === "string" ? this.models.get(t.model) : undefined;
|
|
1028
|
+
if (!jm)
|
|
1029
|
+
throw new Error(`${f.name} goes through ${typeof t.model === "string" ? t.model : "no model"}, which doesn't exist`);
|
|
1030
|
+
const links = jm.fields.filter((x) => x.type === "belongsTo");
|
|
1031
|
+
const named = (k) => (typeof t[k] === "string" && t[k] ? jm.byName.get(t[k]) : undefined);
|
|
1032
|
+
const one = (xs) => (xs.length === 1 ? xs[0] : undefined);
|
|
1033
|
+
const self = named("belongsToSelfField") ?? one(links.filter((x) => parentOf(x) === m.name));
|
|
1034
|
+
if (!self || self.type !== "belongsTo")
|
|
1035
|
+
throw new Error(`${f.name} needs through.belongsToSelfField: the field on ${jm.name} that points at ${m.name}`);
|
|
1036
|
+
const sibling = named("belongsToSiblingField") ?? one(links.filter((x) => x !== self));
|
|
1037
|
+
if (!sibling || sibling.type !== "belongsTo")
|
|
1038
|
+
throw new Error(`${f.name} needs through.belongsToSiblingField: the field on ${jm.name} that points at the records it reaches`);
|
|
1039
|
+
const target = this.models.get(parentOf(sibling) ?? "");
|
|
1040
|
+
if (!target)
|
|
1041
|
+
throw new Error(`${jm.name}.${sibling.name} points at ${parentOf(sibling) ?? "no model"}, which doesn't exist`);
|
|
1042
|
+
return { target, link: null, join: { model: jm, self, sibling } };
|
|
1043
|
+
}
|
|
1044
|
+
/** A row as `plan` reads it, with its related records through `readable` (the caller's filter for each model). */
|
|
1045
|
+
selected(m, row, plan, readable, budget, vectors) {
|
|
1046
|
+
const out = this.present(m, row, vectors || m.fields.some((f) => f.type === "vector" && plan.fields.has(f.name)), plan.fields);
|
|
1047
|
+
for (const rel of plan.relations) {
|
|
1048
|
+
const filter = both(readable?.(rel.target), rel.filter);
|
|
1049
|
+
const t = rel.target;
|
|
1050
|
+
let rows;
|
|
1051
|
+
if (rel.link)
|
|
1052
|
+
rows = this.sorted(t, [...this.table(t).values()].filter((r) => r.data[rel.link.key] === row.id && this.matches(t, r, filter)), rel.sort);
|
|
1053
|
+
else if (rel.join) {
|
|
1054
|
+
const { model: jm, self, sibling } = rel.join;
|
|
1055
|
+
const jf = readable?.(jm);
|
|
1056
|
+
const reached = [...this.table(jm).values()].filter((j) => j.data[self.key] === row.id && this.matches(jm, j, jf))
|
|
1057
|
+
.map((j) => this.table(t).get(j.data[sibling.key])).filter((r) => !!r && this.matches(t, r, filter));
|
|
1058
|
+
rows = this.sorted(t, reached, rel.sort);
|
|
1059
|
+
}
|
|
1060
|
+
else {
|
|
1061
|
+
const id = out[rel.field.name];
|
|
1062
|
+
const r = typeof id === "string" ? this.table(t).get(id) : undefined;
|
|
1063
|
+
rows = r && this.matches(t, r, filter) ? [r] : [];
|
|
1064
|
+
}
|
|
1065
|
+
const kept = rows.slice(0, rel.first + 1);
|
|
1066
|
+
budget.left -= kept.length;
|
|
1067
|
+
if (budget.left < 0)
|
|
1068
|
+
throw invalid([{ field: `select.${rel.field.name}`, message: "reads more than 5000 related records in all; ask for fewer with first" }]);
|
|
1069
|
+
const read = kept.slice(0, rel.first).map((r) => (rel.plan ? this.selected(t, r, rel.plan, readable, budget, false) : this.present(t, r, false)));
|
|
1070
|
+
out[rel.field.name] = rel.field.type === "hasMany" || rel.field.type === "hasManyThrough" ? { records: read, hasNextPage: kept.length > rel.first } : read[0] ?? null;
|
|
1071
|
+
}
|
|
1072
|
+
return out;
|
|
1073
|
+
}
|
|
938
1074
|
// ---- writing ----
|
|
939
1075
|
prepare(m, params, current) {
|
|
940
1076
|
if (!isObj(params))
|
|
@@ -1160,6 +1296,56 @@ function shopifyMock() {
|
|
|
1160
1296
|
};
|
|
1161
1297
|
return mock;
|
|
1162
1298
|
}
|
|
1299
|
+
const textOf = (content) => typeof content === "string" ? content
|
|
1300
|
+
: Array.isArray(content) ? content.map((p) => (p && typeof p === "object" && typeof p.text === "string" ? p.text : "")).join("") : "";
|
|
1301
|
+
/** The gateway as the test app's `ai` sees it: chat completions answered from `on`'s handlers, embeddings by `embed`. */
|
|
1302
|
+
function aiMock(embed) {
|
|
1303
|
+
const handlers = [];
|
|
1304
|
+
const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "x-request-id": "req_test" } });
|
|
1305
|
+
const refuse = (status, message) => json(status, { error: { code: "invalid_request", message } });
|
|
1306
|
+
const serve = async (input, init = {}) => {
|
|
1307
|
+
const path = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url).pathname;
|
|
1308
|
+
const body = JSON.parse(typeof init.body === "string" ? init.body : "{}");
|
|
1309
|
+
const model = String(body.model ?? "");
|
|
1310
|
+
if (path.endsWith("/embeddings")) {
|
|
1311
|
+
if (!embed)
|
|
1312
|
+
return refuse(400, "The test app has no embed function: pass `embed` to createTestApp or loadApp.");
|
|
1313
|
+
const texts = typeof body.input === "string" ? [body.input] : body.input;
|
|
1314
|
+
const vectors = await embed(model, texts);
|
|
1315
|
+
return json(200, { object: "list", model, data: vectors.map((embedding, index) => ({ object: "embedding", index, embedding })), usage: { prompt_tokens: 0, total_tokens: 0 } });
|
|
1316
|
+
}
|
|
1317
|
+
if (!path.endsWith("/chat/completions"))
|
|
1318
|
+
return refuse(404, `The test app's ai answers chat completions and embeddings, not ${path.replace(/^.*\/ai/, "")}. Use the chat model (ib(model) or ib.chat).`);
|
|
1319
|
+
const messages = (Array.isArray(body.messages) ? body.messages : []);
|
|
1320
|
+
const prompt = textOf([...messages].reverse().find((m) => m.role === "user")?.content);
|
|
1321
|
+
const call = { model, messages, prompt, body };
|
|
1322
|
+
mock.calls.push(call);
|
|
1323
|
+
const h = handlers.find((x) => (typeof x.match === "string" ? prompt.includes(x.match) : x.match.test(prompt)));
|
|
1324
|
+
if (!h)
|
|
1325
|
+
return refuse(400, `No mock answers this prompt; add one with app.ai.on(…): ${prompt.replace(/\s+/g, " ").trim().slice(0, 120)}`);
|
|
1326
|
+
let text;
|
|
1327
|
+
try {
|
|
1328
|
+
text = typeof h.answer === "function" ? await h.answer(call) : h.answer;
|
|
1329
|
+
}
|
|
1330
|
+
catch (e) {
|
|
1331
|
+
return refuse(400, e.message);
|
|
1332
|
+
}
|
|
1333
|
+
const usage = { prompt_tokens: Math.ceil(prompt.length / 4), completion_tokens: Math.ceil(text.length / 4), total_tokens: 0 };
|
|
1334
|
+
usage.total_tokens = usage.prompt_tokens + usage.completion_tokens;
|
|
1335
|
+
const base = { id: "chatcmpl-test", created: Math.floor(Date.now() / 1000), model };
|
|
1336
|
+
if (!body.stream)
|
|
1337
|
+
return json(200, { ...base, object: "chat.completion", choices: [{ index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" }], usage });
|
|
1338
|
+
const chunk = (delta, finish, extra = {}) => `data: ${JSON.stringify({ ...base, object: "chat.completion.chunk", choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`;
|
|
1339
|
+
const sse = chunk({ role: "assistant", content: text }, null) + chunk({}, "stop", { usage }) + "data: [DONE]\n\n";
|
|
1340
|
+
return new Response(sse, { status: 200, headers: { "content-type": "text/event-stream", "x-request-id": "req_test" } });
|
|
1341
|
+
};
|
|
1342
|
+
const mock = {
|
|
1343
|
+
calls: [],
|
|
1344
|
+
on(match, answer) { handlers.unshift({ match, answer }); return mock; },
|
|
1345
|
+
client: () => createAiClient({ url: "https://api.test.invalid", token: "ibenv_test", app: "test", fetch: serve }),
|
|
1346
|
+
};
|
|
1347
|
+
return mock;
|
|
1348
|
+
}
|
|
1163
1349
|
let fixtureSeq = 0;
|
|
1164
1350
|
const nextId = () => 1000 + ++fixtureSeq;
|
|
1165
1351
|
const iso = (t = Date.now()) => new Date(t).toISOString();
|
|
@@ -1712,6 +1898,7 @@ export function createTestApp(o = {}) {
|
|
|
1712
1898
|
const registry = Object.fromEntries(Object.entries(o.actions ?? {}).map(([k, m]) => [k, typeof m === "function" ? m : async () => m]));
|
|
1713
1899
|
const environment = o.environment ?? "development";
|
|
1714
1900
|
const shopify = shopifyMock();
|
|
1901
|
+
const ai = aiMock(o.embed);
|
|
1715
1902
|
const jobs = [];
|
|
1716
1903
|
const logs = [];
|
|
1717
1904
|
const perms = readPermissions(o.permissions);
|
|
@@ -1761,7 +1948,7 @@ export function createTestApp(o = {}) {
|
|
|
1761
1948
|
});
|
|
1762
1949
|
const req = { phase: p, model, action, params, record: rec, isNew, environment, shop, caller: how.caller ?? null, ...(how.background ? { background: true } : {}) };
|
|
1763
1950
|
try {
|
|
1764
|
-
return await Promise.race([runPhase(wire(req), registry, { api, shopify: shopify.client, echo: o.echo ?? false }), late]);
|
|
1951
|
+
return await Promise.race([runPhase(wire(req), registry, { api, shopify: shopify.client, ai: ai.client(), echo: o.echo ?? false }), late]);
|
|
1765
1952
|
}
|
|
1766
1953
|
finally {
|
|
1767
1954
|
clearTimeout(timer);
|
|
@@ -1821,7 +2008,7 @@ export function createTestApp(o = {}) {
|
|
|
1821
2008
|
};
|
|
1822
2009
|
const otherStore = (shop) => denied(`This call is for ${shop}; it can't reach another store's records.`);
|
|
1823
2010
|
/** The record by id when the filter lets the call see it (undefined: no narrowing), else null. */
|
|
1824
|
-
const findVisible = async (model, id, filter) => (filter ? (await store.findMany(model, { filter: { AND: [{ id: { equals: id } }, filter] }, first: 1 })).records[0] ?? null : store.findOne(model, id));
|
|
2011
|
+
const findVisible = async (model, id, filter, select, readable) => (filter ? (await store.findMany(model, { filter: { AND: [{ id: { equals: id } }, filter] }, first: 1, select, readable })).records[0] ?? null : store.findOne(model, id, { select, readable }));
|
|
1825
2012
|
/** Refuses a run the scope doesn't allow; a record its store or grant doesn't reach is answered as missing. */
|
|
1826
2013
|
async function canRun(scope, model, action, id) {
|
|
1827
2014
|
if (!isScoped(scope))
|
|
@@ -1843,7 +2030,9 @@ export function createTestApp(o = {}) {
|
|
|
1843
2030
|
const modelClient = (name, scope) => {
|
|
1844
2031
|
const scoped = isScoped(scope);
|
|
1845
2032
|
const readOf = (filter) => (scoped ? readFilter(perms, scope, store.model(name), filter) : filter);
|
|
1846
|
-
|
|
2033
|
+
// A select's related records are read through the same store and role, model by model.
|
|
2034
|
+
const readable = scoped ? (m) => readFilter(perms, scope, m) : undefined;
|
|
2035
|
+
const narrow = (q) => { const filter = readOf(q.filter); return { ...q, ...(filter ? { filter } : {}), ...(readable ? { readable } : {}) }; };
|
|
1847
2036
|
// A file goes to a record the role may make or change.
|
|
1848
2037
|
const uploadable = () => {
|
|
1849
2038
|
if (!scoped)
|
|
@@ -1857,7 +2046,7 @@ export function createTestApp(o = {}) {
|
|
|
1857
2046
|
};
|
|
1858
2047
|
return {
|
|
1859
2048
|
build: () => { throw new Error("build() makes a record for an action's run to save(); outside an action, use create()."); },
|
|
1860
|
-
findOne: async (id) => findVisible(name, id, readOf()),
|
|
2049
|
+
findOne: async (id, o = {}) => findVisible(name, id, readOf(), wire(o.select), readable),
|
|
1861
2050
|
findMany: async (q = {}) => store.findMany(name, narrow(wire(q))),
|
|
1862
2051
|
findFirst: async (q = {}) => (await store.findMany(name, { ...narrow(wire(q)), first: 1 })).records[0] ?? null,
|
|
1863
2052
|
search: async (field, near, q = {}) => (await store.findMany(name, { ...narrow(wire(q)), search: { field, near } })),
|
|
@@ -1977,6 +2166,8 @@ export function createTestApp(o = {}) {
|
|
|
1977
2166
|
get(_t, prop) {
|
|
1978
2167
|
if (prop === "$global")
|
|
1979
2168
|
return $global;
|
|
2169
|
+
if (prop === "$model")
|
|
2170
|
+
return (name) => made[name];
|
|
1980
2171
|
if (prop === "enqueue")
|
|
1981
2172
|
return queue;
|
|
1982
2173
|
if (prop === "forShop")
|
|
@@ -2181,8 +2372,9 @@ export function createTestApp(o = {}) {
|
|
|
2181
2372
|
return queued;
|
|
2182
2373
|
},
|
|
2183
2374
|
shopify,
|
|
2375
|
+
ai,
|
|
2184
2376
|
logs,
|
|
2185
|
-
reset() { store.clear(); jobs.length = 0; scheduled.clear(); syncRuns.length = 0; logs.length = 0; shopify.calls.length = 0; },
|
|
2377
|
+
reset() { store.clear(); jobs.length = 0; scheduled.clear(); syncRuns.length = 0; logs.length = 0; shopify.calls.length = 0; ai.calls.length = 0; },
|
|
2186
2378
|
};
|
|
2187
2379
|
}
|
|
2188
2380
|
// ---- 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.10.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": [
|