@mccaskie-labs/workbench-directory 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # @mccaskie-labs/workbench-directory
2
+
3
+ ## 0.1.0
4
+
5
+ - First version (`docs/capabilities/29-directory.md`): `createDirectory` over the app's own database with `directoryMigration`. Business, member or job listings made from a workbench-forms form (`npx workbench-directory generate` copies each kind's fields from `workbench/forms/<form>.json`), approved by the owner before they show, with later edits waiting for approval while the page keeps the approved words. Postgres full-text search (word-start matching, English and Tagalog alike) with category, area, tick and choice filters, featured first; members-only kinds for signed-in viewers. Free, paid once or paid monthly or yearly plans, approved before paying: `charge()` gives the invoice line for the payments tool and `paid()` extends a listing once per payment id at the plan's price, featuring it when the plan does. `tick()` for reminders before and after a listing ends, `cleanup()` after `retention_months`; `preview()` for a share card with no personal detail. Service role only, one lock per lister for the listing limit. The search box, results, listing page, plan choice, "My listings" and refusals in `./ui` (`wb-directory-*`, `DIRECTORY_STYLES`, words in English, Tagalog and Taglish, money to 2 decimal places), and `npx workbench-directory generate|migration`.
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # @mccaskie-labs/workbench-directory
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A directory with paid listings for apps built on Workbench, a private platform: businesses, members or jobs, approved by the owner, searched and filtered by visitors, free or paid. Spec: `docs/capabilities/29-directory.md`. Published publicly so Workbench projects can install it with no token; it is not supported for other uses.
4
+
5
+ ```sh
6
+ npm install @mccaskie-labs/workbench-directory
7
+ ```
8
+
9
+ ## Set up
10
+
11
+ 1. Make each kind's listing form with the forms questions, such as `workbench/forms/business_listing.json`: a required name field (`"personal": false` for a business's name), a summary, single-choice category and area fields, any tick or choice fields to filter by, and the lister's own email (not shown).
12
+ 2. Write `workbench/directory.json` (the client questions in `capabilities/directory.json` fill it):
13
+
14
+ ```json
15
+ {
16
+ "format": 1,
17
+ "country": "AU",
18
+ "currency": "AUD",
19
+ "time_zone": "Australia/Sydney",
20
+ "kinds": [
21
+ {
22
+ "kind": "business",
23
+ "label": "Business",
24
+ "form": "business_listing",
25
+ "who_sees": "everyone",
26
+ "title": "business_name",
27
+ "summary": "about",
28
+ "category": "category",
29
+ "place": "suburb",
30
+ "website": "website",
31
+ "search": ["services"],
32
+ "filters": ["open_weekends"],
33
+ "show": ["services", "phone", "website", "open_weekends"],
34
+ "plans": [
35
+ { "plan": "free", "label": "Free listing", "price": 0, "days": null },
36
+ { "plan": "featured", "label": "Featured for 30 days", "price": 40, "days": 30, "featured": true }
37
+ ]
38
+ }
39
+ ]
40
+ }
41
+ ```
42
+
43
+ Prices are dollars or pesos, at most 2 decimal places. A plan with `"every": "month"` needs the payments tool's repeating payments.
44
+
45
+ 3. `npx workbench-directory generate` copies each form's fields, checks everything, prints what listers will be offered, and writes `src/directory.generated.ts` (`DIRECTORY`). Checks can run `npx workbench-directory generate --check`.
46
+ 4. `npx workbench-directory migration` writes `directoryMigration` and its down file into `supabase/migrations` and `supabase/rollback`. It creates functions, so Control asks for approval even on staging.
47
+
48
+ ## Use
49
+
50
+ ```ts
51
+ import { createDirectory } from '@mccaskie-labs/workbench-directory'
52
+ import { readSearch, renderListing, renderMine, renderPlans, renderRefusal, renderResults, renderSearch } from '@mccaskie-labs/workbench-directory/ui'
53
+ import { DIRECTORY } from './directory.generated'
54
+
55
+ const directory = createDirectory({ db: serviceClient, config: DIRECTORY })
56
+
57
+ // The listing form (forms' validate first): lister is the signed-in member's own id.
58
+ const r = await directory.submit({ kind: 'business', lister: member.id, answers, plan: form.plan })
59
+ if (!r.ok) return renderRefusal(r, DIRECTORY) // too_many
60
+
61
+ // The owner's admin page.
62
+ const waiting = await directory.queue()
63
+ const a = await directory.approve(id, { by: owner.email }) // a.needs_payment: email the pay link
64
+ await directory.reject(id, { by: owner.email, reason: 'Not a local business' })
65
+
66
+ // Paying: approved listings only.
67
+ const c = await directory.charge(id, { lister: member.id })
68
+ // payments.createInvoice(invoiceSource({ account, currency: c.currency, lines: c.lines, tax, source: c.source }), billTo)
69
+ // in the payments webhook, on { kind: 'paid' } with source.type 'listing':
70
+ await directory.paid({ listing: invoice.source.id, paymentRef: payment.id, amountCents: payment.amount_cents })
71
+
72
+ // The directory page.
73
+ const s = readSearch(url, DIRECTORY, 'business')
74
+ const results = await directory.search({ ...s, viewer: { signedIn: !!member } })
75
+ const html = renderSearch(DIRECTORY, 'business', { action: '/directory', current: s }) + renderResults(results, DIRECTORY, { hrefFor: (l) => `/directory/${l.slug}` })
76
+
77
+ // The daily cron.
78
+ const { reminders, ended } = await directory.tick() // email each lister once
79
+ await directory.cleanup()
80
+ ```
81
+
82
+ - A refusal is an answer (`{ ok: false, reason }`), never a throw: `not_found`, `too_many`, `not_approved`. `DirectoryError` is for the app's own mistakes and database failures (`bad_input`, `unknown_plan`, `wrong_amount`, `store_failed`).
83
+ - `update` before approval replaces the listing; after, it waits for the owner and the page keeps the approved words. `withdraw` deletes the lister's own listing; `hide`, `unhide` and `remove` are the owner's.
84
+ - `bySlug(slug)` and `search` show only live listings, only the fields the kind shows, and members-only kinds only with `viewer: { signedIn: true }`. `preview(listing)` gives a share card's title and description with no personal detail.
85
+
86
+ ## Look
87
+
88
+ Every element `./ui` draws has a `wb-directory-*` class with a default rule in `DIRECTORY_STYLES` (`./styles`); `npx workbench-ui styles` puts them in the project's `public/styles/workbench.css`, and the project restyles them in `project.css`. The words are in `DIRECTORY_WORDS` (English, Tagalog, Taglish) under `ui.wbdirectory.*`.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import type { DirectoryConfig } from "./types.ts";
3
+ export declare const DIRECTORY_FILE = "workbench/directory.json";
4
+ export declare const DIRECTORY_MODULE = "src/directory.generated.ts";
5
+ /** What the settings mean, in lines for the owner. */
6
+ export declare function summaryLines(c: DirectoryConfig): string[];
7
+ /** The generated module for checked settings. */
8
+ export declare function moduleText(c: DirectoryConfig): string;
9
+ /** Reads workbench/directory.json and each kind's form, and checks them. Throws naming every problem. */
10
+ export declare function readDirectory(dir: string): DirectoryConfig;
11
+ /** Runs one command; returns the exit code. */
12
+ export declare function run(argv: string[], log?: (s: string) => void, err?: (s: string) => void): number;
package/dist/cli.js ADDED
@@ -0,0 +1,174 @@
1
+ #!/usr/bin/env node
2
+ // `npx workbench-directory generate [--check] [dir]`, run in a project's
3
+ // folder: reads workbench/directory.json, copies each kind's fields from its
4
+ // form (workbench/forms/<form>.json, by workbench-forms' formData, so a field's
5
+ // type, longest, choices and whether it's a personal detail come from one
6
+ // place), checks the lot, prints what listers will be offered, and writes
7
+ // src/directory.generated.ts: DIRECTORY for createDirectory. --check writes
8
+ // nothing and fails when the file is out of date or wrong.
9
+ //
10
+ // `npx workbench-directory migration [dir]` writes directoryMigration into
11
+ // supabase/migrations/<timestamp>_workbench_directory.sql with its down file
12
+ // in supabase/rollback/, unless a directory migration is already there.
13
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
14
+ import { dirname, join, resolve } from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+ import { formData, readAnswers } from "@mccaskie-labs/workbench-forms/answers";
17
+ import { DEFAULT_MAX_PER_LISTER, DEFAULT_REMIND_DAYS, DEFAULT_RETENTION_MONTHS, directoryProblems, directoryWarnings, shownFields } from "./config.js";
18
+ import { directoryMigration } from "./migration.js";
19
+ const USAGE = "usage: workbench-directory generate [--check] [dir]\n workbench-directory migration [dir]";
20
+ export const DIRECTORY_FILE = "workbench/directory.json";
21
+ export const DIRECTORY_MODULE = "src/directory.generated.ts";
22
+ const read = (path) => readFileSync(path, "utf8").replace(/\r\n/g, "\n");
23
+ function money(c, n) {
24
+ return `${c.currency} ${n.toFixed(2)}`;
25
+ }
26
+ /** What the settings mean, in lines for the owner. */
27
+ export function summaryLines(c) {
28
+ const lines = [];
29
+ for (const k of c.kinds) {
30
+ lines.push(`${k.label} listings, from form ${k.form}: ${k.who_sees === "everyone" ? "anyone can see and search them" : "only signed-in members see them"}. Each is approved by you before it shows.`);
31
+ const found = ["name", k.summary && "summary", k.category && "category", k.place && "area", ...(k.search ?? [])].filter(Boolean).join(", ");
32
+ lines.push(` Found by: ${found}.${k.filters?.length ? ` Filters: ${k.filters.join(", ")}.` : ""}`);
33
+ lines.push(` Shown on the listing: ${shownFields(k).join(", ") || "only its name"}.`);
34
+ for (const p of k.plans) {
35
+ const price = p.price === 0 ? (p.days ? `free for ${p.days} days, renewed for free` : "free, never ends") : p.every ? `${money(c, p.price)} a ${p.every}` : `${money(c, p.price)} for ${p.days} days`;
36
+ lines.push(` Plan "${p.label}": ${price}${p.featured ? ", featured (shown first)" : ""}.`);
37
+ }
38
+ lines.push(` Up to ${k.max_per_lister ?? DEFAULT_MAX_PER_LISTER} listings each.`);
39
+ }
40
+ lines.push(`Listers are emailed ${c.remind_days ?? DEFAULT_REMIND_DAYS} days before a listing ends; rejected and ended listings are deleted after ${c.retention_months ?? DEFAULT_RETENTION_MONTHS} months.`);
41
+ for (const w of directoryWarnings(c))
42
+ lines.push(`WARNING: ${w}`);
43
+ return lines;
44
+ }
45
+ /** The generated module for checked settings. */
46
+ export function moduleText(c) {
47
+ return [
48
+ `// Generated by \`npx workbench-directory generate\` from ${DIRECTORY_FILE} and the forms it names. Don't edit: change the`,
49
+ "// JSON and generate again (Checks runs `npx workbench-directory generate --check`).",
50
+ "",
51
+ 'import type { DirectoryConfig } from "@mccaskie-labs/workbench-directory";',
52
+ "",
53
+ `export const DIRECTORY = ${JSON.stringify(c, null, 2)} as const satisfies DirectoryConfig;`,
54
+ "",
55
+ ].join("\n");
56
+ }
57
+ /** Reads workbench/directory.json and each kind's form, and checks them. Throws naming every problem. */
58
+ export function readDirectory(dir) {
59
+ const path = join(dir, DIRECTORY_FILE);
60
+ if (!existsSync(path))
61
+ throw new Error(`${DIRECTORY_FILE} is missing: answer the directory questions first (capabilities/directory.json, offer)`);
62
+ let parsed;
63
+ try {
64
+ parsed = JSON.parse(read(path));
65
+ }
66
+ catch (e) {
67
+ throw new Error(`${DIRECTORY_FILE}: not valid JSON (${e.message})`);
68
+ }
69
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
70
+ throw new Error(`${DIRECTORY_FILE}: not a JSON object`);
71
+ const { $schema: _, ...rest } = parsed;
72
+ const problems = [];
73
+ if (Array.isArray(rest.kinds)) {
74
+ rest.kinds = rest.kinds.map((k) => {
75
+ if (typeof k !== "object" || k === null || Array.isArray(k))
76
+ return k;
77
+ const kind = k;
78
+ if ("fields" in kind || "required" in kind) {
79
+ problems.push(`${DIRECTORY_FILE} kind ${String(kind.kind)}: "fields" and "required" come from the form; leave them out`);
80
+ return kind;
81
+ }
82
+ if (typeof kind.form !== "string" || !/^[a-z][a-z0-9_]*$/.test(kind.form))
83
+ return kind;
84
+ const file = `workbench/forms/${kind.form}.json`;
85
+ if (!existsSync(join(dir, file))) {
86
+ problems.push(`${DIRECTORY_FILE} kind ${String(kind.kind)}: "form" names ${kind.form}, and there is no ${file}`);
87
+ return kind;
88
+ }
89
+ try {
90
+ const answers = readAnswers(JSON.parse(read(join(dir, file))), file);
91
+ if (answers.status !== "done")
92
+ throw new Error(`${file} is still a draft: finish the form's questions first`);
93
+ const data = formData(answers, undefined, file);
94
+ return { ...kind, fields: data.properties, required: data.required };
95
+ }
96
+ catch (e) {
97
+ problems.push(`${DIRECTORY_FILE} kind ${String(kind.kind)}: ${e.message}`);
98
+ return kind;
99
+ }
100
+ });
101
+ }
102
+ if (problems.length)
103
+ throw new Error(problems.join("\n"));
104
+ const more = directoryProblems(rest, DIRECTORY_FILE);
105
+ if (more.length)
106
+ throw new Error(more.join("\n"));
107
+ return rest;
108
+ }
109
+ function migrationStamp(at) {
110
+ return at.toISOString().replace(/[-:T]/g, "").slice(0, 14);
111
+ }
112
+ /** Runs one command; returns the exit code. */
113
+ export function run(argv, log = console.log, err = console.error) {
114
+ const [command, ...rest] = argv;
115
+ const check = rest.includes("--check");
116
+ const bad = rest.find((a) => a.startsWith("--") && a !== "--check");
117
+ if (bad || (command !== "generate" && command !== "migration") || (command === "migration" && check)) {
118
+ err(bad ? `${bad} isn't an option\n${USAGE}` : USAGE);
119
+ return 2;
120
+ }
121
+ const dir = resolve(rest.find((a) => !a.startsWith("--")) ?? ".");
122
+ try {
123
+ if (command === "migration") {
124
+ const folder = join(dir, "supabase/migrations");
125
+ if (existsSync(folder) && readdirSync(folder).some((f) => f.endsWith("_workbench_directory.sql"))) {
126
+ log("supabase/migrations already has the directory migration; nothing written");
127
+ return 0;
128
+ }
129
+ const name = `${migrationStamp(new Date())}_workbench_directory.sql`;
130
+ mkdirSync(folder, { recursive: true });
131
+ mkdirSync(join(dir, "supabase/rollback"), { recursive: true });
132
+ writeFileSync(join(folder, name), `-- workbench-directory: listings, search and paid listings (docs/capabilities/29-directory.md)\n${directoryMigration.up}`);
133
+ writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${directoryMigration.down}`);
134
+ log(`wrote supabase/migrations/${name} and its down file`);
135
+ return 0;
136
+ }
137
+ const c = readDirectory(dir);
138
+ for (const line of summaryLines(c))
139
+ log(line);
140
+ const out = join(dir, DIRECTORY_MODULE);
141
+ const text = moduleText(c);
142
+ const current = existsSync(out) ? read(out) : null;
143
+ if (check) {
144
+ if (current !== text) {
145
+ err(`${DIRECTORY_MODULE} is out of date: run \`npx workbench-directory generate\` and commit it`);
146
+ return 1;
147
+ }
148
+ log(`${DIRECTORY_MODULE} is current`);
149
+ return 0;
150
+ }
151
+ if (current !== text) {
152
+ mkdirSync(dirname(out), { recursive: true });
153
+ writeFileSync(out, text);
154
+ log(`wrote ${DIRECTORY_MODULE}`);
155
+ }
156
+ else
157
+ log(`${DIRECTORY_MODULE} is current`);
158
+ return 0;
159
+ }
160
+ catch (e) {
161
+ err(e.message);
162
+ return 1;
163
+ }
164
+ }
165
+ const isMain = (() => {
166
+ try {
167
+ return process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
168
+ }
169
+ catch {
170
+ return false;
171
+ }
172
+ })();
173
+ if (isMain)
174
+ process.exitCode = run(process.argv.slice(2));
@@ -0,0 +1,23 @@
1
+ import type { DirectoryConfig, KindConfig, PlanConfig } from "./types.ts";
2
+ /** Dollars or pesos (15.5) to cents (1550). */
3
+ export declare const toCents: (amount: number) => number;
4
+ export declare const DEFAULT_MAX_PER_LISTER = 5;
5
+ export declare const DEFAULT_REMIND_DAYS = 7;
6
+ export declare const DEFAULT_RETENTION_MONTHS = 12;
7
+ /** The fields a kind's page shows: `show`, or every field that isn't a personal detail or one of the name, summary, category, place and website. */
8
+ export declare function shownFields(k: KindConfig): string[];
9
+ /** A kind's plan by name, or undefined. */
10
+ export declare const planOf: (k: KindConfig, plan: string) => PlanConfig | undefined;
11
+ /** The plans as the database functions take them: { plan: { cents, days, every, featured } }. */
12
+ export declare function plansJson(k: KindConfig): Record<string, {
13
+ cents: number;
14
+ days: number | null;
15
+ every: string | null;
16
+ featured: boolean;
17
+ }>;
18
+ /** Every problem with the settings, or none. */
19
+ export declare function directoryProblems(input: unknown, where?: string): string[];
20
+ /** Warnings that don't stop the settings, for the owner to read. */
21
+ export declare function directoryWarnings(c: DirectoryConfig): string[];
22
+ /** The settings, checked; throws naming every problem. */
23
+ export declare function checkDirectory<C extends DirectoryConfig>(c: C): C;
package/dist/config.js ADDED
@@ -0,0 +1,248 @@
1
+ // Checks the directory's settings: workbench/directory.json once the
2
+ // generator has added each kind's form fields. The generator runs these before
3
+ // it writes src/directory.generated.ts, and createDirectory runs them again at
4
+ // startup, so a listing can never be stored against settings that don't hold.
5
+ import { DirectoryError } from "./errors.js";
6
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7
+ const isMoney = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1_000_000 && Math.abs(Math.round(v * 100) - v * 100) < 1e-6;
8
+ const isWhole = (v, min, max) => typeof v === "number" && Number.isInteger(v) && v >= min && v <= max;
9
+ const isText = (v, max) => typeof v === "string" && v.trim().length > 0 && v.length <= max;
10
+ /** Dollars or pesos (15.5) to cents (1550). */
11
+ export const toCents = (amount) => Math.round(amount * 100);
12
+ const KIND_NAME = /^[a-z][a-z0-9_]{0,30}$/;
13
+ const PLAN_NAME = /^[a-z][a-z0-9_-]{0,30}$/;
14
+ export const DEFAULT_MAX_PER_LISTER = 5;
15
+ export const DEFAULT_REMIND_DAYS = 7;
16
+ export const DEFAULT_RETENTION_MONTHS = 12;
17
+ const KIND_KEYS = ["kind", "label", "form", "who_sees", "title", "summary", "category", "place", "website", "search", "filters", "show", "plans", "max_per_lister", "fields", "required"];
18
+ const TOP_KEYS = ["$schema", "format", "country", "currency", "time_zone", "kinds", "remind_days", "retention_months"];
19
+ const PLAN_KEYS = ["plan", "label", "price", "days", "every", "featured"];
20
+ const ROLES = ["title", "summary", "category", "place", "website"];
21
+ function validTimeZone(tz) {
22
+ try {
23
+ new Intl.DateTimeFormat("en", { timeZone: tz });
24
+ return true;
25
+ }
26
+ catch {
27
+ return false;
28
+ }
29
+ }
30
+ /** The fields a kind's page shows: `show`, or every field that isn't a personal detail or one of the name, summary, category, place and website. */
31
+ export function shownFields(k) {
32
+ if (k.show)
33
+ return [...k.show];
34
+ const roles = new Set(ROLES.map((r) => k[r]).filter((f) => typeof f === "string"));
35
+ return Object.keys(k.fields).filter((f) => !roles.has(f) && !k.fields[f].personal);
36
+ }
37
+ /** A kind's plan by name, or undefined. */
38
+ export const planOf = (k, plan) => k.plans.find((p) => p.plan === plan);
39
+ /** The plans as the database functions take them: { plan: { cents, days, every, featured } }. */
40
+ export function plansJson(k) {
41
+ return Object.fromEntries(k.plans.map((p) => [p.plan, { cents: toCents(p.price), days: p.days ?? null, every: p.every ?? null, featured: p.featured === true }]));
42
+ }
43
+ function planProblems(where, plans) {
44
+ const p = [];
45
+ if (!Array.isArray(plans) || plans.length < 1 || plans.length > 6)
46
+ return [`${where}: "plans" must list 1 to 6 ways to pay, such as [{ "plan": "free", "label": "Free listing", "price": 0, "days": null }]`];
47
+ const seen = new Set();
48
+ for (const raw of plans) {
49
+ if (!isObject(raw)) {
50
+ p.push(`${where}: each plan must be an object`);
51
+ continue;
52
+ }
53
+ const name = typeof raw.plan === "string" && PLAN_NAME.test(raw.plan) ? raw.plan : null;
54
+ const at = `${where} plan ${name ?? JSON.stringify(raw.plan)}`;
55
+ if (!name)
56
+ p.push(`${at}: "plan" must be lower case letters, digits, hyphens or underscores, such as "featured"`);
57
+ else if (seen.has(name))
58
+ p.push(`${at}: named twice`);
59
+ else
60
+ seen.add(name);
61
+ for (const k of Object.keys(raw))
62
+ if (!PLAN_KEYS.includes(k))
63
+ p.push(`${at}: unknown setting "${k}"`);
64
+ if (!isText(raw.label, 60))
65
+ p.push(`${at}: "label" is needed, 1 to 60 characters`);
66
+ if (!isMoney(raw.price)) {
67
+ p.push(`${at}: "price" must be 0 or more, with at most 2 decimal places`);
68
+ continue;
69
+ }
70
+ const days = raw.days ?? null;
71
+ if (days !== null && !isWhole(days, 1, 730))
72
+ p.push(`${at}: "days" must be 1 to 730, or null`);
73
+ if (raw.every !== undefined && raw.every !== "month" && raw.every !== "year")
74
+ p.push(`${at}: "every" must be "month" or "year"`);
75
+ if (raw.featured !== undefined && typeof raw.featured !== "boolean")
76
+ p.push(`${at}: "featured" must be true or false`);
77
+ if (raw.price === 0) {
78
+ if (raw.every !== undefined)
79
+ p.push(`${at}: a free plan doesn't repeat, so it has no "every"`);
80
+ if (raw.featured === true)
81
+ p.push(`${at}: a featured spot is paid for, so a free plan can't be featured`);
82
+ }
83
+ else {
84
+ if (raw.every !== undefined && days !== null)
85
+ p.push(`${at}: a paid plan has "days" (paid once) or "every" (paid monthly or yearly), not both`);
86
+ if (raw.every === undefined && days === null)
87
+ p.push(`${at}: a paid plan needs "days" (how long one payment lasts) or "every"`);
88
+ }
89
+ }
90
+ return p;
91
+ }
92
+ function fieldProblems(where, fields, required) {
93
+ if (!isObject(fields) || Object.keys(fields).length === 0)
94
+ return [`${where}: "fields" is missing: run \`npx workbench-directory generate\`, which copies them from the kind's form`];
95
+ const p = [];
96
+ for (const [name, f] of Object.entries(fields)) {
97
+ if (!isObject(f) || !["string", "number", "boolean", "array"].includes(f.type) || typeof f.kind !== "string" || typeof f.description !== "string") {
98
+ p.push(`${where}: field ${name} isn't a form field (type, kind and description)`);
99
+ }
100
+ }
101
+ if (!Array.isArray(required) || !required.every((r) => typeof r === "string" && r in fields))
102
+ p.push(`${where}: "required" must list fields of the form`);
103
+ return p;
104
+ }
105
+ function kindProblems(where0, k) {
106
+ const name = typeof k.kind === "string" && KIND_NAME.test(k.kind) ? k.kind : null;
107
+ const where = `${where0} kind ${name ?? JSON.stringify(k.kind)}`;
108
+ const p = [];
109
+ if (!name)
110
+ p.push(`${where}: "kind" must be lower case letters, digits and underscores, such as "business"`);
111
+ for (const key of Object.keys(k))
112
+ if (!KIND_KEYS.includes(key))
113
+ p.push(`${where}: unknown setting "${key}"`);
114
+ if (!isText(k.label, 60))
115
+ p.push(`${where}: "label" is needed, 1 to 60 characters`);
116
+ if (typeof k.form !== "string" || !/^[a-z][a-z0-9_]*$/.test(k.form))
117
+ p.push(`${where}: "form" is the name of a form in workbench/forms/`);
118
+ if (k.who_sees !== "everyone" && k.who_sees !== "signed_in")
119
+ p.push(`${where}: "who_sees" must be "everyone" or "signed_in"`);
120
+ if (k.max_per_lister !== undefined && !isWhole(k.max_per_lister, 1, 100))
121
+ p.push(`${where}: "max_per_lister" must be 1 to 100`);
122
+ p.push(...planProblems(where, k.plans));
123
+ const fp = fieldProblems(where, k.fields, k.required);
124
+ if (fp.length)
125
+ return [...p, ...fp];
126
+ const fields = k.fields;
127
+ const required = k.required;
128
+ const field = (role, v) => {
129
+ if (v === undefined)
130
+ return null;
131
+ if (typeof v !== "string" || !(v in fields)) {
132
+ p.push(`${where}: "${role}" names ${JSON.stringify(v)}, which isn't a field of form ${String(k.form)}`);
133
+ return null;
134
+ }
135
+ return fields[v];
136
+ };
137
+ if (k.title === undefined)
138
+ p.push(`${where}: "title" names the field that is the listing's name`);
139
+ const title = field("title", k.title);
140
+ if (title && (title.type !== "string" || title.enum))
141
+ p.push(`${where}: "title" must be a text field`);
142
+ if (title && !required.includes(k.title))
143
+ p.push(`${where}: the "title" field ${String(k.title)} must be required in form ${String(k.form)}`);
144
+ const summary = field("summary", k.summary);
145
+ if (summary && (summary.type !== "string" || summary.enum))
146
+ p.push(`${where}: "summary" must be a text field`);
147
+ for (const role of ["category", "place"]) {
148
+ const f = field(role, k[role]);
149
+ if (f && (f.kind !== "choice" || f.type !== "string"))
150
+ p.push(`${where}: "${role}" must be a choice field with one answer`);
151
+ }
152
+ const website = field("website", k.website);
153
+ if (website && (website.type !== "string" || website.enum))
154
+ p.push(`${where}: "website" must be a text field`);
155
+ const list = (key) => {
156
+ const v = k[key];
157
+ if (v === undefined)
158
+ return [];
159
+ if (!Array.isArray(v) || !v.every((x) => typeof x === "string")) {
160
+ p.push(`${where}: "${key}" must be a list of field names`);
161
+ return [];
162
+ }
163
+ for (const x of v)
164
+ if (!(x in fields))
165
+ p.push(`${where}: "${key}" names ${x}, which isn't a field of form ${String(k.form)}`);
166
+ if (new Set(v).size !== v.length)
167
+ p.push(`${where}: "${key}" names a field twice`);
168
+ return v.filter((x) => x in fields);
169
+ };
170
+ for (const f of list("search")) {
171
+ if (fields[f].personal)
172
+ p.push(`${where}: "search" can't include ${f}: it holds a personal detail (${fields[f].personal})`);
173
+ if (fields[f].type === "boolean")
174
+ p.push(`${where}: "search" can't include ${f}: a tick has no words to search (make it a filter)`);
175
+ }
176
+ for (const f of list("filters")) {
177
+ const s = fields[f];
178
+ if (s.kind !== "choice" && s.kind !== "tick")
179
+ p.push(`${where}: "filters" can't include ${f}: only choice and tick fields filter`);
180
+ if (s.personal)
181
+ p.push(`${where}: "filters" can't include ${f}: it holds a personal detail`);
182
+ }
183
+ list("show");
184
+ return p;
185
+ }
186
+ /** Every problem with the settings, or none. */
187
+ export function directoryProblems(input, where = "workbench/directory.json") {
188
+ if (!isObject(input))
189
+ return [`${where}: not a JSON object`];
190
+ const c = input;
191
+ const p = [];
192
+ if (c.format !== 1)
193
+ p.push(`${where}: "format" must be 1`);
194
+ if (typeof c.country !== "string" || !/^[A-Z]{2}$/.test(c.country))
195
+ p.push(`${where}: "country" must be a two-letter code in capitals, such as "AU"`);
196
+ if (typeof c.currency !== "string" || !/^[A-Z]{3}$/.test(c.currency))
197
+ p.push(`${where}: "currency" must be a three-letter code in capitals, such as "AUD"`);
198
+ if (typeof c.time_zone !== "string" || !validTimeZone(c.time_zone))
199
+ p.push(`${where}: "time_zone" must be a time zone name, such as "Australia/Sydney"`);
200
+ if (c.remind_days !== undefined && !isWhole(c.remind_days, 1, 30))
201
+ p.push(`${where}: "remind_days" must be 1 to 30`);
202
+ if (c.retention_months !== undefined && !isWhole(c.retention_months, 1, 60))
203
+ p.push(`${where}: "retention_months" must be 1 to 60`);
204
+ for (const k of Object.keys(c))
205
+ if (!TOP_KEYS.includes(k))
206
+ p.push(`${where}: unknown setting "${k}"`);
207
+ if (!Array.isArray(c.kinds) || c.kinds.length < 1 || c.kinds.length > 10) {
208
+ p.push(`${where}: "kinds" must list 1 to 10 kinds of listing, such as businesses and members`);
209
+ return p;
210
+ }
211
+ const seen = new Set();
212
+ for (const k of c.kinds) {
213
+ if (!isObject(k)) {
214
+ p.push(`${where}: each kind must be an object`);
215
+ continue;
216
+ }
217
+ if (typeof k.kind === "string") {
218
+ if (seen.has(k.kind))
219
+ p.push(`${where}: kind ${k.kind} is named twice`);
220
+ seen.add(k.kind);
221
+ }
222
+ p.push(...kindProblems(where, k));
223
+ }
224
+ return p;
225
+ }
226
+ /** Warnings that don't stop the settings, for the owner to read. */
227
+ export function directoryWarnings(c) {
228
+ const w = [];
229
+ for (const k of c.kinds) {
230
+ if (k.who_sees === "everyone") {
231
+ const personal = shownFields(k).filter((f) => k.fields[f].personal);
232
+ if (personal.length)
233
+ w.push(`${k.label} listings show ${personal.join(", ")} to everyone: each is a personal detail, so the form must say it is shown on the listing.`);
234
+ if (k.fields[k.title].personal)
235
+ w.push(`${k.label} listings are public and named by ${k.title}, a personal detail: think about "who_sees": "signed_in" for a member directory.`);
236
+ }
237
+ if (k.plans.some((p) => p.every))
238
+ w.push(`${k.label} has a plan paid monthly or yearly: it needs the payments tool's repeating payments (workbench-payments 0.3.0).`);
239
+ }
240
+ return w;
241
+ }
242
+ /** The settings, checked; throws naming every problem. */
243
+ export function checkDirectory(c) {
244
+ const problems = directoryProblems(c, "directory config");
245
+ if (problems.length)
246
+ throw new DirectoryError("bad_config", problems.join("\n"));
247
+ return c;
248
+ }