@inferencebureau/apps-sdk 0.3.0 → 0.4.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 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
@@ -39,6 +39,13 @@ export interface FieldDef {
39
39
  dimensions?: number;
40
40
  /** File fields: keep the files on a public CDN, read as a plain URL. Otherwise they read through a URL signed for an hour. */
41
41
  allowPublicAccess?: boolean;
42
+ /**
43
+ * A synced Shopify field's: `"later"` isn't written from webhooks, only by sync passes (the hourly reconcile, a
44
+ * run), which fill it even when nothing else changed; `"onWebhook"` has the record fetched from the Admin API when
45
+ * a webhook's payload doesn't carry the field (products, collections, customers, orders, draft orders). Unset, a
46
+ * webhook writes what its payload carries.
47
+ */
48
+ fetch?: "onWebhook" | "later";
42
49
  parent?: {
43
50
  model: string;
44
51
  };
@@ -71,8 +78,19 @@ export interface AppSettings {
71
78
  webhooks?: WebhookSetting[];
72
79
  /** Actions queued on a cron schedule, `params.scheduledAt` the time it was due. */
73
80
  schedules?: ScheduleSetting[];
81
+ /** How the Shopify app installs, and the scopes it asks for later. */
82
+ shopify?: ShopifyInstallSettings;
74
83
  [key: string]: unknown;
75
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
+ }
76
94
  export interface WebhookSetting {
77
95
  /** A Shopify webhook topic, e.g. orders/create. The app's scopes must allow it. */
78
96
  topic: string;
@@ -245,11 +263,70 @@ export type Api = {
245
263
  * request's `api` already are.
246
264
  */
247
265
  asRole(role: string, session?: CallerSession): Api;
266
+ /** Shopify sync on demand: one store, some or all of its synced models, everything or what changed since a date. */
267
+ shopifySync: ShopifySync;
248
268
  };
269
+ export interface SyncRunOptions {
270
+ /** The store (x.myshopify.com); an `api.forShop(shop)` client's own store when left out. */
271
+ shop?: string;
272
+ /** Synced models by name (a child brings its parent: shopifyProductVariant syncs products); all of them when unset. */
273
+ models?: string[];
274
+ /** Only records Shopify changed after this; everything when unset. */
275
+ since?: string | Date;
276
+ /** Run each model's create, update and delete actions for what the run writes (default true). */
277
+ runActions?: boolean;
278
+ /** Write every record, even ones Shopify hasn't changed since the stored copy (default false). */
279
+ force?: boolean;
280
+ }
281
+ export interface SyncCounts {
282
+ created: number;
283
+ updated: number;
284
+ deleted: number;
285
+ skipped: number;
286
+ failed: number;
287
+ errors: string[];
288
+ }
289
+ export interface SyncRun {
290
+ id: string;
291
+ shop: string;
292
+ models: string[] | null;
293
+ since: string | null;
294
+ runActions: boolean;
295
+ force: boolean;
296
+ /** A run whose function stopped without finishing reads as failed. */
297
+ state: "running" | "succeeded" | "failed" | "aborted";
298
+ abortRequested: boolean;
299
+ /** What it wrote, by model, once it's done. */
300
+ counts: Record<string, SyncCounts> | null;
301
+ error: string | null;
302
+ actor: string;
303
+ source: string;
304
+ createdAt: string;
305
+ heartbeatAt: string;
306
+ finishedAt: string | null;
307
+ }
308
+ export interface ShopifySync {
309
+ /** Starts a run and returns it at once, `running`; one store runs one at a time. Pass `wait` to resolve once it's done. */
310
+ run(o: SyncRunOptions & {
311
+ wait?: boolean | {
312
+ timeoutMs?: number;
313
+ intervalMs?: number;
314
+ };
315
+ }): Promise<SyncRun>;
316
+ get(id: string): Promise<SyncRun | null>;
317
+ /** Runs, newest first; one store's with `shop`. */
318
+ list(o?: {
319
+ shop?: string;
320
+ limit?: number;
321
+ }): Promise<SyncRun[]>;
322
+ /** Stops a running run before its next page; what it wrote stays. */
323
+ abort(id: string): Promise<SyncRun>;
324
+ }
249
325
  /** Who a role-scoped call is for, filling `{ $session: … }` in permissions.ib.ts filters. */
250
326
  export interface CallerSession {
251
327
  userId?: string | null;
252
328
  customerId?: string | null;
329
+ customerRecordId?: string | null;
253
330
  }
254
331
  export interface EnqueueOptions {
255
332
  /** The record a model's action works on. */
@@ -304,6 +381,26 @@ export interface ShopifyClient {
304
381
  environment?: string;
305
382
  /** Runs an Admin GraphQL query or mutation and returns its `data`; GraphQL errors throw ShopifyError. */
306
383
  graphql<T = any>(query: string, variables?: Record<string, unknown>): Promise<T>;
384
+ /**
385
+ * The store's free trial as Inference Bureau keeps it, so it survives a reinstall (Billing's helpers use it).
386
+ * `createShopifyClient` and an action's `shopify` have it; a client of your own may leave it out.
387
+ */
388
+ trial?: {
389
+ get(): Promise<TrialRecord | null>;
390
+ /** Records the trial as started (the first start is kept). */
391
+ start(o: {
392
+ days: number;
393
+ startedAt?: string;
394
+ subscriptionId?: string;
395
+ }): Promise<TrialRecord>;
396
+ };
397
+ }
398
+ /** When a store's first trial started, and how long it was. */
399
+ export interface TrialRecord {
400
+ shop: string;
401
+ startedAt: string;
402
+ days: number;
403
+ subscriptionId: string | null;
307
404
  }
308
405
  export declare class ShopifyError extends Error {
309
406
  readonly errors: unknown[];
@@ -346,6 +443,11 @@ export interface SubscriptionRequest {
346
443
  replacementBehavior?: "APPLY_IMMEDIATELY" | "APPLY_ON_NEXT_BILLING_CYCLE" | "STANDARD";
347
444
  /** Force a test charge, or (in production on a real store only) a real one. */
348
445
  test?: boolean;
446
+ /**
447
+ * With `trialDays`: offer only what's left of the store's first trial, so uninstalling and reinstalling doesn't
448
+ * start another (default true). The trial runs from when it first started, installed or not.
449
+ */
450
+ trackTrial?: boolean;
349
451
  }
350
452
  export interface AppSubscription {
351
453
  id: string;
@@ -391,7 +493,13 @@ export declare function requestSubscription(shopify: ShopifyClient, plan: Subscr
391
493
  confirmationUrl: string;
392
494
  subscriptionId: string;
393
495
  test: boolean;
496
+ trialDays?: number;
394
497
  }>;
498
+ /**
499
+ * Days left of a `days`-day trial for the client's store: all of them before its first trial, else what's left of
500
+ * the window since that one started (reinstalling doesn't reset it). `days` when the client can't say.
501
+ */
502
+ export declare function trialDaysLeft(shopify: ShopifyClient, days: number, now?: number): Promise<number>;
395
503
  /** The store's active subscriptions to this app (usually one), with each line's price or usage cap and balance. */
396
504
  export declare function activeSubscriptions(shopify: ShopifyClient): Promise<AppSubscription[]>;
397
505
  /**
@@ -419,6 +527,91 @@ export declare function cancelSubscription(shopify: ShopifyClient, id: string, o
419
527
  * to pick or change their plan. `appHandle` is the app's handle in the Partner Dashboard.
420
528
  */
421
529
  export declare function managedPricingUrl(shop: string, appHandle: string): string;
530
+ /** The plan a store is on: its active subscription's name, and whether it's still in its trial. */
531
+ export interface CurrentPlan {
532
+ name: string;
533
+ /** ACTIVE, or another of Shopify's statuses only when asked for (`statuses`). */
534
+ status: string;
535
+ subscriptionId: string;
536
+ test: boolean;
537
+ inTrial: boolean;
538
+ /** When the trial ends, or null without one. */
539
+ trialEndsAt: string | null;
540
+ currentPeriodEnd: string | null;
541
+ /** Read from the synced shopifyAppSubscription model, or asked of Shopify. */
542
+ source: "synced" | "shopify";
543
+ }
544
+ /**
545
+ * The store's current plan, or null when it has no active subscription. With `api`, read from the synced
546
+ * shopifyAppSubscription model when the app syncs it (no Admin API call); otherwise, or when it isn't synced, asked
547
+ * of Shopify. A trial is measured from the store's first one (see `trialDaysLeft`), which this records when it sees
548
+ * one running that Inference Bureau hadn't.
549
+ */
550
+ export declare function currentPlan(shopify: ShopifyClient, o?: {
551
+ api?: Api;
552
+ now?: number;
553
+ }): Promise<CurrentPlan | null>;
554
+ /** A store without the plan a route or action needs. `status` is 402; `toResponse()` answers it as JSON. */
555
+ export declare class PlanRequiredError extends Error {
556
+ readonly plans: string[];
557
+ readonly current: CurrentPlan | null;
558
+ readonly status = 402;
559
+ constructor(message: string, plans: string[], current: CurrentPlan | null);
560
+ toResponse(): Response;
561
+ }
562
+ /**
563
+ * The store's plan when it's one of `plans` (by name, any case), or any active plan when `plans` is empty; else
564
+ * throws PlanRequiredError. `allowTrial: false` refuses a plan still in its trial. In an action, pass its `shopify`;
565
+ * in a route, `createShopifyClient(session.shop)`.
566
+ *
567
+ * const plan = await requirePlan(shopify, ["Pro", "Plus"], { api });
568
+ */
569
+ export declare function requirePlan(shopify: ShopifyClient | null, plans?: string | string[], o?: {
570
+ api?: Api;
571
+ allowTrial?: boolean;
572
+ now?: number;
573
+ }): Promise<CurrentPlan>;
574
+ export interface PurchaseRequest {
575
+ /** What the merchant sees on Shopify's approval page and their bill. */
576
+ name: string;
577
+ price: Money;
578
+ /** Where Shopify sends the merchant after they approve or decline. */
579
+ returnUrl: string;
580
+ test?: boolean;
581
+ }
582
+ export interface OneTimePurchase {
583
+ id: string;
584
+ name: string;
585
+ status: string;
586
+ test: boolean;
587
+ createdAt: string;
588
+ price: Money;
589
+ }
590
+ /**
591
+ * A one-time charge (a setup fee, a pack of credits, a lifetime unlock): returns Shopify's `confirmationUrl` for the
592
+ * merchant to approve, as `requestSubscription` does. It's paid once its status is ACTIVE (`oneTimePurchases`).
593
+ */
594
+ export declare function requestPurchase(shopify: ShopifyClient, p: PurchaseRequest): Promise<{
595
+ confirmationUrl: string;
596
+ purchaseId: string;
597
+ test: boolean;
598
+ }>;
599
+ /** The store's one-time purchases of this app, newest first (the latest 50). */
600
+ export declare function oneTimePurchases(shopify: ShopifyClient): Promise<OneTimePurchase[]>;
601
+ /** Whether the store has paid for the one-time purchase of this name (status ACTIVE). */
602
+ export declare function hasPurchased(shopify: ShopifyClient, name: string): Promise<boolean>;
603
+ /**
604
+ * Credits the store against its future app charges (a refund, a goodwill gesture). Shopify takes it off what the
605
+ * store next owes the app; it's never paid out. A test credit outside production or on a development store.
606
+ */
607
+ export declare function grantCredit(shopify: ShopifyClient, c: {
608
+ description: string;
609
+ amount: Money;
610
+ test?: boolean;
611
+ }): Promise<{
612
+ id: string;
613
+ test: boolean;
614
+ }>;
422
615
  export interface ShopifySession {
423
616
  /** The store the admin page is open in (x.myshopify.com). */
424
617
  shop: string;
@@ -429,6 +622,8 @@ export interface ShopifySession {
429
622
  preview?: {
430
623
  actor: string;
431
624
  };
625
+ /** The scopes the store has granted the app. */
626
+ scopes: string[];
432
627
  /** The app's API for this staff member: the store's records only, as the `shopify-app-users` role. */
433
628
  api: Api;
434
629
  }
@@ -439,6 +634,17 @@ export interface ShopifySession {
439
634
  * Inference Bureau holds, so the check happens there; never trust a shop named any other way.
440
635
  */
441
636
  export declare function verifyShopifySession(request: Request | string, o?: ClientOptions): Promise<ShopifySession | null>;
637
+ /**
638
+ * The answer for a request that needs scopes the store hasn't granted (`session.scopes`), e.g. settings.ib.ts's
639
+ * `optionalScopes`: 403 naming them. The browser helpers' `sessionFetch` asks the merchant for them with Shopify's
640
+ * approval (App Bridge's `shopify.scopes.request`) and sends the request again once they're granted.
641
+ *
642
+ * const missing = ["read_orders"].filter((s) => !session.scopes.includes(s));
643
+ * if (missing.length) return scopesRequired(missing);
644
+ */
645
+ export declare function scopesRequired(scopes: string[]): Response;
646
+ /** The header `scopesRequired` names the missing scopes in, for the browser helpers. */
647
+ export declare const MISSING_SCOPES_HEADER = "x-ib-missing-scopes";
442
648
  export interface ProxyRequest {
443
649
  /** The store whose storefront made the request (x.myshopify.com). */
444
650
  shop: string;
@@ -450,14 +656,47 @@ export interface ProxyRequest {
450
656
  api: Api;
451
657
  }
452
658
  /**
453
- * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or null for
454
- * anything else. Shopify's own signature was checked before it was passed on; this checks ours, so only a real
455
- * storefront request is trusted with a shop and customer.
659
+ * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or from a
660
+ * customer account extension (web/app/extension/, `pathPrefix` "/extension"), or null for anything else. Shopify's
661
+ * own signature (the extension's session token) was checked before it was passed on; this checks ours, so only a
662
+ * real storefront request is trusted with a shop and customer.
456
663
  */
457
664
  export declare function verifyProxyRequest(request: Request, o?: {
458
665
  token?: string;
459
666
  now?: () => number;
460
667
  } & Omit<ClientOptions, "token" | "shop" | "role" | "session">): Promise<ProxyRequest | null>;
668
+ /** A signed-in storefront customer, from the app proxy or a customer account extension. */
669
+ export interface StorefrontCustomer {
670
+ shop: string;
671
+ /** Their Shopify id, as the app proxy gives it (numeric), and as a gid. */
672
+ customerId: string;
673
+ customerGid: string;
674
+ /**
675
+ * Their synced shopifyCustomer record, made now if the sync hadn't brought it yet (a customer who just signed up).
676
+ * Null when the app doesn't sync customers or the store hasn't granted read_customers.
677
+ */
678
+ customer: AppRecord | null;
679
+ /** The app proxy (web/app/proxy/) or a customer account extension (web/app/extension/). */
680
+ source: "proxy" | "extension";
681
+ /**
682
+ * The app's API for this customer, as the `storefront-customers` role: the store's records only, what the role is
683
+ * granted in permissions.ib.ts, and of models that belong to a customer (a `belongsTo` shopifyCustomer, the
684
+ * customer record itself, synced orders), only theirs; new ones are made as theirs. Actions it runs see `caller`.
685
+ */
686
+ api: Api;
687
+ }
688
+ /**
689
+ * The signed-in customer behind a storefront request (the app proxy, or a customer account extension), or null for a
690
+ * guest or anything that isn't a storefront request. Their shopifyCustomer record comes with them.
691
+ *
692
+ * const me = await verifyCustomerRequest(request);
693
+ * if (!me) return Response.json({ error: "Sign in to see your wishlist." }, { status: 401 });
694
+ * const items = await me.api.wishlistItem.findMany(); // theirs only
695
+ */
696
+ export declare function verifyCustomerRequest(request: Request, o?: {
697
+ token?: string;
698
+ now?: () => number;
699
+ } & Omit<ClientOptions, "token" | "shop" | "role" | "session">): Promise<StorefrontCustomer | null>;
461
700
  export interface LogLine {
462
701
  level: "debug" | "info" | "warn" | "error";
463
702
  message: string;
@@ -485,6 +724,18 @@ export interface ActionContext {
485
724
  /** The store this run is about (an install, a webhook, or the caller's `shop`), and the Admin API for it. */
486
725
  shop: string | null;
487
726
  shopify: ShopifyClient | null;
727
+ /**
728
+ * Who called, when the call was held to a role: a signed-in storefront customer (verifyCustomerRequest's `api`),
729
+ * staff in the store's admin (verifyShopifySession's), a shopper. Null for the app's own calls, webhooks and jobs.
730
+ */
731
+ caller: ActionCaller | null;
732
+ }
733
+ export interface ActionCaller {
734
+ role: string;
735
+ userId?: string | null;
736
+ /** A storefront customer's Shopify id (numeric), and their shopifyCustomer record's id when the app syncs customers. */
737
+ customerId?: string | null;
738
+ customerRecordId?: string | null;
488
739
  }
489
740
  export type ActionRun = (ctx: ActionContext) => unknown | Promise<unknown>;
490
741
  export type ActionOnSuccess = (ctx: ActionContext) => void | Promise<void>;
package/dist/index.js CHANGED
@@ -81,7 +81,7 @@ export function createClient(o = {}) {
81
81
  // The scope only narrows what the token may do; Inference Bureau applies it (and refuses a malformed one).
82
82
  const scope = {
83
83
  ...(o.shop ? { "x-ib-shop": o.shop } : {}), ...(o.role ? { "x-ib-role": o.role } : {}),
84
- ...(o.role && o.session ? { "x-ib-session": JSON.stringify({ userId: o.session.userId ?? null, customerId: o.session.customerId ?? null }) } : {}),
84
+ ...(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 } : {}) }) } : {}),
85
85
  };
86
86
  async function call(method, path, body) {
87
87
  const res = await f(`${base}${path}`, {
@@ -138,6 +138,33 @@ export function createClient(o = {}) {
138
138
  const cache = new Map();
139
139
  const $global = (action, params = {}) => call("POST", `/actions/${encodeURIComponent(action)}`, { params });
140
140
  const enqueue = (action, params = {}, o = {}) => call("POST", "/jobs", { action, params, ...o, ...(o.runAt instanceof Date ? { runAt: o.runAt.toISOString() } : {}) });
141
+ const sync = "/shopify/sync";
142
+ const getRun = async (id) => {
143
+ try {
144
+ return await call("GET", `${sync}/${encodeURIComponent(id)}`);
145
+ }
146
+ catch (e) {
147
+ if (e instanceof ApiError && e.status === 404)
148
+ return null;
149
+ throw e;
150
+ }
151
+ };
152
+ const shopifySync = {
153
+ async run({ wait, since, ...r }) {
154
+ let run = await call("POST", sync, { ...r, ...(since !== undefined ? { since: since instanceof Date ? since.toISOString() : since } : {}) });
155
+ if (!wait)
156
+ return run;
157
+ const { timeoutMs = 10 * 60_000, intervalMs = 2_000 } = wait === true ? {} : wait;
158
+ for (const end = Date.now() + timeoutMs; run.state === "running" && Date.now() < end;) {
159
+ await new Promise((done) => setTimeout(done, intervalMs));
160
+ run = (await getRun(run.id)) ?? run;
161
+ }
162
+ return run;
163
+ },
164
+ get: getRun,
165
+ list: async (q = {}) => (await call("GET", `${sync}?${new URLSearchParams({ ...(q.shop ? { shop: q.shop } : {}), ...(q.limit ? { limit: String(q.limit) } : {}) })}`)).data,
166
+ abort: (id) => call("POST", `${sync}/${encodeURIComponent(id)}/abort`),
167
+ };
141
168
  const forShop = (shop) => createClient({ ...o, url, token, app, environment, fetch: f, shop });
142
169
  const asRole = (role, session) => createClient({ ...o, url, token, app, environment, fetch: f, role, ...(session ? { session } : {}) });
143
170
  return new Proxy({}, {
@@ -150,6 +177,8 @@ export function createClient(o = {}) {
150
177
  return forShop;
151
178
  if (prop === "asRole")
152
179
  return asRole;
180
+ if (prop === "shopifySync")
181
+ return shopifySync;
153
182
  if (typeof prop !== "string" || prop === "then")
154
183
  return undefined;
155
184
  if (!cache.has(prop))
@@ -174,11 +203,23 @@ export function createShopifyClient(shop, o = {}) {
174
203
  const app = o.app ?? envVar("IB_APP") ?? "";
175
204
  const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
176
205
  const f = o.fetch ?? fetch;
206
+ const base = `${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify`;
207
+ const trialCall = async (init) => {
208
+ const res = await f(`${base}/billing/trial${init.query ?? ""}`, { ...init, headers: { authorization: `Bearer ${token}`, "content-type": "application/json" } });
209
+ const json = (await res.json().catch(() => ({})));
210
+ if (!res.ok)
211
+ throw new ApiError(json.error?.message ?? `The API answered ${res.status}.`, res.status, json.error?.code ?? null);
212
+ return json.trial ?? null;
213
+ };
177
214
  return {
178
215
  shop,
179
216
  environment,
217
+ trial: {
218
+ get: () => trialCall({ method: "GET", query: `?shop=${encodeURIComponent(shop)}` }),
219
+ start: async (t) => (await trialCall({ method: "POST", body: JSON.stringify({ shop, ...t }) })),
220
+ },
180
221
  async graphql(query, variables = {}) {
181
- const res = await f(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/graphql`, {
222
+ const res = await f(`${base}/graphql`, {
182
223
  method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ shop, query, variables, ...(o.priority ? { priority: o.priority } : {}), ...(o.maxRetries !== undefined ? { maxRetries: o.maxRetries } : {}) }),
183
224
  });
184
225
  const json = (await res.json().catch(() => ({})));
@@ -226,16 +267,27 @@ export async function requestSubscription(shopify, plan) {
226
267
  ...(plan.usage ? [{ plan: { appUsagePricingDetails: { cappedAmount: money(plan.usage.cappedAmount), terms: plan.usage.terms } } }] : []),
227
268
  ];
228
269
  const test = await isTestCharge(shopify, plan.test);
270
+ const trialDays = plan.trialDays && plan.trackTrial !== false ? await trialDaysLeft(shopify, plan.trialDays) : plan.trialDays;
229
271
  const data = await shopify.graphql(`
230
272
  mutation BillingSubscribe($name: String!, $lineItems: [AppSubscriptionLineItemInput!]!, $returnUrl: URL!, $trialDays: Int, $test: Boolean, $replacementBehavior: AppSubscriptionReplacementBehavior) {
231
273
  appSubscriptionCreate(name: $name, lineItems: $lineItems, returnUrl: $returnUrl, trialDays: $trialDays, test: $test, replacementBehavior: $replacementBehavior) {
232
274
  confirmationUrl appSubscription { id } userErrors { field message }
233
275
  }
234
- }`, { name: plan.name, lineItems, returnUrl: plan.returnUrl, trialDays: plan.trialDays ?? null, test, replacementBehavior: plan.replacementBehavior ?? null });
276
+ }`, { name: plan.name, lineItems, returnUrl: plan.returnUrl, trialDays: trialDays || null, test, replacementBehavior: plan.replacementBehavior ?? null });
235
277
  userErrorsOf("start the subscription", data.appSubscriptionCreate.userErrors);
236
278
  if (!data.appSubscriptionCreate.confirmationUrl || !data.appSubscriptionCreate.appSubscription)
237
279
  throw new ShopifyBillingError("Shopify didn't return a confirmation URL.");
238
- return { confirmationUrl: data.appSubscriptionCreate.confirmationUrl, subscriptionId: data.appSubscriptionCreate.appSubscription.id, test };
280
+ return { confirmationUrl: data.appSubscriptionCreate.confirmationUrl, subscriptionId: data.appSubscriptionCreate.appSubscription.id, test, ...(plan.trialDays ? { trialDays: trialDays ?? 0 } : {}) };
281
+ }
282
+ /**
283
+ * Days left of a `days`-day trial for the client's store: all of them before its first trial, else what's left of
284
+ * the window since that one started (reinstalling doesn't reset it). `days` when the client can't say.
285
+ */
286
+ export async function trialDaysLeft(shopify, days, now = Date.now()) {
287
+ const t = shopify.trial ? await shopify.trial.get() : null;
288
+ if (!t)
289
+ return days;
290
+ return Math.max(0, days - Math.floor((now - Date.parse(t.startedAt)) / 86_400_000));
239
291
  }
240
292
  const SUBSCRIPTION = `id name status test trialDays currentPeriodEnd createdAt
241
293
  lineItems { id plan { pricingDetails { __typename
@@ -286,6 +338,123 @@ export async function cancelSubscription(shopify, id, o = {}) {
286
338
  export function managedPricingUrl(shop, appHandle) {
287
339
  return `https://admin.shopify.com/store/${shop.replace(/\.myshopify\.com$/, "")}/charges/${encodeURIComponent(appHandle)}/pricing_plans`;
288
340
  }
341
+ const DAY = 86_400_000;
342
+ const isoPlus = (at, days) => new Date(Date.parse(at) + days * DAY).toISOString();
343
+ /**
344
+ * The store's current plan, or null when it has no active subscription. With `api`, read from the synced
345
+ * shopifyAppSubscription model when the app syncs it (no Admin API call); otherwise, or when it isn't synced, asked
346
+ * of Shopify. A trial is measured from the store's first one (see `trialDaysLeft`), which this records when it sees
347
+ * one running that Inference Bureau hadn't.
348
+ */
349
+ export async function currentPlan(shopify, o = {}) {
350
+ const now = o.now ?? Date.now();
351
+ let sub = null;
352
+ let read = false;
353
+ if (o.api) {
354
+ try {
355
+ const r = await o.api.shopifyAppSubscription.findFirst({ filter: { shop: { equals: shopify.shop }, status: { equals: "active" } }, sort: { shopifyCreatedAt: "Descending" } });
356
+ read = true;
357
+ if (r)
358
+ 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" };
359
+ }
360
+ catch (e) {
361
+ // Not synced: the model doesn't exist. Anything else is a real failure.
362
+ if (!(e instanceof ApiError && (e.status === 404 || e.code === "not_found")))
363
+ throw e;
364
+ }
365
+ }
366
+ if (!read) {
367
+ const [a] = await activeSubscriptions(shopify);
368
+ if (a)
369
+ sub = { name: a.name, status: a.status, subscriptionId: a.id, test: a.test, currentPeriodEnd: a.currentPeriodEnd, trialDays: a.trialDays, createdAt: a.createdAt, source: "shopify" };
370
+ }
371
+ if (!sub)
372
+ return null;
373
+ const { trialDays, createdAt, ...plan } = sub;
374
+ let trialEndsAt = null;
375
+ if (trialDays > 0) {
376
+ const t = shopify.trial ? await shopify.trial.get().catch(() => null) : null;
377
+ trialEndsAt = t ? isoPlus(t.startedAt, Math.min(t.days, trialDays)) : isoPlus(createdAt, trialDays);
378
+ if (!t && shopify.trial && Date.parse(trialEndsAt) > now)
379
+ await shopify.trial.start({ days: trialDays, startedAt: createdAt, subscriptionId: sub.subscriptionId }).catch(() => undefined);
380
+ }
381
+ return { ...plan, inTrial: !!trialEndsAt && Date.parse(trialEndsAt) > now, trialEndsAt };
382
+ }
383
+ /** A store without the plan a route or action needs. `status` is 402; `toResponse()` answers it as JSON. */
384
+ export class PlanRequiredError extends Error {
385
+ plans;
386
+ current;
387
+ status = 402;
388
+ constructor(message, plans, current) {
389
+ super(message);
390
+ this.plans = plans;
391
+ this.current = current;
392
+ }
393
+ toResponse() {
394
+ return Response.json({ error: { code: "plan_required", message: this.message, plans: this.plans, current: this.current?.name ?? null } }, { status: 402 });
395
+ }
396
+ }
397
+ /**
398
+ * The store's plan when it's one of `plans` (by name, any case), or any active plan when `plans` is empty; else
399
+ * throws PlanRequiredError. `allowTrial: false` refuses a plan still in its trial. In an action, pass its `shopify`;
400
+ * in a route, `createShopifyClient(session.shop)`.
401
+ *
402
+ * const plan = await requirePlan(shopify, ["Pro", "Plus"], { api });
403
+ */
404
+ export async function requirePlan(shopify, plans = [], o = {}) {
405
+ const want = (Array.isArray(plans) ? plans : [plans]).filter(Boolean);
406
+ if (!shopify)
407
+ throw new PlanRequiredError("This needs a store: the run has no shop.", want, null);
408
+ const plan = await currentPlan(shopify, o);
409
+ const named = want.length ? want.join(" or ") : "a plan";
410
+ if (!plan)
411
+ throw new PlanRequiredError(`${shopify.shop} needs ${named} for this.`, want, null);
412
+ if (want.length && !want.some((p) => p.toLowerCase() === plan.name.toLowerCase()))
413
+ throw new PlanRequiredError(`${shopify.shop} is on ${plan.name}; this needs ${named}.`, want, plan);
414
+ if (o.allowTrial === false && plan.inTrial)
415
+ throw new PlanRequiredError(`${shopify.shop} is still in its ${plan.name} trial; this needs a paid plan.`, want, plan);
416
+ return plan;
417
+ }
418
+ /**
419
+ * A one-time charge (a setup fee, a pack of credits, a lifetime unlock): returns Shopify's `confirmationUrl` for the
420
+ * merchant to approve, as `requestSubscription` does. It's paid once its status is ACTIVE (`oneTimePurchases`).
421
+ */
422
+ export async function requestPurchase(shopify, p) {
423
+ const test = await isTestCharge(shopify, p.test);
424
+ const data = await shopify.graphql(`
425
+ mutation BillingPurchase($name: String!, $price: MoneyInput!, $returnUrl: URL!, $test: Boolean) {
426
+ appPurchaseOneTimeCreate(name: $name, price: $price, returnUrl: $returnUrl, test: $test) { confirmationUrl appPurchaseOneTime { id } userErrors { field message } }
427
+ }`, { name: p.name, price: money(p.price), returnUrl: p.returnUrl, test });
428
+ userErrorsOf("start the purchase", data.appPurchaseOneTimeCreate.userErrors);
429
+ if (!data.appPurchaseOneTimeCreate.confirmationUrl || !data.appPurchaseOneTimeCreate.appPurchaseOneTime)
430
+ throw new ShopifyBillingError("Shopify didn't return a confirmation URL.");
431
+ return { confirmationUrl: data.appPurchaseOneTimeCreate.confirmationUrl, purchaseId: data.appPurchaseOneTimeCreate.appPurchaseOneTime.id, test };
432
+ }
433
+ /** The store's one-time purchases of this app, newest first (the latest 50). */
434
+ export async function oneTimePurchases(shopify) {
435
+ const data = await shopify.graphql(`query BillingPurchases {
436
+ currentAppInstallation { oneTimePurchases(first: 50, sortKey: CREATED_AT, reverse: true) { nodes { id name status test createdAt price { amount currencyCode } } } } }`);
437
+ return data.currentAppInstallation.oneTimePurchases.nodes;
438
+ }
439
+ /** Whether the store has paid for the one-time purchase of this name (status ACTIVE). */
440
+ export async function hasPurchased(shopify, name) {
441
+ return (await oneTimePurchases(shopify)).some((p) => p.status === "ACTIVE" && p.name === name);
442
+ }
443
+ /**
444
+ * Credits the store against its future app charges (a refund, a goodwill gesture). Shopify takes it off what the
445
+ * store next owes the app; it's never paid out. A test credit outside production or on a development store.
446
+ */
447
+ export async function grantCredit(shopify, c) {
448
+ const test = await isTestCharge(shopify, c.test);
449
+ const data = await shopify.graphql(`
450
+ mutation BillingCredit($description: String!, $amount: MoneyInput!, $test: Boolean) {
451
+ appCreditCreate(description: $description, amount: $amount, test: $test) { appCredit { id } userErrors { field message } }
452
+ }`, { description: c.description, amount: money(c.amount), test });
453
+ userErrorsOf("grant the credit", data.appCreditCreate.userErrors);
454
+ if (!data.appCreditCreate.appCredit)
455
+ throw new ShopifyBillingError("Shopify didn't create the credit.");
456
+ return { id: data.appCreditCreate.appCredit.id, test };
457
+ }
289
458
  /**
290
459
  * The store and staff member behind a request from one of the app's pages in the Shopify admin, or null when it
291
460
  * carries no valid session token. App Bridge's `shopify.idToken()` gives the page its token; send it as
@@ -296,11 +465,13 @@ export async function verifyShopifySession(request, o = {}) {
296
465
  const token = typeof request === "string" ? request : (request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
297
466
  if (!token || token.split(".").length !== 3)
298
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";
299
470
  const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
300
471
  const app = o.app ?? envVar("IB_APP") ?? "";
301
472
  const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
302
473
  const res = await (o.fetch ?? fetch)(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/session`, {
303
- 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 } : {}) }),
304
475
  });
305
476
  const json = (await res.json().catch(() => ({})));
306
477
  // A refused session token is an answer (null); anything else, like the app's own token being refused, is an error.
@@ -309,13 +480,27 @@ export async function verifyShopifySession(request, o = {}) {
309
480
  if (!res.ok)
310
481
  throw new ApiError(json.error?.message ?? `Checking the session failed (${res.status}).`, res.status, json.error?.code ?? null);
311
482
  const api = createClient({ ...o, shop: json.shop, role: "shopify-app-users", session: { userId: json.userId } });
312
- 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 };
313
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";
314
498
  const hex = (b) => Array.from(new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
315
499
  /**
316
- * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or null for
317
- * anything else. Shopify's own signature was checked before it was passed on; this checks ours, so only a real
318
- * storefront request is trusted with a shop and customer.
500
+ * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or from a
501
+ * customer account extension (web/app/extension/, `pathPrefix` "/extension"), or null for anything else. Shopify's
502
+ * own signature (the extension's session token) was checked before it was passed on; this checks ours, so only a
503
+ * real storefront request is trusted with a shop and customer.
319
504
  */
320
505
  export async function verifyProxyRequest(request, o = {}) {
321
506
  const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
@@ -335,3 +520,32 @@ export async function verifyProxyRequest(request, o = {}) {
335
520
  const api = createClient({ ...client, token, shop, role: "storefront-shoppers", session: { customerId: customer || null } });
336
521
  return { shop, customerId: customer || null, pathPrefix: prefix, api };
337
522
  }
523
+ /**
524
+ * The signed-in customer behind a storefront request (the app proxy, or a customer account extension), or null for a
525
+ * guest or anything that isn't a storefront request. Their shopifyCustomer record comes with them.
526
+ *
527
+ * const me = await verifyCustomerRequest(request);
528
+ * if (!me) return Response.json({ error: "Sign in to see your wishlist." }, { status: 401 });
529
+ * const items = await me.api.wishlistItem.findMany(); // theirs only
530
+ */
531
+ export async function verifyCustomerRequest(request, o = {}) {
532
+ const proxied = await verifyProxyRequest(request, o);
533
+ if (!proxied?.customerId)
534
+ return null;
535
+ const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
536
+ const { now: _now, ...client } = o;
537
+ const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
538
+ const app = o.app ?? envVar("IB_APP") ?? "", environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
539
+ const res = await (o.fetch ?? fetch)(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/customer`, {
540
+ method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ shop: proxied.shop, customerId: proxied.customerId }),
541
+ });
542
+ const json = (await res.json().catch(() => ({})));
543
+ if (!res.ok)
544
+ throw new ApiError(json.error?.message ?? `Looking up the customer failed (${res.status}).`, res.status, json.error?.code ?? null);
545
+ const customer = json.customer ?? null;
546
+ const api = createClient({ ...client, token, shop: proxied.shop, role: "storefront-customers", session: { customerId: proxied.customerId, customerRecordId: customer?.id ?? null } });
547
+ return {
548
+ shop: proxied.shop, customerId: proxied.customerId, customerGid: json.customerGid ?? `gid://shopify/Customer/${proxied.customerId}`, customer,
549
+ source: proxied.pathPrefix === "/extension" ? "extension" : "proxy", api,
550
+ };
551
+ }
package/dist/runtime.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * signature, runs the action file, and answers with what `run` asked to happen to the record. Inference Bureau
5
5
  * applies that in one transaction, then calls again for `onSuccess` with the saved record.
6
6
  */
7
- import { type ActionModule, type Api, type AppRecord, type LogLine, type ShopifyClient } from "./index.js";
7
+ import { type ActionCaller, type ActionModule, type Api, type AppRecord, type LogLine, type ShopifyClient } from "./index.js";
8
8
  /** Action modules by key: `<model>/<action>` for model actions, `$global/<action>` for global ones. */
9
9
  export type ActionRegistry = Record<string, () => Promise<ActionModule>>;
10
10
  export interface ActionRequest {
@@ -20,6 +20,8 @@ export interface ActionRequest {
20
20
  shop?: string | null;
21
21
  /** Nobody is waiting on the run (a job, a webhook, a schedule): its Shopify calls give way to requests. */
22
22
  background?: boolean;
23
+ /** Who called, when the call was held to a role. */
24
+ caller?: ActionCaller | null;
23
25
  }
24
26
  export type ActionResponse = {
25
27
  ok: true;
package/dist/runtime.js CHANGED
@@ -49,7 +49,7 @@ export async function runAction(req, registry, o = {}) {
49
49
  const ctx = {
50
50
  params: req.params ?? {}, record, api: scopedApi(o.api ?? createClient(o.token ? { token: o.token } : {}), req.shop), logger: collector(logs, o.echo ?? true),
51
51
  model: req.model, action: req.action, environment: req.environment,
52
- shop: req.shop ?? null, shopify: req.shop ? (o.shopify?.(req.shop) ?? createShopifyClient(req.shop, { ...(o.token ? { token: o.token } : {}), ...(req.background ? { priority: "background" } : {}) })) : null,
52
+ 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,
53
53
  };
54
54
  if (req.phase === "onSuccess") {
55
55
  await mod.onSuccess?.(ctx);
package/dist/test.d.ts CHANGED
@@ -15,7 +15,7 @@
15
15
  * File fields keep their files in memory: `base64` reads back as a `data:` URL, `copyURL` as the URL itself (not
16
16
  * fetched, size 0), and `upload`/`createUpload` tokens as the upload (a `createUpload` needs no PUT here).
17
17
  */
18
- import { ApiError, type ActionModule, type Api, type AppRecord, type AppSettings, type Job, type LogLine, type ModelSchema } from "./index.js";
18
+ import { ApiError, type ActionModule, type Api, type AppRecord, type AppSettings, type Job, type LogLine, type ModelSchema, type SyncRun } from "./index.js";
19
19
  type Embed = (model: string, input: string[]) => Promise<number[][]>;
20
20
  /** The store a test app installs on and runs as, unless a test names another. */
21
21
  export declare const TEST_SHOP = "test-shop.myshopify.com";
@@ -233,6 +233,8 @@ export interface TestApp {
233
233
  }): Promise<TestRun[]>;
234
234
  /** Jobs `api.enqueue` queued, in order. */
235
235
  jobs: Job[];
236
+ /** Shopify sync runs `api.shopifySync.run` started, in order (each succeeds at once, writing nothing). */
237
+ syncRuns: SyncRun[];
236
238
  /** Runs every queued job once (and the ones they queue), whatever its delay. A failed job stays queued while it has tries left. */
237
239
  runJobs(): Promise<Job[]>;
238
240
  shopify: ShopifyMock;
package/dist/test.js CHANGED
@@ -892,6 +892,31 @@ export function createTestApp(o = {}) {
892
892
  jobs.push(job);
893
893
  return wire(job);
894
894
  };
895
+ // Runs succeed at once and write nothing: a test sees what was asked for in `syncRuns`.
896
+ const shopifySync = (shop) => {
897
+ const find = (id) => syncRuns.find((r) => r.id === id) ?? null;
898
+ return {
899
+ run: async ({ wait: _wait, since, ...q }) => {
900
+ const target = q.shop ?? shop;
901
+ if (!target)
902
+ throw new ApiError("Name the store: shop.", 400, "invalid_request");
903
+ if (shop && target !== shop)
904
+ throw otherStore(shop);
905
+ const at = new Date((o.now ?? Date.now)()).toISOString();
906
+ const r = {
907
+ id: `syn_${String(syncRuns.length + 1).padStart(6, "0")}`, shop: target, models: q.models?.length ? q.models : null, since: since === undefined ? null : new Date(since).toISOString(),
908
+ runActions: q.runActions ?? true, force: q.force ?? false, state: "succeeded", abortRequested: false, counts: {}, error: null, actor: "test", source: "api", createdAt: at, heartbeatAt: at, finishedAt: at,
909
+ };
910
+ syncRuns.push(r);
911
+ return r;
912
+ },
913
+ get: async (id) => find(id),
914
+ list: async (q = {}) => syncRuns.filter((r) => !(q.shop ?? shop) || r.shop === (q.shop ?? shop)).reverse().slice(0, q.limit ?? 50),
915
+ abort: async (id) => { const r = find(id); if (!r)
916
+ throw notFound(`There's no sync run ${id}.`); return r; },
917
+ };
918
+ };
919
+ const syncRuns = [];
895
920
  const apis = new Map();
896
921
  /** The API, for every store or one (`forShop`). Roles aren't applied here: `asRole` gives the same API. */
897
922
  const apiFor = (shop) => {
@@ -918,6 +943,8 @@ export function createTestApp(o = {}) {
918
943
  return (s) => apiFor(s);
919
944
  if (prop === "asRole")
920
945
  return () => made;
946
+ if (prop === "shopifySync")
947
+ return shopifySync(shop);
921
948
  if (typeof prop !== "string" || prop === "then")
922
949
  return undefined;
923
950
  if (!clients.has(prop))
@@ -1082,10 +1109,11 @@ export function createTestApp(o = {}) {
1082
1109
  uninstall: (shop = TEST_SHOP) => shopHook(shop, "uninstall", { state: "uninstalled", uninstalledAt: iso((o.now ?? Date.now)()) }),
1083
1110
  webhook,
1084
1111
  jobs,
1112
+ syncRuns,
1085
1113
  runJobs,
1086
1114
  shopify,
1087
1115
  logs,
1088
- reset() { store.clear(); jobs.length = 0; logs.length = 0; shopify.calls.length = 0; },
1116
+ reset() { store.clear(); jobs.length = 0; syncRuns.length = 0; logs.length = 0; shopify.calls.length = 0; },
1089
1117
  };
1090
1118
  }
1091
1119
  // ---- 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.0",
3
+ "version": "0.4.1",
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": [