@redeemid/emdash 0.0.3 → 0.0.4

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
@@ -2,17 +2,18 @@
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.3, early.** Runs on Node and Cloudflare Workers. Sign-in, the member mirror, webhooks, levels, rules, the page gate, the Shopify cart and checkout are covered by an end-to-end test against a fake store.
5
+ **Status: 0.0.4, early.** Runs on Node and Cloudflare Workers. Sign-in, the member mirror, webhooks, levels, rules, teasers, badges, the page gate, the Shopify cart and checkout are covered by an end-to-end test against a fake store.
6
6
 
7
7
  ## What it does
8
8
 
9
9
  - **Sign in with the store's customer account.** Members click "Sign in" on your site, sign in on the store's account page and come back signed in. They become EmDash Subscribers. That role only means "signed in"; it never grants content.
10
10
  - **Mirrors the customer.** Email, name, tags and enabled/disabled status, kept current by signed Shopify webhooks.
11
11
  - **Levels from tags.** You map Shopify customer tags to levels. Set tags in Shopify Flow or any app; RedeemID only reads them.
12
- - **Rules per collection or term.** Lock a collection, or only entries in a category or tag.
12
+ - **Rules like RedeemID's on WordPress.** Lock a collection, entries with a term (and its child terms), or set a site default; a term can also open its entries to everyone. When several term rules cover an entry, readers must pass all of them.
13
+ - **Teasers and badges.** Locked entries can show their first paragraphs, up to a word count. `<AccessBadge>` names the level an entry needs and shows a lock to readers it keeps out.
13
14
  - **Plans, cart and checkout.** `<Plan>` shows a Shopify product's price and adds it to the visitor's Shopify cart; `<Cart>` shows the count and opens Shopify checkout.
14
15
  - **Account.** Members get an Account link to their Shopify customer account (orders, profile, addresses) and Sign out, which also ends the Shopify session.
15
- - **Paywall break block.** Editors write one body and drop a "Paywall break" block where members-only content starts, picking which levels may read on. `<Content>` renders the body and leaves the rest off the page for everyone else.
16
+ - **Paywall break block.** Editors write one body and drop a "Paywall break" block where members-only content starts, picking which levels may read on, or leaving it to the entry's rule. `<Content>` renders the body and leaves the rest off the page for everyone else.
16
17
  - **Plan block.** Editors add a Shopify product to any page with the "Plan" block: title, price and a buy button.
17
18
  - **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.
18
19
  - **Keeps members out of EmDash's own APIs**, so the gate is the only way to read locked content.
@@ -41,6 +42,8 @@ const config = {
41
42
  { collection: "posts", taxonomy: "category", term: "members", levels: ["member", "pro"] },
42
43
  { collection: "posts", taxonomy: "category", term: "pro", levels: ["pro"] },
43
44
  ],
45
+ // Optional: locked posts with no paywall break show the paragraphs within their first 40 words.
46
+ teaser: { posts: 40 },
44
47
  };
45
48
 
46
49
  export default defineConfig({
@@ -76,6 +79,19 @@ In Shopify, give the Customer Account API client these settings:
76
79
 
77
80
  Point webhooks (`customers/create`, `customers/update`, `customers/delete`, `customers/disable`, `customers/enable`, `customers/merge`, `customer.tags_added`, `customer.tags_removed`, `customers/redact`) at `https://your-site.example/_emdash/api/auth/redeemid/webhook`.
78
81
 
82
+ ### Rules
83
+
84
+ Each rule names a collection and the levels, any of which may read. An empty `levels` list, or the built-in `signed-in` level, means any signed-in member.
85
+
86
+ | Rule | Covers |
87
+ | --- | --- |
88
+ | `{ collection: "reports", levels: ["gold"] }` | Every entry in the collection |
89
+ | `{ collection: "posts", taxonomy: "category", term: "investigations", levels: ["gold"] }` | Entries with that term, or with a child of it in a hierarchical taxonomy. A child's own rule wins over its parent's. |
90
+ | `{ collection: "posts", taxonomy: "tag", term: "free-to-read", levels: [], open: true }` | Opens entries with that term to everyone, whatever else covers them |
91
+ | `{ collection: "*", levels: [] }` | The site default, for collections with no rule of their own |
92
+
93
+ Term rules beat the collection's rule, which beats the site default. When several term rules cover one entry (a story in Investigations, Gold, and Culture, Silver), readers must pass every one of them, so only Gold + Silver members read it. Set `combine: "any"` to let one of them be enough.
94
+
79
95
  ## Use it in templates
80
96
 
81
97
  EmDash has no content filter hook, so templates decide what to render. Render the entry body with `<Content>` instead of `<PortableText>`:
@@ -89,10 +105,21 @@ import Content from "@redeemid/emdash/components/Content.astro";
89
105
  </Content>
90
106
  ```
91
107
 
92
- Everything before the first Paywall break block is shown to everyone. What follows reaches the page only for readers the break allows: the levels picked on it, or when none are picked the entry's rule, or else any signed-in member. A body with no break follows the entry's rule as a whole. Plain `<PortableText>` ignores the break and shows everything, so use `<Content>` for any body that may hold one.
108
+ Everything before the first Paywall break block is shown to everyone. What follows reaches the page only for readers the break allows: the levels picked on it ("Signed in" for any member), or when none are picked the entry's rule. With none picked and no rule covering the entry, the break changes nothing, as on WordPress. A body with no break follows the entry's rule as a whole; readers it keeps out see the collection's `teaser` (the paragraphs within that many words, never half a paragraph), if one is set. Plain `<PortableText>` ignores the break and shows everything, so use `<Content>` for any body that may hold one.
93
109
 
94
110
  To lock a part of a template that isn't the body, wrap it in `<Gate>` (`<Gate levels={["pro"]}>…</Gate>`).
95
111
 
112
+ Show what an entry needs with `<AccessBadge>`, on cards and on the entry. It reads the entry's rules (and a paywall break's levels when you pass `content`), shows "Free" for open entries (`free=""` hides it), and adds `is-locked` and a lock for readers it keeps out. `data-redeemid-level` holds the level slugs, for colours:
113
+
114
+ ```astro
115
+ ---
116
+ import AccessBadge from "@redeemid/emdash/components/AccessBadge.astro";
117
+ ---
118
+ <AccessBadge collection="posts" terms={post.data.terms} content={post.data.content} />
119
+ ```
120
+
121
+ In your own code (`@redeemid/emdash/access`), `entryRequirement(config, collection, terms)` gives what an entry needs (a list of clauses, each passed by any of its levels, or `null` when open), and `canRead(Astro, entry)` gives the verdict for the visitor.
122
+
96
123
  Add the account box and cart to your header. Visitors see Sign in; members see their name, levels, Account and Sign out. The cart shows how many items are in the visitor's Shopify cart and goes to its checkout:
97
124
 
98
125
  ```astro
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@redeemid/emdash",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
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",
package/src/access.ts CHANGED
@@ -34,15 +34,33 @@ export interface Viewer {
34
34
 
35
35
  export type Reason = "open" | "allowed" | "sign_in" | "upgrade" | "disabled" | "unconfigured";
36
36
 
37
+ /**
38
+ * What an entry needs, in conjunctive form: every clause must pass, and a
39
+ * clause passes when the reader holds any of its levels. An empty clause means
40
+ * any signed-in member. `null` means the entry is open to everyone.
41
+ */
42
+ export type Requirement = string[][] | null;
43
+
44
+ /**
45
+ * The built-in level every signed-in member holds, as on WordPress. A clause
46
+ * with it passes for any signed-in member, like an empty clause.
47
+ */
48
+ export const SIGNED_IN = "signed-in";
49
+
37
50
  export interface Verdict {
38
51
  allowed: boolean;
39
52
  reason: Reason;
40
- /** Levels any of which would unlock the entry. Empty = any signed-in member. */
41
- required: string[];
53
+ /** What the entry needs (see Requirement). `[]` when it is open. */
54
+ required: string[][];
42
55
  viewer: Viewer;
43
56
  }
44
57
 
45
- export type Terms = Record<string, Array<{ slug: string } | string> | undefined>;
58
+ /** A term as EmDash hydrates it onto an entry, or just its slug. */
59
+ export type TermRef = { slug: string; id?: string; parentId?: string | null } | string;
60
+ export type Terms = Record<string, TermRef[] | undefined>;
61
+
62
+ /** Parent slug by term slug, per taxonomy, for walking up a hierarchy. */
63
+ export type TermTree = Record<string, Record<string, string | null>>;
46
64
 
47
65
  export function levelsFor(tags: string[], levels: LevelConfig[] = []): string[] {
48
66
  const held = new Set(tags.map((t) => t.toLowerCase()));
@@ -55,25 +73,157 @@ export function levelsFor(tags: string[], levels: LevelConfig[] = []): string[]
55
73
  .map((l) => l.slug);
56
74
  }
57
75
 
76
+ const slugOf = (t: TermRef) => (typeof t === "string" ? t : t.slug);
77
+
78
+ /**
79
+ * The clauses, simplified: duplicates go, a clause that contains another
80
+ * clause goes (needing Pro already passes "Member or Pro"), and an empty
81
+ * clause goes when a level clause is there (any level implies signed in).
82
+ */
83
+ function reduce(clauses: string[][]): string[][] {
84
+ const seen = new Set<string>();
85
+ const out: string[][] = [];
86
+ for (const c of clauses) {
87
+ const sorted = c.includes(SIGNED_IN) ? [] : [...new Set(c)].sort();
88
+ const key = sorted.join("|");
89
+ if (seen.has(key)) continue;
90
+ seen.add(key);
91
+ out.push(sorted);
92
+ }
93
+ const levelled = out.filter((c) => c.length > 0);
94
+ if (levelled.length === 0) return out;
95
+ return levelled.filter((c) => !levelled.some((o) => o !== c && o.length < c.length && o.every((l) => c.includes(l))));
96
+ }
97
+
98
+ function combined(rules: RuleConfig[], mode: "all" | "any"): string[][] {
99
+ if (mode === "any") {
100
+ return rules.some((r) => r.levels.length === 0) ? [[]] : [[...new Set(rules.flatMap((r) => r.levels))]];
101
+ }
102
+ return reduce(rules.map((r) => r.levels));
103
+ }
104
+
58
105
  /**
59
- * Required levels for an entry, or null when no rule covers it.
60
- * Term rules beat collection rules; several matching term rules combine.
106
+ * What an entry needs (see Requirement), from the site's rules.
107
+ *
108
+ * Each term the entry carries is walked up its taxonomy (with `tree`) to the
109
+ * nearest term that has a rule, so a child term takes its parent's rule unless
110
+ * it has its own. Any matching `open` rule opens the entry.
61
111
  */
62
- export function requiredLevels(rules: RuleConfig[] = [], collection: string, terms: Terms = {}): string[] | null {
112
+ export function requirement(
113
+ rules: RuleConfig[] = [],
114
+ collection: string,
115
+ terms: Terms = {},
116
+ options: { combine?: "all" | "any"; tree?: TermTree } = {},
117
+ ): Requirement {
118
+ const mode = options.combine ?? "all";
63
119
  const forCollection = rules.filter((r) => r.collection === collection);
64
- const termRules = forCollection.filter((r) => {
65
- if (!r.taxonomy || !r.term) return false;
66
- const list = terms[r.taxonomy] ?? [];
67
- return list.some((t) => (typeof t === "string" ? t : t.slug) === r.term);
120
+ const matched: RuleConfig[] = [];
121
+ for (const [taxonomy, list] of Object.entries(terms)) {
122
+ const taxRules = forCollection.filter((r) => r.taxonomy === taxonomy && r.term);
123
+ if (taxRules.length === 0) continue;
124
+ const parents = options.tree?.[taxonomy] ?? {};
125
+ for (const ref of list ?? []) {
126
+ let slug: string | null = slugOf(ref);
127
+ const seen = new Set<string>();
128
+ while (slug && !seen.has(slug)) {
129
+ seen.add(slug);
130
+ const own = taxRules.filter((r) => r.term === slug);
131
+ if (own.length > 0) {
132
+ matched.push(...own);
133
+ break;
134
+ }
135
+ slug = parents[slug] ?? null;
136
+ }
137
+ }
138
+ }
139
+ if (matched.some((r) => r.open)) return null;
140
+ if (matched.length > 0) return combined(matched, mode);
141
+ const whole = forCollection.filter((r) => !r.taxonomy && !r.term && !r.open);
142
+ if (whole.length > 0) return combined(whole, mode);
143
+ const site = rules.filter((r) => r.collection === "*" && !r.taxonomy && !r.term && !r.open);
144
+ if (site.length > 0) return combined(site, mode);
145
+ return null;
146
+ }
147
+
148
+ /** Does someone holding `held` pass `required`? Signed-in membership is checked by the caller. */
149
+ export function passes(held: string[], required: string[][]): boolean {
150
+ return required.every((clause) => clause.length === 0 || clause.includes(SIGNED_IN) || clause.some((l) => held.includes(l)));
151
+ }
152
+
153
+ /**
154
+ * The requirement in words, for badges and admin pages: "Gold + Silver",
155
+ * "Silver or Gold", "Signed in". `null` gives `open`.
156
+ */
157
+ export function describe(required: Requirement, levels: LevelConfig[] = [], open = "Free"): string {
158
+ if (required === null) return open;
159
+ const name = (slug: string) => levels.find((l) => l.slug === slug)?.name ?? slug;
160
+ const parts = reduce(required).filter((c) => c.length > 0).map((c) => c.map(name).join(" or "));
161
+ return parts.length ? parts.join(" + ") : "Signed in";
162
+ }
163
+
164
+ /**
165
+ * Parent slugs for the taxonomies whose rules could cover an entry through a
166
+ * parent term. Reads EmDash's term lists (cached by EmDash) only when a term
167
+ * on the entry has no rule of its own.
168
+ */
169
+ export async function termTree(rules: RuleConfig[] = [], collection: string, terms: Terms = {}): Promise<TermTree> {
170
+ const tree: TermTree = {};
171
+ const forCollection = rules.filter((r) => r.collection === collection && r.taxonomy && r.term);
172
+ const wanted = Object.entries(terms).filter(([taxonomy, list]) => {
173
+ const own = new Set(forCollection.filter((r) => r.taxonomy === taxonomy).map((r) => r.term));
174
+ return own.size > 0 && (list ?? []).some((t) => !own.has(slugOf(t)));
68
175
  });
69
- const chosen = termRules.length > 0 ? termRules : forCollection.filter((r) => !r.taxonomy && !r.term);
70
- if (chosen.length === 0) return null;
71
- // Any rule that admits every member wins.
72
- if (chosen.some((r) => r.levels.length === 0)) return [];
73
- return [...new Set(chosen.flatMap((r) => r.levels))];
176
+ if (wanted.length === 0) return tree;
177
+ try {
178
+ const { getTaxonomyTerms } = await import("emdash");
179
+ for (const [taxonomy] of wanted) {
180
+ type Node = { id: string; slug: string; parentId?: string | null; children?: Node[] };
181
+ const flat: Node[] = [];
182
+ const walk = (list: Node[]) => list.forEach((n) => (flat.push(n), walk(n.children ?? [])));
183
+ walk((await getTaxonomyTerms(taxonomy)) as Node[]);
184
+ const byId = new Map(flat.map((n) => [n.id, n.slug]));
185
+ const byGroup = new Map(flat.map((n) => [(n as { translationGroup?: string | null }).translationGroup ?? n.id, n.slug]));
186
+ tree[taxonomy] = Object.fromEntries(
187
+ flat.map((n) => [n.slug, n.parentId ? (byId.get(n.parentId) ?? byGroup.get(n.parentId) ?? null) : null]),
188
+ );
189
+ }
190
+ } catch {
191
+ // No term lists (outside an EmDash request): only direct term rules apply.
192
+ }
193
+ return tree;
194
+ }
195
+
196
+ /** The entry's requirement with the site's config, walking term parents. */
197
+ export async function entryRequirement(
198
+ config: RedeemIDConfig | null,
199
+ collection: string,
200
+ terms: Terms = {},
201
+ ): Promise<Requirement> {
202
+ if (!config) return null;
203
+ const tree = await termTree(config.rules, collection, terms);
204
+ return requirement(config.rules, collection, terms, { combine: config.combine, tree });
74
205
  }
75
206
 
207
+ const viewers = new WeakMap<object, Promise<Viewer>>();
208
+
209
+ /** The visitor, read once per request (badges on a list page all ask). */
76
210
  export async function viewer(astro: AstroLike): Promise<Viewer> {
211
+ const key = astro.locals as object;
212
+ if (key && typeof key === "object") {
213
+ const known = viewers.get(key);
214
+ if (known) {
215
+ const v = await known;
216
+ if (v.signedIn) astro.response?.headers.set("Cache-Control", "private, no-store");
217
+ return v;
218
+ }
219
+ const fresh = readViewer(astro);
220
+ viewers.set(key, fresh);
221
+ return fresh;
222
+ }
223
+ return readViewer(astro);
224
+ }
225
+
226
+ async function readViewer(astro: AstroLike): Promise<Viewer> {
77
227
  const locals = astro.locals as Locals;
78
228
  const user = locals.user;
79
229
  if (!user?.id || user.disabled) return { signedIn: false, member: null, levels: [] };
@@ -90,14 +240,22 @@ export async function viewer(astro: AstroLike): Promise<Viewer> {
90
240
  return { signedIn: true, member, levels };
91
241
  }
92
242
 
243
+ /**
244
+ * May this visitor read the entry? `override` replaces the entry's rule, for a
245
+ * part of a page locked to its own levels (a paywall break with levels).
246
+ */
93
247
  export async function canRead(
94
248
  astro: AstroLike,
95
249
  entry: { collection: string; terms?: Terms },
96
- override?: { levels: string[] },
250
+ override?: { levels: string[] } | { required: string[][] },
97
251
  ): Promise<Verdict> {
98
252
  const locals = astro.locals as Locals;
99
253
  const config: RedeemIDConfig | null = siteConfig(locals.emdash?.config);
100
- const required = override ? override.levels : requiredLevels(config?.rules, entry.collection, entry.terms);
254
+ const required: Requirement = override
255
+ ? "required" in override
256
+ ? override.required
257
+ : [override.levels]
258
+ : await entryRequirement(config, entry.collection, entry.terms);
101
259
  const v = await viewer(astro);
102
260
 
103
261
  if (required === null) return { allowed: true, reason: "open", required: [], viewer: v };
@@ -105,7 +263,7 @@ export async function canRead(
105
263
  if (!v.signedIn) return { allowed: false, reason: "sign_in", required, viewer: v };
106
264
  if (v.member?.status === "disabled") return { allowed: false, reason: "disabled", required, viewer: v };
107
265
  if (!v.member) return { allowed: false, reason: "upgrade", required, viewer: v };
108
- const ok = required.length === 0 || required.some((l) => v.levels.includes(l));
266
+ const ok = passes(v.levels, required);
109
267
  return { allowed: ok, reason: ok ? "allowed" : "upgrade", required, viewer: v };
110
268
  }
111
269
 
@@ -22,3 +22,25 @@ export function splitAtPaywall<T>(value: T[] | null | undefined): {
22
22
  const levels = Array.isArray(raw) ? raw.filter((l): l is string => typeof l === "string" && l !== "") : [];
23
23
  return { open: blocks.slice(0, at), locked: blocks.slice(at + 1), levels, paywall: true };
24
24
  }
25
+
26
+ type TextNode = { _type?: unknown; children?: Array<{ text?: unknown }> };
27
+
28
+ /**
29
+ * The text blocks within the first `words` words of a body, as on WordPress:
30
+ * a block is never cut in half, so a block that would pass the count ends the
31
+ * teaser. Images and custom blocks are left out. 0 gives nothing.
32
+ */
33
+ export function teaser<T>(value: T[] | null | undefined, words: number): T[] {
34
+ if (!Array.isArray(value) || !(words > 0)) return [];
35
+ const out: T[] = [];
36
+ let count = 0;
37
+ for (const b of value) {
38
+ const node = b as TextNode;
39
+ if (node?._type !== "block") continue;
40
+ const text = (node.children ?? []).map((c) => (typeof c.text === "string" ? c.text : "")).join("");
41
+ count += text.split(/\s+/).filter(Boolean).length;
42
+ if (count > words) break;
43
+ out.push(b);
44
+ }
45
+ return out;
46
+ }
@@ -0,0 +1,45 @@
1
+ ---
2
+ /**
3
+ * The level an entry needs, read from its rules (and from a paywall break
4
+ * with levels), like the Access Badge block on WordPress:
5
+ *
6
+ * <AccessBadge collection="posts" terms={post.data.terms} content={post.data.content} />
7
+ *
8
+ * Open entries show `free` ("Free"; pass free="" to show nothing). The badge
9
+ * carries `data-redeemid-level` (the level slugs) for styling, and
10
+ * `is-locked` with a lock for readers who can't read the members part.
11
+ */
12
+ import { canRead, describe, entryRequirement, type Terms } from "../access.js";
13
+ import { splitAtPaywall } from "../blocks-names.js";
14
+ import { siteConfig } from "../site-config.js";
15
+
16
+ interface Props {
17
+ collection: string;
18
+ terms?: Terms;
19
+ /** The entry's body, so a paywall break's levels count. */
20
+ content?: unknown[] | null;
21
+ free?: string;
22
+ class?: string;
23
+ }
24
+
25
+ const { collection, terms, content, free = "Free", class: className } = Astro.props;
26
+ const config = siteConfig((Astro.locals as { emdash?: { config?: unknown } }).emdash?.config);
27
+ const split = splitAtPaywall(content);
28
+ const required = split.paywall && split.levels.length
29
+ ? [split.levels]
30
+ : await entryRequirement(config, collection, terms);
31
+ const label = describe(required, config?.levels, free);
32
+ const locked = required !== null && !(await canRead(Astro, { collection, terms }, { required })).allowed;
33
+ const slugs = required?.flat().join(" ") || (required ? "signed-in" : "free");
34
+ ---
35
+
36
+ {label && (
37
+ <span
38
+ class:list={["redeemid-badge", { "is-locked": locked }, className]}
39
+ data-redeemid-level={slugs}
40
+ >
41
+ {locked && <span class="redeemid-badge__lock" aria-hidden="true">🔒&#xFE0E; </span>}
42
+ {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
+ </span>
45
+ )}
@@ -6,14 +6,15 @@
6
6
  *
7
7
  * Everything before the first "Paywall break" block is shown to everyone.
8
8
  * What follows reaches the page only for readers who may read it: the levels
9
- * picked on the break, or when none are picked the entry's rule, or else any
10
- * signed-in member. Others get the "locked" slot (or a built-in notice).
11
- * A body with no break follows the entry's rule as a whole.
9
+ * picked on the break, or when none are picked the entry's rule (with no rule,
10
+ * the break changes nothing, as on WordPress). Others get the "locked" slot (or a built-in notice).
11
+ * A body with no break follows the entry's rule as a whole; readers who can't
12
+ * read it see the collection's teaser (config `teaser`, in words), if any.
12
13
  */
13
14
  import { PortableText } from "emdash/ui";
14
15
 
15
- import { canRead, requiredLevels, signInUrl, type Terms } from "../access.js";
16
- import { splitAtPaywall } from "../blocks-names.js";
16
+ import { canRead, entryRequirement, signInUrl, type Terms } from "../access.js";
17
+ import { splitAtPaywall, teaser } from "../blocks-names.js";
17
18
  import { siteConfig } from "../site-config.js";
18
19
 
19
20
  interface Props {
@@ -25,13 +26,19 @@ interface Props {
25
26
  const { value, collection = "", terms } = Astro.props;
26
27
  const split = splitAtPaywall(value);
27
28
  const config = siteConfig((Astro.locals as { emdash?: { config?: unknown } }).emdash?.config);
28
- const levels = split.paywall
29
+ // A break with levels picked locks the rest to them; with none picked it
30
+ // follows the entry's rule, and does nothing when no rule covers the entry.
31
+ const required = split.paywall
29
32
  ? split.levels.length
30
- ? split.levels
31
- : (requiredLevels(config?.rules, collection, terms) ?? [])
33
+ ? [split.levels]
34
+ : await entryRequirement(config, collection, terms)
32
35
  : undefined;
33
- const verdict = await canRead(Astro, { collection, terms }, levels ? { levels } : undefined);
34
- const shown = split.paywall ? split.open : verdict.allowed ? split.open : [];
36
+ const verdict =
37
+ split.paywall && required === null
38
+ ? { allowed: true, reason: "open" as const }
39
+ : await canRead(Astro, { collection, terms }, required ? { required } : undefined);
40
+ const words = config?.teaser?.[collection] ?? 0;
41
+ const shown = split.paywall ? split.open : verdict.allowed ? split.open : teaser(split.open, words);
35
42
  const here = Astro.url.pathname + Astro.url.search;
36
43
  ---
37
44
 
package/src/config.ts CHANGED
@@ -18,18 +18,32 @@ export interface LevelConfig {
18
18
  }
19
19
 
20
20
  /**
21
- * Who may read entries. A rule with `term` applies to entries that carry that
22
- * term; a rule without one applies to the whole collection. Term rules win
23
- * over collection rules for the same entry.
21
+ * Who may read entries, like RedeemID's content rules on WordPress:
22
+ *
23
+ * - A rule with `taxonomy` and `term` covers entries that carry that term, or
24
+ * a child of it in a hierarchical taxonomy (a child's own rule wins over its
25
+ * parent's).
26
+ * - A rule with neither covers the whole collection.
27
+ * - `collection: "*"` is the site default, for collections with no rule.
28
+ *
29
+ * Term rules beat the collection rule, which beats the site default. When
30
+ * several term rules cover one entry, a reader must pass every one of them
31
+ * (most restrictive), unless `combine` is "any".
24
32
  */
25
33
  export interface RuleConfig {
34
+ /** Collection slug, or "*" for the site default. */
26
35
  collection: string;
27
36
  /** Taxonomy slug, e.g. "category". Requires `term`. */
28
37
  taxonomy?: string;
29
38
  /** Term slug, e.g. "premium". */
30
39
  term?: string;
31
- /** Level slugs that may read. An empty list means signed-in members of any level. */
40
+ /** Level slugs, any of which may read. An empty list means any signed-in member. */
32
41
  levels: string[];
42
+ /**
43
+ * A term rule that opens its entries to everyone, whatever else covers them
44
+ * ("Opens" on WordPress). `levels` is ignored.
45
+ */
46
+ open?: boolean;
33
47
  }
34
48
 
35
49
  export interface RedeemIDConfig {
@@ -43,6 +57,17 @@ export interface RedeemIDConfig {
43
57
  label?: string;
44
58
  levels?: LevelConfig[];
45
59
  rules?: RuleConfig[];
60
+ /**
61
+ * How several term rules on one entry combine: "all" (default, the most
62
+ * restrictive: pass every rule) or "any" (pass one of them).
63
+ */
64
+ combine?: "all" | "any";
65
+ /**
66
+ * Teaser length in words, per collection, for locked entries with no paywall
67
+ * break: readers who can't read on see this many words of the body. Without
68
+ * one they see none of it.
69
+ */
70
+ teaser?: Record<string, number>;
46
71
  /**
47
72
  * Extra /_emdash path prefixes signed-in members may use. Everything else
48
73
  * under /_emdash is refused to Subscribers (see guard.ts).
package/src/plugin.ts CHANGED
@@ -11,8 +11,9 @@
11
11
  * auth provider's routes.
12
12
  *
13
13
  * - "Paywall break" (`redeemid-paywall`): everything after it in the body is
14
- * for members. Pick the levels that may read on; none picked means any
15
- * signed-in member, or the entry's rule when one covers it.
14
+ * for members. Pick the levels that may read on ("Signed in" for any
15
+ * member); none picked means the entry's rule, and nothing is locked when
16
+ * no rule covers the entry, as on WordPress.
16
17
  * - "Plan" (`redeemid-plan`): a Shopify product's title and price with a
17
18
  * button that adds it to the cart and opens checkout.
18
19
  *
@@ -23,7 +24,7 @@
23
24
  import type { ResolvedPlugin, RouteContext } from "emdash";
24
25
  import { definePlugin } from "emdash";
25
26
 
26
- import { levelsFor } from "./access.js";
27
+ import { describe, levelsFor, SIGNED_IN } from "./access.js";
27
28
  import { env, ENV, storeDomain, type RedeemIDConfig } from "./config.js";
28
29
  import { discover } from "./shopify.js";
29
30
  import { stores, type MemberRecord } from "./storage.js";
@@ -35,7 +36,10 @@ import { PAYWALL_BLOCK, PLAN_BLOCK } from "./blocks-names.js";
35
36
  export { PAYWALL_BLOCK, PLAN_BLOCK };
36
37
 
37
38
  function blocks(config: RedeemIDConfig) {
38
- const levelOptions = (config.levels ?? []).map((l) => ({ label: l.name, value: l.slug }));
39
+ const levelOptions = [
40
+ { label: "Signed in (any member)", value: SIGNED_IN },
41
+ ...(config.levels ?? []).map((l) => ({ label: l.name, value: l.slug })),
42
+ ];
39
43
  return [
40
44
  {
41
45
  type: PAYWALL_BLOCK,
@@ -46,7 +50,7 @@ function blocks(config: RedeemIDConfig) {
46
50
  {
47
51
  type: "checkbox" as const,
48
52
  action_id: "levels",
49
- label: "Who can read on (none = any signed-in member)",
53
+ label: "Who can read on (none = the entry's rule)",
50
54
  options: levelOptions,
51
55
  },
52
56
  ],
@@ -255,10 +259,13 @@ async function statusPage(config: RedeemIDConfig, request: Request) {
255
259
  { key: "levels", label: "Who can read" },
256
260
  ],
257
261
  rows: rules.map((r) => ({
258
- where: r.taxonomy && r.term ? `${r.collection}, ${r.taxonomy}: ${r.term}` : `All ${r.collection}`,
259
- levels: r.levels.length
260
- ? r.levels.map((s) => levels.find((l) => l.slug === s)?.name ?? s).join(" or ")
261
- : "Any signed-in member",
262
+ where:
263
+ r.taxonomy && r.term
264
+ ? `${r.collection === "*" ? "Every collection" : r.collection}, ${r.taxonomy}: ${r.term} (and its child terms)`
265
+ : r.collection === "*"
266
+ ? "Site default (collections with no rule)"
267
+ : `All ${r.collection}`,
268
+ levels: r.open ? "Everyone (opens the entry)" : r.levels.length ? describe([r.levels], levels) : "Any signed-in member",
262
269
  })),
263
270
  }
264
271
  : { type: "context", text: "No rules. Entries are open unless their body has a paywall break." },
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const VERSION = "0.0.3";
1
+ export const VERSION = "0.0.4";