@inferencebureau/apps-sdk 0.3.0 → 0.4.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/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
  };
@@ -245,11 +252,70 @@ export type Api = {
245
252
  * request's `api` already are.
246
253
  */
247
254
  asRole(role: string, session?: CallerSession): Api;
255
+ /** Shopify sync on demand: one store, some or all of its synced models, everything or what changed since a date. */
256
+ shopifySync: ShopifySync;
248
257
  };
258
+ export interface SyncRunOptions {
259
+ /** The store (x.myshopify.com); an `api.forShop(shop)` client's own store when left out. */
260
+ shop?: string;
261
+ /** Synced models by name (a child brings its parent: shopifyProductVariant syncs products); all of them when unset. */
262
+ models?: string[];
263
+ /** Only records Shopify changed after this; everything when unset. */
264
+ since?: string | Date;
265
+ /** Run each model's create, update and delete actions for what the run writes (default true). */
266
+ runActions?: boolean;
267
+ /** Write every record, even ones Shopify hasn't changed since the stored copy (default false). */
268
+ force?: boolean;
269
+ }
270
+ export interface SyncCounts {
271
+ created: number;
272
+ updated: number;
273
+ deleted: number;
274
+ skipped: number;
275
+ failed: number;
276
+ errors: string[];
277
+ }
278
+ export interface SyncRun {
279
+ id: string;
280
+ shop: string;
281
+ models: string[] | null;
282
+ since: string | null;
283
+ runActions: boolean;
284
+ force: boolean;
285
+ /** A run whose function stopped without finishing reads as failed. */
286
+ state: "running" | "succeeded" | "failed" | "aborted";
287
+ abortRequested: boolean;
288
+ /** What it wrote, by model, once it's done. */
289
+ counts: Record<string, SyncCounts> | null;
290
+ error: string | null;
291
+ actor: string;
292
+ source: string;
293
+ createdAt: string;
294
+ heartbeatAt: string;
295
+ finishedAt: string | null;
296
+ }
297
+ export interface ShopifySync {
298
+ /** Starts a run and returns it at once, `running`; one store runs one at a time. Pass `wait` to resolve once it's done. */
299
+ run(o: SyncRunOptions & {
300
+ wait?: boolean | {
301
+ timeoutMs?: number;
302
+ intervalMs?: number;
303
+ };
304
+ }): Promise<SyncRun>;
305
+ get(id: string): Promise<SyncRun | null>;
306
+ /** Runs, newest first; one store's with `shop`. */
307
+ list(o?: {
308
+ shop?: string;
309
+ limit?: number;
310
+ }): Promise<SyncRun[]>;
311
+ /** Stops a running run before its next page; what it wrote stays. */
312
+ abort(id: string): Promise<SyncRun>;
313
+ }
249
314
  /** Who a role-scoped call is for, filling `{ $session: … }` in permissions.ib.ts filters. */
250
315
  export interface CallerSession {
251
316
  userId?: string | null;
252
317
  customerId?: string | null;
318
+ customerRecordId?: string | null;
253
319
  }
254
320
  export interface EnqueueOptions {
255
321
  /** The record a model's action works on. */
@@ -304,6 +370,26 @@ export interface ShopifyClient {
304
370
  environment?: string;
305
371
  /** Runs an Admin GraphQL query or mutation and returns its `data`; GraphQL errors throw ShopifyError. */
306
372
  graphql<T = any>(query: string, variables?: Record<string, unknown>): Promise<T>;
373
+ /**
374
+ * The store's free trial as Inference Bureau keeps it, so it survives a reinstall (Billing's helpers use it).
375
+ * `createShopifyClient` and an action's `shopify` have it; a client of your own may leave it out.
376
+ */
377
+ trial?: {
378
+ get(): Promise<TrialRecord | null>;
379
+ /** Records the trial as started (the first start is kept). */
380
+ start(o: {
381
+ days: number;
382
+ startedAt?: string;
383
+ subscriptionId?: string;
384
+ }): Promise<TrialRecord>;
385
+ };
386
+ }
387
+ /** When a store's first trial started, and how long it was. */
388
+ export interface TrialRecord {
389
+ shop: string;
390
+ startedAt: string;
391
+ days: number;
392
+ subscriptionId: string | null;
307
393
  }
308
394
  export declare class ShopifyError extends Error {
309
395
  readonly errors: unknown[];
@@ -346,6 +432,11 @@ export interface SubscriptionRequest {
346
432
  replacementBehavior?: "APPLY_IMMEDIATELY" | "APPLY_ON_NEXT_BILLING_CYCLE" | "STANDARD";
347
433
  /** Force a test charge, or (in production on a real store only) a real one. */
348
434
  test?: boolean;
435
+ /**
436
+ * With `trialDays`: offer only what's left of the store's first trial, so uninstalling and reinstalling doesn't
437
+ * start another (default true). The trial runs from when it first started, installed or not.
438
+ */
439
+ trackTrial?: boolean;
349
440
  }
350
441
  export interface AppSubscription {
351
442
  id: string;
@@ -391,7 +482,13 @@ export declare function requestSubscription(shopify: ShopifyClient, plan: Subscr
391
482
  confirmationUrl: string;
392
483
  subscriptionId: string;
393
484
  test: boolean;
485
+ trialDays?: number;
394
486
  }>;
487
+ /**
488
+ * Days left of a `days`-day trial for the client's store: all of them before its first trial, else what's left of
489
+ * the window since that one started (reinstalling doesn't reset it). `days` when the client can't say.
490
+ */
491
+ export declare function trialDaysLeft(shopify: ShopifyClient, days: number, now?: number): Promise<number>;
395
492
  /** The store's active subscriptions to this app (usually one), with each line's price or usage cap and balance. */
396
493
  export declare function activeSubscriptions(shopify: ShopifyClient): Promise<AppSubscription[]>;
397
494
  /**
@@ -419,6 +516,91 @@ export declare function cancelSubscription(shopify: ShopifyClient, id: string, o
419
516
  * to pick or change their plan. `appHandle` is the app's handle in the Partner Dashboard.
420
517
  */
421
518
  export declare function managedPricingUrl(shop: string, appHandle: string): string;
519
+ /** The plan a store is on: its active subscription's name, and whether it's still in its trial. */
520
+ export interface CurrentPlan {
521
+ name: string;
522
+ /** ACTIVE, or another of Shopify's statuses only when asked for (`statuses`). */
523
+ status: string;
524
+ subscriptionId: string;
525
+ test: boolean;
526
+ inTrial: boolean;
527
+ /** When the trial ends, or null without one. */
528
+ trialEndsAt: string | null;
529
+ currentPeriodEnd: string | null;
530
+ /** Read from the synced shopifyAppSubscription model, or asked of Shopify. */
531
+ source: "synced" | "shopify";
532
+ }
533
+ /**
534
+ * The store's current plan, or null when it has no active subscription. With `api`, read from the synced
535
+ * shopifyAppSubscription model when the app syncs it (no Admin API call); otherwise, or when it isn't synced, asked
536
+ * of Shopify. A trial is measured from the store's first one (see `trialDaysLeft`), which this records when it sees
537
+ * one running that Inference Bureau hadn't.
538
+ */
539
+ export declare function currentPlan(shopify: ShopifyClient, o?: {
540
+ api?: Api;
541
+ now?: number;
542
+ }): Promise<CurrentPlan | null>;
543
+ /** A store without the plan a route or action needs. `status` is 402; `toResponse()` answers it as JSON. */
544
+ export declare class PlanRequiredError extends Error {
545
+ readonly plans: string[];
546
+ readonly current: CurrentPlan | null;
547
+ readonly status = 402;
548
+ constructor(message: string, plans: string[], current: CurrentPlan | null);
549
+ toResponse(): Response;
550
+ }
551
+ /**
552
+ * The store's plan when it's one of `plans` (by name, any case), or any active plan when `plans` is empty; else
553
+ * throws PlanRequiredError. `allowTrial: false` refuses a plan still in its trial. In an action, pass its `shopify`;
554
+ * in a route, `createShopifyClient(session.shop)`.
555
+ *
556
+ * const plan = await requirePlan(shopify, ["Pro", "Plus"], { api });
557
+ */
558
+ export declare function requirePlan(shopify: ShopifyClient | null, plans?: string | string[], o?: {
559
+ api?: Api;
560
+ allowTrial?: boolean;
561
+ now?: number;
562
+ }): Promise<CurrentPlan>;
563
+ export interface PurchaseRequest {
564
+ /** What the merchant sees on Shopify's approval page and their bill. */
565
+ name: string;
566
+ price: Money;
567
+ /** Where Shopify sends the merchant after they approve or decline. */
568
+ returnUrl: string;
569
+ test?: boolean;
570
+ }
571
+ export interface OneTimePurchase {
572
+ id: string;
573
+ name: string;
574
+ status: string;
575
+ test: boolean;
576
+ createdAt: string;
577
+ price: Money;
578
+ }
579
+ /**
580
+ * A one-time charge (a setup fee, a pack of credits, a lifetime unlock): returns Shopify's `confirmationUrl` for the
581
+ * merchant to approve, as `requestSubscription` does. It's paid once its status is ACTIVE (`oneTimePurchases`).
582
+ */
583
+ export declare function requestPurchase(shopify: ShopifyClient, p: PurchaseRequest): Promise<{
584
+ confirmationUrl: string;
585
+ purchaseId: string;
586
+ test: boolean;
587
+ }>;
588
+ /** The store's one-time purchases of this app, newest first (the latest 50). */
589
+ export declare function oneTimePurchases(shopify: ShopifyClient): Promise<OneTimePurchase[]>;
590
+ /** Whether the store has paid for the one-time purchase of this name (status ACTIVE). */
591
+ export declare function hasPurchased(shopify: ShopifyClient, name: string): Promise<boolean>;
592
+ /**
593
+ * Credits the store against its future app charges (a refund, a goodwill gesture). Shopify takes it off what the
594
+ * store next owes the app; it's never paid out. A test credit outside production or on a development store.
595
+ */
596
+ export declare function grantCredit(shopify: ShopifyClient, c: {
597
+ description: string;
598
+ amount: Money;
599
+ test?: boolean;
600
+ }): Promise<{
601
+ id: string;
602
+ test: boolean;
603
+ }>;
422
604
  export interface ShopifySession {
423
605
  /** The store the admin page is open in (x.myshopify.com). */
424
606
  shop: string;
@@ -450,14 +632,47 @@ export interface ProxyRequest {
450
632
  api: Api;
451
633
  }
452
634
  /**
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.
635
+ * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or from a
636
+ * customer account extension (web/app/extension/, `pathPrefix` "/extension"), or null for anything else. Shopify's
637
+ * own signature (the extension's session token) was checked before it was passed on; this checks ours, so only a
638
+ * real storefront request is trusted with a shop and customer.
456
639
  */
457
640
  export declare function verifyProxyRequest(request: Request, o?: {
458
641
  token?: string;
459
642
  now?: () => number;
460
643
  } & Omit<ClientOptions, "token" | "shop" | "role" | "session">): Promise<ProxyRequest | null>;
644
+ /** A signed-in storefront customer, from the app proxy or a customer account extension. */
645
+ export interface StorefrontCustomer {
646
+ shop: string;
647
+ /** Their Shopify id, as the app proxy gives it (numeric), and as a gid. */
648
+ customerId: string;
649
+ customerGid: string;
650
+ /**
651
+ * Their synced shopifyCustomer record, made now if the sync hadn't brought it yet (a customer who just signed up).
652
+ * Null when the app doesn't sync customers or the store hasn't granted read_customers.
653
+ */
654
+ customer: AppRecord | null;
655
+ /** The app proxy (web/app/proxy/) or a customer account extension (web/app/extension/). */
656
+ source: "proxy" | "extension";
657
+ /**
658
+ * The app's API for this customer, as the `storefront-customers` role: the store's records only, what the role is
659
+ * granted in permissions.ib.ts, and of models that belong to a customer (a `belongsTo` shopifyCustomer, the
660
+ * customer record itself, synced orders), only theirs; new ones are made as theirs. Actions it runs see `caller`.
661
+ */
662
+ api: Api;
663
+ }
664
+ /**
665
+ * The signed-in customer behind a storefront request (the app proxy, or a customer account extension), or null for a
666
+ * guest or anything that isn't a storefront request. Their shopifyCustomer record comes with them.
667
+ *
668
+ * const me = await verifyCustomerRequest(request);
669
+ * if (!me) return Response.json({ error: "Sign in to see your wishlist." }, { status: 401 });
670
+ * const items = await me.api.wishlistItem.findMany(); // theirs only
671
+ */
672
+ export declare function verifyCustomerRequest(request: Request, o?: {
673
+ token?: string;
674
+ now?: () => number;
675
+ } & Omit<ClientOptions, "token" | "shop" | "role" | "session">): Promise<StorefrontCustomer | null>;
461
676
  export interface LogLine {
462
677
  level: "debug" | "info" | "warn" | "error";
463
678
  message: string;
@@ -485,6 +700,18 @@ export interface ActionContext {
485
700
  /** The store this run is about (an install, a webhook, or the caller's `shop`), and the Admin API for it. */
486
701
  shop: string | null;
487
702
  shopify: ShopifyClient | null;
703
+ /**
704
+ * Who called, when the call was held to a role: a signed-in storefront customer (verifyCustomerRequest's `api`),
705
+ * staff in the store's admin (verifyShopifySession's), a shopper. Null for the app's own calls, webhooks and jobs.
706
+ */
707
+ caller: ActionCaller | null;
708
+ }
709
+ export interface ActionCaller {
710
+ role: string;
711
+ userId?: string | null;
712
+ /** A storefront customer's Shopify id (numeric), and their shopifyCustomer record's id when the app syncs customers. */
713
+ customerId?: string | null;
714
+ customerRecordId?: string | null;
488
715
  }
489
716
  export type ActionRun = (ctx: ActionContext) => unknown | Promise<unknown>;
490
717
  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
@@ -313,9 +482,10 @@ export async function verifyShopifySession(request, o = {}) {
313
482
  }
314
483
  const hex = (b) => Array.from(new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
315
484
  /**
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.
485
+ * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or from a
486
+ * customer account extension (web/app/extension/, `pathPrefix` "/extension"), or null for anything else. Shopify's
487
+ * own signature (the extension's session token) was checked before it was passed on; this checks ours, so only a
488
+ * real storefront request is trusted with a shop and customer.
319
489
  */
320
490
  export async function verifyProxyRequest(request, o = {}) {
321
491
  const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
@@ -335,3 +505,32 @@ export async function verifyProxyRequest(request, o = {}) {
335
505
  const api = createClient({ ...client, token, shop, role: "storefront-shoppers", session: { customerId: customer || null } });
336
506
  return { shop, customerId: customer || null, pathPrefix: prefix, api };
337
507
  }
508
+ /**
509
+ * The signed-in customer behind a storefront request (the app proxy, or a customer account extension), or null for a
510
+ * guest or anything that isn't a storefront request. Their shopifyCustomer record comes with them.
511
+ *
512
+ * const me = await verifyCustomerRequest(request);
513
+ * if (!me) return Response.json({ error: "Sign in to see your wishlist." }, { status: 401 });
514
+ * const items = await me.api.wishlistItem.findMany(); // theirs only
515
+ */
516
+ export async function verifyCustomerRequest(request, o = {}) {
517
+ const proxied = await verifyProxyRequest(request, o);
518
+ if (!proxied?.customerId)
519
+ return null;
520
+ const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
521
+ const { now: _now, ...client } = o;
522
+ const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
523
+ const app = o.app ?? envVar("IB_APP") ?? "", environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
524
+ const res = await (o.fetch ?? fetch)(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/customer`, {
525
+ method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ shop: proxied.shop, customerId: proxied.customerId }),
526
+ });
527
+ const json = (await res.json().catch(() => ({})));
528
+ if (!res.ok)
529
+ throw new ApiError(json.error?.message ?? `Looking up the customer failed (${res.status}).`, res.status, json.error?.code ?? null);
530
+ const customer = json.customer ?? null;
531
+ const api = createClient({ ...client, token, shop: proxied.shop, role: "storefront-customers", session: { customerId: proxied.customerId, customerRecordId: customer?.id ?? null } });
532
+ return {
533
+ shop: proxied.shop, customerId: proxied.customerId, customerGid: json.customerGid ?? `gid://shopify/Customer/${proxied.customerId}`, customer,
534
+ source: proxied.pathPrefix === "/extension" ? "extension" : "proxy", api,
535
+ };
536
+ }
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.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": [