@mccaskie-labs/workbench-settings 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,37 @@
1
+ # @mccaskie-labs/workbench-settings
2
+
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - New setting types for the tools' owner settings (brief 7, `docs/builder-ready.md` B10):
8
+
9
+ - `duration`: written as tools write it (`30m`, `24h`, `2d`), kept in its shortest spelling, `min` and `max` in minutes. `durationMinutes` gives its length.
10
+ - `money`: typed as an amount ("50", "A$1,250.00"; a comma only groups thousands), kept as whole cents, shown in the setting's `currency` (A$50.00, ₱300.00). `formatMoney` gives the words.
11
+ - `lines: true` on `text`: a box of several lines (a new `wb-settings-lines` class that grows with what is typed), keeping its line breaks, up to 2000 characters (`MAX_LINES_TEXT`), for opening hours or an answer to a common question.
12
+ - A duration's bounds are shown in words ("14 days", `durationText`), and one longest (`textMax`) is used by the field and the check.
13
+ - A setting's `answers` may be a dotted path inside the answers file, such as `invoice.due_days`.
14
+
15
+ ## 0.2.0
16
+
17
+ ### Minor Changes
18
+
19
+ - Design mode's settings (docs/look-studio.md §8):
20
+
21
+ - `designSettings({ looks, schemes, siteLayouts, toolLayouts, check })` declares look, scheme, layout and a `layouts` map keyed by tool or `tool@/path`.
22
+ - A new `map` setting type, shown read only with Put back.
23
+ - A setting's own `check(value)`, run at every save; the words come back on `bad_value` as `error.problem.words`.
24
+ - `carries: true`, with `exportGroup`, `importGroup` and `markCarried`, and the `workbench_settings_carried` table in the one migration, so an approved release takes the test site's design to the live site. The page says "On the test site only" until then.
25
+ - `sameValue`, and three new classes: `wb-settings-carry`, `wb-settings-map` and `wb-settings-map-item`.
26
+
27
+ ## 0.1.1
28
+
29
+ ### Patch Changes
30
+
31
+ - `./samples` (`SETTINGS_SAMPLES`): the Settings page with a new address waiting for its code, just saved, and something to fix, drawn by the new `drawSettingsPage` (the page's body from settings already read), for the style guide and the look previewer.
32
+
33
+ ## 0.1.0
34
+
35
+ ### Minor Changes
36
+
37
+ - First version: one Settings page in the app's admin (`renderSettingsPage`, `settingsAction`), the store in the app's own database (`settingsMigration`, `npx workbench-settings migration`), values worked out as the owner's change over the project's answer over the tool's default (`createSettings`, `settings.get`), Put back, Recent changes kept 90 days, and a new email address proved with an emailed six-digit code (five tries, 24 hours, at most one code a minute and five a day; Cancel; a failed send leaves nothing waiting) before it is used. Email's settings ship here (`EMAIL_SETTINGS`: where replies go, the name emails come from), with `withReplyTo` for tools that take a `business` callback. Words in English, Tagalog and Taglish; every element has a `wb-settings-*` class (`SETTINGS_STYLES`) whose colours, fonts and corners default to the shared theme tokens. The store already takes an object value up to 8 KB, so a later map setting (Design mode's per-tool layouts) needs no new migration.
package/README.md CHANGED
@@ -1,3 +1,55 @@
1
- # Temporary Holding Version
1
+ # @mccaskie-labs/workbench-settings
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
+ One Settings page in a Workbench app's admin, where the app's owner changes the settings Workbench's tools allow, with no code change and no redeploy. The design is `docs/project-settings.md` in the Workbench repo.
4
+
5
+ - Each tool declares its owner settings as data (`ToolSettings`). Email's ship here as `EMAIL_SETTINGS`: where customers' replies go, and the name emails come from.
6
+ - A value is the owner's change, else the project's answer (`workbench/<tool>.json`), else the tool's default. Tools read it when they run: `settings.get("email", "reply_to")`, or `withReplyTo(settings, business)` for a tool that takes a `business` callback.
7
+ - Saves are kept in the app's own database with who made them; Recent changes lists them for 90 days, and Put back returns a setting to how the app was built.
8
+ - A new email address is proved first: a six-digit code is emailed to it and the owner types it in. The old address stays until then. Five tries, 24 hours, at most one code a minute and five a day, and only a hash of the code is stored. Cancel drops a waiting change, and a code email that fails to send leaves nothing waiting.
9
+
10
+ ## Use
11
+
12
+ ```ts
13
+ import { createSettings, EMAIL_SETTINGS, renderSettingsPage, settingsAction, withReplyTo } from "@mccaskie-labs/workbench-settings";
14
+
15
+ const settings = createSettings({ db: serviceClient, tools: [EMAIL_SETTINGS], appName: brand.name, mailer, answers: { email: emailAnswers } });
16
+
17
+ // GET and POST /admin/settings, behind the sign-in and the admins check:
18
+ const outcome = request.method === "POST" ? await settingsAction(settings, new URLSearchParams(await request.text()), admin.email) : undefined;
19
+ const body = await renderSettingsPage(settings, { endpoint: "/admin/settings", outcome, history: await settings.history() });
20
+ ```
21
+
22
+ Refuse a post from another site before calling `settingsAction` (check the Origin, or pass the app's anti-forgery token in `renderSettingsPage`'s `fields`). Then:
23
+
24
+ 1. `npx workbench-settings migration` writes the tables and functions into `supabase/migrations` with a down file.
25
+ 2. Add the email template `settings_code` to the app's email catalogue.
26
+ 3. Call `settings.cleanup()` once a day from the app's cron.
27
+
28
+ ## Types
29
+
30
+ `text` (one line, up to 500 characters; with `lines: true` a box of several lines, up to 2000, for opening hours or an answer to a common question), `email`, `choice`, `whole`, `duration` (as tools write it: `30m`, `24h`, `2d`; `min` and `max` in minutes), `money` (typed as an amount, kept as whole cents, shown in the setting's `currency` as A$50.00; `min` and `max` in cents) and `map` (design mode's). A setting's `answers` may be a dotted path inside the answers file, such as `invoice.due_days`.
31
+
32
+ - A money value from an answers file or a default is whole cents (2500 is A$25.00); typed text is an amount, and a comma only groups thousands ("50,5" is refused).
33
+ - Several-line text keeps its line breaks as `\n`: a tool that shows it on a page escapes it and keeps the breaks (`white-space: pre-line`, or one `<br>` per line).
34
+ - A setting that changes what a customer is charged, or where money or personal details go, is never `live` (`docs/project-settings.md` §5): until the guarded kind is built, leave it out.
35
+
36
+ Restyle the page in the project's `public/styles/project.css` with the `wb-settings-*` classes and `--wb-settings-*` variables (`SETTINGS_STYLES`); they default to the project's theme tokens.
37
+
38
+ ## Design mode (0.2.0)
39
+
40
+ `designSettings({ looks, schemes, siteLayouts, toolLayouts, check })` declares the "design" settings that design mode's "Keep this" saves (`docs/look-studio.md` §8). Pass in the choices: workbench-ui's `LOOKS`, the schemes, and each tool's `ToolStyles.layouts` ids. The settings are:
41
+
42
+ - `look`, `scheme` and `layout`, as choices;
43
+ - `layouts`, a **map** of a tool (`bookings`) or a tool on one page (`orders@/shop`) to a layout id, checked against `toolLayouts` at every save.
44
+
45
+ Read them on every request with `settings.get("design", "look")`. One read covers every setting and is held 60 seconds per isolate.
46
+
47
+ Any `SettingDef` can take a `check(value)` that returns `null`, or the words to show. A refused save throws `bad_value` with `error.problem.words`.
48
+
49
+ The design group is marked `carries: true`. The owner tries values on the test site, and the next release the owner approves takes them to the live site:
50
+
51
+ 1. On the test site, `settings.exportGroup("design")` gives every key, with `null` where the owner hasn't changed it.
52
+ 2. On the live site, `settings.importGroup("design", rows, by)` checks every row, then saves or puts back each one that differs.
53
+ 3. Back on the test site, `settings.markCarried("design", rows, by)` records what the live site now holds.
54
+
55
+ Until step 3, the page says "On the test site only" under each changed value. Workbench never reads the rows. The project's own Worker serves steps 1 to 3 to the release run, behind the project key.
@@ -0,0 +1,40 @@
1
+ import type { SettingDef, SettingValue, ToolSettings, Words } from "./types.ts";
2
+ import type { SettingsWordKey } from "./words.ts";
3
+ /** The longest one-line text any setting may hold. */
4
+ export declare const MAX_TEXT = 500;
5
+ /** The longest text a setting drawn as several lines (`lines: true`) may hold. */
6
+ export declare const MAX_LINES_TEXT = 2000;
7
+ /** A text setting's longest when its declaration gives no `max`: one line, and several lines. */
8
+ export declare const DEFAULT_TEXT_MAX = 200;
9
+ export declare const DEFAULT_LINES_MAX = 1000;
10
+ /** The longest duration any setting may hold: a year, in minutes. */
11
+ export declare const MAX_DURATION_MINUTES = 525600;
12
+ /** The longest a text setting takes, as the check and the page's field both use it. */
13
+ export declare function textMax(def: SettingDef): number;
14
+ /** A duration's length in minutes ("2d" is 2880), or null when it isn't one. */
15
+ export declare function durationMinutes(text: string): number | null;
16
+ /** Cents as the page shows them: 5000 in AUD is "A$50.00"; with no currency, "50.00". */
17
+ export declare function formatMoney(cents: number, currency?: string): string;
18
+ export declare const MAX_EMAIL = 254;
19
+ /** A map's most names, and its largest size as JSON (the store holds up to 8 KB). */
20
+ export declare const MAX_MAP_ENTRIES = 200;
21
+ export declare const MAX_MAP_BYTES = 6000;
22
+ export type Checked = {
23
+ ok: true;
24
+ value: SettingValue | null;
25
+ } | {
26
+ ok: false;
27
+ problem: SettingsWordKey;
28
+ values?: Record<string, string>;
29
+ words?: Words;
30
+ };
31
+ /** True when two values are the same, maps included. */
32
+ export declare function sameValue(a: SettingValue | null | undefined, b: SettingValue | null | undefined): boolean;
33
+ /**
34
+ * Checks what the owner typed for a setting, then the setting's own `check`.
35
+ * Text is trimmed; an empty field means "no value" (null), which only a
36
+ * setting with no `min` above 0 may hold. A map takes an object or its JSON.
37
+ */
38
+ export declare function checkValue(def: SettingDef, raw: unknown): Checked;
39
+ /** Every problem with a set of declarations, or an empty list. */
40
+ export declare function settingsProblems(tools: readonly ToolSettings[]): string[];
package/dist/check.js ADDED
@@ -0,0 +1,263 @@
1
+ // The one check for a declared setting, used by the page and by every save,
2
+ // and the check of the declarations themselves.
3
+ const KEY = /^[a-z][a-z0-9_]{0,39}$/;
4
+ const TOOL = /^[a-z][a-z0-9-]{0,39}$/;
5
+ /** Plain enough for a reply-to address: one @, no spaces or angle brackets, a dot in the domain. */
6
+ const EMAIL = /^[^\s@<>()",;:\\[\]]+@[^\s@<>()",;:\\[\]]+\.[^\s@<>()",;:\\[\]]+$/;
7
+ /** Control, invisible and direction-changing characters never belong in a setting (they could disguise a sender's name). */
8
+ // eslint-disable-next-line no-control-regex
9
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u180e\u200b-\u200f\u2028-\u202e\u2060-\u206f\ufeff]/;
10
+ /** The longest one-line text any setting may hold. */
11
+ export const MAX_TEXT = 500;
12
+ /** The longest text a setting drawn as several lines (`lines: true`) may hold. */
13
+ export const MAX_LINES_TEXT = 2000;
14
+ /** A text setting's longest when its declaration gives no `max`: one line, and several lines. */
15
+ export const DEFAULT_TEXT_MAX = 200;
16
+ export const DEFAULT_LINES_MAX = 1000;
17
+ /** The longest duration any setting may hold: a year, in minutes. */
18
+ export const MAX_DURATION_MINUTES = 525_600;
19
+ /** A duration as tools write them: "30m", "24h", "2d". */
20
+ const DURATION = /^(\d{1,6})\s*(m|h|d)$/;
21
+ const UNIT_MINUTES = { m: 1, h: 60, d: 1440 };
22
+ const CURRENCY = /^[A-Z]{3}$/;
23
+ /** The longest a text setting takes, as the check and the page's field both use it. */
24
+ export function textMax(def) {
25
+ return def.lines ? Math.min(def.max ?? DEFAULT_LINES_MAX, MAX_LINES_TEXT) : Math.min(def.max ?? DEFAULT_TEXT_MAX, MAX_TEXT);
26
+ }
27
+ /** A duration's length in minutes ("2d" is 2880), or null when it isn't one. */
28
+ export function durationMinutes(text) {
29
+ const m = DURATION.exec(text.trim().toLowerCase());
30
+ if (!m)
31
+ return null;
32
+ return Number(m[1]) * UNIT_MINUTES[m[2]];
33
+ }
34
+ /** Cents as the page shows them: 5000 in AUD is "A$50.00"; with no currency, "50.00". */
35
+ export function formatMoney(cents, currency) {
36
+ if (currency && CURRENCY.test(currency)) {
37
+ try {
38
+ return new Intl.NumberFormat("en-US", { style: "currency", currency, minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(cents / 100);
39
+ }
40
+ catch {
41
+ // An unknown code falls through to the plain amount.
42
+ }
43
+ }
44
+ return (cents / 100).toFixed(2);
45
+ }
46
+ /** What an owner typed as an amount ("50", "50.5", "A$1,250.00", "₱300") in cents, or null. */
47
+ function parseMoney(text) {
48
+ const amount = text.replace(/^[A-Za-z]{0,3}\s*[$₱€£¥]?\s*/, "").trim();
49
+ // A comma only ever groups thousands ("1,250"): "50,5" is refused, never read as 505.
50
+ if (!/^(\d{1,3}(,\d{3})+|\d{1,9})(\.\d{1,2})?$/.test(amount))
51
+ return null;
52
+ const m = /^(\d{1,9})(?:\.(\d{1,2}))?$/.exec(amount.replace(/,/g, ""));
53
+ if (!m)
54
+ return null;
55
+ return Number(m[1]) * 100 + Number((m[2] ?? "0").padEnd(2, "0"));
56
+ }
57
+ export const MAX_EMAIL = 254;
58
+ /** A map's most names, and its largest size as JSON (the store holds up to 8 KB). */
59
+ export const MAX_MAP_ENTRIES = 200;
60
+ export const MAX_MAP_BYTES = 6000;
61
+ /** A map's name: a tool, or a tool on one page (`orders@/shop`). */
62
+ const MAP_NAME = /^[a-z][a-z0-9-]{0,39}(@\/[A-Za-z0-9/_.~-]{0,200})?$/;
63
+ /** A map's value: a name such as a layout's id. */
64
+ const MAP_VALUE = /^[a-z][a-z0-9-]{0,39}$/;
65
+ /** A map's names in a fixed order, so two equal maps store and compare the same. */
66
+ function checkMap(raw) {
67
+ let v = raw;
68
+ if (typeof v === "string") {
69
+ if (!v.trim())
70
+ return { ok: true, value: null };
71
+ try {
72
+ v = JSON.parse(v);
73
+ }
74
+ catch {
75
+ return { ok: false, problem: "problem.map" };
76
+ }
77
+ }
78
+ if (typeof v !== "object" || v === null || Array.isArray(v))
79
+ return { ok: false, problem: "problem.map" };
80
+ const entries = Object.entries(v);
81
+ if (!entries.length)
82
+ return { ok: true, value: null };
83
+ if (entries.length > MAX_MAP_ENTRIES)
84
+ return { ok: false, problem: "problem.map" };
85
+ const out = {};
86
+ for (const [name, value] of entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
87
+ if (!MAP_NAME.test(name) || typeof value !== "string" || !MAP_VALUE.test(value))
88
+ return { ok: false, problem: "problem.map" };
89
+ out[name] = value;
90
+ }
91
+ if (new TextEncoder().encode(JSON.stringify(out)).length > MAX_MAP_BYTES)
92
+ return { ok: false, problem: "problem.map" };
93
+ return { ok: true, value: Object.freeze(out) };
94
+ }
95
+ /** True when two values are the same, maps included. */
96
+ export function sameValue(a, b) {
97
+ if (a === b)
98
+ return true;
99
+ if (a === null || a === undefined || b === null || b === undefined)
100
+ return false;
101
+ return typeof a === "object" && typeof b === "object" && JSON.stringify(a) === JSON.stringify(b);
102
+ }
103
+ /**
104
+ * Checks what the owner typed for a setting, then the setting's own `check`.
105
+ * Text is trimmed; an empty field means "no value" (null), which only a
106
+ * setting with no `min` above 0 may hold. A map takes an object or its JSON.
107
+ */
108
+ export function checkValue(def, raw) {
109
+ const c = checkType(def, raw);
110
+ if (!c.ok || c.value === null || !def.check)
111
+ return c;
112
+ let words;
113
+ try {
114
+ words = def.check(c.value);
115
+ }
116
+ catch {
117
+ return { ok: false, problem: "problem.text" };
118
+ }
119
+ return words ? { ok: false, problem: "problem.check", words } : c;
120
+ }
121
+ function checkType(def, raw) {
122
+ if (raw === null || raw === undefined)
123
+ return { ok: true, value: null };
124
+ if (def.type === "map")
125
+ return checkMap(raw);
126
+ // A box of several lines keeps its line breaks (as \n, whatever the browser sent); no other control character is allowed.
127
+ const lines = def.type === "text" && def.lines === true;
128
+ const text = typeof raw === "number" ? String(raw) : typeof raw === "string" ? (lines ? raw.replace(/\r\n?/g, "\n") : raw).trim() : null;
129
+ if (text === null)
130
+ return { ok: false, problem: "problem.text" };
131
+ if (text === "")
132
+ return (def.min ?? 0) > 0 && def.type !== "whole" ? { ok: false, problem: "problem.required" } : { ok: true, value: null };
133
+ if (CONTROL.test(lines ? text.replace(/\n/g, "") : text))
134
+ return { ok: false, problem: "problem.text" };
135
+ switch (def.type) {
136
+ case "text": {
137
+ const max = textMax(def);
138
+ const min = def.min ?? 1;
139
+ const n = [...text].length;
140
+ if (n > max)
141
+ return { ok: false, problem: "problem.too_long", values: { max: String(max) } };
142
+ if (n < min)
143
+ return { ok: false, problem: "problem.too_short", values: { min: String(min) } };
144
+ return { ok: true, value: text };
145
+ }
146
+ case "email": {
147
+ if (text.length > MAX_EMAIL || !EMAIL.test(text))
148
+ return { ok: false, problem: "problem.email" };
149
+ // Domains are case-blind; the local part is left as typed.
150
+ const at = text.lastIndexOf("@");
151
+ return { ok: true, value: `${text.slice(0, at)}@${text.slice(at + 1).toLowerCase()}` };
152
+ }
153
+ case "choice": {
154
+ if (!def.choices?.some((c) => c.value === text))
155
+ return { ok: false, problem: "problem.choice" };
156
+ return { ok: true, value: text };
157
+ }
158
+ case "whole": {
159
+ if (!/^-?\d{1,12}$/.test(text))
160
+ return { ok: false, problem: "problem.whole" };
161
+ const n = Number(text);
162
+ if (def.min !== undefined && n < def.min)
163
+ return { ok: false, problem: "problem.too_small", values: { min: String(def.min) } };
164
+ if (def.max !== undefined && n > def.max)
165
+ return { ok: false, problem: "problem.too_big", values: { max: String(def.max) } };
166
+ return { ok: true, value: n };
167
+ }
168
+ case "duration": {
169
+ const n = durationMinutes(text);
170
+ if (n === null || n > MAX_DURATION_MINUTES)
171
+ return { ok: false, problem: "problem.duration" };
172
+ if (def.min !== undefined && n < def.min)
173
+ return { ok: false, problem: "problem.too_short_time", values: { min: durationWords(def.min) } };
174
+ if (def.max !== undefined && n > def.max)
175
+ return { ok: false, problem: "problem.too_long_time", values: { max: durationWords(def.max) } };
176
+ const m = DURATION.exec(text.trim().toLowerCase());
177
+ return { ok: true, value: `${Number(m[1])}${m[2]}` };
178
+ }
179
+ case "money": {
180
+ // A number from a file or a default is already cents; typed text is an amount.
181
+ const n = typeof raw === "number" ? (Number.isSafeInteger(raw) && raw >= 0 ? raw : null) : parseMoney(text);
182
+ if (n === null)
183
+ return { ok: false, problem: "problem.money" };
184
+ if (def.min !== undefined && n < def.min)
185
+ return { ok: false, problem: "problem.too_small", values: { min: formatMoney(def.min, def.currency) } };
186
+ if (def.max !== undefined && n > def.max)
187
+ return { ok: false, problem: "problem.too_big", values: { max: formatMoney(def.max, def.currency) } };
188
+ return { ok: true, value: n };
189
+ }
190
+ default:
191
+ return { ok: false, problem: "problem.text" };
192
+ }
193
+ }
194
+ /** Minutes as a duration's own shortest spelling: 2880 is "2d", 90 is "90m". */
195
+ function durationWords(minutes) {
196
+ if (minutes % 1440 === 0)
197
+ return `${minutes / 1440}d`;
198
+ if (minutes % 60 === 0)
199
+ return `${minutes / 60}h`;
200
+ return `${minutes}m`;
201
+ }
202
+ /** Every problem with a set of declarations, or an empty list. */
203
+ export function settingsProblems(tools) {
204
+ const out = [];
205
+ const seen = new Set();
206
+ for (const t of tools) {
207
+ const at = `settings for ${t.tool}`;
208
+ if (t.format !== 1)
209
+ out.push(`${at}: format must be 1`);
210
+ if (!TOOL.test(t.tool))
211
+ out.push(`${at}: tool must be lower case letters, digits and dashes`);
212
+ if (seen.has(t.tool))
213
+ out.push(`${at}: declared twice`);
214
+ seen.add(t.tool);
215
+ if (!t.title?.en)
216
+ out.push(`${at}: title.en is missing`);
217
+ const keys = new Set();
218
+ if (!t.settings.length)
219
+ out.push(`${at}: no settings`);
220
+ for (const s of t.settings) {
221
+ const where = `${at}: ${s.key}`;
222
+ if (!KEY.test(s.key))
223
+ out.push(`${where}: key must be lower case letters, digits and underscores`);
224
+ if (keys.has(s.key))
225
+ out.push(`${where}: declared twice`);
226
+ keys.add(s.key);
227
+ if (!s.label?.en)
228
+ out.push(`${where}: label.en is missing`);
229
+ if (s.personal && s.kind === "live")
230
+ out.push(`${where}: decides where personal information goes, so it can't be live: make it checked`);
231
+ if (s.kind === "checked" && s.type !== "email")
232
+ out.push(`${where}: only an email address can be checked (by an emailed code)`);
233
+ if (t.carries && s.kind === "checked")
234
+ out.push(`${where}: a carried tool can't hold a checked setting (a code proves an address on one site only)`);
235
+ if (s.type === "map" && s.default !== undefined && s.default !== null)
236
+ out.push(`${where}: a map has no default: leave it out`);
237
+ if (s.check !== undefined && typeof s.check !== "function")
238
+ out.push(`${where}: check must be a function`);
239
+ if (s.type === "choice" && !(s.choices && s.choices.length >= 2))
240
+ out.push(`${where}: a choice needs at least two choices`);
241
+ if (s.type !== "choice" && s.choices)
242
+ out.push(`${where}: only a choice has choices`);
243
+ for (const [name, n] of [["min", s.min], ["max", s.max]])
244
+ if (n !== undefined && !Number.isSafeInteger(n))
245
+ out.push(`${where}: ${name} must be a whole number`);
246
+ if (s.type === "text" && s.max !== undefined && (s.max < 1 || s.max > (s.lines ? MAX_LINES_TEXT : MAX_TEXT)))
247
+ out.push(`${where}: max must be 1 to ${s.lines ? MAX_LINES_TEXT : MAX_TEXT}`);
248
+ if (s.lines !== undefined && s.type !== "text")
249
+ out.push(`${where}: only text can be drawn as lines`);
250
+ if (s.currency !== undefined && (s.type !== "money" || !CURRENCY.test(s.currency)))
251
+ out.push(`${where}: currency is a three-letter code, on money only`);
252
+ if (s.type === "duration" && s.max !== undefined && (s.max < 1 || s.max > MAX_DURATION_MINUTES))
253
+ out.push(`${where}: max must be 1 to ${MAX_DURATION_MINUTES} minutes`);
254
+ if ((s.type === "duration" || s.type === "money") && s.min !== undefined && s.min < 0)
255
+ out.push(`${where}: min can't be below 0`);
256
+ if (s.min !== undefined && s.max !== undefined && s.min > s.max)
257
+ out.push(`${where}: min is above max`);
258
+ if (s.default !== undefined && s.default !== null && !checkValue(s, s.default).ok)
259
+ out.push(`${where}: its default doesn't pass its own check`);
260
+ }
261
+ }
262
+ return out;
263
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ /** Runs one command; returns the exit code. */
3
+ export declare function run(argv: string[], log?: (s: string) => void, err?: (s: string) => void, now?: () => Date): number;
package/dist/cli.js ADDED
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ // `npx workbench-settings migration [dir]`, run in a project's folder: writes
3
+ // settingsMigration into supabase/migrations/<timestamp>_workbench_settings.sql,
4
+ // and its down file into supabase/rollback/, unless a settings migration is
5
+ // already there.
6
+ import { existsSync, mkdirSync, readdirSync, realpathSync, writeFileSync } from "node:fs";
7
+ import { join, resolve } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { settingsMigration } from "./migration.js";
10
+ const USAGE = "usage: workbench-settings migration [dir]";
11
+ function migrationStamp(at) {
12
+ return at.toISOString().replace(/[-:T]/g, "").slice(0, 14);
13
+ }
14
+ /** Runs one command; returns the exit code. */
15
+ export function run(argv, log = console.log, err = console.error, now = () => new Date()) {
16
+ const [command, ...rest] = argv;
17
+ if (command !== "migration" || rest.length > 1 || rest.some((a) => a.startsWith("--"))) {
18
+ err(USAGE);
19
+ return 2;
20
+ }
21
+ try {
22
+ const dir = resolve(rest[0] ?? ".");
23
+ const folder = join(dir, "supabase/migrations");
24
+ if (existsSync(folder) && readdirSync(folder).some((f) => f.endsWith("_workbench_settings.sql"))) {
25
+ log("supabase/migrations already has the settings migration; nothing written");
26
+ return 0;
27
+ }
28
+ const name = `${migrationStamp(now())}_workbench_settings.sql`;
29
+ mkdirSync(folder, { recursive: true });
30
+ mkdirSync(join(dir, "supabase/rollback"), { recursive: true });
31
+ writeFileSync(join(folder, name), `-- workbench-settings: the owner's Settings page\n${settingsMigration.up}`);
32
+ writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${settingsMigration.down}`);
33
+ log(`wrote supabase/migrations/${name} and its down file`);
34
+ return 0;
35
+ }
36
+ catch (e) {
37
+ err(e.message);
38
+ return 1;
39
+ }
40
+ }
41
+ const isMain = (() => {
42
+ try {
43
+ return process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ })();
49
+ if (isMain)
50
+ process.exitCode = run(process.argv.slice(2));
@@ -0,0 +1,20 @@
1
+ import type { ToolSettings, Words } from "./types.ts";
2
+ /** One thing to choose from: an id and its name. */
3
+ export interface DesignChoice {
4
+ id: string;
5
+ title: string | Words;
6
+ }
7
+ export interface DesignOptions {
8
+ /** The looks (workbench-ui's LOOKS): Clean, Warm, Calm... */
9
+ looks: readonly DesignChoice[];
10
+ /** The colour schemes: light and dark. */
11
+ schemes: readonly DesignChoice[];
12
+ /** The site's page layouts. Leave out when the site has one. */
13
+ siteLayouts?: readonly DesignChoice[];
14
+ /** Each tool's layouts by tool id (its ToolStyles.layouts), for the layouts map. */
15
+ toolLayouts: Readonly<Record<string, readonly string[]>>;
16
+ /** A check on the look and scheme together, such as the contrast fixer's. Null to accept. */
17
+ check?: (key: "look" | "scheme" | "layout", value: string) => Words | null;
18
+ }
19
+ /** The "design" settings, from the looks, schemes and layouts the app has. */
20
+ export declare function designSettings(o: DesignOptions): ToolSettings;
package/dist/design.js ADDED
@@ -0,0 +1,59 @@
1
+ // Design mode's settings (docs/look-studio.md §8): the look, the colour
2
+ // scheme, the site layout and each tool's layout that an admin chose with
3
+ // "Keep this" on the test site. They carry: an approved release takes them to
4
+ // the live site (settings.exportGroup, importGroup, markCarried).
5
+ //
6
+ // The choices come from the caller (workbench-ui's LOOKS and each tool's
7
+ // ToolStyles.layouts), so this package depends on neither. A layout is
8
+ // checked against the tool's own list at every save; a tool or layout the
9
+ // app no longer has is refused, and a stored one is ignored.
10
+ const words = (t) => (typeof t === "string" ? { en: t } : t);
11
+ const choices = (list) => list.map((c) => ({ value: c.id, label: words(c.title) }));
12
+ const NOT_A_LAYOUT = {
13
+ en: "One of those layouts isn't one this site has. Choose it again in design mode.",
14
+ tl: "Ang isa sa mga layout na iyan ay wala sa site na ito. Piliin ulit sa design mode.",
15
+ taglish: "Isa sa mga layout na yan ay wala sa site na ito. Piliin ulit sa design mode.",
16
+ };
17
+ /** The "design" settings, from the looks, schemes and layouts the app has. */
18
+ export function designSettings(o) {
19
+ const outer = o.check;
20
+ const checkOf = (key) => (outer ? { check: (v) => (typeof v === "string" ? outer(key, v) : null) } : {});
21
+ const layouts = (v) => {
22
+ for (const [name, layout] of Object.entries(v)) {
23
+ const tool = name.split("@")[0];
24
+ if (!o.toolLayouts[tool]?.includes(layout))
25
+ return NOT_A_LAYOUT;
26
+ }
27
+ return null;
28
+ };
29
+ return {
30
+ format: 1,
31
+ tool: "design",
32
+ carries: true,
33
+ title: { en: "Design", tl: "Disenyo", taglish: "Design" },
34
+ about: {
35
+ en: "The look and layouts chosen in design mode. Try them on the test site; the live site gets them with the next release you approve.",
36
+ tl: "Ang itsura at mga layout na pinili sa design mode. Subukan sa test site; makukuha ito ng live site sa susunod na release na aaprubahan mo.",
37
+ taglish: "Ang look at layouts na pinili sa design mode. I-try sa test site; makukuha ito ng live site sa next release na i-approve mo.",
38
+ },
39
+ settings: [
40
+ { key: "look", type: "choice", kind: "live", label: { en: "Look", tl: "Itsura", taglish: "Look" }, choices: choices(o.looks), ...checkOf("look") },
41
+ { key: "scheme", type: "choice", kind: "live", label: { en: "Colours", tl: "Mga kulay", taglish: "Colours" }, choices: choices(o.schemes), ...checkOf("scheme") },
42
+ ...(o.siteLayouts && o.siteLayouts.length >= 2
43
+ ? [{ key: "layout", type: "choice", kind: "live", label: { en: "Page layout", tl: "Ayos ng page", taglish: "Page layout" }, choices: choices(o.siteLayouts), ...checkOf("layout") }]
44
+ : []),
45
+ {
46
+ key: "layouts",
47
+ type: "map",
48
+ kind: "live",
49
+ label: { en: "Tool layouts", tl: "Ayos ng mga tool", taglish: "Tool layouts" },
50
+ help: {
51
+ en: "How each tool is laid out, on every page or on one. Change these in design mode.",
52
+ tl: "Kung paano nakaayos ang bawat tool, sa lahat ng page o sa isa. Baguhin ito sa design mode.",
53
+ taglish: "Kung paano naka-layout ang bawat tool, sa lahat ng page o sa isa. I-change ito sa design mode.",
54
+ },
55
+ check: layouts,
56
+ },
57
+ ],
58
+ };
59
+ }
@@ -0,0 +1,2 @@
1
+ import type { ToolSettings } from "./types.ts";
2
+ export declare const EMAIL_SETTINGS: ToolSettings;
package/dist/email.js ADDED
@@ -0,0 +1,46 @@
1
+ // The email settings an owner may change: where customers' replies go, and
2
+ // the name emails come from. Email is plumbing every tool sends through, so
3
+ // its declarations ship here; other tools ship their own next to their code
4
+ // (docs/project-settings.md §3).
5
+ //
6
+ // The app reads them where it builds its mailer and its tools:
7
+ // from: { address, name: (await settings.get("email", "from_name")) ?? brand.name }
8
+ // business: withReplyTo(settings, async () => ({ name: brand.name }))
9
+ export const EMAIL_SETTINGS = {
10
+ format: 1,
11
+ tool: "email",
12
+ title: { en: "Emails", tl: "Mga email", taglish: "Emails" },
13
+ about: {
14
+ en: "How the emails your app sends to customers look to them, and where their replies go.",
15
+ tl: "Kung paano lumalabas sa mga customer ang mga email ng app mo, at kung saan napupunta ang mga sagot nila.",
16
+ taglish: "Kung paano lumalabas sa customers ang emails ng app mo, at saan napupunta ang replies nila.",
17
+ },
18
+ settings: [
19
+ {
20
+ key: "reply_to",
21
+ type: "email",
22
+ kind: "checked",
23
+ personal: true,
24
+ answers: "reply_to",
25
+ label: { en: "Replies go to", tl: "Saan napupunta ang mga sagot", taglish: "Saan napupunta ang replies" },
26
+ help: {
27
+ en: "When a customer presses Reply on one of your app's emails, it goes to this address. We email a code to a new address first, to make sure it's right.",
28
+ tl: "Kapag pinindot ng customer ang Reply sa email ng app mo, dito ito mapupunta. Mag-e-email muna kami ng code sa bagong address para masigurong tama ito.",
29
+ taglish: "Pag nag-Reply ang customer sa email ng app mo, dito ito mapupunta. Mag-e-email muna kami ng code sa bagong address para sure na tama.",
30
+ },
31
+ },
32
+ {
33
+ key: "from_name",
34
+ type: "text",
35
+ kind: "live",
36
+ max: 60,
37
+ answers: "from_name",
38
+ label: { en: "Emails come from", tl: "Pangalan ng nagpapadala", taglish: "Pangalan ng sender" },
39
+ help: {
40
+ en: "The name customers see beside your emails in their inbox, such as your business's name. Left empty, it's your brand name.",
41
+ tl: "Ang pangalang nakikita ng mga customer sa tabi ng mga email mo sa inbox nila, gaya ng pangalan ng negosyo mo. Kung walang laman, ang pangalan ng brand mo.",
42
+ taglish: "Ang name na nakikita ng customers sa tabi ng emails mo sa inbox nila, like ang name ng business mo. Kung empty, ang brand name mo.",
43
+ },
44
+ },
45
+ ],
46
+ };
@@ -0,0 +1,31 @@
1
+ export type SettingsErrorCode =
2
+ /** A tool's declarations are out of shape (settingsProblems names each problem). */
3
+ "bad_declaration"
4
+ /** No such tool or setting among the declarations given to createSettings. */
5
+ | "unknown_setting"
6
+ /** The value doesn't pass the setting's check. */
7
+ | "bad_value"
8
+ /** A checked setting needs a mailer to send its code, and none was given. */
9
+ | "mailer_needed"
10
+ /** A code was sent for this setting less than a minute ago. */
11
+ | "too_soon"
12
+ /** Five codes were sent for this setting in the last day. */
13
+ | "too_many"
14
+ /** The code email couldn't be sent; nothing is left waiting. */
15
+ | "send_failed"
16
+ /** A call's arguments are out of shape (the admin's name). */
17
+ | "bad_input"
18
+ /** The database refused or failed. */
19
+ | "store_failed";
20
+ export declare class SettingsError extends Error {
21
+ readonly code: SettingsErrorCode;
22
+ /** For bad_value: what's wrong, in the page's words (a SettingsWordKey) and its values. */
23
+ readonly problem?: {
24
+ word: string;
25
+ values?: Readonly<Record<string, string>>;
26
+ words?: {
27
+ en: string;
28
+ } & Partial<Record<string, string>>;
29
+ };
30
+ constructor(code: SettingsErrorCode, message: string, problem?: SettingsError["problem"]);
31
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,14 @@
1
+ // Every failure carries a permanent code, so an app can act on it without
2
+ // reading the words. Messages never hold a value an owner typed.
3
+ export class SettingsError extends Error {
4
+ code;
5
+ /** For bad_value: what's wrong, in the page's words (a SettingsWordKey) and its values. */
6
+ problem;
7
+ constructor(code, message, problem) {
8
+ super(message);
9
+ this.name = "SettingsError";
10
+ this.code = code;
11
+ if (problem)
12
+ this.problem = problem;
13
+ }
14
+ }