@inferencebureau/apps-sdk 0.14.0 → 0.15.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/README.md +1 -1
- package/dist/index.d.ts +227 -6
- package/dist/index.js +157 -15
- package/dist/react.d.ts +110 -38
- package/dist/react.js +173 -43
- package/dist/runtime.d.ts +5 -1
- package/dist/runtime.js +10 -3
- package/dist/test.d.ts +2 -1
- package/dist/test.js +328 -14
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@ npm install @inferencebureau/apps-sdk
|
|
|
9
9
|
```
|
|
10
10
|
|
|
11
11
|
Apps built on Inference Bureau get the SDK in every build already; install it to have the types in your editor, or to
|
|
12
|
-
use the client from your own code. It's ESM, uses only `fetch` and Web Crypto, and runs on Node
|
|
12
|
+
use the client from your own code. It's ESM, uses only `fetch` and Web Crypto, and runs on Node 22+, edge runtimes and
|
|
13
13
|
Next.js without `transpilePackages`.
|
|
14
14
|
|
|
15
15
|
```ts
|
package/dist/index.d.ts
CHANGED
|
@@ -30,6 +30,8 @@ export interface FieldDef {
|
|
|
30
30
|
type: FieldType;
|
|
31
31
|
/** Where the field's values are kept. The schema editor sets it; keep it when renaming the field so its values follow. */
|
|
32
32
|
storageKey?: string;
|
|
33
|
+
/** A line on what the field holds, for the app's API reference, its generated types and its MCP server. */
|
|
34
|
+
description?: string;
|
|
33
35
|
default?: unknown;
|
|
34
36
|
validations?: FieldValidations;
|
|
35
37
|
options?: string[];
|
|
@@ -115,6 +117,8 @@ export interface IndexDef {
|
|
|
115
117
|
export interface ModelSchema {
|
|
116
118
|
type: "ib/model-schema/v1";
|
|
117
119
|
storageKey?: string;
|
|
120
|
+
/** A line on what a record of the model is, for the app's API reference, its generated types and its MCP server. */
|
|
121
|
+
description?: string;
|
|
118
122
|
fields: Record<string, FieldDef>;
|
|
119
123
|
indexes?: IndexDef[];
|
|
120
124
|
}
|
|
@@ -138,8 +142,18 @@ export interface AppSettings {
|
|
|
138
142
|
* no credentials for one. Inference Bureau's `ai` client is always on and needs no entry.
|
|
139
143
|
*/
|
|
140
144
|
integrations?: IntegrationSetting[];
|
|
145
|
+
/** Whether the team is emailed when production fails. On unless `{ failures: false }`. */
|
|
146
|
+
alerts?: AlertSetting;
|
|
141
147
|
[key: string]: unknown;
|
|
142
148
|
}
|
|
149
|
+
/**
|
|
150
|
+
* Failure emails: when an action, job, deploy, release or request fails in production, the team's owners, admins and
|
|
151
|
+
* the members who can see the app get an email naming what failed, at most one every 12 hours per app (failures in
|
|
152
|
+
* the meantime are sent together when the 12 hours are up). Development's failures are never emailed.
|
|
153
|
+
*/
|
|
154
|
+
export interface AlertSetting {
|
|
155
|
+
failures?: boolean;
|
|
156
|
+
}
|
|
143
157
|
/** `resend`: the app's email through the team's own Resend account, as RESEND_API_KEY and EMAIL_FROM. */
|
|
144
158
|
export type IntegrationSetting = "resend";
|
|
145
159
|
/**
|
|
@@ -149,7 +163,7 @@ export type IntegrationSetting = "resend";
|
|
|
149
163
|
* Shopify's extensions (https://extensions.shopifycdn.com, where Sidekick tools run) are always allowed.
|
|
150
164
|
*/
|
|
151
165
|
export interface CorsSetting {
|
|
152
|
-
/** `https://shop.example.com`, `https://*.example.com` for its subdomains, `http://localhost:3000`, or `*`. */
|
|
166
|
+
/** `https://shop.example.com`, `https://*.example.com` for its subdomains, `http://localhost:3000`, `http://localhost:*` for any local port, or `*`. */
|
|
153
167
|
origins?: string[];
|
|
154
168
|
/** The paths it covers, e.g. `/api/*` for everything under /api. Every path unless named. */
|
|
155
169
|
paths?: string[];
|
|
@@ -246,11 +260,80 @@ export interface FindManyOptions<M extends ModelTypes = UntypedModel, S extends
|
|
|
246
260
|
* library that asks for an offset; at most 10,000, and not with `after`. Cursors are faster for reading every page.
|
|
247
261
|
*/
|
|
248
262
|
skip?: number;
|
|
249
|
-
/** Words to find in the model's text fields: records holding every one (any case, part of a word counts),
|
|
263
|
+
/** Words to find in the model's text fields: records holding every one (any case, part of a word counts), the best matches first unless sorted: the words together, words that start or are whole words, short fields over rich text. */
|
|
250
264
|
search?: string;
|
|
251
265
|
/** Which fields to read, and which related records with them (SelectOf); every field and no related records when left out. */
|
|
252
266
|
select?: S;
|
|
253
267
|
}
|
|
268
|
+
/**
|
|
269
|
+
* An aggregate: `{ count: true }` counts records, `{ count: "field" }` those holding a value in it, and `{ sum | avg |
|
|
270
|
+
* min | max: "field" }` works one out over a number field (min and max also over dates and text).
|
|
271
|
+
*/
|
|
272
|
+
export type AggregateSpec<F extends string = string> = {
|
|
273
|
+
count: true | F;
|
|
274
|
+
} | {
|
|
275
|
+
sum: F;
|
|
276
|
+
} | {
|
|
277
|
+
avg: F;
|
|
278
|
+
} | {
|
|
279
|
+
min: F;
|
|
280
|
+
} | {
|
|
281
|
+
max: F;
|
|
282
|
+
};
|
|
283
|
+
export type DateInterval = "hour" | "day" | "week" | "month" | "quarter" | "year";
|
|
284
|
+
/**
|
|
285
|
+
* An aggregate query (`aggregate`): the aggregates to work out, each by the name it answers with, over the records
|
|
286
|
+
* `filter` and `search` leave, in groups by `groupBy`'s fields or one group of them all. A dateTime groups by
|
|
287
|
+
* `{ field, interval }` into buckets in `timeZone` (UTC unless given), labelled "2026-10-21T14:00" (hour),
|
|
288
|
+
* "2026-10-21" (day, and week from its Monday), "2026-10", "2026-Q4" or "2026". `sort` orders the groups by a field
|
|
289
|
+
* they're grouped by or an aggregate's name; by the groups' values otherwise. `first` groups (100 unless given, at
|
|
290
|
+
* most 1000), and `hasMore` says when there are more.
|
|
291
|
+
*
|
|
292
|
+
* const { groups } = await api.review.aggregate({
|
|
293
|
+
* groupBy: ["product", { field: "createdAt", interval: "month" }],
|
|
294
|
+
* aggregates: { reviews: { count: true }, rating: { avg: "rating" } },
|
|
295
|
+
* filter: { status: { equals: "approved" } },
|
|
296
|
+
* });
|
|
297
|
+
* // [{ product: "rec_…", createdAt: "2026-10", reviews: 12, rating: 4.25 }, …]
|
|
298
|
+
*/
|
|
299
|
+
export interface AggregateOptions<M extends ModelTypes = UntypedModel, A extends {
|
|
300
|
+
[name: string]: AggregateSpec<M["sortable"]>;
|
|
301
|
+
} = {
|
|
302
|
+
[name: string]: AggregateSpec<M["sortable"]>;
|
|
303
|
+
}> {
|
|
304
|
+
groupBy?: (M["sortable"] | {
|
|
305
|
+
field: M["sortable"];
|
|
306
|
+
interval: DateInterval;
|
|
307
|
+
})[];
|
|
308
|
+
aggregates: A;
|
|
309
|
+
filter?: Filter<M["filter"]>;
|
|
310
|
+
search?: string;
|
|
311
|
+
sort?: {
|
|
312
|
+
[name: string]: SortDirection;
|
|
313
|
+
} | {
|
|
314
|
+
[name: string]: SortDirection;
|
|
315
|
+
}[];
|
|
316
|
+
first?: number;
|
|
317
|
+
timeZone?: string;
|
|
318
|
+
}
|
|
319
|
+
/** One group: the values it's grouped by, and each aggregate by its name (a count is always a number). */
|
|
320
|
+
export type AggregateGroup<A = {
|
|
321
|
+
[name: string]: AggregateSpec;
|
|
322
|
+
}> = string extends keyof A ? {
|
|
323
|
+
[field: string]: string | number | boolean | null;
|
|
324
|
+
} : {
|
|
325
|
+
[K in keyof A]: A[K] extends {
|
|
326
|
+
count: unknown;
|
|
327
|
+
} ? number : number | string | null;
|
|
328
|
+
} & {
|
|
329
|
+
[field: string]: string | number | boolean | null;
|
|
330
|
+
};
|
|
331
|
+
export interface AggregateResult<A = {
|
|
332
|
+
[name: string]: AggregateSpec;
|
|
333
|
+
}> {
|
|
334
|
+
groups: AggregateGroup<A>[];
|
|
335
|
+
hasMore: boolean;
|
|
336
|
+
}
|
|
254
337
|
/**
|
|
255
338
|
* What a read's `select` names: fields as `true` (the id always comes), and relationships as `true` for their records
|
|
256
339
|
* with every field, or `{ select }` to choose theirs. A hasMany or hasManyThrough also takes `filter`, `sort` and
|
|
@@ -409,21 +492,27 @@ export type ModelClients = Typed<AppModels> extends true ? {
|
|
|
409
492
|
} : {
|
|
410
493
|
[model: string]: ModelClient;
|
|
411
494
|
};
|
|
495
|
+
/** A model's name: one the generated file lists, or any before there is one. */
|
|
496
|
+
export type ModelName = Typed<AppModels> extends true ? keyof AppModels & string : string;
|
|
412
497
|
type Globals = Typed<AppGlobalActions> extends true ? AppGlobalActions : {
|
|
413
498
|
[action: string]: ActionTypes;
|
|
414
499
|
};
|
|
415
|
-
|
|
416
|
-
type
|
|
500
|
+
/** A global action's name, the same way. */
|
|
501
|
+
export type GlobalName = keyof Globals & string;
|
|
502
|
+
/** A global action's params and result, by name. */
|
|
503
|
+
export type GlobalOf<A extends string> = A extends keyof Globals ? (Globals[A] extends ActionTypes ? Globals[A] : ActionTypes) : ActionTypes;
|
|
417
504
|
/** What `enqueue` takes: a global action, or `<model>.<action>`. */
|
|
418
505
|
export type ActionName = Typed<AppModels> extends true ? GlobalName | {
|
|
419
506
|
[K in keyof AppModels & string]: AppModels[K] extends ModelTypes ? `${K}.${keyof AppModels[K]["actions"] & string}` : never;
|
|
420
507
|
}[keyof AppModels & string] : string;
|
|
421
|
-
|
|
508
|
+
/** A model's types by name (ModelTypes): the generated file's, or UntypedModel. */
|
|
509
|
+
export type ModelOf<N extends string> = N extends keyof AppModels ? (AppModels[N] extends ModelTypes ? AppModels[N] : UntypedModel) : UntypedModel;
|
|
422
510
|
/** A model's record as the API reads it, by name: `ModelRecord<"review">`. Any record before the app has generated types. */
|
|
423
511
|
export type ModelRecord<N extends string> = ModelOf<N>["record"];
|
|
424
512
|
/** What creating or updating a model's record takes, by name. */
|
|
425
513
|
export type ModelInput<N extends string> = ModelOf<N>["input"];
|
|
426
|
-
|
|
514
|
+
/** What `enqueue` passes an action (ActionName) as its params. */
|
|
515
|
+
export 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"];
|
|
427
516
|
export interface RecordPage<T = AppRecord> {
|
|
428
517
|
records: T[];
|
|
429
518
|
hasNextPage: boolean;
|
|
@@ -599,6 +688,10 @@ export interface ModelClient<M extends ModelTypes = UntypedModel> {
|
|
|
599
688
|
}): Promise<ReadOf<M, S> | null>;
|
|
600
689
|
findMany<S extends SelectOf<M> | undefined = undefined>(o?: FindManyOptions<M, S>): Promise<RecordPage<ReadOf<M, S>>>;
|
|
601
690
|
findFirst<S extends SelectOf<M> | undefined = undefined>(o?: Omit<FindManyOptions<M, S>, "first" | "after">): Promise<ReadOf<M, S> | null>;
|
|
691
|
+
/** Counts, sums, averages, least and most over the records, in groups or all together (AggregateOptions). */
|
|
692
|
+
aggregate<A extends {
|
|
693
|
+
[name: string]: AggregateSpec<M["sortable"]>;
|
|
694
|
+
}>(o: AggregateOptions<M, A>): Promise<AggregateResult<A>>;
|
|
602
695
|
/** Nearest records to text (embedded with the field's model) or a vector, nearest first, with `_distance`. */
|
|
603
696
|
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> & {
|
|
604
697
|
_distance: number;
|
|
@@ -678,6 +771,12 @@ export type Api = ModelClients & {
|
|
|
678
771
|
* `api.<model>` is when the generated types list it, any name otherwise; a model that doesn't exist answers 404.
|
|
679
772
|
*/
|
|
680
773
|
$model<N extends string>(name: N): ModelClient<ModelOf<N>>;
|
|
774
|
+
/**
|
|
775
|
+
* Which of the models had records created, updated or deleted since `cursor`, for a live query to read again.
|
|
776
|
+
* Waits up to `wait` seconds (25 at most) for one to; without a cursor it answers at once with one to start from.
|
|
777
|
+
* Held to the client's store and role as reads are: a store's client hears only of its records.
|
|
778
|
+
*/
|
|
779
|
+
$changes(o: ChangesOptions): Promise<Changes>;
|
|
681
780
|
/** Runs a global action (`api/actions/<name>.ts`). */
|
|
682
781
|
$global<A extends GlobalName>(action: A, params?: GlobalOf<A>["params"]): Promise<{
|
|
683
782
|
result?: GlobalOf<A>["result"];
|
|
@@ -710,7 +809,60 @@ export type Api = ModelClients & {
|
|
|
710
809
|
asRole(role: string, session?: CallerSession): Api;
|
|
711
810
|
/** Shopify sync on demand: one store, some or all of its synced models, everything or what changed since a date. */
|
|
712
811
|
shopifySync: ShopifySync;
|
|
812
|
+
/**
|
|
813
|
+
* The app's own files, by path, apart from any record: an export, a generated image, an asset an action makes.
|
|
814
|
+
* Under `public/` a file is on the CDN with a lasting URL; anywhere else it's private, read through a URL signed for
|
|
815
|
+
* an hour. Counted in the app's storage. Not through a role-held `api`: hand a browser a file's URL from a route.
|
|
816
|
+
*/
|
|
817
|
+
files: FilesClient;
|
|
713
818
|
};
|
|
819
|
+
/** A file in the app's storage. `url` is the CDN's for a public file and signed for an hour for a private one. */
|
|
820
|
+
export interface StorageFile {
|
|
821
|
+
path: string;
|
|
822
|
+
access: "private" | "public";
|
|
823
|
+
url: string | null;
|
|
824
|
+
size: number;
|
|
825
|
+
mimeType: string | null;
|
|
826
|
+
uploadedAt: string;
|
|
827
|
+
}
|
|
828
|
+
export interface StoragePage {
|
|
829
|
+
files: StorageFile[];
|
|
830
|
+
hasNextPage: boolean;
|
|
831
|
+
endCursor: string | null;
|
|
832
|
+
}
|
|
833
|
+
/** A direct upload to storage: PUT the file to `url` with `headers` within the hour; it lands at its path. */
|
|
834
|
+
export interface StorageUpload {
|
|
835
|
+
url: string;
|
|
836
|
+
method: "PUT";
|
|
837
|
+
headers: Record<string, string>;
|
|
838
|
+
expiresAt: string;
|
|
839
|
+
}
|
|
840
|
+
/** The most bytes `files.put` sends in the request itself; a bigger file goes straight to storage. */
|
|
841
|
+
export declare const STORAGE_INLINE_BYTES: number;
|
|
842
|
+
export interface FilesClient {
|
|
843
|
+
/**
|
|
844
|
+
* Stores a file at `path` (segments of letters, digits, `.`, `_` and `-`), replacing one there, up to 1 GiB: over
|
|
845
|
+
* 4 MiB it goes straight to storage. The type is `mimeType`, else the Blob's, else guessed from the path.
|
|
846
|
+
*/
|
|
847
|
+
put(path: string, body: Blob | ArrayBuffer | Uint8Array | string, o?: {
|
|
848
|
+
mimeType?: string;
|
|
849
|
+
}): Promise<StorageFile>;
|
|
850
|
+
/** The file at `path`, with a fresh `url`, or null. */
|
|
851
|
+
get(path: string): Promise<StorageFile | null>;
|
|
852
|
+
/** The files under `prefix` (all of them without one), private ones first: a page of `first` (100 unless given, up to 1000), `after` the previous page's `endCursor`. */
|
|
853
|
+
list(o?: {
|
|
854
|
+
prefix?: string;
|
|
855
|
+
first?: number;
|
|
856
|
+
after?: string | null;
|
|
857
|
+
}): Promise<StoragePage>;
|
|
858
|
+
/** Deletes the file at `path`; nothing happens when there's none. */
|
|
859
|
+
delete(path: string): Promise<void>;
|
|
860
|
+
/** A direct upload for a browser to PUT to (or any file over 4 MiB): at most `size` bytes when given, of `mimeType` (else guessed from the path). */
|
|
861
|
+
createUpload(path: string, o?: {
|
|
862
|
+
mimeType?: string;
|
|
863
|
+
size?: number;
|
|
864
|
+
}): Promise<StorageUpload>;
|
|
865
|
+
}
|
|
714
866
|
export interface SyncRunOptions {
|
|
715
867
|
/** The store (x.myshopify.com); an `api.forShop(shop)` client's own store when left out. */
|
|
716
868
|
shop?: string;
|
|
@@ -767,6 +919,19 @@ export interface ShopifySync {
|
|
|
767
919
|
/** Stops a running run before its next page; what it wrote stays. */
|
|
768
920
|
abort(id: string): Promise<SyncRun>;
|
|
769
921
|
}
|
|
922
|
+
export interface ChangesOptions {
|
|
923
|
+
/** The models to hear about, by name. */
|
|
924
|
+
models: string[];
|
|
925
|
+
/** From the last answer; without one the answer is a cursor for now. */
|
|
926
|
+
cursor?: string | null;
|
|
927
|
+
/** Seconds to wait for a change before answering that none came (0 to 25). */
|
|
928
|
+
wait?: number;
|
|
929
|
+
}
|
|
930
|
+
/** What changed since a cursor: the models, by name, and the cursor to ask with next. */
|
|
931
|
+
export interface Changes {
|
|
932
|
+
cursor: string;
|
|
933
|
+
models: string[];
|
|
934
|
+
}
|
|
770
935
|
/** Who a role-scoped call is for, filling `{ $session: … }` in permissions.ib.ts filters. */
|
|
771
936
|
export interface CallerSession {
|
|
772
937
|
userId?: string | null;
|
|
@@ -831,6 +996,10 @@ export type RecordsRequest = {
|
|
|
831
996
|
model: string;
|
|
832
997
|
id: string;
|
|
833
998
|
select?: Record<string, unknown>;
|
|
999
|
+
} | {
|
|
1000
|
+
op: "aggregate";
|
|
1001
|
+
model: string;
|
|
1002
|
+
options: AggregateOptions;
|
|
834
1003
|
} | {
|
|
835
1004
|
op: "create";
|
|
836
1005
|
model: string;
|
|
@@ -865,12 +1034,33 @@ export type RecordsRequest = {
|
|
|
865
1034
|
op: "global";
|
|
866
1035
|
action: string;
|
|
867
1036
|
params?: Record<string, unknown>;
|
|
1037
|
+
} | {
|
|
1038
|
+
op: "enqueue";
|
|
1039
|
+
action: string;
|
|
1040
|
+
params?: Record<string, unknown>;
|
|
1041
|
+
options?: Omit<EnqueueOptions, "shop" | "runAt"> & {
|
|
1042
|
+
runAt?: string;
|
|
1043
|
+
};
|
|
1044
|
+
} | {
|
|
1045
|
+
op: "changes";
|
|
1046
|
+
models: string[];
|
|
1047
|
+
cursor?: string | null;
|
|
868
1048
|
};
|
|
869
1049
|
export interface ServeRecordsOptions {
|
|
870
1050
|
/** The models the route answers for; every model when unset. */
|
|
871
1051
|
models?: string[];
|
|
872
1052
|
/** The global actions it runs; none when unset. */
|
|
873
1053
|
globalActions?: string[];
|
|
1054
|
+
/**
|
|
1055
|
+
* The actions it queues as background jobs (`useEnqueue`): global actions' names and `<model>.<action>`; none when
|
|
1056
|
+
* unset. A job runs for the request's store and is held to its role, the way `api.enqueue` is.
|
|
1057
|
+
*/
|
|
1058
|
+
enqueueActions?: string[];
|
|
1059
|
+
/**
|
|
1060
|
+
* Seconds a live query's watch waits for a change before the route answers that none came (25 unless given, 0 to
|
|
1061
|
+
* 25). The route's function must be allowed to run that long; a shorter wait just means more requests.
|
|
1062
|
+
*/
|
|
1063
|
+
liveWait?: number;
|
|
874
1064
|
}
|
|
875
1065
|
/**
|
|
876
1066
|
* The app's records route, for its pages' own scripts: the hooks and AutoTable/AutoForm in
|
|
@@ -1336,6 +1526,11 @@ export type GlobalActionRun = (ctx: Omit<ActionContext, "record"> & {
|
|
|
1336
1526
|
export interface ActionOptions {
|
|
1337
1527
|
/** create: works on a new record; update and custom: on the record named by id; delete: removes it. */
|
|
1338
1528
|
actionType?: "create" | "update" | "delete" | "custom";
|
|
1529
|
+
/**
|
|
1530
|
+
* A line on what the action does, for the app's API reference, its generated types and its MCP server. Inference
|
|
1531
|
+
* Bureau reads it from the file, like `params`: keep `options` a plain object literal.
|
|
1532
|
+
*/
|
|
1533
|
+
description?: string;
|
|
1339
1534
|
/** Whether what `run` returns goes back to the caller (it's dropped otherwise). */
|
|
1340
1535
|
returnType?: boolean;
|
|
1341
1536
|
/**
|
|
@@ -1361,6 +1556,8 @@ export interface ParamDef {
|
|
|
1361
1556
|
type: "string" | "number" | "boolean" | "dateTime" | "enum" | "json" | "object" | "array";
|
|
1362
1557
|
/** Callers must pass it. */
|
|
1363
1558
|
required?: boolean;
|
|
1559
|
+
/** A line on what the param is, for the app's API reference, its generated types and its MCP server. */
|
|
1560
|
+
description?: string;
|
|
1364
1561
|
/** enum: the values it takes. */
|
|
1365
1562
|
options?: string[];
|
|
1366
1563
|
/** object: its keys. */
|
|
@@ -1368,6 +1565,30 @@ export interface ParamDef {
|
|
|
1368
1565
|
/** array: each item. */
|
|
1369
1566
|
items?: ParamDef;
|
|
1370
1567
|
}
|
|
1568
|
+
export interface CaptureOptions {
|
|
1569
|
+
/** Searchable in Sentry. Values are cut to 200 characters. */
|
|
1570
|
+
tags?: Record<string, string | number | boolean | null | undefined>;
|
|
1571
|
+
/** Shown on the event, not searchable. */
|
|
1572
|
+
extra?: Record<string, unknown>;
|
|
1573
|
+
level?: "fatal" | "error" | "warning" | "info";
|
|
1574
|
+
/** The runtime's own reports: thrown out of an action, not caught by the app. */
|
|
1575
|
+
handled?: boolean;
|
|
1576
|
+
/** Defaults to SENTRY_DSN. */
|
|
1577
|
+
dsn?: string;
|
|
1578
|
+
/** Defaults to IB_ENVIRONMENT: development or production. */
|
|
1579
|
+
environment?: string;
|
|
1580
|
+
fetch?: typeof fetch;
|
|
1581
|
+
}
|
|
1582
|
+
/** A DSN's parts, or null when it isn't one: `https://<key>@<host>[/<path>]/<project>`. */
|
|
1583
|
+
export declare function parseDsn(dsn: string): {
|
|
1584
|
+
key: string;
|
|
1585
|
+
envelope: string;
|
|
1586
|
+
} | null;
|
|
1587
|
+
/**
|
|
1588
|
+
* Reports an error to the app's Sentry project. Answers the event's id, or null when there's no DSN or Sentry didn't
|
|
1589
|
+
* take it. Never throws, and gives up after three seconds.
|
|
1590
|
+
*/
|
|
1591
|
+
export declare function captureException(error: unknown, o?: CaptureOptions): Promise<string | null>;
|
|
1371
1592
|
export interface ShopifyPrivacyCustomer {
|
|
1372
1593
|
id: number;
|
|
1373
1594
|
email?: string | null;
|
package/dist/index.js
CHANGED
|
@@ -116,6 +116,8 @@ export function newRecordId() {
|
|
|
116
116
|
return `rec_${Date.now().toString(36)}${Array.from(bytes, (b) => ID_CHARS[b % 36]).join("")}`;
|
|
117
117
|
}
|
|
118
118
|
// ---- the API ----
|
|
119
|
+
/** Tries again of a call the API turned away before doing anything (all the environment's calls running, or busy). */
|
|
120
|
+
const CALL_RETRIES = 2;
|
|
119
121
|
export class ApiError extends Error {
|
|
120
122
|
status;
|
|
121
123
|
code;
|
|
@@ -129,6 +131,8 @@ export class ApiError extends Error {
|
|
|
129
131
|
}
|
|
130
132
|
/** The most records one bulk call takes. */
|
|
131
133
|
export const MAX_BULK = 250;
|
|
134
|
+
/** The most bytes `files.put` sends in the request itself; a bigger file goes straight to storage. */
|
|
135
|
+
export const STORAGE_INLINE_BYTES = 4 * 1024 * 1024;
|
|
132
136
|
const envVar = (name) => globalThis.process?.env?.[name];
|
|
133
137
|
/** The app's API. In an app's deployment every option comes from its environment variables. */
|
|
134
138
|
export function createClient(o = {}) {
|
|
@@ -143,22 +147,36 @@ export function createClient(o = {}) {
|
|
|
143
147
|
...(o.shop ? { "x-ib-shop": o.shop } : {}), ...(o.role ? { "x-ib-role": o.role } : {}),
|
|
144
148
|
...(o.role && o.session ? { "x-ib-session": JSON.stringify({ userId: o.session.userId ?? null, customerId: o.session.customerId ?? null, ...(o.session.customerRecordId ? { customerRecordId: o.session.customerRecordId } : {}) }) } : {}),
|
|
145
149
|
};
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
150
|
+
/**
|
|
151
|
+
* A call with a JSON body (or none); `raw` sends bytes as they are, with their type when known. A call turned away
|
|
152
|
+
* before it did anything is tried again, up to CALL_RETRIES times after Retry-After: the environment's calls all
|
|
153
|
+
* running (429 concurrency_limit_exceeded), or, for a read, the database's connections busy (503 reason busy).
|
|
154
|
+
*/
|
|
155
|
+
async function call(method, path, body, raw) {
|
|
156
|
+
const read = method === "GET" || /\/records\/(query|aggregate)$/.test(path);
|
|
157
|
+
for (let tries = 0;; tries++) {
|
|
158
|
+
const res = await f(`${base}${path}`, {
|
|
159
|
+
method, headers: { authorization: `Bearer ${token}`, ...scope, ...(raw ? (raw.type ? { "content-type": raw.type } : {}) : body === undefined ? {} : { "content-type": "application/json" }) },
|
|
160
|
+
...(raw ? { body: raw.body } : body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
161
|
+
});
|
|
162
|
+
if (res.status === 204)
|
|
163
|
+
return undefined;
|
|
164
|
+
const text = await res.text();
|
|
165
|
+
let json = {};
|
|
166
|
+
try {
|
|
167
|
+
json = text ? JSON.parse(text) : {};
|
|
168
|
+
}
|
|
169
|
+
catch { /* reported below */ }
|
|
170
|
+
if (res.ok)
|
|
171
|
+
return json;
|
|
172
|
+
const turnedAway = (res.status === 429 && json.error?.code === "concurrency_limit_exceeded") || (read && res.status === 503 && json.error?.reason === "busy");
|
|
173
|
+
if (turnedAway && tries < CALL_RETRIES) {
|
|
174
|
+
const after = Math.min(5, Number(res.headers.get("retry-after")) || 1);
|
|
175
|
+
await new Promise((done) => setTimeout(done, after * 1000 * (0.75 + Math.random() * 0.5)));
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
160
178
|
throw new ApiError(json.error?.message ?? `The API answered ${res.status}.`, res.status, json.error?.code ?? null, json.error?.problems ?? []);
|
|
161
|
-
|
|
179
|
+
}
|
|
162
180
|
}
|
|
163
181
|
const model = (name) => {
|
|
164
182
|
const m = `/models/${encodeURIComponent(name)}`;
|
|
@@ -181,6 +199,7 @@ export function createClient(o = {}) {
|
|
|
181
199
|
findMany: (o = {}) => query({ ...o }),
|
|
182
200
|
findFirst: async (o = {}) => (await query({ ...o, first: 1 })).records[0] ?? null,
|
|
183
201
|
search: (field, near, o = {}) => query({ ...o, search: { field, near } }),
|
|
202
|
+
aggregate: (o) => call("POST", `${m}/records/aggregate`, o),
|
|
184
203
|
create: (values) => call("POST", `${m}/records`, values),
|
|
185
204
|
update: (id, values) => call("PATCH", `${m}/records/${encodeURIComponent(id)}`, values),
|
|
186
205
|
delete: (id) => call("DELETE", `${m}/records/${encodeURIComponent(id)}`),
|
|
@@ -212,6 +231,7 @@ export function createClient(o = {}) {
|
|
|
212
231
|
const modelNamed = (name) => { if (!cache.has(name))
|
|
213
232
|
cache.set(name, model(name)); return cache.get(name); };
|
|
214
233
|
const $global = (action, params = {}) => call("POST", `/actions/${encodeURIComponent(action)}`, { params });
|
|
234
|
+
const $changes = (q) => call("POST", "/changes", { models: q.models, ...(q.cursor ? { cursor: q.cursor } : {}), ...(q.wait !== undefined ? { wait: q.wait } : {}) });
|
|
215
235
|
const enqueue = (action, params = {}, o = {}) => call("POST", "/jobs", { action, params, ...o, ...(o.runAt instanceof Date ? { runAt: o.runAt.toISOString() } : {}) });
|
|
216
236
|
const enqueueMany = async (action, jobs, o = {}) => (await call("POST", "/jobs/bulk", { action, jobs, ...o, ...(o.runAt instanceof Date ? { runAt: o.runAt.toISOString() } : {}) })).jobs;
|
|
217
237
|
const sync = "/shopify/sync";
|
|
@@ -241,12 +261,41 @@ export function createClient(o = {}) {
|
|
|
241
261
|
list: async (q = {}) => (await call("GET", `${sync}?${new URLSearchParams({ ...(q.shop ? { shop: q.shop } : {}), ...(q.limit ? { limit: String(q.limit) } : {}) })}`)).data,
|
|
242
262
|
abort: (id) => call("POST", `${sync}/${encodeURIComponent(id)}/abort`),
|
|
243
263
|
};
|
|
264
|
+
const storagePath = (path) => `/storage/${path.replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/")}`;
|
|
265
|
+
const files = {
|
|
266
|
+
async put(path, body, q = {}) {
|
|
267
|
+
const blob = body instanceof Blob ? body : new Blob([body]);
|
|
268
|
+
const mimeType = q.mimeType ?? (blob.type || undefined);
|
|
269
|
+
if (blob.size <= STORAGE_INLINE_BYTES)
|
|
270
|
+
return call("PUT", storagePath(path), undefined, { body: blob, type: mimeType });
|
|
271
|
+
const up = await call("POST", "/storage/uploads", { path, size: blob.size, ...(mimeType ? { mimeType } : {}) });
|
|
272
|
+
const res = await f(up.url, { method: "PUT", headers: up.headers, body: blob });
|
|
273
|
+
if (!res.ok)
|
|
274
|
+
throw new ApiError(`The upload was refused (${res.status}): ${(await res.text()).slice(0, 300)}`, res.status, "upload_failed");
|
|
275
|
+
return call("GET", storagePath(path));
|
|
276
|
+
},
|
|
277
|
+
async get(path) {
|
|
278
|
+
try {
|
|
279
|
+
return await call("GET", storagePath(path));
|
|
280
|
+
}
|
|
281
|
+
catch (e) {
|
|
282
|
+
if (e instanceof ApiError && e.status === 404)
|
|
283
|
+
return null;
|
|
284
|
+
throw e;
|
|
285
|
+
}
|
|
286
|
+
},
|
|
287
|
+
list: (q = {}) => call("GET", `/storage?${new URLSearchParams({ ...(q.prefix ? { prefix: q.prefix } : {}), ...(q.first ? { first: String(q.first) } : {}), ...(q.after ? { after: q.after } : {}) })}`),
|
|
288
|
+
delete: (path) => call("DELETE", storagePath(path)),
|
|
289
|
+
createUpload: (path, q = {}) => call("POST", "/storage/uploads", { path, ...q }),
|
|
290
|
+
};
|
|
244
291
|
const forShop = (shop) => createClient({ ...o, url, token, app, environment, fetch: f, shop });
|
|
245
292
|
const asRole = (role, session) => createClient({ ...o, url, token, app, environment, fetch: f, role, ...(session ? { session } : {}) });
|
|
246
293
|
return new Proxy({}, {
|
|
247
294
|
get(_t, prop) {
|
|
248
295
|
if (prop === "$global")
|
|
249
296
|
return $global;
|
|
297
|
+
if (prop === "$changes")
|
|
298
|
+
return $changes;
|
|
250
299
|
if (prop === "$model")
|
|
251
300
|
return modelNamed;
|
|
252
301
|
if (prop === "enqueue")
|
|
@@ -259,6 +308,8 @@ export function createClient(o = {}) {
|
|
|
259
308
|
return asRole;
|
|
260
309
|
if (prop === "shopifySync")
|
|
261
310
|
return shopifySync;
|
|
311
|
+
if (prop === "files")
|
|
312
|
+
return files;
|
|
262
313
|
if (typeof prop !== "string" || prop === "then")
|
|
263
314
|
return undefined;
|
|
264
315
|
return modelNamed(prop);
|
|
@@ -300,6 +351,24 @@ export async function serveRecords(request, api, o = {}) {
|
|
|
300
351
|
return errorBody(403, "forbidden", `This route doesn't run ${String(body.action)}.`);
|
|
301
352
|
return Response.json(await api.$global(body.action, obj(body.params)));
|
|
302
353
|
}
|
|
354
|
+
if (body.op === "enqueue") {
|
|
355
|
+
if (!str(body.action) || !(o.enqueueActions ?? []).includes(body.action))
|
|
356
|
+
return errorBody(403, "forbidden", `This route doesn't queue ${String(body.action)}.`);
|
|
357
|
+
// The store is the request's own (its api is already that store's), never one the browser names.
|
|
358
|
+
const { shop: _, ...options } = obj(body.options);
|
|
359
|
+
return Response.json(await api.enqueue(body.action, obj(body.params), options));
|
|
360
|
+
}
|
|
361
|
+
// A live query's watch: which of its models changed, waiting for one to (#125).
|
|
362
|
+
if (body.op === "changes") {
|
|
363
|
+
const names = Array.isArray(body.models) ? body.models : [];
|
|
364
|
+
if (!names.length || !names.every(str))
|
|
365
|
+
return errorBody(400, "invalid_request", "Name the models to watch.");
|
|
366
|
+
const other = o.models ? names.find((n) => !o.models.includes(n)) : undefined;
|
|
367
|
+
if (other)
|
|
368
|
+
return errorBody(403, "forbidden", `This route doesn't answer for ${other}.`);
|
|
369
|
+
const wait = Math.min(Math.max(o.liveWait ?? 25, 0), 25);
|
|
370
|
+
return Response.json(await api.$changes({ models: names, cursor: str(body.cursor) ? body.cursor : null, wait }));
|
|
371
|
+
}
|
|
303
372
|
if (!str(body.model))
|
|
304
373
|
return errorBody(400, "invalid_request", "The body names no model.");
|
|
305
374
|
if (o.models && !o.models.includes(body.model))
|
|
@@ -309,6 +378,7 @@ export async function serveRecords(request, api, o = {}) {
|
|
|
309
378
|
switch (body.op) {
|
|
310
379
|
case "describe": return Response.json(await m.describe());
|
|
311
380
|
case "findMany": return Response.json(await m.findMany(obj(b.options)));
|
|
381
|
+
case "aggregate": return Response.json(await m.aggregate(obj(b.options)));
|
|
312
382
|
case "findOne": {
|
|
313
383
|
if (!str(b.id))
|
|
314
384
|
break;
|
|
@@ -771,3 +841,75 @@ export async function verifyCustomerRequest(request, o = {}) {
|
|
|
771
841
|
source: proxied.pathPrefix === "/extension" ? "extension" : "proxy", api,
|
|
772
842
|
};
|
|
773
843
|
}
|
|
844
|
+
/** A DSN's parts, or null when it isn't one: `https://<key>@<host>[/<path>]/<project>`. */
|
|
845
|
+
export function parseDsn(dsn) {
|
|
846
|
+
let u;
|
|
847
|
+
try {
|
|
848
|
+
u = new URL(dsn.trim());
|
|
849
|
+
}
|
|
850
|
+
catch {
|
|
851
|
+
return null;
|
|
852
|
+
}
|
|
853
|
+
const m = /^(.*)\/(\d+)\/?$/.exec(u.pathname);
|
|
854
|
+
if (!u.username || !m || (u.protocol !== "https:" && u.protocol !== "http:"))
|
|
855
|
+
return null;
|
|
856
|
+
return { key: decodeURIComponent(u.username), envelope: `${u.protocol}//${u.host}${m[1]}/api/${m[2]}/envelope/` };
|
|
857
|
+
}
|
|
858
|
+
const FRAME = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/;
|
|
859
|
+
/** A V8 stack's frames as Sentry wants them: the outermost call first. Ours and dependencies' aren't the app's code. */
|
|
860
|
+
function stackFrames(stack) {
|
|
861
|
+
const frames = [];
|
|
862
|
+
for (const line of (stack ?? "").split("\n").slice(1, 51)) {
|
|
863
|
+
const m = FRAME.exec(line);
|
|
864
|
+
if (!m)
|
|
865
|
+
continue;
|
|
866
|
+
const filename = m[2].replace(/^file:\/\//, "");
|
|
867
|
+
const inApp = !/node_modules|^node:|^internal\/|\/ib\/sdk\//.test(filename);
|
|
868
|
+
frames.push({ function: m[1] ?? "?", filename, lineno: Number(m[3]), colno: Number(m[4]), in_app: inApp });
|
|
869
|
+
}
|
|
870
|
+
return frames.reverse();
|
|
871
|
+
}
|
|
872
|
+
/** The error and what caused it, the deepest cause first, as Sentry orders an exception chain. */
|
|
873
|
+
function exceptionChain(error, handled) {
|
|
874
|
+
const out = [];
|
|
875
|
+
let e = error;
|
|
876
|
+
for (let i = 0; i < 5 && e != null; i++) {
|
|
877
|
+
const err = e instanceof Error ? e : new Error(typeof e === "string" ? e : JSON.stringify(e));
|
|
878
|
+
out.unshift({ type: err.name || "Error", value: err.message.slice(0, 8000), stacktrace: { frames: stackFrames(err.stack) }, ...(i === 0 ? { mechanism: { type: "inferencebureau", handled } } : {}) });
|
|
879
|
+
e = err.cause;
|
|
880
|
+
}
|
|
881
|
+
return out;
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Reports an error to the app's Sentry project. Answers the event's id, or null when there's no DSN or Sentry didn't
|
|
885
|
+
* take it. Never throws, and gives up after three seconds.
|
|
886
|
+
*/
|
|
887
|
+
export async function captureException(error, o = {}) {
|
|
888
|
+
const dsn = parseDsn(o.dsn ?? envVar("SENTRY_DSN") ?? "");
|
|
889
|
+
if (!dsn)
|
|
890
|
+
return null;
|
|
891
|
+
try {
|
|
892
|
+
const id = crypto.randomUUID().replace(/-/g, "");
|
|
893
|
+
const app = envVar("IB_APP");
|
|
894
|
+
const version = envVar("IB_FILE_VERSION");
|
|
895
|
+
const tags = Object.fromEntries(Object.entries({ ...(app ? { app } : {}), ...o.tags }).filter(([, v]) => v != null && v !== "").map(([k, v]) => [k, String(v).slice(0, 200)]));
|
|
896
|
+
const event = {
|
|
897
|
+
event_id: id, timestamp: Date.now() / 1000, platform: "node", level: o.level ?? "error",
|
|
898
|
+
environment: o.environment ?? envVar("IB_ENVIRONMENT") ?? "production",
|
|
899
|
+
...(app && version ? { release: `${app}@${version}` } : {}),
|
|
900
|
+
tags, ...(o.extra ? { extra: o.extra } : {}),
|
|
901
|
+
exception: { values: exceptionChain(error, o.handled ?? true) },
|
|
902
|
+
sdk: { name: "inferencebureau.apps-sdk", version: "1" },
|
|
903
|
+
};
|
|
904
|
+
const body = `${JSON.stringify({ event_id: id, sent_at: new Date().toISOString() })}\n${JSON.stringify({ type: "event" })}\n${JSON.stringify(event)}\n`;
|
|
905
|
+
const res = await (o.fetch ?? fetch)(dsn.envelope, {
|
|
906
|
+
method: "POST", body,
|
|
907
|
+
headers: { "content-type": "application/x-sentry-envelope", "x-sentry-auth": `Sentry sentry_version=7, sentry_client=inferencebureau.apps-sdk/1, sentry_key=${dsn.key}` },
|
|
908
|
+
...(typeof AbortSignal.timeout === "function" ? { signal: AbortSignal.timeout(3000) } : {}),
|
|
909
|
+
});
|
|
910
|
+
return res.ok ? id : null;
|
|
911
|
+
}
|
|
912
|
+
catch {
|
|
913
|
+
return null;
|
|
914
|
+
}
|
|
915
|
+
}
|