@inferencebureau/apps-sdk 0.2.1 → 0.3.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,7 +74,9 @@ 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`, and the errors they throw (`ApiError`, `ShopifyError`).
77
+ `verifyShopifySession`, `verifyProxyRequest`, Shopify Billing for public apps (`requestSubscription`,
78
+ `activeSubscriptions`, `recordUsage`, `cancelSubscription`, `managedPricingUrl`), and the errors they throw
79
+ (`ApiError`, `ShopifyError`, `ShopifyBillingError`).
78
80
  - `@inferencebureau/apps-sdk/runtime`: `handleAction`, the signed `/_ib/actions` route every build adds.
79
81
  - `@inferencebureau/apps-sdk/browser`: for an embedded admin page's client code: `sessionFetch`,
80
82
  `shopifySessionToken`, `isPreview`, `previewSession`.
package/dist/index.d.ts CHANGED
@@ -37,6 +37,8 @@ export interface FieldDef {
37
37
  source?: string[];
38
38
  embeddingModel?: string;
39
39
  dimensions?: number;
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
+ allowPublicAccess?: boolean;
40
42
  parent?: {
41
43
  model: string;
42
44
  };
@@ -150,6 +152,37 @@ export declare class ApiError extends Error {
150
152
  message: string;
151
153
  }[]);
152
154
  }
155
+ /** A file field's value as a record reads it. `url` is signed for an hour unless the field has `allowPublicAccess`. */
156
+ export interface FileValue {
157
+ url: string | null;
158
+ fileName: string;
159
+ mimeType: string;
160
+ size: number;
161
+ }
162
+ /**
163
+ * What a write gives a file field: the bytes as base64 (small files), a public https URL to copy, or the token of a
164
+ * direct upload (`createUpload` or `upload`). `null` clears it.
165
+ */
166
+ export type FileInput = {
167
+ base64: string;
168
+ fileName?: string;
169
+ mimeType?: string;
170
+ } | {
171
+ copyURL: string;
172
+ fileName?: string;
173
+ mimeType?: string;
174
+ } | {
175
+ directUploadToken: string;
176
+ fileName?: string;
177
+ };
178
+ /** A direct upload: PUT the file to `url` with `headers` within the hour, then write `{ directUploadToken: token }` within a day. */
179
+ export interface Upload {
180
+ url: string;
181
+ method: "PUT";
182
+ headers: Record<string, string>;
183
+ token: string;
184
+ expiresAt: string;
185
+ }
153
186
  export interface ModelClient {
154
187
  findOne(id: string): Promise<AppRecord | null>;
155
188
  findMany(o?: FindManyOptions): Promise<RecordPage>;
@@ -172,6 +205,22 @@ export interface ModelClient {
172
205
  record: AppRecord | null;
173
206
  result?: unknown;
174
207
  }>;
208
+ /**
209
+ * A direct upload for a file field, for a browser to PUT a file to (up to 1 GiB) without it passing through the app.
210
+ * Give `size` and the upload takes at most that many bytes.
211
+ */
212
+ createUpload(field: string, o?: {
213
+ fileName?: string;
214
+ mimeType?: string;
215
+ size?: number;
216
+ }): Promise<Upload>;
217
+ /** Uploads a file for a file field, straight to storage, and answers the value to write to the field. */
218
+ upload(field: string, body: Blob | ArrayBuffer | Uint8Array, o?: {
219
+ fileName?: string;
220
+ mimeType?: string;
221
+ }): Promise<{
222
+ directUploadToken: string;
223
+ }>;
175
224
  }
176
225
  export type Api = {
177
226
  [model: string]: ModelClient;
@@ -185,7 +234,23 @@ export type Api = {
185
234
  * `id` for the record). It gets up to five minutes, and is retried when it fails.
186
235
  */
187
236
  enqueue(action: string, params?: Record<string, unknown>, options?: EnqueueOptions): Promise<Job>;
237
+ /**
238
+ * The same API for one store: store-owned models (Shopify's, and any with a text field named `shop`) show only that
239
+ * store's records, new ones are made as its, and actions run for it. An action's `api` is already its run's store's.
240
+ */
241
+ forShop(shop: string): Api;
242
+ /**
243
+ * The same API held to a role in accessControl/permissions.ib.ts: only what the role is granted, through its
244
+ * filters, with `session` standing in for `{ $session: "userId" | "customerId" }`. A Shopify session's and a proxy
245
+ * request's `api` already are.
246
+ */
247
+ asRole(role: string, session?: CallerSession): Api;
188
248
  };
249
+ /** Who a role-scoped call is for, filling `{ $session: … }` in permissions.ib.ts filters. */
250
+ export interface CallerSession {
251
+ userId?: string | null;
252
+ customerId?: string | null;
253
+ }
189
254
  export interface EnqueueOptions {
190
255
  /** The record a model's action works on. */
191
256
  id?: string;
@@ -221,6 +286,11 @@ export interface ClientOptions {
221
286
  app?: string;
222
287
  environment?: string;
223
288
  fetch?: typeof fetch;
289
+ /** Narrows every call to one store (see `Api.forShop`). */
290
+ shop?: string;
291
+ /** Holds every call to a role in permissions.ib.ts (see `Api.asRole`). */
292
+ role?: string;
293
+ session?: CallerSession;
224
294
  }
225
295
  /** The app's API. In an app's deployment every option comes from its environment variables. */
226
296
  export declare function createClient(o?: ClientOptions): Api;
@@ -230,15 +300,125 @@ export declare function createClient(o?: ClientOptions): Api;
230
300
  */
231
301
  export interface ShopifyClient {
232
302
  shop: string;
303
+ /** The environment the client calls from (IB_ENVIRONMENT): Billing makes test charges outside production. */
304
+ environment?: string;
233
305
  /** Runs an Admin GraphQL query or mutation and returns its `data`; GraphQL errors throw ShopifyError. */
234
306
  graphql<T = any>(query: string, variables?: Record<string, unknown>): Promise<T>;
235
307
  }
236
308
  export declare class ShopifyError extends Error {
237
309
  readonly errors: unknown[];
238
310
  constructor(message: string, errors: unknown[]);
311
+ /** Shopify was still throttling the store after Inference Bureau waited and tried again. */
312
+ get throttled(): boolean;
313
+ }
314
+ export interface ShopifyClientOptions extends ClientOptions {
315
+ /**
316
+ * `"background"` for work nobody is waiting on: its calls wait until half the store's GraphQL bucket is free, so
317
+ * the embedded admin's requests keep theirs. Actions run by jobs, webhooks and schedules get it on their own.
318
+ */
319
+ priority?: "background" | "request";
320
+ /** Throttled calls Inference Bureau tries again before answering (default 5). */
321
+ maxRetries?: number;
239
322
  }
240
323
  /** The Admin API for `shop`, as the environment (the same options as createClient). */
241
- export declare function createShopifyClient(shop: string, o?: ClientOptions): ShopifyClient;
324
+ export declare function createShopifyClient(shop: string, o?: ShopifyClientOptions): ShopifyClient;
325
+ export interface Money {
326
+ amount: number | string;
327
+ currencyCode: string;
328
+ }
329
+ export interface SubscriptionRequest {
330
+ /** What the merchant sees on Shopify's approval page and their bill. */
331
+ name: string;
332
+ /** Where Shopify sends the merchant after they approve or decline (an embedded page of the app). */
333
+ returnUrl: string;
334
+ /** A fixed charge each period. */
335
+ recurring?: {
336
+ price: Money;
337
+ interval?: "EVERY_30_DAYS" | "ANNUAL";
338
+ };
339
+ /** Usage charges up to a cap each 30 days, recorded with `recordUsage`. `terms` is shown to the merchant. */
340
+ usage?: {
341
+ cappedAmount: Money;
342
+ terms: string;
343
+ };
344
+ trialDays?: number;
345
+ /** What happens to an active subscription: by default Shopify decides (upgrade now, downgrade at period end). */
346
+ replacementBehavior?: "APPLY_IMMEDIATELY" | "APPLY_ON_NEXT_BILLING_CYCLE" | "STANDARD";
347
+ /** Force a test charge, or (in production on a real store only) a real one. */
348
+ test?: boolean;
349
+ }
350
+ export interface AppSubscription {
351
+ id: string;
352
+ name: string;
353
+ status: string;
354
+ test: boolean;
355
+ trialDays: number;
356
+ currentPeriodEnd: string | null;
357
+ createdAt: string;
358
+ lineItems: {
359
+ id: string;
360
+ recurring?: {
361
+ price: Money;
362
+ interval: string;
363
+ };
364
+ usage?: {
365
+ cappedAmount: Money;
366
+ balanceUsed: Money;
367
+ terms: string;
368
+ };
369
+ }[];
370
+ }
371
+ export declare class ShopifyBillingError extends Error {
372
+ readonly userErrors: {
373
+ field?: string[] | null;
374
+ message: string;
375
+ }[];
376
+ constructor(message: string, userErrors?: {
377
+ field?: string[] | null;
378
+ message: string;
379
+ }[]);
380
+ }
381
+ /**
382
+ * Whether a charge for this store is a test charge: always outside production, and in production on a development
383
+ * store (Shopify's `partnerDevelopment` plan), unless `test` says otherwise.
384
+ */
385
+ export declare function isTestCharge(shopify: ShopifyClient, test?: boolean): Promise<boolean>;
386
+ /**
387
+ * Starts a subscription and returns Shopify's `confirmationUrl`: redirect the merchant there (from an embedded page,
388
+ * open it at the top level) to approve. It's active once they do: `activeSubscriptions` or the synced model says so.
389
+ */
390
+ export declare function requestSubscription(shopify: ShopifyClient, plan: SubscriptionRequest): Promise<{
391
+ confirmationUrl: string;
392
+ subscriptionId: string;
393
+ test: boolean;
394
+ }>;
395
+ /** The store's active subscriptions to this app (usually one), with each line's price or usage cap and balance. */
396
+ export declare function activeSubscriptions(shopify: ShopifyClient): Promise<AppSubscription[]>;
397
+ /**
398
+ * Charges usage on a subscription's usage line: the active one's unless `lineItemId` names another. Pass an
399
+ * `idempotencyKey` (an order id, a job id) so a retried action doesn't charge twice. Shopify refuses a charge past
400
+ * the line's cap; raise it with a new subscription (`replacementBehavior: "APPLY_IMMEDIATELY"`).
401
+ */
402
+ export declare function recordUsage(shopify: ShopifyClient, charge: {
403
+ price: Money;
404
+ description: string;
405
+ idempotencyKey?: string;
406
+ lineItemId?: string;
407
+ }): Promise<{
408
+ id: string;
409
+ }>;
410
+ /** Cancels a subscription; `prorate` refunds the unused part of the period. */
411
+ export declare function cancelSubscription(shopify: ShopifyClient, id: string, o?: {
412
+ prorate?: boolean;
413
+ }): Promise<{
414
+ id: string;
415
+ status: string;
416
+ }>;
417
+ /**
418
+ * Shopify's plan page for an app on managed pricing (plans set in the Partner Dashboard): where to send a merchant
419
+ * to pick or change their plan. `appHandle` is the app's handle in the Partner Dashboard.
420
+ */
421
+ export declare function managedPricingUrl(shop: string, appHandle: string): string;
242
422
  export interface ShopifySession {
243
423
  /** The store the admin page is open in (x.myshopify.com). */
244
424
  shop: string;
@@ -249,6 +429,8 @@ export interface ShopifySession {
249
429
  preview?: {
250
430
  actor: string;
251
431
  };
432
+ /** The app's API for this staff member: the store's records only, as the `shopify-app-users` role. */
433
+ api: Api;
252
434
  }
253
435
  /**
254
436
  * The store and staff member behind a request from one of the app's pages in the Shopify admin, or null when it
@@ -264,6 +446,8 @@ export interface ProxyRequest {
264
446
  customerId: string | null;
265
447
  /** Where the storefront reached the app, e.g. /apps/wholesale. */
266
448
  pathPrefix: string;
449
+ /** The app's API for this shopper: the store's records only, as the `storefront-shoppers` role. */
450
+ api: Api;
267
451
  }
268
452
  /**
269
453
  * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or null for
@@ -273,7 +457,7 @@ export interface ProxyRequest {
273
457
  export declare function verifyProxyRequest(request: Request, o?: {
274
458
  token?: string;
275
459
  now?: () => number;
276
- }): Promise<ProxyRequest | null>;
460
+ } & Omit<ClientOptions, "token" | "shop" | "role" | "session">): Promise<ProxyRequest | null>;
277
461
  export interface LogLine {
278
462
  level: "debug" | "info" | "warn" | "error";
279
463
  message: string;
package/dist/index.js CHANGED
@@ -78,9 +78,14 @@ export function createClient(o = {}) {
78
78
  const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
79
79
  const f = o.fetch ?? fetch;
80
80
  const base = `${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}`;
81
+ // The scope only narrows what the token may do; Inference Bureau applies it (and refuses a malformed one).
82
+ const scope = {
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 }) } : {}),
85
+ };
81
86
  async function call(method, path, body) {
82
87
  const res = await f(`${base}${path}`, {
83
- method, headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "content-type": "application/json" }) },
88
+ method, headers: { authorization: `Bearer ${token}`, ...scope, ...(body === undefined ? {} : { "content-type": "application/json" }) },
84
89
  ...(body === undefined ? {} : { body: JSON.stringify(body) }),
85
90
  });
86
91
  if (res.status === 204)
@@ -117,17 +122,34 @@ export function createClient(o = {}) {
117
122
  delete: (id) => call("DELETE", `${m}/records/${encodeURIComponent(id)}`),
118
123
  checkPassword: async (id, password, field) => (await call("POST", `${m}/records/${encodeURIComponent(id)}/check-password`, { password, ...(field ? { field } : {}) })).valid,
119
124
  run: (action, o = {}) => call("POST", `${m}/actions/${encodeURIComponent(action)}`, { ...(o.id ? { id: o.id } : {}), params: o.params ?? {}, ...(o.shop ? { shop: o.shop } : {}) }),
125
+ createUpload: (field, o = {}) => call("POST", `${m}/uploads`, { field, ...o }),
126
+ async upload(field, body, o = {}) {
127
+ const blob = body instanceof Blob ? body : new Blob([body]);
128
+ const fileName = o.fileName ?? (typeof File !== "undefined" && body instanceof File ? body.name : undefined);
129
+ const mimeType = o.mimeType ?? (blob.type || undefined);
130
+ const up = await call("POST", `${m}/uploads`, { field, size: blob.size, ...(fileName ? { fileName } : {}), ...(mimeType ? { mimeType } : {}) });
131
+ const res = await f(up.url, { method: "PUT", headers: up.headers, body: blob });
132
+ if (!res.ok)
133
+ throw new ApiError(`The upload was refused (${res.status}): ${(await res.text()).slice(0, 300)}`, res.status, "upload_failed");
134
+ return { directUploadToken: up.token };
135
+ },
120
136
  };
121
137
  };
122
138
  const cache = new Map();
123
139
  const $global = (action, params = {}) => call("POST", `/actions/${encodeURIComponent(action)}`, { params });
124
140
  const enqueue = (action, params = {}, o = {}) => call("POST", "/jobs", { action, params, ...o, ...(o.runAt instanceof Date ? { runAt: o.runAt.toISOString() } : {}) });
141
+ const forShop = (shop) => createClient({ ...o, url, token, app, environment, fetch: f, shop });
142
+ const asRole = (role, session) => createClient({ ...o, url, token, app, environment, fetch: f, role, ...(session ? { session } : {}) });
125
143
  return new Proxy({}, {
126
144
  get(_t, prop) {
127
145
  if (prop === "$global")
128
146
  return $global;
129
147
  if (prop === "enqueue")
130
148
  return enqueue;
149
+ if (prop === "forShop")
150
+ return forShop;
151
+ if (prop === "asRole")
152
+ return asRole;
131
153
  if (typeof prop !== "string" || prop === "then")
132
154
  return undefined;
133
155
  if (!cache.has(prop))
@@ -142,6 +164,8 @@ export class ShopifyError extends Error {
142
164
  super(message);
143
165
  this.errors = errors;
144
166
  }
167
+ /** Shopify was still throttling the store after Inference Bureau waited and tried again. */
168
+ get throttled() { return this.errors.some((e) => e?.extensions?.code === "THROTTLED"); }
145
169
  }
146
170
  /** The Admin API for `shop`, as the environment (the same options as createClient). */
147
171
  export function createShopifyClient(shop, o = {}) {
@@ -152,9 +176,10 @@ export function createShopifyClient(shop, o = {}) {
152
176
  const f = o.fetch ?? fetch;
153
177
  return {
154
178
  shop,
179
+ environment,
155
180
  async graphql(query, variables = {}) {
156
181
  const res = await f(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/graphql`, {
157
- method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ shop, query, variables }),
182
+ 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 } : {}) }),
158
183
  });
159
184
  const json = (await res.json().catch(() => ({})));
160
185
  if (!res.ok)
@@ -165,6 +190,102 @@ export function createShopifyClient(shop, o = {}) {
165
190
  },
166
191
  };
167
192
  }
193
+ export class ShopifyBillingError extends Error {
194
+ userErrors;
195
+ constructor(message, userErrors = []) {
196
+ super(message);
197
+ this.userErrors = userErrors;
198
+ }
199
+ }
200
+ const money = (m) => ({ amount: Number(m.amount), currencyCode: m.currencyCode });
201
+ const userErrorsOf = (what, errors) => {
202
+ if (errors?.length)
203
+ throw new ShopifyBillingError(`Shopify didn't ${what}: ${errors.map((e) => e.message).join("; ")}`, errors);
204
+ };
205
+ /**
206
+ * Whether a charge for this store is a test charge: always outside production, and in production on a development
207
+ * store (Shopify's `partnerDevelopment` plan), unless `test` says otherwise.
208
+ */
209
+ export async function isTestCharge(shopify, test) {
210
+ if ((shopify.environment ?? "development") !== "production")
211
+ return true;
212
+ if (test !== undefined)
213
+ return test;
214
+ const data = await shopify.graphql(`query BillingShopPlan { shop { plan { partnerDevelopment } } }`);
215
+ return data.shop.plan.partnerDevelopment;
216
+ }
217
+ /**
218
+ * Starts a subscription and returns Shopify's `confirmationUrl`: redirect the merchant there (from an embedded page,
219
+ * open it at the top level) to approve. It's active once they do: `activeSubscriptions` or the synced model says so.
220
+ */
221
+ export async function requestSubscription(shopify, plan) {
222
+ if (!plan.recurring && !plan.usage)
223
+ throw new ShopifyBillingError("A subscription needs a recurring price, usage charges, or both.");
224
+ const lineItems = [
225
+ ...(plan.recurring ? [{ plan: { appRecurringPricingDetails: { price: money(plan.recurring.price), interval: plan.recurring.interval ?? "EVERY_30_DAYS" } } }] : []),
226
+ ...(plan.usage ? [{ plan: { appUsagePricingDetails: { cappedAmount: money(plan.usage.cappedAmount), terms: plan.usage.terms } } }] : []),
227
+ ];
228
+ const test = await isTestCharge(shopify, plan.test);
229
+ const data = await shopify.graphql(`
230
+ mutation BillingSubscribe($name: String!, $lineItems: [AppSubscriptionLineItemInput!]!, $returnUrl: URL!, $trialDays: Int, $test: Boolean, $replacementBehavior: AppSubscriptionReplacementBehavior) {
231
+ appSubscriptionCreate(name: $name, lineItems: $lineItems, returnUrl: $returnUrl, trialDays: $trialDays, test: $test, replacementBehavior: $replacementBehavior) {
232
+ confirmationUrl appSubscription { id } userErrors { field message }
233
+ }
234
+ }`, { name: plan.name, lineItems, returnUrl: plan.returnUrl, trialDays: plan.trialDays ?? null, test, replacementBehavior: plan.replacementBehavior ?? null });
235
+ userErrorsOf("start the subscription", data.appSubscriptionCreate.userErrors);
236
+ if (!data.appSubscriptionCreate.confirmationUrl || !data.appSubscriptionCreate.appSubscription)
237
+ throw new ShopifyBillingError("Shopify didn't return a confirmation URL.");
238
+ return { confirmationUrl: data.appSubscriptionCreate.confirmationUrl, subscriptionId: data.appSubscriptionCreate.appSubscription.id, test };
239
+ }
240
+ const SUBSCRIPTION = `id name status test trialDays currentPeriodEnd createdAt
241
+ lineItems { id plan { pricingDetails { __typename
242
+ ... on AppRecurringPricing { price { amount currencyCode } interval }
243
+ ... on AppUsagePricing { cappedAmount { amount currencyCode } balanceUsed { amount currencyCode } terms } } } }`;
244
+ const subscriptionOf = (s) => ({
245
+ ...s,
246
+ lineItems: s.lineItems.map((l) => {
247
+ const d = l.plan.pricingDetails;
248
+ return d.__typename === "AppUsagePricing" ? { id: l.id, usage: { cappedAmount: d.cappedAmount, balanceUsed: d.balanceUsed, terms: d.terms ?? "" } } : { id: l.id, recurring: { price: d.price, interval: d.interval ?? "EVERY_30_DAYS" } };
249
+ }),
250
+ });
251
+ /** The store's active subscriptions to this app (usually one), with each line's price or usage cap and balance. */
252
+ export async function activeSubscriptions(shopify) {
253
+ const data = await shopify.graphql(`query BillingActive { currentAppInstallation { activeSubscriptions { ${SUBSCRIPTION} } } }`);
254
+ return data.currentAppInstallation.activeSubscriptions.map(subscriptionOf);
255
+ }
256
+ /**
257
+ * Charges usage on a subscription's usage line: the active one's unless `lineItemId` names another. Pass an
258
+ * `idempotencyKey` (an order id, a job id) so a retried action doesn't charge twice. Shopify refuses a charge past
259
+ * the line's cap; raise it with a new subscription (`replacementBehavior: "APPLY_IMMEDIATELY"`).
260
+ */
261
+ export async function recordUsage(shopify, charge) {
262
+ let line = charge.lineItemId;
263
+ if (!line) {
264
+ line = (await activeSubscriptions(shopify)).flatMap((s) => s.lineItems).find((l) => l.usage)?.id;
265
+ if (!line)
266
+ throw new ShopifyBillingError(`${shopify.shop} has no active subscription with usage charges.`);
267
+ }
268
+ const data = await shopify.graphql(`
269
+ mutation BillingUsage($line: ID!, $price: MoneyInput!, $description: String!, $key: String) {
270
+ appUsageRecordCreate(subscriptionLineItemId: $line, price: $price, description: $description, idempotencyKey: $key) { appUsageRecord { id } userErrors { field message } }
271
+ }`, { line, price: money(charge.price), description: charge.description, key: charge.idempotencyKey ?? null });
272
+ userErrorsOf("record the usage charge", data.appUsageRecordCreate.userErrors);
273
+ return { id: data.appUsageRecordCreate.appUsageRecord.id };
274
+ }
275
+ /** Cancels a subscription; `prorate` refunds the unused part of the period. */
276
+ export async function cancelSubscription(shopify, id, o = {}) {
277
+ const data = await shopify.graphql(`
278
+ mutation BillingCancel($id: ID!, $prorate: Boolean) { appSubscriptionCancel(id: $id, prorate: $prorate) { appSubscription { id status } userErrors { field message } } }`, { id, prorate: o.prorate ?? false });
279
+ userErrorsOf("cancel the subscription", data.appSubscriptionCancel.userErrors);
280
+ return data.appSubscriptionCancel.appSubscription;
281
+ }
282
+ /**
283
+ * Shopify's plan page for an app on managed pricing (plans set in the Partner Dashboard): where to send a merchant
284
+ * to pick or change their plan. `appHandle` is the app's handle in the Partner Dashboard.
285
+ */
286
+ export function managedPricingUrl(shop, appHandle) {
287
+ return `https://admin.shopify.com/store/${shop.replace(/\.myshopify\.com$/, "")}/charges/${encodeURIComponent(appHandle)}/pricing_plans`;
288
+ }
168
289
  /**
169
290
  * The store and staff member behind a request from one of the app's pages in the Shopify admin, or null when it
170
291
  * carries no valid session token. App Bridge's `shopify.idToken()` gives the page its token; send it as
@@ -187,7 +308,8 @@ export async function verifyShopifySession(request, o = {}) {
187
308
  return null;
188
309
  if (!res.ok)
189
310
  throw new ApiError(json.error?.message ?? `Checking the session failed (${res.status}).`, res.status, json.error?.code ?? null);
190
- return { shop: json.shop, userId: json.userId, sessionId: json.sessionId, ...(json.preview ? { preview: json.preview } : {}) };
311
+ 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 };
191
313
  }
192
314
  const hex = (b) => Array.from(new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
193
315
  /**
@@ -207,5 +329,9 @@ export async function verifyProxyRequest(request, o = {}) {
207
329
  let d = got.length ^ want.length;
208
330
  for (let i = 0; i < Math.min(got.length, want.length); i++)
209
331
  d |= got.charCodeAt(i) ^ want.charCodeAt(i);
210
- return d === 0 ? { shop, customerId: customer || null, pathPrefix: prefix } : null;
332
+ if (d !== 0)
333
+ return null;
334
+ const { now: _now, ...client } = o;
335
+ const api = createClient({ ...client, token, shop, role: "storefront-shoppers", session: { customerId: customer || null } });
336
+ return { shop, customerId: customer || null, pathPrefix: prefix, api };
211
337
  }
package/dist/runtime.d.ts CHANGED
@@ -18,6 +18,8 @@ export interface ActionRequest {
18
18
  environment: "development" | "production";
19
19
  /** The store the run is about, when there is one. */
20
20
  shop?: string | null;
21
+ /** Nobody is waiting on the run (a job, a webhook, a schedule): its Shopify calls give way to requests. */
22
+ background?: boolean;
21
23
  }
22
24
  export type ActionResponse = {
23
25
  ok: true;
package/dist/runtime.js CHANGED
@@ -30,6 +30,8 @@ function collector(lines, echo) {
30
30
  };
31
31
  return { debug: at("debug"), info: at("info"), warn: at("warn"), error: at("error") };
32
32
  }
33
+ /** An action's `api`: its run's store's records only, when the run is for a store (`createClient()` reaches every store). */
34
+ const scopedApi = (api, shop) => (shop && typeof api.forShop === "function" ? api.forShop(shop) : api);
33
35
  /**
34
36
  * Runs one phase of an action, without checking where the request came from (handleAction does). `api` and
35
37
  * `shopify` stand in for the environment's clients (the test app's in-memory ones); `echo: false` keeps the logger's
@@ -45,9 +47,9 @@ export async function runAction(req, registry, o = {}) {
45
47
  const mod = await load();
46
48
  const record = req.record ? trackRecord({ ...req.record }, req.model) : null;
47
49
  const ctx = {
48
- params: req.params ?? {}, record, api: o.api ?? createClient(o.token ? { token: o.token } : {}), logger: collector(logs, o.echo ?? true),
50
+ params: req.params ?? {}, record, api: scopedApi(o.api ?? createClient(o.token ? { token: o.token } : {}), req.shop), logger: collector(logs, o.echo ?? true),
49
51
  model: req.model, action: req.action, environment: req.environment,
50
- shop: req.shop ?? null, shopify: req.shop ? (o.shopify?.(req.shop) ?? createShopifyClient(req.shop, o.token ? { token: o.token } : {})) : null,
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,
51
53
  };
52
54
  if (req.phase === "onSuccess") {
53
55
  await mod.onSuccess?.(ctx);
package/dist/test.d.ts CHANGED
@@ -11,6 +11,9 @@
11
11
  * as JSON, its writes are applied when `run` returns, then `onSuccess` runs with the saved record. Not covered:
12
12
  * permissions (actions run as the system), `timeoutMS`, webhook `filter`s (Shopify applies them), schedules' timing
13
13
  * and computed or relationship fields other than belongsTo.
14
+ *
15
+ * File fields keep their files in memory: `base64` reads back as a `data:` URL, `copyURL` as the URL itself (not
16
+ * fetched, size 0), and `upload`/`createUpload` tokens as the upload (a `createUpload` needs no PUT here).
14
17
  */
15
18
  import { ApiError, type ActionModule, type Api, type AppRecord, type AppSettings, type Job, type LogLine, type ModelSchema } from "./index.js";
16
19
  type Embed = (model: string, input: string[]) => Promise<number[][]>;
package/dist/test.js CHANGED
@@ -11,11 +11,14 @@
11
11
  * as JSON, its writes are applied when `run` returns, then `onSuccess` runs with the saved record. Not covered:
12
12
  * permissions (actions run as the system), `timeoutMS`, webhook `filter`s (Shopify applies them), schedules' timing
13
13
  * and computed or relationship fields other than belongsTo.
14
+ *
15
+ * File fields keep their files in memory: `base64` reads back as a `data:` URL, `copyURL` as the URL itself (not
16
+ * fetched, size 0), and `upload`/`createUpload` tokens as the upload (a `createUpload` needs no PUT here).
14
17
  */
15
18
  import { ApiError, ShopifyError } from "./index.js";
16
19
  import { runAction as runPhase } from "./runtime.js";
17
20
  /** Kept in `data`; the rest are a vector, the other side of a relationship, or worked out (computed). */
18
- const STORED = new Set(["string", "richText", "email", "url", "color", "number", "dateTime", "enum", "boolean", "roleList", "json", "belongsTo", "password", "encryptedString"]);
21
+ const STORED = new Set(["string", "richText", "email", "url", "color", "number", "dateTime", "enum", "boolean", "roleList", "json", "belongsTo", "password", "encryptedString", "file"]);
19
22
  const SYSTEM = ["id", "createdAt", "updatedAt"];
20
23
  const MAX_PAGE = 250;
21
24
  const MAX_RECORD_BYTES = 256 * 1024;
@@ -110,6 +113,8 @@ function convert(f, v, mode) {
110
113
  }
111
114
  case "password":
112
115
  return typeof v === "string" ? ok(v) : read ? ok(null) : bad("must be text");
116
+ case "file":
117
+ return read ? ok(isObj(v) && "url" in v ? v : null) : fileOf(v);
113
118
  case "vector": {
114
119
  if (!Array.isArray(v) || !v.length || !v.every((x) => typeof x === "number" && Number.isFinite(x)))
115
120
  return read ? ok(null) : bad("must be a list of numbers");
@@ -124,6 +129,50 @@ function convert(f, v, mode) {
124
129
  return read ? ok(null) : bad(`${f.type} fields can't be written yet`);
125
130
  }
126
131
  }
132
+ // ---- files (record-files.ts), in memory ----
133
+ /** Uploads by token: `upload`'s, and `createUpload`'s as if their PUT had happened. */
134
+ const UPLOADS = new Map();
135
+ let uploadSeq = 0;
136
+ const baseName = (name, fallback = "file") => (typeof name === "string" ? name.split(/[\\/]/).pop()?.trim() : "") || fallback;
137
+ const MIME = /^[\w.+-]+\/[\w.+-]+$/;
138
+ const mimeOf = (given) => (typeof given === "string" && MIME.test(given.trim()) ? given.trim().toLowerCase() : "application/octet-stream");
139
+ function fileOf(v) {
140
+ if (!isObj(v))
141
+ return bad("must be { base64, fileName }, { copyURL } or { directUploadToken }");
142
+ const given = ["base64", "copyURL", "directUploadToken"].filter((k) => v[k] !== undefined);
143
+ if (given.length !== 1)
144
+ return bad(typeof v.url === "string" && !given.length ? "a file is written as { copyURL }, { base64 } or { directUploadToken }, not as it reads" : "must have one of base64, copyURL or directUploadToken");
145
+ if (typeof v.directUploadToken === "string") {
146
+ const up = UPLOADS.get(v.directUploadToken);
147
+ return up ? ok({ ...up, ...(typeof v.fileName === "string" ? { fileName: baseName(v.fileName) } : {}) }) : bad("isn't an upload token for this environment");
148
+ }
149
+ if (typeof v.base64 === "string") {
150
+ const b64 = v.base64.replace(/^data:[^;,]*;base64,/, "").replace(/\s+/g, "");
151
+ if (!/^[A-Za-z0-9+/_-]*={0,2}$/.test(b64))
152
+ return bad("has base64 that isn't base64");
153
+ const mimeType = mimeOf(v.mimeType ?? /^data:([^;,]+)/.exec(v.base64)?.[1]);
154
+ return ok({ url: `data:${mimeType};base64,${b64}`, fileName: baseName(v.fileName), mimeType, size: Math.floor((b64.replace(/=+$/, "").length * 3) / 4) });
155
+ }
156
+ if (typeof v.copyURL === "string") {
157
+ let url;
158
+ try {
159
+ url = new URL(v.copyURL);
160
+ }
161
+ catch {
162
+ return bad("couldn't be copied: That is not a URL.");
163
+ }
164
+ if (url.protocol !== "https:")
165
+ return bad("couldn't be copied: Only https:// URLs are fetched.");
166
+ return ok({ url: url.toString(), fileName: baseName(v.fileName ?? decodeURIComponent(url.pathname.split("/").pop() ?? "")), mimeType: mimeOf(v.mimeType), size: 0 });
167
+ }
168
+ return bad("must have one of base64, copyURL or directUploadToken");
169
+ }
170
+ function fileFieldOf(m, field) {
171
+ const f = m.byName.get(field);
172
+ if (!f || f.type !== "file")
173
+ throw new ApiError(`${m.name} has no file field named ${field}`, 400, "invalid_request");
174
+ return f;
175
+ }
127
176
  function defaultOf(f) {
128
177
  if (f.def.default === undefined)
129
178
  return null;
@@ -201,7 +250,7 @@ class Records {
201
250
  const f = m.byName.get(name);
202
251
  if (!f)
203
252
  throw invalid([{ field: name, message: `${m.name} has no field named ${name}` }]);
204
- if (!STORED.has(f.type) || f.type === "password" || f.type === "encryptedString")
253
+ if (!STORED.has(f.type) || f.type === "password" || f.type === "encryptedString" || f.type === "file")
205
254
  throw invalid([{ field: name, message: `${f.type} fields can't be filtered or sorted on` }]);
206
255
  return { f };
207
256
  }
@@ -403,7 +452,7 @@ class Records {
403
452
  continue;
404
453
  }
405
454
  if (!STORED.has(f.type) && f.type !== "vector") {
406
- problems.push({ field: name, message: f.type === "file" ? "file fields can't be written yet" : `a ${f.type} field isn't stored on this record` });
455
+ problems.push({ field: name, message: `a ${f.type} field isn't stored on this record` });
407
456
  continue;
408
457
  }
409
458
  if (f.type === "vector" && Array.isArray(f.def.source) && f.def.source.length) {
@@ -552,7 +601,7 @@ const OPS = ["equals", "notEquals", "in", "notIn", "lessThan", "lessThanOrEqual"
552
601
  const embeddingModelOf = (f) => (typeof f.def.embeddingModel === "string" && f.def.embeddingModel ? f.def.embeddingModel : DEFAULT_EMBEDDING_MODEL);
553
602
  function sourceText(m, f, data) {
554
603
  const names = Array.isArray(f.def.source) ? f.def.source.map(String) : [];
555
- return names.map((n) => m.byName.get(n)).filter((s) => !!s && STORED.has(s.type) && s.type !== "password" && s.type !== "encryptedString")
604
+ return names.map((n) => m.byName.get(n)).filter((s) => !!s && STORED.has(s.type) && s.type !== "password" && s.type !== "encryptedString" && s.type !== "file")
556
605
  .map((s) => { const v = data[s.key]; return v === null || v === undefined ? "" : typeof v === "string" ? v : JSON.stringify(v); })
557
606
  .filter(Boolean).join("\n");
558
607
  }
@@ -761,28 +810,77 @@ export function createTestApp(o = {}) {
761
810
  const dot = action.indexOf(".");
762
811
  return dot < 0 ? { model: null, action } : { model: action.slice(0, dot), action: action.slice(dot + 1) };
763
812
  };
764
- const modelClient = (name) => ({
765
- findOne: async (id) => store.findOne(name, id),
766
- findMany: async (q = {}) => store.findMany(name, wire(q)),
767
- findFirst: async (q = {}) => (await store.findMany(name, { ...wire(q), first: 1 })).records[0] ?? null,
768
- search: async (field, near, q = {}) => (await store.findMany(name, { ...wire(q), search: { field, near } })),
769
- // As through the API: the model's create, update or delete action when it has one, else a direct write.
770
- create: async (values) => (registry[`${name}/create`] ? (await run(name, "create", { params: values })).record : store.create(name, wire(values))),
771
- update: async (id, values) => (registry[`${name}/update`] ? (await run(name, "update", { id, params: values })).record : store.update(name, id, wire(values))),
772
- delete: async (id) => { if (registry[`${name}/delete`])
773
- await run(name, "delete", { id });
774
- else
775
- store.delete(name, id); },
776
- checkPassword: async (id, password, field) => store.checkPassword(name, id, password, field),
777
- run: async (action, q = {}) => {
778
- const r = await run(name, action, q);
779
- return { record: r.record, ...(r.result !== undefined ? { result: r.result } : {}) };
780
- },
781
- });
782
- const clients = new Map();
783
- const $global = async (action, params = {}) => {
784
- const r = await run(null, action, { params });
785
- return r.result !== undefined ? { result: r.result } : {};
813
+ /** The field holding a record's store (access.ts storeField), or null when the model isn't store-owned. */
814
+ const storeFieldOf = (name) => {
815
+ const m = models.get(name);
816
+ if (!m)
817
+ return null;
818
+ if (name === "shopifyShop" && m.byName.has("myshopifyDomain"))
819
+ return "myshopifyDomain";
820
+ const synced = m.fields.find((f) => f.key === "sh_shop");
821
+ if (synced)
822
+ return synced.name;
823
+ const own = m.byName.get("shop");
824
+ return own && ["string", "email", "enum"].includes(own.type) ? "shop" : null;
825
+ };
826
+ const otherStore = (shop) => new ApiError(`This call is for ${shop}; it can't reach another store's records.`, 403, "policy_denied");
827
+ // As through the API, `shop` narrows store-owned models to that store's records (api.forShop, an action's api).
828
+ const modelClient = (name, shop) => {
829
+ const f = shop ? storeFieldOf(name) : null;
830
+ const narrow = (q) => (f ? { ...q, filter: q.filter ? { AND: [q.filter, { [f]: { equals: shop } }] } : { [f]: { equals: shop } } } : q);
831
+ const visible = (id) => { const r = store.findOne(name, id); return r && (!f || r[f] === shop) ? r : null; };
832
+ const reach = (id) => { if (!visible(id))
833
+ throw notFound(`There's no ${name} with id ${id}.`); };
834
+ const owned = (values, isNew) => {
835
+ if (!f)
836
+ return values;
837
+ if (f in values && values[f] !== shop)
838
+ throw otherStore(shop);
839
+ return isNew ? { ...values, [f]: shop } : values;
840
+ };
841
+ const runFor = (q) => {
842
+ if (shop && q.shop && q.shop !== shop)
843
+ throw otherStore(shop);
844
+ return shop ? { ...q, shop } : q;
845
+ };
846
+ return {
847
+ findOne: async (id) => visible(id),
848
+ findMany: async (q = {}) => store.findMany(name, narrow(wire(q))),
849
+ findFirst: async (q = {}) => (await store.findMany(name, { ...narrow(wire(q)), first: 1 })).records[0] ?? null,
850
+ search: async (field, near, q = {}) => (await store.findMany(name, { ...narrow(wire(q)), search: { field, near } })),
851
+ // As through the API: the model's create, update or delete action when it has one, else a direct write.
852
+ create: async (values) => { const v = owned(wire(values), true); return registry[`${name}/create`] ? (await run(name, "create", runFor({ params: v }))).record : store.create(name, v); },
853
+ update: async (id, values) => { reach(id); const v = owned(wire(values), false); return registry[`${name}/update`] ? (await run(name, "update", runFor({ id, params: v }))).record : store.update(name, id, v); },
854
+ delete: async (id) => { reach(id); if (registry[`${name}/delete`])
855
+ await run(name, "delete", runFor({ id }));
856
+ else
857
+ store.delete(name, id); },
858
+ checkPassword: async (id, password, field) => (visible(id) ? store.checkPassword(name, id, password, field) : false),
859
+ run: async (action, q = {}) => {
860
+ if (q.id)
861
+ reach(q.id);
862
+ const r = await run(name, action, runFor(q));
863
+ return { record: r.record, ...(r.result !== undefined ? { result: r.result } : {}) };
864
+ },
865
+ createUpload: async (field, q = {}) => {
866
+ fileFieldOf(store.model(name), field);
867
+ const token = `upload_${String(++uploadSeq).padStart(6, "0")}`, fileName = baseName(q.fileName);
868
+ const mimeType = q.mimeType === undefined ? null : mimeOf(q.mimeType);
869
+ UPLOADS.set(token, { url: `https://uploads.test/${token}/${encodeURIComponent(fileName)}`, fileName, mimeType: mimeType ?? "application/octet-stream", size: q.size ?? 0 });
870
+ return { url: `https://uploads.test/${token}`, method: "PUT", headers: mimeType ? { "content-type": mimeType } : {}, token, expiresAt: new Date((o.now ?? Date.now)() + 3_600_000).toISOString() };
871
+ },
872
+ upload: async (field, body, q = {}) => {
873
+ fileFieldOf(store.model(name), field);
874
+ const blob = body instanceof Blob ? body : new Blob([body]);
875
+ const bytes = new Uint8Array(await blob.arrayBuffer());
876
+ let bin = "";
877
+ for (const b of bytes)
878
+ bin += String.fromCharCode(b);
879
+ const mimeType = mimeOf(q.mimeType ?? blob.type), token = `upload_${String(++uploadSeq).padStart(6, "0")}`;
880
+ UPLOADS.set(token, { url: `data:${mimeType};base64,${btoa(bin)}`, fileName: baseName(q.fileName ?? (typeof File !== "undefined" && body instanceof File ? body.name : undefined)), mimeType, size: bytes.length });
881
+ return { directUploadToken: token };
882
+ },
883
+ };
786
884
  };
787
885
  const enqueue = async (action, params = {}, q = {}) => {
788
886
  const t = (o.now ?? Date.now)();
@@ -794,19 +892,43 @@ export function createTestApp(o = {}) {
794
892
  jobs.push(job);
795
893
  return wire(job);
796
894
  };
797
- const api = new Proxy({}, {
798
- get(_t, prop) {
799
- if (prop === "$global")
800
- return $global;
801
- if (prop === "enqueue")
802
- return enqueue;
803
- if (typeof prop !== "string" || prop === "then")
804
- return undefined;
805
- if (!clients.has(prop))
806
- clients.set(prop, modelClient(prop));
807
- return clients.get(prop);
808
- },
809
- });
895
+ const apis = new Map();
896
+ /** The API, for every store or one (`forShop`). Roles aren't applied here: `asRole` gives the same API. */
897
+ const apiFor = (shop) => {
898
+ const key = shop ?? "";
899
+ if (apis.has(key))
900
+ return apis.get(key);
901
+ const clients = new Map();
902
+ const $global = async (action, params = {}) => {
903
+ const r = await run(null, action, { params, ...(shop ? { shop } : {}) });
904
+ return r.result !== undefined ? { result: r.result } : {};
905
+ };
906
+ const queue = (action, params = {}, q = {}) => {
907
+ if (shop && q.shop && q.shop !== shop)
908
+ throw otherStore(shop);
909
+ return enqueue(action, params, shop ? { ...q, shop } : q);
910
+ };
911
+ const made = new Proxy({}, {
912
+ get(_t, prop) {
913
+ if (prop === "$global")
914
+ return $global;
915
+ if (prop === "enqueue")
916
+ return queue;
917
+ if (prop === "forShop")
918
+ return (s) => apiFor(s);
919
+ if (prop === "asRole")
920
+ return () => made;
921
+ if (typeof prop !== "string" || prop === "then")
922
+ return undefined;
923
+ if (!clients.has(prop))
924
+ clients.set(prop, modelClient(prop, shop));
925
+ return clients.get(prop);
926
+ },
927
+ });
928
+ apis.set(key, made);
929
+ return made;
930
+ };
931
+ const api = apiFor(null);
810
932
  // ---- Shopify's side ----
811
933
  const shopModel = () => models.get("shopifyShop");
812
934
  const shopRecord = async (shop) => (shopModel()?.byName.has("myshopifyDomain") ? (await store.findMany("shopifyShop", { filter: { myshopifyDomain: { equals: shop } }, first: 1 })).records[0] ?? null : null);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencebureau/apps-sdk",
3
- "version": "0.2.1",
3
+ "version": "0.3.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": [