@inferencebureau/apps-sdk 0.4.0 → 0.5.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 CHANGED
@@ -74,12 +74,12 @@ with a key linked to the app.
74
74
  Entry points:
75
75
 
76
76
  - `@inferencebureau/apps-sdk`: metadata types, action helpers, `createClient`, `createShopifyClient`,
77
- `verifyShopifySession`, `verifyProxyRequest`, Shopify Billing for public apps (`requestSubscription`,
77
+ `verifyShopifySession` (and `scopesRequired` for optional scopes), `verifyProxyRequest`, Shopify Billing for public apps (`requestSubscription`,
78
78
  `activeSubscriptions`, `recordUsage`, `cancelSubscription`, `managedPricingUrl`), and the errors they throw
79
79
  (`ApiError`, `ShopifyError`, `ShopifyBillingError`).
80
80
  - `@inferencebureau/apps-sdk/runtime`: `handleAction`, the signed `/_ib/actions` route every build adds.
81
81
  - `@inferencebureau/apps-sdk/browser`: for an embedded admin page's client code: `sessionFetch`,
82
- `shopifySessionToken`, `isPreview`, `previewSession`.
82
+ `shopifySessionToken`, `isPreview`, `previewSession`, `requestScopes`.
83
83
  - `@inferencebureau/apps-sdk/test`: for the app's tests: `loadApp` (or `createTestApp`) runs actions against
84
84
  in-memory records with the records engine's rules, mocks the Shopify Admin API, delivers webhooks and installs,
85
85
  and runs queued jobs; `fixtures` has Shopify's webhook payloads. Node only, under Vitest with this package inlined:
package/dist/browser.d.ts CHANGED
@@ -13,5 +13,15 @@ export declare function previewSession(): string | null;
13
13
  export declare const isPreview: () => boolean;
14
14
  /** The session token for the page's requests: the preview's, else App Bridge's, else null (not in the admin). */
15
15
  export declare function shopifySessionToken(): Promise<string | null>;
16
- /** `fetch` with the session token as `Authorization: Bearer …`, for the app's own routes. */
16
+ /**
17
+ * Asks the merchant to grant optional scopes (settings.ib.ts `shopify.optionalScopes`) with Shopify's approval
18
+ * (App Bridge's `shopify.scopes.request`). True once every one is granted; false when the merchant declines, or the
19
+ * page isn't in the Shopify admin (the preview has no App Bridge to ask with).
20
+ */
21
+ export declare function requestScopes(scopes: string[]): Promise<boolean>;
22
+ /**
23
+ * `fetch` with the session token as `Authorization: Bearer …`, for the app's own routes. A route that answers
24
+ * `scopesRequired(...)` gets Shopify's approval for those scopes shown to the merchant, and the request is sent once
25
+ * more if they grant them; otherwise its 403 comes back as it was.
26
+ */
17
27
  export declare function sessionFetch(input: string | URL, init?: RequestInit): Promise<Response>;
package/dist/browser.js CHANGED
@@ -8,6 +8,10 @@
8
8
  * the tab (sessionStorage) so the page's own navigation keeps it, and taken off the address bar.
9
9
  */
10
10
  const KEY = "ib_preview";
11
+ /** The header `scopesRequired` (the SDK's server side) names missing scopes in. */
12
+ const MISSING_SCOPES_HEADER = "x-ib-missing-scopes";
13
+ /** The header a request sent again after the merchant granted scopes carries, for `verifyShopifySession`. */
14
+ const REFRESH_SCOPES_HEADER = "x-ib-refresh-scopes";
11
15
  function storage() {
12
16
  try {
13
17
  return window.sessionStorage;
@@ -84,12 +88,45 @@ function plainRequest(input, init, headers) {
84
88
  xhr.send((init.body ?? null));
85
89
  });
86
90
  }
87
- /** `fetch` with the session token as `Authorization: Bearer …`, for the app's own routes. */
91
+ /**
92
+ * Asks the merchant to grant optional scopes (settings.ib.ts `shopify.optionalScopes`) with Shopify's approval
93
+ * (App Bridge's `shopify.scopes.request`). True once every one is granted; false when the merchant declines, or the
94
+ * page isn't in the Shopify admin (the preview has no App Bridge to ask with).
95
+ */
96
+ export async function requestScopes(scopes) {
97
+ const bridge = globalThis.shopify;
98
+ if (!scopes.length)
99
+ return true;
100
+ if (isPreview() || !bridge?.scopes?.request)
101
+ return false;
102
+ try {
103
+ const r = await bridge.scopes.request(scopes);
104
+ return r.result === "granted-all" || scopes.every((s) => r.detail?.granted?.includes(s));
105
+ }
106
+ catch {
107
+ return false;
108
+ }
109
+ }
110
+ /**
111
+ * `fetch` with the session token as `Authorization: Bearer …`, for the app's own routes. A route that answers
112
+ * `scopesRequired(...)` gets Shopify's approval for those scopes shown to the merchant, and the request is sent once
113
+ * more if they grant them; otherwise its 403 comes back as it was.
114
+ */
88
115
  export async function sessionFetch(input, init = {}) {
89
116
  const preview = previewSession();
90
- const token = preview ?? (await shopifySessionToken());
91
- const headers = new Headers(init.headers);
92
- if (token)
93
- headers.set("authorization", `Bearer ${token}`);
94
- return preview ? plainRequest(input, init, headers) : fetch(input, { ...init, headers });
117
+ const send = async (granted = false) => {
118
+ const token = preview ?? (await shopifySessionToken());
119
+ const headers = new Headers(init.headers);
120
+ if (token)
121
+ headers.set("authorization", `Bearer ${token}`);
122
+ // The route's session check reads the store's grant again, so it sees what was just granted.
123
+ if (granted)
124
+ headers.set(REFRESH_SCOPES_HEADER, "1");
125
+ return preview ? plainRequest(input, init, headers) : fetch(input, { ...init, headers });
126
+ };
127
+ const res = await send();
128
+ const missing = res.status === 403 ? (res.headers.get(MISSING_SCOPES_HEADER) ?? "").split(",").map((s) => s.trim()).filter(Boolean) : [];
129
+ // A body that's a stream can't be sent twice.
130
+ const resendable = init.body == null || typeof init.body === "string" || init.body instanceof URLSearchParams || init.body instanceof FormData || init.body instanceof Blob;
131
+ return missing.length && resendable && (await requestScopes(missing)) ? send(true) : res;
95
132
  }
package/dist/index.d.ts CHANGED
@@ -78,8 +78,24 @@ export interface AppSettings {
78
78
  webhooks?: WebhookSetting[];
79
79
  /** Actions queued on a cron schedule, `params.scheduledAt` the time it was due. */
80
80
  schedules?: ScheduleSetting[];
81
+ /** How the Shopify app installs, and the scopes it asks for later. */
82
+ shopify?: ShopifyInstallSettings;
81
83
  [key: string]: unknown;
82
84
  }
85
+ export interface ShopifyInstallSettings {
86
+ /**
87
+ * `managed` (the default): Shopify installs the app with the scopes from the dashboard, and the app's first load in
88
+ * the admin records the store, with no redirect or second approval screen. `oauth`: the authorization redirect.
89
+ */
90
+ install?: "managed" | "oauth";
91
+ /** Scopes the app asks for once it needs them, in the admin: `requestScopes` from the browser helpers. */
92
+ optionalScopes?: string[];
93
+ /**
94
+ * What the app's Sidekick tools cover, for Sidekick to match merchants' questions to the app, e.g. "Search and
95
+ * compare product bundles and their discounts". Required once an extension defines tools (at most 256 tokens).
96
+ */
97
+ sidekickSummary?: string;
98
+ }
83
99
  export interface WebhookSetting {
84
100
  /** A Shopify webhook topic, e.g. orders/create. The app's scopes must allow it. */
85
101
  topic: string;
@@ -124,6 +140,8 @@ export interface FindManyOptions {
124
140
  sort?: Sort | Sort[];
125
141
  first?: number;
126
142
  after?: string | null;
143
+ /** 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. */
144
+ search?: string;
127
145
  }
128
146
  export interface RecordPage<T = AppRecord> {
129
147
  records: T[];
@@ -195,7 +213,7 @@ export interface ModelClient {
195
213
  findMany(o?: FindManyOptions): Promise<RecordPage>;
196
214
  findFirst(o?: Omit<FindManyOptions, "first" | "after">): Promise<AppRecord | null>;
197
215
  /** Nearest records to text (embedded with the field's model) or a vector, nearest first, with `_distance`. */
198
- search(field: string, near: string | number[], o?: Omit<FindManyOptions, "sort">): Promise<RecordPage<AppRecord & {
216
+ search(field: string, near: string | number[], o?: Omit<FindManyOptions, "sort" | "search">): Promise<RecordPage<AppRecord & {
199
217
  _distance: number;
200
218
  }>>;
201
219
  create(values: Record<string, unknown>): Promise<AppRecord>;
@@ -611,6 +629,8 @@ export interface ShopifySession {
611
629
  preview?: {
612
630
  actor: string;
613
631
  };
632
+ /** The scopes the store has granted the app. */
633
+ scopes: string[];
614
634
  /** The app's API for this staff member: the store's records only, as the `shopify-app-users` role. */
615
635
  api: Api;
616
636
  }
@@ -621,6 +641,17 @@ export interface ShopifySession {
621
641
  * Inference Bureau holds, so the check happens there; never trust a shop named any other way.
622
642
  */
623
643
  export declare function verifyShopifySession(request: Request | string, o?: ClientOptions): Promise<ShopifySession | null>;
644
+ /**
645
+ * The answer for a request that needs scopes the store hasn't granted (`session.scopes`), e.g. settings.ib.ts's
646
+ * `optionalScopes`: 403 naming them. The browser helpers' `sessionFetch` asks the merchant for them with Shopify's
647
+ * approval (App Bridge's `shopify.scopes.request`) and sends the request again once they're granted.
648
+ *
649
+ * const missing = ["read_orders"].filter((s) => !session.scopes.includes(s));
650
+ * if (missing.length) return scopesRequired(missing);
651
+ */
652
+ export declare function scopesRequired(scopes: string[]): Response;
653
+ /** The header `scopesRequired` names the missing scopes in, for the browser helpers. */
654
+ export declare const MISSING_SCOPES_HEADER = "x-ib-missing-scopes";
624
655
  export interface ProxyRequest {
625
656
  /** The store whose storefront made the request (x.myshopify.com). */
626
657
  shop: string;
package/dist/index.js CHANGED
@@ -465,11 +465,13 @@ export async function verifyShopifySession(request, o = {}) {
465
465
  const token = typeof request === "string" ? request : (request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
466
466
  if (!token || token.split(".").length !== 3)
467
467
  return null;
468
+ // Sent again after the merchant granted scopes (the browser helpers' sessionFetch): the store's grant is read again.
469
+ const refresh = typeof request !== "string" && request.headers.get("x-ib-refresh-scopes") === "1";
468
470
  const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
469
471
  const app = o.app ?? envVar("IB_APP") ?? "";
470
472
  const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
471
473
  const res = await (o.fetch ?? fetch)(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/session`, {
472
- method: "POST", headers: { authorization: `Bearer ${o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? ""}`, "content-type": "application/json" }, body: JSON.stringify({ token }),
474
+ method: "POST", headers: { authorization: `Bearer ${o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? ""}`, "content-type": "application/json" }, body: JSON.stringify({ token, ...(refresh ? { refresh: true } : {}) }),
473
475
  });
474
476
  const json = (await res.json().catch(() => ({})));
475
477
  // A refused session token is an answer (null); anything else, like the app's own token being refused, is an error.
@@ -478,8 +480,21 @@ export async function verifyShopifySession(request, o = {}) {
478
480
  if (!res.ok)
479
481
  throw new ApiError(json.error?.message ?? `Checking the session failed (${res.status}).`, res.status, json.error?.code ?? null);
480
482
  const api = createClient({ ...o, shop: json.shop, role: "shopify-app-users", session: { userId: json.userId } });
481
- return { shop: json.shop, userId: json.userId, sessionId: json.sessionId, ...(json.preview ? { preview: json.preview } : {}), api };
483
+ return { shop: json.shop, userId: json.userId, sessionId: json.sessionId, ...(json.preview ? { preview: json.preview } : {}), scopes: json.scopes ?? [], api };
482
484
  }
485
+ /**
486
+ * The answer for a request that needs scopes the store hasn't granted (`session.scopes`), e.g. settings.ib.ts's
487
+ * `optionalScopes`: 403 naming them. The browser helpers' `sessionFetch` asks the merchant for them with Shopify's
488
+ * approval (App Bridge's `shopify.scopes.request`) and sends the request again once they're granted.
489
+ *
490
+ * const missing = ["read_orders"].filter((s) => !session.scopes.includes(s));
491
+ * if (missing.length) return scopesRequired(missing);
492
+ */
493
+ export function scopesRequired(scopes) {
494
+ return Response.json({ error: { code: "missing_scopes", message: `The store hasn't granted ${scopes.join(", ")}.`, scopes } }, { status: 403, headers: { [MISSING_SCOPES_HEADER]: scopes.join(",") } });
495
+ }
496
+ /** The header `scopesRequired` names the missing scopes in, for the browser helpers. */
497
+ export const MISSING_SCOPES_HEADER = "x-ib-missing-scopes";
483
498
  const hex = (b) => Array.from(new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
484
499
  /**
485
500
  * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or from a
package/dist/test.js CHANGED
@@ -296,6 +296,10 @@ class Records {
296
296
  }
297
297
  case "isSet": return arg !== false;
298
298
  case "startsWith": return col.startsWith(String(v(arg)));
299
+ case "contains":
300
+ if (t.column !== "id")
301
+ throw wrong("contains needs a text field");
302
+ return col.toLowerCase().includes(String(v(arg)).toLowerCase());
299
303
  default: return compare(col, v(arg));
300
304
  }
301
305
  }
@@ -330,6 +334,13 @@ class Records {
330
334
  throw wrong("startsWith needs text");
331
335
  return asText(row.data[f.key])?.startsWith(arg) ?? false;
332
336
  }
337
+ case "contains": {
338
+ if (!TEXT_SEARCHED.has(f.type))
339
+ throw wrong("contains needs a text field");
340
+ if (typeof arg !== "string")
341
+ throw wrong("contains needs text");
342
+ return asText(row.data[f.key])?.toLowerCase().includes(arg.toLowerCase()) ?? false;
343
+ }
333
344
  default: {
334
345
  const value = val(arg);
335
346
  return compare(this.comparable(row, t), f.type === "number" || f.type === "boolean" ? value : asText(value));
@@ -392,13 +403,33 @@ class Records {
392
403
  return 0;
393
404
  });
394
405
  }
406
+ /** As the API's text search: every word in one of the text fields, and the rows holding the whole phrase. */
407
+ textSearch(m, rows, text) {
408
+ const words = searchWords(text);
409
+ if (!words.length)
410
+ return null;
411
+ const fields = m.fields.filter((f) => TEXT_SEARCHED.has(f.type));
412
+ if (!fields.length)
413
+ throw invalid([{ field: "search", message: `${m.name} has no text fields to search` }]);
414
+ const docOf = (r) => fields.map((f) => asText(r.data[f.key])).filter((x) => x !== null).join(" ").toLowerCase();
415
+ const found = rows.filter((r) => { const doc = docOf(r); return words.every((w) => doc.includes(w)); });
416
+ const whole = text.trim().toLowerCase();
417
+ return { rows: found, phrase: new Set(found.filter((r) => docOf(r).includes(whole)).map((r) => r.id)) };
418
+ }
395
419
  async findMany(model, o = {}) {
396
420
  const m = this.model(model);
397
421
  const first = Math.min(Math.max(1, Math.floor(o.first ?? 50)), MAX_PAGE);
398
422
  const offset = offsetOf(o.after);
399
423
  let rows = [...this.table(m).values()].filter((r) => this.matches(m, r, o.filter));
400
424
  let distances = null;
401
- if (o.search) {
425
+ const text = typeof o.search === "string" ? this.textSearch(m, rows, o.search) : null;
426
+ if (text) {
427
+ rows = this.sorted(m, text.rows, o.sort);
428
+ // Unsorted, the rows holding the whole phrase come first (a stable sort keeps the default order within each).
429
+ if (!o.sort)
430
+ rows.sort((a, b) => Number(text.phrase.has(b.id)) - Number(text.phrase.has(a.id)));
431
+ }
432
+ else if (o.search && typeof o.search === "object") {
402
433
  const f = m.byName.get(o.search.field);
403
434
  if (!f || f.type !== "vector")
404
435
  throw invalid([{ field: o.search.field, message: `${m.name} has no vector field named ${o.search.field}` }]);
@@ -597,7 +628,9 @@ class Records {
597
628
  return typeof stored === "string" && stored === password;
598
629
  }
599
630
  }
600
- const OPS = ["equals", "notEquals", "in", "notIn", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual", "isSet", "startsWith"];
631
+ const OPS = ["equals", "notEquals", "in", "notIn", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual", "isSet", "startsWith", "contains"];
632
+ const TEXT_SEARCHED = new Set(["string", "richText", "email", "url", "enum"]);
633
+ const searchWords = (text) => text.toLowerCase().match(/[\p{L}\p{N}]+(?:['’.@-][\p{L}\p{N}]+)*/gu) ?? [];
601
634
  const embeddingModelOf = (f) => (typeof f.def.embeddingModel === "string" && f.def.embeddingModel ? f.def.embeddingModel : DEFAULT_EMBEDDING_MODEL);
602
635
  function sourceText(m, f, data) {
603
636
  const names = Array.isArray(f.def.source) ? f.def.source.map(String) : [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencebureau/apps-sdk",
3
- "version": "0.4.0",
3
+ "version": "0.5.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": [