@inferencebureau/apps-sdk 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auto.d.ts ADDED
@@ -0,0 +1,113 @@
1
+ /**
2
+ * What AutoTable and AutoForm work out from a model's description (ModelDescription), with no React and no look:
3
+ * which fields are columns and which are inputs, how a value reads in a cell, and how a form's typed text becomes a
4
+ * record's value. Both renderers (react.tsx's plain one, polaris.tsx's) draw the same answers.
5
+ */
6
+ import type { AppRecord, FieldDescription, ModelDescription, SortDirection } from "./index.js";
7
+ /** "emailVerified" → "Email verified", "shopifyId" → "Shopify ID". */
8
+ export declare function labelOf(name: string): string;
9
+ /** What a record is called where it's shown in a cell or a picker: its title, name, email and so on, else its id. */
10
+ export declare function recordLabel(record: Record<string, unknown> | null | undefined): string;
11
+ export interface Column {
12
+ field: FieldDescription;
13
+ name: string;
14
+ label: string;
15
+ sortable: boolean;
16
+ /** Right-aligned with tabular figures. */
17
+ numeric: boolean;
18
+ }
19
+ /** A column the app names: the field, or the field with its own heading. */
20
+ export type ColumnOption = string | {
21
+ field: string;
22
+ label: string;
23
+ };
24
+ /**
25
+ * A table's columns: the ones named, in order, else the first six fields that read well in a cell (no long text,
26
+ * json, secrets or relationship lists), then when each record was last changed.
27
+ */
28
+ export declare function columnsOf(d: ModelDescription, named?: ColumnOption[]): Column[];
29
+ /** What a read selects for these columns: each field, and a belongsTo's whole record so it can be named. */
30
+ export declare function selectFor(columns: Column[]): Record<string, unknown>;
31
+ export type Tone = "neutral" | "success" | "info" | "warning" | "critical";
32
+ /** One cell, as both renderers draw it. */
33
+ export type Display = {
34
+ kind: "empty";
35
+ } | {
36
+ kind: "text";
37
+ text: string;
38
+ mono?: boolean;
39
+ } | {
40
+ kind: "boolean";
41
+ value: boolean;
42
+ text: string;
43
+ } | {
44
+ kind: "tags";
45
+ tags: string[];
46
+ } | {
47
+ kind: "link";
48
+ href: string;
49
+ text: string;
50
+ } | {
51
+ kind: "color";
52
+ color: string;
53
+ } | {
54
+ kind: "file";
55
+ text: string;
56
+ href: string | null;
57
+ image: string | null;
58
+ };
59
+ export declare function formatDate(iso: string): string;
60
+ /** How a field's value reads in a cell. */
61
+ export declare function display(f: FieldDescription, value: unknown): Display;
62
+ /** A sort a list can be put in, worded for its field's type. */
63
+ export interface SortOption {
64
+ value: string;
65
+ label: string;
66
+ field: string | null;
67
+ direction: SortDirection;
68
+ }
69
+ /** The sorts a table offers: newest first (the API's own order), then each sortable column both ways. */
70
+ export declare function sortOptions(columns: Column[]): SortOption[];
71
+ /** Which control a field's input is. */
72
+ export type InputKind = "text" | "textarea" | "email" | "url" | "color" | "number" | "password" | "dateTime" | "boolean" | "select" | "multiselect" | "list" | "json" | "file" | "record";
73
+ /** What a form keeps for a field while it's being typed in. */
74
+ export type FormValue = string | boolean | string[] | File | null;
75
+ export interface FormFieldSpec {
76
+ field: FieldDescription;
77
+ name: string;
78
+ label: string;
79
+ kind: InputKind;
80
+ required: boolean;
81
+ options: string[];
82
+ /** A belongsTo's model, whose records the picker lists. */
83
+ parent: string | null;
84
+ }
85
+ export declare function inputKind(f: FieldDescription): InputKind | null;
86
+ /** A field a form takes, the app may name it or label it its own way. */
87
+ export type FieldOption = string | {
88
+ field: string;
89
+ label: string;
90
+ };
91
+ /** A form's fields: the ones named, else every field a value can be written to except secrets' hashes and vectors. */
92
+ export declare function formFieldsOf(d: ModelDescription, named?: FieldOption[], exclude?: string[]): FormFieldSpec[];
93
+ /** An ISO time as a local `YYYY-MM-DDTHH:mm`, what a date and time input holds. */
94
+ export declare function toLocalInput(iso: string): string;
95
+ /** What a form starts a field at, from a record's value (or the field's default for a new one). */
96
+ export declare function initialValue(s: FormFieldSpec, value: unknown): FormValue;
97
+ /** A form value as the record's value, or why it can't be one. `undefined` leaves the field out of the write. */
98
+ export declare function toRecordValue(s: FormFieldSpec, v: FormValue): {
99
+ ok: true;
100
+ value: unknown;
101
+ } | {
102
+ ok: false;
103
+ message: string;
104
+ };
105
+ /** Whether a form value is still what it started as. */
106
+ export declare function unchanged(a: FormValue, b: FormValue): boolean;
107
+ /** The field a refusal's problem is about: `rating` for `rating`, and for `address.city`. */
108
+ export declare const problemField: (field: string) => string;
109
+ /** Records as their id and name, for a belongsTo picker. */
110
+ export declare const choicesOf: (records: AppRecord[]) => {
111
+ value: string;
112
+ label: string;
113
+ }[];
package/dist/auto.js ADDED
@@ -0,0 +1,197 @@
1
+ /** "emailVerified" → "Email verified", "shopifyId" → "Shopify ID". */
2
+ export function labelOf(name) {
3
+ const words = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/[_-]+/g, " ").trim().split(/\s+/);
4
+ const out = words.map((w, i) => {
5
+ const lower = w.toLowerCase();
6
+ if (lower === "id" || lower === "url" || lower === "sku" || lower === "gid")
7
+ return lower.toUpperCase();
8
+ return i === 0 ? lower.charAt(0).toUpperCase() + lower.slice(1) : lower;
9
+ });
10
+ return out.join(" ");
11
+ }
12
+ const NAMING = ["title", "name", "displayName", "label", "email", "handle", "sku", "subject", "myshopifyDomain"];
13
+ /** What a record is called where it's shown in a cell or a picker: its title, name, email and so on, else its id. */
14
+ export function recordLabel(record) {
15
+ if (!record)
16
+ return "";
17
+ for (const k of NAMING) {
18
+ const v = record[k];
19
+ if (typeof v === "string" && v.trim())
20
+ return v;
21
+ }
22
+ const first = ["firstName", "lastName"].map((k) => record[k]).filter((v) => typeof v === "string" && v).join(" ");
23
+ return first || String(record.id ?? "");
24
+ }
25
+ /** Fields no list or form shows unless named: secrets, and the hashes and tokens that stand in for them. */
26
+ const HIDDEN = /(hash|token|secret)$/i;
27
+ const COLUMN_TYPES = new Set(["string", "email", "url", "color", "number", "dateTime", "enum", "boolean", "belongsTo", "file", "computed", "roleList"]);
28
+ const SORTABLE_TYPES = new Set(["string", "email", "url", "color", "number", "dateTime", "enum", "boolean", "computed"]);
29
+ const MAX_COLUMNS = 6;
30
+ const isNumeric = (f) => f.type === "number" || (f.type === "computed" && f.valueType === "number");
31
+ const column = (f, label) => ({
32
+ field: f, name: f.name, label: label ?? labelOf(f.name),
33
+ sortable: SORTABLE_TYPES.has(f.type) && !(f.type === "enum" && f.allowMultiple) && !(f.type === "computed" && !f.valueType),
34
+ numeric: isNumeric(f),
35
+ });
36
+ /**
37
+ * A table's columns: the ones named, in order, else the first six fields that read well in a cell (no long text,
38
+ * json, secrets or relationship lists), then when each record was last changed.
39
+ */
40
+ export function columnsOf(d, named) {
41
+ const byName = new Map(d.fields.map((f) => [f.name, f]));
42
+ if (named?.length) {
43
+ return named.flatMap((c) => {
44
+ const name = typeof c === "string" ? c : c.field;
45
+ const f = byName.get(name);
46
+ return f ? [column(f, typeof c === "string" ? undefined : c.label)] : [];
47
+ });
48
+ }
49
+ const picked = d.fields.filter((f) => !f.system && COLUMN_TYPES.has(f.type) && !HIDDEN.test(f.name)).slice(0, MAX_COLUMNS).map((f) => column(f));
50
+ const updated = byName.get("updatedAt");
51
+ return updated ? [...picked, column(updated, "Updated")] : picked;
52
+ }
53
+ /** What a read selects for these columns: each field, and a belongsTo's whole record so it can be named. */
54
+ export function selectFor(columns) {
55
+ return Object.fromEntries(columns.map((c) => [c.name, true]));
56
+ }
57
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
58
+ export function formatDate(iso) {
59
+ const d = new Date(iso);
60
+ if (Number.isNaN(d.getTime()))
61
+ return iso;
62
+ return d.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
63
+ }
64
+ const truncate = (s, n = 80) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
65
+ /** How a field's value reads in a cell. */
66
+ export function display(f, value) {
67
+ if (value === null || value === undefined || value === "")
68
+ return { kind: "empty" };
69
+ const type = f.type === "computed" ? (f.valueType ?? "string") : f.type;
70
+ switch (type) {
71
+ case "boolean": return { kind: "boolean", value: value === true, text: value === true ? "Yes" : "No" };
72
+ case "dateTime": return { kind: "text", text: formatDate(String(value)) };
73
+ case "number": return { kind: "text", text: typeof value === "number" ? value.toLocaleString() : String(value) };
74
+ case "enum":
75
+ case "roleList": return { kind: "tags", tags: (Array.isArray(value) ? value : [value]).map(String) };
76
+ case "url": return { kind: "link", href: String(value), text: truncate(String(value).replace(/^https?:\/\//, ""), 48) };
77
+ case "email": return { kind: "link", href: `mailto:${String(value)}`, text: String(value) };
78
+ case "color": return { kind: "color", color: String(value) };
79
+ case "id": return { kind: "text", text: String(value), mono: true };
80
+ case "file": {
81
+ if (!isObj(value))
82
+ return { kind: "empty" };
83
+ const file = value;
84
+ return { kind: "file", text: file.fileName, href: file.url, image: file.url && /^image\//.test(file.mimeType) ? file.url : null };
85
+ }
86
+ case "belongsTo": return isObj(value) ? { kind: "text", text: recordLabel(value) } : { kind: "text", text: String(value), mono: true };
87
+ case "json": return { kind: "text", text: truncate(JSON.stringify(value)), mono: true };
88
+ default: return { kind: "text", text: truncate(String(value), 120) };
89
+ }
90
+ }
91
+ /** The sorts a table offers: newest first (the API's own order), then each sortable column both ways. */
92
+ export function sortOptions(columns) {
93
+ const out = [{ value: "", label: "Newest first", field: null, direction: "Descending" }];
94
+ for (const c of columns) {
95
+ if (!c.sortable || c.name === "updatedAt" || c.name === "createdAt")
96
+ continue;
97
+ const type = c.field.type === "computed" ? c.field.valueType : c.field.type;
98
+ const [up, down] = type === "number" ? ["lowest first", "highest first"] : type === "dateTime" ? ["oldest first", "newest first"] : type === "boolean" ? ["no first", "yes first"] : ["A–Z", "Z–A"];
99
+ out.push({ value: `${c.name}:Ascending`, label: `${c.label}, ${up}`, field: c.name, direction: "Ascending" });
100
+ out.push({ value: `${c.name}:Descending`, label: `${c.label}, ${down}`, field: c.name, direction: "Descending" });
101
+ }
102
+ const updated = columns.find((c) => c.name === "updatedAt");
103
+ if (updated)
104
+ out.push({ value: "updatedAt:Descending", label: "Recently updated", field: "updatedAt", direction: "Descending" });
105
+ return out;
106
+ }
107
+ const KIND = {
108
+ string: "text", richText: "textarea", email: "email", url: "url", color: "color", number: "number", password: "password", encryptedString: "password",
109
+ dateTime: "dateTime", boolean: "boolean", roleList: "list", json: "json", file: "file", belongsTo: "record",
110
+ };
111
+ export function inputKind(f) {
112
+ if (f.type === "enum")
113
+ return f.allowMultiple ? "multiselect" : "select";
114
+ return KIND[f.type] ?? null;
115
+ }
116
+ /** A form's fields: the ones named, else every field a value can be written to except secrets' hashes and vectors. */
117
+ export function formFieldsOf(d, named, exclude = []) {
118
+ const byName = new Map(d.fields.map((f) => [f.name, f]));
119
+ const spec = (f, label) => {
120
+ const kind = inputKind(f);
121
+ return kind ? [{ field: f, name: f.name, label: label ?? labelOf(f.name), kind, required: f.required === true, options: f.options ?? [], parent: f.parent ?? null }] : [];
122
+ };
123
+ if (named?.length) {
124
+ return named.flatMap((c) => {
125
+ const f = byName.get(typeof c === "string" ? c : c.field);
126
+ return f ? spec(f, typeof c === "string" ? undefined : c.label) : [];
127
+ });
128
+ }
129
+ return d.fields.filter((f) => f.writable && !f.system && f.type !== "vector" && !HIDDEN.test(f.name) && !exclude.includes(f.name)).flatMap((f) => spec(f));
130
+ }
131
+ const pad = (n) => String(n).padStart(2, "0");
132
+ /** An ISO time as a local `YYYY-MM-DDTHH:mm`, what a date and time input holds. */
133
+ export function toLocalInput(iso) {
134
+ const d = new Date(iso);
135
+ if (Number.isNaN(d.getTime()))
136
+ return "";
137
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
138
+ }
139
+ /** What a form starts a field at, from a record's value (or the field's default for a new one). */
140
+ export function initialValue(s, value) {
141
+ switch (s.kind) {
142
+ case "boolean": return value === true;
143
+ case "multiselect": return Array.isArray(value) ? value.map(String) : [];
144
+ case "list": return Array.isArray(value) ? value.map(String).join(", ") : "";
145
+ case "json": return value === null || value === undefined ? "" : JSON.stringify(value, null, 2);
146
+ case "dateTime": return typeof value === "string" ? toLocalInput(value) : "";
147
+ // Never shown again once set; typing one replaces it.
148
+ case "password": return "";
149
+ // A file is kept as it is unless another is chosen.
150
+ case "file": return null;
151
+ case "record": return isObj(value) ? String(value.id ?? "") : value === null || value === undefined ? "" : String(value);
152
+ case "number": return typeof value === "number" ? String(value) : "";
153
+ default: return typeof value === "string" ? value : value === null || value === undefined ? "" : String(value);
154
+ }
155
+ }
156
+ /** A form value as the record's value, or why it can't be one. `undefined` leaves the field out of the write. */
157
+ export function toRecordValue(s, v) {
158
+ const blank = v === null || v === "" || (Array.isArray(v) && v.length === 0);
159
+ if (s.required && blank && s.kind !== "boolean" && s.kind !== "password" && s.kind !== "file")
160
+ return { ok: false, message: "Required" };
161
+ if (blank)
162
+ return { ok: true, value: s.kind === "password" || s.kind === "file" ? undefined : s.kind === "multiselect" || s.kind === "list" ? [] : null };
163
+ switch (s.kind) {
164
+ case "boolean": return { ok: true, value: v === true };
165
+ case "number": {
166
+ const n = Number(String(v).replace(/,/g, ""));
167
+ return Number.isFinite(n) ? { ok: true, value: n } : { ok: false, message: "Enter a number" };
168
+ }
169
+ case "dateTime": {
170
+ const d = new Date(String(v));
171
+ return Number.isNaN(d.getTime()) ? { ok: false, message: "Enter a date and time" } : { ok: true, value: d.toISOString() };
172
+ }
173
+ case "json": {
174
+ try {
175
+ return { ok: true, value: JSON.parse(String(v)) };
176
+ }
177
+ catch {
178
+ return { ok: false, message: "Enter valid JSON" };
179
+ }
180
+ }
181
+ case "list": return { ok: true, value: String(v).split(",").map((x) => x.trim()).filter(Boolean) };
182
+ case "multiselect": return { ok: true, value: v };
183
+ // Uploaded by the form before the write; it puts the upload's token here.
184
+ case "file": return { ok: true, value: undefined };
185
+ default: return { ok: true, value: String(v) };
186
+ }
187
+ }
188
+ /** Whether a form value is still what it started as. */
189
+ export function unchanged(a, b) {
190
+ if (Array.isArray(a) && Array.isArray(b))
191
+ return a.length === b.length && a.every((x, i) => x === b[i]);
192
+ return a === b;
193
+ }
194
+ /** The field a refusal's problem is about: `rating` for `rating`, and for `address.city`. */
195
+ export const problemField = (field) => field.split(/[.[]/)[0] ?? field;
196
+ /** Records as their id and name, for a belongsTo picker. */
197
+ export const choicesOf = (records) => records.map((r) => ({ value: r.id, label: recordLabel(r) }));
package/dist/index.d.ts CHANGED
@@ -99,10 +99,24 @@ export type ComputedAggregate = ({
99
99
  }) & {
100
100
  filter?: Filter;
101
101
  };
102
+ /**
103
+ * An index on a model's records, kept as metadata like the rest of the schema and built in the background after a
104
+ * save or deploy (nothing blocks on it). `{ fields: ["shop", "createdAt"] }` serves equality on its first field with
105
+ * ranges and sorting on the rest; `unique: true` makes the fields' values unique together, checked by the database;
106
+ * `search: true` with fields serves `startsWith` and `contains` on each of them, and alone serves the model's text
107
+ * search. Fields are string, email, url, color, enum (one option), number, boolean, dateTime, belongsTo, or `id`,
108
+ * `createdAt`, `updatedAt`; `search` takes the text types (and rich text).
109
+ */
110
+ export interface IndexDef {
111
+ fields?: string[];
112
+ unique?: boolean;
113
+ search?: boolean;
114
+ }
102
115
  export interface ModelSchema {
103
116
  type: "ib/model-schema/v1";
104
117
  storageKey?: string;
105
118
  fields: Record<string, FieldDef>;
119
+ indexes?: IndexDef[];
106
120
  }
107
121
  /**
108
122
  * `settings.ib.ts`. Keep it a plain object literal: Inference Bureau reads `webhooks` and `schedules` from the file.
@@ -189,6 +203,12 @@ export interface AppRecord {
189
203
  /**
190
204
  * Which records a list returns: `{ field: { equals: x } }`, with AND, OR and NOT lists. `F` is a model's fields and
191
205
  * their filters, from the app's generated client types (`web/ib-client.d.ts`); any field without them.
206
+ *
207
+ * Filters reach through relationships, up to 3 deep, to the related records the call can read: a belongsTo or hasOne
208
+ * takes a filter on its record's fields, a hasMany or hasManyThrough `{ some | every | none: filter }` (RelatedListFilter).
209
+ *
210
+ * api.review.findMany({ filter: { product: { vendor: { equals: "Acme" } } } });
211
+ * api.product.findMany({ filter: { reviews: { some: { rating: { lessThan: 3 } } } } });
192
212
  */
193
213
  export type Filter<F extends object = {
194
214
  [field: string]: unknown;
@@ -197,14 +217,20 @@ export type Filter<F extends object = {
197
217
  OR?: Filter<F>[];
198
218
  NOT?: Filter<F>[];
199
219
  } & 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> : {
220
+ /**
221
+ * A list's order: the field to sort by, or several in turn. A belongsTo sorts by its record's fields,
222
+ * `{ product: { title: "Ascending" } }`, records without one last. `K` is a model's sortable fields once the client is
223
+ * generated, which types the belongsTo's too (SortOf).
224
+ */
225
+ export type Sort<K extends string = string> = string extends K ? {
226
+ [field: string]: SortDirection | Sort;
227
+ } : {
202
228
  [P in K]?: SortDirection;
203
229
  };
204
230
  export type SortDirection = "Ascending" | "Descending";
205
231
  export interface FindManyOptions<M extends ModelTypes = UntypedModel, S extends SelectOf<M> | undefined = undefined> {
206
232
  filter?: Filter<M["filter"]>;
207
- sort?: Sort<M["sortable"]> | Sort<M["sortable"]>[];
233
+ sort?: SortOf<M> | SortOf<M>[];
208
234
  first?: number;
209
235
  after?: string | null;
210
236
  /** 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. */
@@ -240,9 +266,13 @@ type RelatedSelectOf<R extends RelationTypes> = {
240
266
  select?: SelectOf<ModelOf<R["model"]>>;
241
267
  } & (R["many"] extends true ? {
242
268
  filter?: Filter<ModelOf<R["model"]>["filter"]>;
243
- sort?: Sort<ModelOf<R["model"]>["sortable"]> | Sort<ModelOf<R["model"]>["sortable"]>[];
269
+ sort?: SortOf<ModelOf<R["model"]>> | SortOf<ModelOf<R["model"]>>[];
244
270
  first?: number;
245
271
  } : {});
272
+ /** A model's sort: the generated file's, else by its sortable fields. */
273
+ export type SortOf<M extends ModelTypes> = M extends {
274
+ sort: infer S extends object;
275
+ } ? S : Sort<M["sortable"]>;
246
276
  type RelationsOf<M extends ModelTypes> = M extends {
247
277
  relations: infer R extends {
248
278
  [field: string]: RelationTypes;
@@ -291,6 +321,14 @@ export interface StringFilter<V extends string = string> extends OrderedFilter<V
291
321
  }
292
322
  /** Dates as ISO 8601 text or a Date. */
293
323
  export type DateTimeFilter = OrderedFilter<string | Date>;
324
+ /** A hasMany or hasManyThrough's filter: records with `some` of its records matching, `every` one (or none at all), or `none`. */
325
+ export interface RelatedListFilter<F extends object = {
326
+ [field: string]: unknown;
327
+ }> {
328
+ some?: Filter<F>;
329
+ every?: Filter<F>;
330
+ none?: Filter<F>;
331
+ }
294
332
  /**
295
333
  * The app's models, filled in by `web/ib-client.d.ts`: Inference Bureau writes that file into development whenever a
296
334
  * schema or an action changes, `ib-apps dev` and `ib-apps pull` bring it down, and deploys carry it to production.
@@ -312,6 +350,8 @@ export interface ModelTypes {
312
350
  filter: object;
313
351
  /** The fields it can sort on. */
314
352
  sortable: string;
353
+ /** Its sort, a belongsTo's through to its record's fields; `Sort<sortable>` when the generated file has none. */
354
+ sort?: object;
315
355
  /** Its vector fields (`search`), file fields (`createUpload`, `upload`) and password fields (`checkPassword`). */
316
356
  vectors: string;
317
357
  files: string;
@@ -376,6 +416,35 @@ export interface RecordPage<T = AppRecord> {
376
416
  hasNextPage: boolean;
377
417
  endCursor: string | null;
378
418
  }
419
+ /**
420
+ * A model as the API describes it (`describe()`): its fields in schema order between `id` and the timestamps, which
421
+ * AutoTable and AutoForm draw from. `writable` fields take a value; `stored` ones filter and sort.
422
+ */
423
+ export interface ModelDescription {
424
+ name: string;
425
+ fields: FieldDescription[];
426
+ }
427
+ export interface FieldDescription {
428
+ name: string;
429
+ type: FieldType | "id";
430
+ /** id, createdAt and updatedAt. */
431
+ system?: boolean;
432
+ stored?: boolean;
433
+ writable?: boolean;
434
+ required?: boolean;
435
+ options?: string[];
436
+ allowMultiple?: boolean;
437
+ allowPublicAccess?: boolean;
438
+ /** A belongsTo's model. */
439
+ parent?: string;
440
+ /** A hasOne's, hasMany's or hasManyThrough's model. */
441
+ related?: string;
442
+ /** A computed field's value type. */
443
+ valueType?: "string" | "number" | "boolean" | "dateTime" | null;
444
+ default?: unknown;
445
+ }
446
+ /** A schema's description, as the API gives it for a model, for code that has the schema and no API (the test harness). */
447
+ export declare function describeSchema(name: string, schema: ModelSchema): ModelDescription;
379
448
  /**
380
449
  * A record being worked on in an action: its fields, plus what the action has asked to happen to it. Its fields read
381
450
  * as `any`, since one action file doesn't say which model's it is, so they pass to the generated client's typed calls.
@@ -473,7 +542,45 @@ export interface CheckPasswordOptions {
473
542
  email?: string;
474
543
  ip?: string;
475
544
  }
545
+ /** The most records one bulk call takes. */
546
+ export declare const MAX_BULK = 250;
547
+ /** Why one record of a batch was refused: as a single write's ApiError says it, with `problems` for invalid values and `event` and `logs` for an action that threw. */
548
+ export interface BulkFailure {
549
+ index: number;
550
+ id?: string;
551
+ error: {
552
+ code: string;
553
+ message: string;
554
+ problems?: {
555
+ field: string;
556
+ message: string;
557
+ }[];
558
+ event?: string;
559
+ logs?: unknown[];
560
+ };
561
+ }
562
+ export interface BulkCounts {
563
+ succeeded: number;
564
+ failed: number;
565
+ created?: number;
566
+ updated?: number;
567
+ }
568
+ /** A batch's outcome: the records as written, null in a refused one's place; which failed and why; and counts. The rest are saved. */
569
+ export interface BulkResult<T = AppRecord> {
570
+ records: (T | null)[];
571
+ failed: BulkFailure[];
572
+ counts: BulkCounts;
573
+ }
574
+ export interface BulkDeleteResult {
575
+ deleted: string[];
576
+ failed: BulkFailure[];
577
+ counts: BulkCounts;
578
+ }
579
+ /** The field (or fields) an upsert finds its record by: a stored field with a value in `values`, or `id`. */
580
+ export type UpsertOn<M extends ModelTypes = UntypedModel> = (keyof M["input"] & string) | "id";
476
581
  export interface ModelClient<M extends ModelTypes = UntypedModel> {
582
+ /** The model's fields as the API describes them (ModelDescription): what AutoTable and AutoForm draw from. */
583
+ describe(): Promise<ModelDescription>;
477
584
  findOne<S extends SelectOf<M> | undefined = undefined>(id: string, o?: {
478
585
  select?: S;
479
586
  }): Promise<ReadOf<M, S> | null>;
@@ -487,6 +594,32 @@ export interface ModelClient<M extends ModelTypes = UntypedModel> {
487
594
  create(values: M["input"]): Promise<M["record"]>;
488
595
  update(id: string, values: M["input"]): Promise<M["record"]>;
489
596
  delete(id: string): Promise<void>;
597
+ /**
598
+ * Updates the record whose `on` field (or fields) hold the values' values, or creates one when there's none, the
599
+ * way `update` and `create` go. A unique validation on the field keeps two upserts at once from both creating.
600
+ */
601
+ upsert(o: {
602
+ on: UpsertOn<M> | UpsertOn<M>[];
603
+ values: M["input"];
604
+ }): Promise<{
605
+ record: M["record"];
606
+ created: boolean;
607
+ }>;
608
+ /**
609
+ * Up to 250 records in one call, each the way a single write goes (the model's action when it has one). Direct
610
+ * writes share one transaction, each rolled back alone when refused; the answer names which failed and why, and
611
+ * the rest are saved.
612
+ */
613
+ bulkCreate(values: M["input"][]): Promise<BulkResult<M["record"]>>;
614
+ bulkUpdate(records: {
615
+ id: string;
616
+ values: M["input"];
617
+ }[]): Promise<BulkResult<M["record"]>>;
618
+ bulkDelete(ids: string[]): Promise<BulkDeleteResult>;
619
+ bulkUpsert(o: {
620
+ on: UpsertOn<M> | UpsertOn<M>[];
621
+ records: M["input"][];
622
+ }): Promise<BulkResult<M["record"]>>;
490
623
  /**
491
624
  * A new record for an action's `run` to `save()`, written with the action's own record in one transaction. It has
492
625
  * its id already, so other records can point at it. Only an action's `api` builds records.
@@ -542,6 +675,15 @@ export type Api = ModelClients & {
542
675
  * it fails.
543
676
  */
544
677
  enqueue<A extends ActionName>(action: A, params?: ParamsOf<A>, options?: EnqueueOptions): Promise<Job>;
678
+ /**
679
+ * Queues up to 250 jobs for one action in one call, the options shared: one per entry, with its record's `id` and
680
+ * `params`. Every entry is checked before any is queued; the jobs come back in order. For one job over a whole
681
+ * batch, pass the batch as a global action's params instead.
682
+ */
683
+ enqueueMany<A extends ActionName>(action: A, jobs: {
684
+ id?: string;
685
+ params?: ParamsOf<A>;
686
+ }[], options?: Omit<EnqueueOptions, "id">): Promise<Job[]>;
545
687
  /**
546
688
  * The same API for one store: store-owned models (Shopify's, and any with a text field named `shop`) show only that
547
689
  * 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.
@@ -661,6 +803,75 @@ export interface ClientOptions {
661
803
  }
662
804
  /** The app's API. In an app's deployment every option comes from its environment variables. */
663
805
  export declare function createClient(o?: ClientOptions): Api;
806
+ /** What the browser's records client (`@inferencebureau/apps-sdk/react`) sends the app's records route. */
807
+ export type RecordsRequest = {
808
+ op: "describe";
809
+ model: string;
810
+ } | {
811
+ op: "findMany";
812
+ model: string;
813
+ options?: Omit<FindManyOptions, "select"> & {
814
+ select?: Record<string, unknown>;
815
+ };
816
+ } | {
817
+ op: "findOne";
818
+ model: string;
819
+ id: string;
820
+ select?: Record<string, unknown>;
821
+ } | {
822
+ op: "create";
823
+ model: string;
824
+ values: Record<string, unknown>;
825
+ } | {
826
+ op: "update";
827
+ model: string;
828
+ id: string;
829
+ values: Record<string, unknown>;
830
+ } | {
831
+ op: "delete";
832
+ model: string;
833
+ id: string;
834
+ } | {
835
+ op: "bulkDelete";
836
+ model: string;
837
+ ids: string[];
838
+ } | {
839
+ op: "run";
840
+ model: string;
841
+ action: string;
842
+ id?: string;
843
+ params?: Record<string, unknown>;
844
+ } | {
845
+ op: "createUpload";
846
+ model: string;
847
+ field: string;
848
+ fileName?: string;
849
+ mimeType?: string;
850
+ size?: number;
851
+ } | {
852
+ op: "global";
853
+ action: string;
854
+ params?: Record<string, unknown>;
855
+ };
856
+ export interface ServeRecordsOptions {
857
+ /** The models the route answers for; every model when unset. */
858
+ models?: string[];
859
+ /** The global actions it runs; none when unset. */
860
+ globalActions?: string[];
861
+ }
862
+ /**
863
+ * The app's records route, for its pages' own scripts: the hooks and AutoTable/AutoForm in
864
+ * `@inferencebureau/apps-sdk/react` and `/polaris` call it. `api` is whoever the request is from: a Shopify session's
865
+ * (`verifyShopifySession`), or a signed-in user's role (`createClient().asRole(...)`); null answers 401. Every call
866
+ * goes through that api, so permissions.ib.ts decides what a page may read and change, never the browser.
867
+ *
868
+ * // web/app/api/records/route.ts
869
+ * export async function POST(request: Request) {
870
+ * const session = await verifyShopifySession(request);
871
+ * return serveRecords(request, session?.api ?? null);
872
+ * }
873
+ */
874
+ export declare function serveRecords(request: Request, api: Api | null, o?: ServeRecordsOptions): Promise<Response>;
664
875
  /**
665
876
  * The Shopify Admin API for one store the app is installed on, through Inference Bureau: the store's token stays
666
877
  * with us, and each call is checked against the environment's install.