@redeemid/emdash 0.0.8 → 0.0.10

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.
Files changed (41) hide show
  1. package/README.md +127 -2
  2. package/docs/shopify-setup.md +5 -1
  3. package/package.json +5 -1
  4. package/src/access.ts +9 -3
  5. package/src/admin-api.ts +191 -0
  6. package/src/blocks/ContributionBlock.astro +1 -1
  7. package/src/blocks/PlanBlock.astro +1 -1
  8. package/src/blocks/PreferencesBlock.astro +12 -0
  9. package/src/blocks/index.ts +2 -0
  10. package/src/blocks-names.ts +1 -0
  11. package/src/components/AccessBadge.astro +4 -3
  12. package/src/components/Account.astro +5 -4
  13. package/src/components/Cart.astro +4 -1
  14. package/src/components/CartView.astro +14 -13
  15. package/src/components/Collection.astro +2 -1
  16. package/src/components/Content.astro +10 -4
  17. package/src/components/Contribution.astro +4 -3
  18. package/src/components/Feature.astro +20 -0
  19. package/src/components/LockedPanel.astro +10 -8
  20. package/src/components/MemberCard.astro +22 -13
  21. package/src/components/Notices.astro +10 -2
  22. package/src/components/Plan.astro +3 -2
  23. package/src/components/Preferences.astro +102 -0
  24. package/src/components/Product.astro +6 -5
  25. package/src/config.ts +53 -0
  26. package/src/descriptor.ts +1 -0
  27. package/src/events.ts +75 -0
  28. package/src/features.ts +39 -0
  29. package/src/files.ts +191 -0
  30. package/src/guard.ts +43 -2
  31. package/src/index.ts +1 -0
  32. package/src/plugin.ts +142 -3
  33. package/src/preferences.ts +298 -0
  34. package/src/routes/callback.ts +8 -1
  35. package/src/routes/preferences.ts +82 -0
  36. package/src/routes/webhook.ts +5 -3
  37. package/src/staff.ts +220 -0
  38. package/src/storage.ts +3 -1
  39. package/src/text.ts +174 -0
  40. package/src/version.ts +1 -1
  41. package/src/webhooks.ts +11 -2
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Shopify customer accounts, member levels and paywalls for [EmDash](https://github.com/emdash-cms/emdash) sites. Shopify runs the store and the customer account; EmDash runs the content.
4
4
 
5
- **Status: 0.0.8, early.** Runs on Node and Cloudflare Workers. Sign-in, the member mirror, webhooks, levels, rules, the meter and drip, teasers, badges, the page gate, the Shopify cart and checkout are covered by an end-to-end test against a fake store.
5
+ **Status: 0.0.10, early.** Runs on Node and Cloudflare Workers. Sign-in, the member mirror, webhooks, levels, rules, the meter and drip, teasers, badges, the page gate, the Shopify cart and checkout, the staff tools, preferences, protected files, replacement text and outbound events are covered by an end-to-end test against a fake store.
6
6
 
7
7
  ## What it does
8
8
 
@@ -20,7 +20,12 @@ Shopify customer accounts, member levels and paywalls for [EmDash](https://githu
20
20
  - **The wall.** Readers kept out see why and what to do next: sign in, or join, with each level's own wall text. `<Notices>` shows the messages sign-in, Buy, Cart and Account send readers back with.
21
21
  - **Plan block.** Editors add a Shopify product to any page with the "Plan" block: title, price and a buy button.
22
22
  - **Shop.** `<Product>`, `<Collection>` and `<CartView>` (with the Product and Collection blocks) give the site product pages, collection grids and a cart page with quantities and discount codes. `<Contribution>` (and its block) takes pay-what-you-want amounts. Carts note the page each sale started on.
23
- - **In the admin.** RedeemID shows under Plugins with a Members page (Shopify customers, tags, levels), a Status page (secrets, store discovery, the URLs to give Shopify, levels and rules) and a dashboard widget.
23
+ - **Features.** Name perks members hold through levels or tags (ad-free, a supporter thank-you) and show them with `<Feature>` or `hasFeature()`.
24
+ - **In the admin.** RedeemID shows under Plugins with a Members page (Shopify customers, tags, levels; open a member to resync them or add and remove tags, which are written to Shopify), a bulk resync you start yourself, a Status page (secrets, store discovery, webhook subscriptions with a Register button, recent deliveries, levels and rules), an Access test and a dashboard widget.
25
+ - **Member preferences.** Members see and change customer fields you define in Shopify, such as topics or a newsletter choice, with `<Preferences>` or its block. Answers are saved on the Shopify customer, ready for Flow, segments and email; the site keeps no copy.
26
+ - **Protected files.** Put uploads in a media folder named in `files`, and every download checks the reader's levels, features or the entries that use the file. Copied links are no use to anyone else.
27
+ - **Replacement text.** Put any string members and visitors see in your own words, one string at a time, with `text`.
28
+ - **Outbound events.** Signed JSON POSTs to a URL of yours when a member signs in, their levels change, or they use the meter, for a CRM, an email tool or your own code.
24
29
  - **Keeps members out of EmDash's own APIs**, so the gate is the only way to read locked content.
25
30
 
26
31
  ## Install
@@ -76,6 +81,8 @@ Set these secrets in the environment (`.env` locally, `wrangler secret put` on W
76
81
  | `REDEEMID_SHOPIFY_CUSTOMER_ACCOUNT_CLIENT_ID` | Customer Account API | Client ID of the Headless storefront's Customer Account API client |
77
82
  | `REDEEMID_SHOPIFY_CUSTOMER_ACCOUNT_CLIENT_SECRET` | Customer Account API | Its client secret. Confidential clients only; leave unset for a public client. |
78
83
  | `REDEEMID_SHOPIFY_ADMIN_APP_CLIENT_SECRET` | Webhooks (Admin API app) | Client secret of the Shopify app that sends the webhooks. Shopify signs each webhook with it. |
84
+ | `REDEEMID_SHOPIFY_ADMIN_APP_CLIENT_ID` | Admin API (staff tools) | Client ID of that same app. Optional; with it, staff can resync members, edit tags in Shopify and register webhooks. |
85
+ | `REDEEMID_EVENTS_SECRET` | None | Optional. Signs outbound events; set it with `events.url`. |
79
86
  | `REDEEMID_SHOPIFY_STOREFRONT_PRIVATE_TOKEN` | Storefront API | Private access token, for the plan cards and checkout (server-side). |
80
87
  | `REDEEMID_SHOPIFY_STOREFRONT_PUBLIC_TOKEN` | Storefront API | Public access token. Only used when the private token isn't set. |
81
88
 
@@ -111,6 +118,124 @@ The meter lets a signed-in reader who can't read an entry open it anyway, `limit
111
118
 
112
119
  Drip holds a rule's entries back from members who pass it until they've held their level for `drip` days. A level starts when the customer first had its tag (for a `match: "all"` level, the last of its tags); with several levels the earliest counts, and with none known, the first sign-in. RedeemID notes when each tag first arrives from sign-in and webhooks, and forgets a tag when Shopify removes it. The wall shows the date the entry opens.
113
120
 
121
+ ### Features
122
+
123
+ ```ts
124
+ features: [
125
+ { slug: "ad-free", name: "Ad-free", levels: ["gold", "premium"] },
126
+ { slug: "supporter", name: "Supporter", tags: ["supporter"] },
127
+ ],
128
+ ```
129
+
130
+ A member holds a feature through any of its levels or tags; like levels, features come only from the mirrored tags. `<MemberCard>` lists them under the member's levels.
131
+
132
+ ```astro
133
+ ---
134
+ import Feature from "@redeemid/emdash/components/Feature.astro";
135
+ import { hasFeature } from "@redeemid/emdash/features";
136
+ ---
137
+ <Feature slug="supporter"><p>Thanks for your support.</p><p slot="else">Become a supporter.</p></Feature>
138
+ {!(await hasFeature(Astro, "ad-free")) && <aside class="ad">…</aside>}
139
+ ```
140
+
141
+ ### Preferences
142
+
143
+ ```ts
144
+ preferences: [
145
+ { key: "preferences.topics" }, // members can change it
146
+ { key: "preferences.level", access: "view" }, // members only see it
147
+ ],
148
+ ```
149
+
150
+ Define each field in Shopify (**Settings → Custom data → Customers**). The definition sets its name, type and limits, such as allowed choices or a minimum and maximum. List the ones members get in `preferences`, in the order to show them. Reading and saving use the Admin API app (`REDEEMID_SHOPIFY_ADMIN_APP_CLIENT_ID`, with `read_customers` and `write_customers`), always on the signed-in member's own customer. Fields in the `membership` namespace are never offered. Preferences never open content.
151
+
152
+ `<Preferences>` (or the Preferences block) is a form with a control for each field. It works without JavaScript and comes back with the `preferences_saved`, `preferences_refused` or `preferences_unavailable` notice. Visitors see its `signed-out` slot.
153
+
154
+ | Shopify type | Value |
155
+ | --- | --- |
156
+ | Single line text | A string; with choices, one of them |
157
+ | Multi-line text | A string |
158
+ | List of single line text | A list of strings; with choices, each one of them |
159
+ | True or false | `true` or `false` |
160
+ | Integer | A whole number |
161
+ | Decimal | A number, as a string |
162
+ | Date | `YYYY-MM-DD` |
163
+
164
+ Every value is checked against the definition before it goes to Shopify; one refusal saves nothing, and an empty value clears the field. Scripts can use `/_emdash/api/auth/redeemid/preferences` too: `GET` returns `{ fields }` with values, `POST` with JSON `{ values: { "namespace.key": value } }` saves. A refused save answers `400` with `fields` mapping each key to `unknown_field`, `read_only`, `invalid_type`, `invalid_choice`, `invalid_length` or `invalid_range`. Saves are limited to 10 a minute per member (`429`). From your own code, `readPreferences()` and `savePreferences()` in `@redeemid/emdash/preferences` do the same.
165
+
166
+ A save sends the `preferences.saved` event with the field names changed, never the answers.
167
+
168
+ ### Protected files
169
+
170
+ ```ts
171
+ files: [
172
+ { folder: "Gold downloads", levels: ["gold"] },
173
+ { folder: "Member downloads", levels: [] }, // any signed-in member
174
+ { folder: "Supporter extras", features: ["supporter"] },
175
+ { folder: "Story files", entries: true }, // whoever can read an entry that uses it
176
+ ],
177
+ ```
178
+
179
+ Upload files into a folder in the EmDash media library. Folder names match without regard to case. Every request for a file in a protected folder at `/_emdash/api/media/file/…` is checked before EmDash serves it:
180
+
181
+ - **Allowed:** the file, sent with `Cache-Control: private, no-store`.
182
+ - **Signed out:** a 401 page with a sign-in link that comes back to the file.
183
+ - **Signed in without access:** a 403 page.
184
+
185
+ A rule lets in members who hold any of its `levels` (an empty list means any signed-in member) or `features`. With `entries: true`, it also lets in whoever can read a published entry that uses the file: its rule, its drip, and the levels picked on its Paywall break or Members only parts. Staff can always download. Disabled members can't. If a file can't be checked, it isn't served.
186
+
187
+ Limits:
188
+
189
+ - Only EmDash's file route is checked. Don't give the storage bucket a public URL of its own.
190
+ - Image services that fetch the file without the reader's cookies, such as a CDN image resizer, get refused, so keep protected images out of resized `<Image>` output.
191
+ - Moving a file out of the folder makes it public again.
192
+
193
+ ### Replacement text
194
+
195
+ ```ts
196
+ text: {
197
+ "Sign in": "Log in",
198
+ "This is for members. {signIn} to read on.": "Members only. {signIn} to keep reading.",
199
+ "This is for {level} members.": "{level} members only.",
200
+ },
201
+ ```
202
+
203
+ Each key is a string's original English; its value is the new text. Only the strings you name change. There is no find-and-replace across strings, so replacing "Sign in" leaves "Sign in to download this file." alone: to change a word everywhere, replace each string that uses it. `STRINGS` in `@redeemid/emdash/text` lists every string, grouped by where it shows (account, badge, cart, wall, meter, member card, notices, plan, preferences, product, files).
204
+
205
+ Some strings have placeholders such as `{level}` or `{signIn}` (a link), filled in when the text shows. A replacement may use its original's placeholders, in any order or not at all, but no others. Text is plain: HTML in a replacement shows as typed. A replacement that uses another placeholder, or names a string RedeemID doesn't show, is ignored, so the original shows, and the Status page lists it with the reason.
206
+
207
+ Props win over `text`: a `label` or `title` you pass, or Notices `messages`, is used as given. Staff screens in the admin aren't covered.
208
+
209
+ ### Events
210
+
211
+ ```ts
212
+ events: { url: "https://hooks.example.com/redeemid", only: ["member.signed_in", "member.levels_changed"] },
213
+ ```
214
+
215
+ With `REDEEMID_EVENTS_SECRET` set, RedeemID POSTs `{ id, event, at, data }` to the URL. Headers: `X-RedeemID-Event`, `X-RedeemID-Delivery` (the `id`) and `X-RedeemID-Signature: sha256=<hex HMAC-SHA256 of the raw body with the secret>`. Check the signature before you trust a body. Sending waits at most 3 seconds and never breaks the page; a failed send is logged and dropped, not retried.
216
+
217
+ | Event | `data` |
218
+ | --- | --- |
219
+ | `member.signed_in` | `customerId`, `levels`, `first` (first sign-in), `refresh` |
220
+ | `member.levels_changed` | `customerId`, `levels`, `added`, `removed`, `source` (`sign-in`, the webhook topic, or a staff resync or tag edit) |
221
+ | `meter.used` | `userId` (EmDash), `entry` (`collection:id`), `used`, `limit`, `period` (`2026-11`, or `2026-W45` by week) |
222
+ | `meter.exhausted` | the same, sent with the last free read |
223
+ | `preferences.saved` | `customerId`, `fields` (the `namespace.key` names changed) |
224
+
225
+ No event carries an email address or a name: match people by the Shopify `customerId`. `only` limits which events are sent; leave it out for all of them.
226
+
227
+ ### Staff tools
228
+
229
+ With `REDEEMID_SHOPIFY_ADMIN_APP_CLIENT_ID` set (it also runs member preferences), RedeemID gets an Admin API token for the webhook app with the client credentials grant (the app must belong to the same Shopify organization as the store, as Dev Dashboard apps do) and needs the `read_customers` and `write_customers` scopes. Then, in the admin:
230
+
231
+ - **Member detail.** Open a member from the Members page to see their levels, tags and features, resync them from Shopify, or add and remove tags. Tag edits are made in Shopify, then read back; nothing is granted on the EmDash side.
232
+ - **Bulk resync.** Reads the 50 members synced longest ago from Shopify in one request. Run it again for the next 50. It never runs on its own.
233
+ - **Webhooks.** The Status page lists the store's subscriptions to this site and registers any that are missing (`customers/redact` stays in the app's own settings).
234
+ - **Recent deliveries.** The last webhooks the site took, with their topics and times.
235
+ - **Access test.** Enter a collection, terms and a reader's tags to see what the entry needs and whether that reader gets in.
236
+
237
+ Resync updates email, name and tags. Status stays with the enable and disable webhooks.
238
+
114
239
  ## Use it in templates
115
240
 
116
241
  EmDash has no content filter hook, so templates decide what to render. Render the entry body with `<Content>` instead of `<PortableText>`:
@@ -29,6 +29,8 @@ RedeemID keeps tags and status current from webhooks. Point these topics at `htt
29
29
 
30
30
  Subscribe them from a Shopify app on the store (for example a Dev Dashboard app). If the app already sends webhooks to another site, add this URL as extra subscriptions. `customers/merge` needs the `read_customer_merge` scope. Shopify signs every webhook with that app's **client secret**, which is the site's webhook secret.
31
31
 
32
+ For the staff tools (member resync, tag edits written to Shopify, the Register webhooks button) and member preferences, give the same app the `read_customers` and `write_customers` Admin API scopes and set its **client ID** as well. RedeemID uses the client credentials grant, which works when the app and the store are in the same Shopify organization.
33
+
32
34
  ## 3. The site
33
35
 
34
36
  Add the package and config as in the [README](../README.md#install), with `shop` set to the store's domain. A custom customer-account domain works as well as `*.myshopify.com`.
@@ -40,6 +42,8 @@ npx wrangler secret put REDEEMID_SHOPIFY_STORE_DOMAIN # e.g. m
40
42
  npx wrangler secret put REDEEMID_SHOPIFY_CUSTOMER_ACCOUNT_CLIENT_ID # Customer Account API client ID
41
43
  npx wrangler secret put REDEEMID_SHOPIFY_CUSTOMER_ACCOUNT_CLIENT_SECRET # confidential clients only
42
44
  npx wrangler secret put REDEEMID_SHOPIFY_ADMIN_APP_CLIENT_SECRET # the webhook app's client secret
45
+ npx wrangler secret put REDEEMID_SHOPIFY_ADMIN_APP_CLIENT_ID # optional; the webhook app's client ID, for the staff tools
46
+ npx wrangler secret put REDEEMID_EVENTS_SECRET # optional; signs outbound events (events.url)
43
47
  npx wrangler secret put REDEEMID_SHOPIFY_STOREFRONT_PRIVATE_TOKEN # Headless storefront's Storefront API private token (plans, checkout)
44
48
  npx wrangler secret put REDEEMID_SHOPIFY_STOREFRONT_PUBLIC_TOKEN # optional; used only without the private token
45
49
  ```
@@ -53,4 +57,4 @@ The Workers free plan is enough: RedeemID is a native plugin and doesn't need sa
53
57
  3. Click **Sign in**, sign in with that customer's email, and you come back to the post, unlocked.
54
58
  4. Add or remove the tag in Shopify; the post opens or locks again once the webhook arrives.
55
59
 
56
- If sign-in sends you back with `?redeemid_notice=…`, the code says why: `not_configured` (secrets or `shop` missing), `sign_in_unavailable` (store discovery failed), `sign_in_expired`, `staff_account`, `site_not_ready`, `email_required`, `token_failed`, `bad_id_token`, `identity_failed`. A Buy button can return `plan_unavailable` (no such product, or sold out) or `checkout_failed`. The Cart link returns `cart_empty` when there's nothing in the cart, and Account returns `account_unavailable` when store discovery fails. Cart changes return `cart_added`, `cart_updated`, `discount_applied` or `discount_not_applicable`. Refresh membership returns `refreshed` once it has read the member's tags again.
60
+ If sign-in sends you back with `?redeemid_notice=…`, the code says why: `not_configured` (secrets or `shop` missing), `sign_in_unavailable` (store discovery failed), `sign_in_expired`, `staff_account`, `site_not_ready`, `email_required`, `token_failed`, `bad_id_token`, `identity_failed`. A Buy button can return `plan_unavailable` (no such product, or sold out) or `checkout_failed`. The Cart link returns `cart_empty` when there's nothing in the cart, and Account returns `account_unavailable` when store discovery fails. Cart changes return `cart_added`, `cart_updated`, `discount_applied` or `discount_not_applicable`. Refresh membership returns `refreshed` once it has read the member's tags again. Preferences return `preferences_saved`, `preferences_refused` or `preferences_unavailable`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@redeemid/emdash",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "description": "Shopify customer accounts, member levels and paywalls for EmDash sites. Shopify runs commerce; EmDash runs content.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -15,6 +15,10 @@
15
15
  "./access": "./src/access.ts",
16
16
  "./guard.ts": "./src/guard.ts",
17
17
  "./storefront": "./src/storefront.ts",
18
+ "./features": "./src/features.ts",
19
+ "./events": "./src/events.ts",
20
+ "./preferences": "./src/preferences.ts",
21
+ "./text": "./src/text.ts",
18
22
  "./plugin": "./src/plugin.ts",
19
23
  "./blocks": "./src/blocks/index.ts",
20
24
  "./components/*": "./src/components/*",
package/src/access.ts CHANGED
@@ -277,11 +277,11 @@ export function passes(held: string[], required: string[][]): boolean {
277
277
  * The requirement in words, for badges and admin pages: "Gold + Silver",
278
278
  * "Silver or Gold", "Signed in". `null` gives `open`.
279
279
  */
280
- export function describe(required: Requirement, levels: LevelConfig[] = [], open = "Free"): string {
280
+ export function describe(required: Requirement, levels: LevelConfig[] = [], open = "Free", signedIn = "Signed in"): string {
281
281
  if (required === null) return open;
282
282
  const name = (slug: string) => levels.find((l) => l.slug === slug)?.name ?? slug;
283
283
  const parts = reduce(required).filter((c) => c.length > 0).map((c) => c.map(name).join(" or "));
284
- return parts.length ? parts.join(" + ") : "Signed in";
284
+ return parts.length ? parts.join(" + ") : signedIn;
285
285
  }
286
286
 
287
287
  /**
@@ -469,7 +469,13 @@ export async function readEntry(
469
469
  const used = consume(record.items, `${entry.collection}:${entry.id}`, meter.limit);
470
470
  const info = { limit: meter.limit, period };
471
471
  if (!used.allowed) return { ...verdict, meterLeft: 0, meter: info };
472
- if (used.items !== record.items) await s.meter.put(key, { ...record, items: used.items });
472
+ if (used.items !== record.items) {
473
+ await s.meter.put(key, { ...record, items: used.items });
474
+ const { emit } = await import("./events.js");
475
+ const data = { userId: user.id, entry: `${entry.collection}:${entry.id}`, used: used.items.length, limit: meter.limit, period: record.period };
476
+ await emit(config, "meter.used", data);
477
+ if (used.left === 0) await emit(config, "meter.exhausted", data);
478
+ }
473
479
  return { ...verdict, allowed: true, reason: "metered", meterLeft: used.left, meter: info };
474
480
  } catch {
475
481
  return verdict;
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Shopify Admin API, for staff tools only: resync a member, write tags to
3
+ * Shopify, register webhooks. The token comes from the client credentials
4
+ * grant of the Shopify app whose webhooks the site receives
5
+ * (REDEEMID_SHOPIFY_ADMIN_APP_CLIENT_ID + _CLIENT_SECRET). Tokens last about
6
+ * a day; this keeps one per store in memory until shortly before expiry.
7
+ *
8
+ * Nothing here grants access: tag edits go to Shopify, and the mirror only
9
+ * changes from what Shopify answers.
10
+ */
11
+
12
+ import { env, ENV, shopOrigin, type RedeemIDConfig } from "./config.js";
13
+ import { USER_AGENT } from "./shopify.js";
14
+ import { cleanTags, emptyMember, stampTags, type MemberRecord, type Stores } from "./storage.js";
15
+
16
+ export const ADMIN_API_VERSION = "2026-10";
17
+
18
+ /** Webhook topics RedeemID needs, as the Admin API names them. customers/redact is set in the app's config, not here. */
19
+ export const WEBHOOK_TOPICS = [
20
+ "CUSTOMERS_CREATE",
21
+ "CUSTOMERS_UPDATE",
22
+ "CUSTOMERS_DELETE",
23
+ "CUSTOMERS_DISABLE",
24
+ "CUSTOMERS_ENABLE",
25
+ "CUSTOMERS_MERGE",
26
+ "CUSTOMER_TAGS_ADDED",
27
+ "CUSTOMER_TAGS_REMOVED",
28
+ ] as const;
29
+
30
+ const MARGIN_MS = 5 * 60 * 1000;
31
+ const tokens = new Map<string, { token: string; until: number; scope: string }>();
32
+
33
+ export function adminConfigured(): boolean {
34
+ return Boolean(env(ENV.adminClientId) && env(ENV.webhookSecret));
35
+ }
36
+
37
+ export function resetAdminToken(): void {
38
+ tokens.clear();
39
+ }
40
+
41
+ export class AdminError extends Error {}
42
+
43
+ async function token(config: RedeemIDConfig, fetcher: typeof fetch): Promise<{ token: string; scope: string }> {
44
+ const origin = shopOrigin(config);
45
+ const hit = tokens.get(origin);
46
+ if (hit && hit.until > Date.now()) return hit;
47
+ const clientId = env(ENV.adminClientId);
48
+ const secret = env(ENV.webhookSecret);
49
+ if (!clientId || !secret) throw new AdminError(`Set ${ENV.adminClientId} and ${ENV.webhookSecret} to use the staff tools.`);
50
+ const res = await fetcher(`${origin}/admin/oauth/access_token`, {
51
+ method: "POST",
52
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json", "User-Agent": USER_AGENT },
53
+ body: new URLSearchParams({ grant_type: "client_credentials", client_id: clientId, client_secret: secret }).toString(),
54
+ });
55
+ const body = (await res.json().catch(() => ({}))) as { access_token?: string; expires_in?: number; scope?: string; error?: string };
56
+ if (!res.ok || !body.access_token) {
57
+ // shop_not_permitted: the app and the store are not in the same Shopify organization.
58
+ throw new AdminError(`Shopify refused the Admin API token (${body.error ?? res.status}).`);
59
+ }
60
+ const life = (body.expires_in && body.expires_in > 0 ? body.expires_in : 3600) * 1000;
61
+ const value = { token: body.access_token, until: Date.now() + Math.max(60_000, life - MARGIN_MS), scope: body.scope ?? "" };
62
+ tokens.set(origin, value);
63
+ return value;
64
+ }
65
+
66
+ /** The scopes the Admin API token carries, or an error message. */
67
+ export async function adminScopes(config: RedeemIDConfig, fetcher: typeof fetch = fetch): Promise<string> {
68
+ return (await token(config, fetcher)).scope;
69
+ }
70
+
71
+ export async function admin<T>(config: RedeemIDConfig, query: string, variables: Record<string, unknown> = {}, fetcher: typeof fetch = fetch, retry = true): Promise<T> {
72
+ const t = await token(config, fetcher);
73
+ const res = await fetcher(`${shopOrigin(config)}/admin/api/${ADMIN_API_VERSION}/graphql.json`, {
74
+ method: "POST",
75
+ headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": USER_AGENT, "X-Shopify-Access-Token": t.token },
76
+ body: JSON.stringify({ query, variables }),
77
+ });
78
+ if (res.status === 401 && retry) {
79
+ tokens.delete(shopOrigin(config));
80
+ return admin(config, query, variables, fetcher, false);
81
+ }
82
+ const body = (await res.json().catch(() => ({}))) as { data?: T; errors?: Array<{ message?: string }> };
83
+ if (!res.ok || !body.data) throw new AdminError(body.errors?.[0]?.message ?? `Admin API request failed (${res.status}).`);
84
+ return body.data;
85
+ }
86
+
87
+ const gid = (id: string) => `gid://shopify/Customer/${id}`;
88
+
89
+ export interface AdminCustomer {
90
+ customerId: string;
91
+ email: string | null;
92
+ firstName: string | null;
93
+ lastName: string | null;
94
+ tags: string[];
95
+ updatedAt: number | null;
96
+ }
97
+
98
+ /** Up to 100 customers by numeric id. Customers Shopify no longer has are left out. */
99
+ export async function customers(config: RedeemIDConfig, ids: string[], fetcher: typeof fetch = fetch): Promise<AdminCustomer[]> {
100
+ if (ids.length === 0) return [];
101
+ type Node = { id: string; firstName: string | null; lastName: string | null; tags: string[]; updatedAt: string; defaultEmailAddress: { emailAddress: string | null } | null } | null;
102
+ const data = await admin<{ nodes: Node[] }>(
103
+ config,
104
+ `query RedeemIDCustomers($ids: [ID!]!) { nodes(ids: $ids) { ... on Customer { id firstName lastName tags updatedAt defaultEmailAddress { emailAddress } } } }`,
105
+ { ids: ids.slice(0, 100).map(gid) },
106
+ fetcher,
107
+ );
108
+ return data.nodes
109
+ .filter((n): n is NonNullable<Node> => Boolean(n?.id))
110
+ .map((n) => ({
111
+ customerId: n.id.replace(/^gid:\/\/shopify\/Customer\//, ""),
112
+ email: n.defaultEmailAddress?.emailAddress?.toLowerCase() ?? null,
113
+ firstName: n.firstName || null,
114
+ lastName: n.lastName || null,
115
+ tags: cleanTags(n.tags),
116
+ updatedAt: Number.isFinite(Date.parse(n.updatedAt)) ? Date.parse(n.updatedAt) : null,
117
+ }));
118
+ }
119
+
120
+ /**
121
+ * Read members from Shopify again and update the mirror: profile and tags.
122
+ * Status stays with the enable/disable webhooks. Members Shopify no longer
123
+ * has are reported in `missing` and left alone.
124
+ */
125
+ export async function resync(config: RedeemIDConfig, s: Stores, ids: string[], source = "resync", fetcher: typeof fetch = fetch): Promise<{ updated: MemberRecord[]; missing: string[] }> {
126
+ const found = await customers(config, ids, fetcher);
127
+ const updated: MemberRecord[] = [];
128
+ for (const c of found) {
129
+ const m = (await s.members.get(c.customerId)) ?? emptyMember(c.customerId);
130
+ m.email = c.email ?? m.email;
131
+ m.firstName = c.firstName ?? m.firstName;
132
+ m.lastName = c.lastName ?? m.lastName;
133
+ m.tags = c.tags;
134
+ m.profileUpdatedAt = c.updatedAt ?? m.profileUpdatedAt;
135
+ m.syncedAt = new Date().toISOString();
136
+ m.source = source;
137
+ await s.members.put(c.customerId, stampTags(m));
138
+ updated.push(m);
139
+ }
140
+ const seen = new Set(found.map((c) => c.customerId));
141
+ return { updated, missing: ids.filter((id) => !seen.has(id)) };
142
+ }
143
+
144
+ /** Add or remove tags on the Shopify customer. Shopify then sends the tag webhook; callers resync to show it now. */
145
+ export async function editTags(config: RedeemIDConfig, customerId: string, change: "add" | "remove", tags: string[], fetcher: typeof fetch = fetch): Promise<void> {
146
+ const clean = cleanTags(tags);
147
+ if (clean.length === 0) return;
148
+ const m = change === "add" ? "tagsAdd" : "tagsRemove";
149
+ const data = await admin<Record<string, { userErrors: Array<{ message: string }> }>>(
150
+ config,
151
+ `mutation RedeemIDTags($id: ID!, $tags: [String!]!) { ${m}(id: $id, tags: $tags) { userErrors { field message } } }`,
152
+ { id: gid(customerId), tags: clean },
153
+ fetcher,
154
+ );
155
+ const err = data[m]?.userErrors[0];
156
+ if (err) throw new AdminError(err.message);
157
+ }
158
+
159
+ export interface Subscription {
160
+ id: string;
161
+ topic: string;
162
+ uri: string;
163
+ }
164
+
165
+ export async function webhookSubscriptions(config: RedeemIDConfig, fetcher: typeof fetch = fetch): Promise<Subscription[]> {
166
+ type Node = { id: string; topic: string; uri?: string | null };
167
+ const data = await admin<{ webhookSubscriptions: { nodes: Node[] } }>(
168
+ config,
169
+ `query RedeemIDWebhooks { webhookSubscriptions(first: 100) { nodes { id topic uri } } }`,
170
+ {},
171
+ fetcher,
172
+ );
173
+ return data.webhookSubscriptions.nodes.map((n) => ({ id: n.id, topic: n.topic, uri: n.uri ?? "" }));
174
+ }
175
+
176
+ /** Register the topics RedeemID needs that no subscription sends to `uri` yet. Returns the topics it added. */
177
+ export async function registerWebhooks(config: RedeemIDConfig, uri: string, fetcher: typeof fetch = fetch): Promise<string[]> {
178
+ const have = await webhookSubscriptions(config, fetcher);
179
+ const missing = WEBHOOK_TOPICS.filter((t) => !have.some((h) => h.topic === t && h.uri === uri));
180
+ for (const topic of missing) {
181
+ const data = await admin<{ webhookSubscriptionCreate: { userErrors: Array<{ message: string }> } }>(
182
+ config,
183
+ `mutation RedeemIDWebhook($topic: WebhookSubscriptionTopic!, $uri: String!) { webhookSubscriptionCreate(topic: $topic, webhookSubscription: { uri: $uri, format: JSON }) { userErrors { field message } } }`,
184
+ { topic, uri },
185
+ fetcher,
186
+ );
187
+ const err = data.webhookSubscriptionCreate.userErrors[0];
188
+ if (err) throw new AdminError(`${topic}: ${err.message}`);
189
+ }
190
+ return [...missing];
191
+ }
@@ -18,7 +18,7 @@ const amounts = (node.amounts ?? "")
18
18
  <Contribution
19
19
  handle={handle}
20
20
  title={node.title?.trim() || undefined}
21
- label={node.label?.trim() || "Give"}
21
+ label={node.label?.trim() || undefined}
22
22
  amounts={amounts.length ? amounts : undefined}
23
23
  />
24
24
  )}
@@ -10,4 +10,4 @@ const { node } = Astro.props;
10
10
  const handle = (node.handle ?? "").trim();
11
11
  ---
12
12
 
13
- {handle && <Plan handle={handle} title={node.title?.trim() || undefined} label={node.label?.trim() || "Join"} levels={Array.isArray(node.levels) ? node.levels : []} />}
13
+ {handle && <Plan handle={handle} title={node.title?.trim() || undefined} label={node.label?.trim() || undefined} levels={Array.isArray(node.levels) ? node.levels : []} />}
@@ -0,0 +1,12 @@
1
+ ---
2
+ /** The "Preferences" block: the signed-in member's preferences form. */
3
+ import Preferences from "../components/Preferences.astro";
4
+
5
+ interface Props {
6
+ node: { title?: string; label?: string };
7
+ }
8
+
9
+ const { node } = Astro.props;
10
+ ---
11
+
12
+ <Preferences title={node.title?.trim() || undefined} label={node.label?.trim() || undefined} />
@@ -6,6 +6,7 @@ import Marker from "./PaywallBreak.astro";
6
6
  import CollectionBlock from "./CollectionBlock.astro";
7
7
  import ContributionBlock from "./ContributionBlock.astro";
8
8
  import PlanBlock from "./PlanBlock.astro";
9
+ import PreferencesBlock from "./PreferencesBlock.astro";
9
10
  import ProductBlock from "./ProductBlock.astro";
10
11
 
11
12
  export const blockComponents = {
@@ -16,4 +17,5 @@ export const blockComponents = {
16
17
  "redeemid-product": ProductBlock,
17
18
  "redeemid-collection": CollectionBlock,
18
19
  "redeemid-contribution": ContributionBlock,
20
+ "redeemid-preferences": PreferencesBlock,
19
21
  };
@@ -4,6 +4,7 @@ export const PLAN_BLOCK = "redeemid-plan";
4
4
  export const PRODUCT_BLOCK = "redeemid-product";
5
5
  export const COLLECTION_BLOCK = "redeemid-collection";
6
6
  export const CONTRIBUTION_BLOCK = "redeemid-contribution";
7
+ export const PREFERENCES_BLOCK = "redeemid-preferences";
7
8
  /** Starts a members-only part of the body; it runs to the next end block. */
8
9
  export const MEMBERS_BLOCK = "redeemid-members";
9
10
  export const MEMBERS_END_BLOCK = "redeemid-members-end";
@@ -12,6 +12,7 @@
12
12
  import { canRead, describe, entryRequirement, type Terms } from "../access.js";
13
13
  import { splitAtPaywall } from "../blocks-names.js";
14
14
  import { siteConfig } from "../site-config.js";
15
+ import { text } from "../text.js";
15
16
 
16
17
  interface Props {
17
18
  collection: string;
@@ -22,13 +23,13 @@ interface Props {
22
23
  class?: string;
23
24
  }
24
25
 
25
- const { collection, terms, content, free = "Free", class: className } = Astro.props;
26
26
  const config = siteConfig((Astro.locals as { emdash?: { config?: unknown } }).emdash?.config);
27
+ const { collection, terms, content, free = text(config, "Free"), class: className } = Astro.props;
27
28
  const split = splitAtPaywall(content);
28
29
  const required = split.paywall && split.levels.length
29
30
  ? [split.levels]
30
31
  : await entryRequirement(config, collection, terms);
31
- const label = describe(required, config?.levels, free);
32
+ const label = describe(required, config?.levels, free, text(config, "Signed in"));
32
33
  const locked = required !== null && !(await canRead(Astro, { collection, terms }, { required })).allowed;
33
34
  const slugs = required?.flat().join(" ") || (required ? "signed-in" : "free");
34
35
  ---
@@ -40,6 +41,6 @@ const slugs = required?.flat().join(" ") || (required ? "signed-in" : "free");
40
41
  >
41
42
  {locked && <span class="redeemid-badge__lock" aria-hidden="true">🔒&#xFE0E; </span>}
42
43
  {label}
43
- {locked && <span style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap"> (locked)</span>}
44
+ {locked && <span style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap">{text(config, " (locked)")}</span>}
44
45
  </span>
45
46
  )}
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { siteConfig } from "../site-config.js";
6
6
  import { accountUrl, signInUrl, signOutUrl, viewer } from "../access.js";
7
+ import { text } from "../text.js";
7
8
 
8
9
  const v = await viewer(Astro);
9
10
  const config = siteConfig((Astro.locals as { emdash?: { config?: unknown } }).emdash?.config);
@@ -14,14 +15,14 @@ const names = (config?.levels ?? []).filter((l) => v.levels.includes(l.slug)).ma
14
15
  <div class="redeemid-account" data-redeemid-signed-in={v.signedIn ? "true" : "false"}>
15
16
  {v.signedIn ? (
16
17
  <>
17
- <span class="redeemid-account__who">{v.member?.firstName ?? v.member?.email ?? "Signed in"}</span>
18
+ <span class="redeemid-account__who">{v.member?.firstName ?? v.member?.email ?? text(config, "Signed in")}</span>
18
19
  {names.length > 0 && <span class="redeemid-account__levels">{names.join(", ")}</span>}
19
- <a class="redeemid-account__link" href={accountUrl(here)}>Account</a>
20
+ <a class="redeemid-account__link" href={accountUrl(here)}>{text(config, "Account")}</a>
20
21
  <form method="post" action={signOutUrl(here)}>
21
- <button type="submit">Sign out</button>
22
+ <button type="submit">{text(config, "Sign out")}</button>
22
23
  </form>
23
24
  </>
24
25
  ) : (
25
- <a href={signInUrl(here)}>{config?.label ?? "Sign in"}</a>
26
+ <a href={signInUrl(here)}>{config?.label ?? text(config, "Sign in")}</a>
26
27
  )}
27
28
  </div>
@@ -5,12 +5,15 @@
5
5
  */
6
6
  import { cartUrl } from "../access.js";
7
7
  import { readCart } from "../cart.js";
8
+ import { siteConfig } from "../site-config.js";
9
+ import { text } from "../text.js";
8
10
 
9
11
  interface Props {
10
12
  label?: string;
11
13
  }
12
14
 
13
- const { label = "Cart" } = Astro.props;
15
+ const config = siteConfig((Astro.locals as { emdash?: { config?: unknown } }).emdash?.config);
16
+ const { label = text(config, "Cart") } = Astro.props;
14
17
  const ref = await readCart(Astro.session);
15
18
  const count = ref?.count ?? 0;
16
19
  const here = Astro.url.pathname + Astro.url.search;
@@ -11,6 +11,7 @@ import { cartUrl } from "../access.js";
11
11
  import { readCart, saveCart } from "../cart.js";
12
12
  import { siteConfig } from "../site-config.js";
13
13
  import { cartDetails, money, type CartDetails } from "../storefront.js";
14
+ import { text } from "../text.js";
14
15
 
15
16
  interface Props {
16
17
  /** Link for each line's product; `{handle}` is replaced. */
@@ -19,8 +20,8 @@ interface Props {
19
20
  empty?: string;
20
21
  }
21
22
 
22
- const { productHref, empty = "Your cart is empty." } = Astro.props;
23
23
  const config = siteConfig((Astro.locals as { emdash?: { config?: unknown } }).emdash?.config);
24
+ const { productHref, empty = text(config, "Your cart is empty.") } = Astro.props;
24
25
  const ref = await readCart(Astro.session);
25
26
  let cart: CartDetails | null = null;
26
27
  let failed = false;
@@ -43,7 +44,7 @@ const code = cart?.discountCodes[0];
43
44
 
44
45
  <section class="redeemid-cartview" data-redeemid-cart-count={cart?.totalQuantity ?? 0}>
45
46
  {failed ? (
46
- <p>Your cart isn't available right now. Try again in a few minutes.</p>
47
+ <p>{text(config, "Your cart isn't available right now. Try again in a few minutes.")}</p>
47
48
  ) : !cart || cart.lines.length === 0 ? (
48
49
  <p class="redeemid-cartview__empty">{empty}</p>
49
50
  ) : (
@@ -57,20 +58,20 @@ const code = cart?.discountCodes[0];
57
58
  {href(l.productHandle) ? <a href={href(l.productHandle)}>{l.productTitle}</a> : l.productTitle}
58
59
  {l.variantTitle && l.variantTitle !== "Default Title" && <span> · {l.variantTitle}</span>}
59
60
  </p>
60
- <p class="redeemid-cartview__price">{money(l.price)} each · {money(l.total)}</p>
61
+ <p class="redeemid-cartview__price">{text(config, "{price} each · {total}", { price: money(l.price), total: money(l.total) })}</p>
61
62
  <form method="post" action={action} class="redeemid-cartview__quantity">
62
63
  <input type="hidden" name="action" value="update" />
63
64
  <input type="hidden" name="line" value={l.id} />
64
65
  <input type="hidden" name="return" value={here} />
65
- <label for={`q-${l.id}`}>Quantity</label>
66
+ <label for={`q-${l.id}`}>{text(config, "Quantity")}</label>
66
67
  <input id={`q-${l.id}`} name="quantity" type="number" min="0" max="1000" value={l.quantity} inputmode="numeric" />
67
- <button type="submit">Update</button>
68
+ <button type="submit">{text(config, "Update")}</button>
68
69
  </form>
69
70
  <form method="post" action={action}>
70
71
  <input type="hidden" name="action" value="remove" />
71
72
  <input type="hidden" name="line" value={l.id} />
72
73
  <input type="hidden" name="return" value={here} />
73
- <button type="submit" class="redeemid-cartview__remove">Remove<span style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap"> {l.productTitle}</span></button>
74
+ <button type="submit" class="redeemid-cartview__remove">{text(config, "Remove")}<span style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap"> {l.productTitle}</span></button>
74
75
  </form>
75
76
  </div>
76
77
  </li>
@@ -79,19 +80,19 @@ const code = cart?.discountCodes[0];
79
80
  <form method="post" action={action} class="redeemid-cartview__discount">
80
81
  <input type="hidden" name="action" value="discount" />
81
82
  <input type="hidden" name="return" value={here} />
82
- <label for="redeemid-discount">Discount code</label>
83
+ <label for="redeemid-discount">{text(config, "Discount code")}</label>
83
84
  <input id="redeemid-discount" name="code" type="text" value={code?.code ?? ""} autocomplete="off" />
84
- <button type="submit">Apply</button>
85
- {code && !code.applicable && <p class="redeemid-cartview__code-note">{code.code} doesn't apply to this cart.</p>}
85
+ <button type="submit">{text(config, "Apply")}</button>
86
+ {code && !code.applicable && <p class="redeemid-cartview__code-note">{text(config, "{code} doesn't apply to this cart.", { code: code.code })}</p>}
86
87
  </form>
87
88
  <dl class="redeemid-cartview__totals">
88
- <dt>Subtotal</dt>
89
+ <dt>{text(config, "Subtotal")}</dt>
89
90
  <dd>{money(cart.subtotal)}</dd>
90
- <dt>Total</dt>
91
+ <dt>{text(config, "Total")}</dt>
91
92
  <dd>{money(cart.total)}</dd>
92
93
  </dl>
93
- <p class="redeemid-cartview__note">Taxes and shipping are worked out at checkout.</p>
94
- <a class="redeemid-cartview__checkout" href={cartUrl(here)}>Checkout</a>
94
+ <p class="redeemid-cartview__note">{text(config, "Taxes and shipping are worked out at checkout.")}</p>
95
+ <a class="redeemid-cartview__checkout" href={cartUrl(here)}>{text(config, "Checkout")}</a>
95
96
  </>
96
97
  )}
97
98
  </section>