@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/dist/page.js ADDED
@@ -0,0 +1,232 @@
1
+ // The Settings page's body: one section per tool, one small form per
2
+ // setting (Save, and Put back once the owner has changed it), the code form
3
+ // while a checked change waits, and Recent changes. Plain HTML forms that
4
+ // post to one address, so it works with no script. The app puts the body in
5
+ // its own admin shell (workbench-ui's shell({ admin: true })), behind its
6
+ // sign-in, for its admins only. Every element carries a wb-settings-* class
7
+ // (SETTINGS_STYLES).
8
+ import { checkValue, formatMoney, textMax } from "./check.js";
9
+ import { SettingsError } from "./errors.js";
10
+ import { durationText, phrase, settingsWord } from "./words.js";
11
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
12
+ function defaultWhen(timeZone, lang) {
13
+ const f = new Intl.DateTimeFormat(lang === "en" ? "en-AU" : "en-PH", { day: "numeric", month: "short", year: "numeric", hour: "numeric", minute: "2-digit", timeZone });
14
+ return (iso) => f.format(new Date(iso));
15
+ }
16
+ const shown = (v, lang, t, def) => {
17
+ if (v === null || v === undefined)
18
+ return settingsWord("not_set", lang, {}, t);
19
+ if (typeof v === "object")
20
+ return Object.entries(v).map(([name, value]) => `${name}: ${value}`).join(", ");
21
+ const choice = def?.choices?.find((c) => c.value === v);
22
+ if (choice)
23
+ return phrase(choice.label, lang);
24
+ if (def?.type === "money" && typeof v === "number")
25
+ return formatMoney(v, def.currency);
26
+ return String(v);
27
+ };
28
+ /** A duration bound in a problem ("too long: 14d at most") as words: "14 days". */
29
+ function readable(word, values, lang, t) {
30
+ if (!values || (word !== "problem.too_short_time" && word !== "problem.too_long_time"))
31
+ return values;
32
+ return Object.fromEntries(Object.entries(values).map(([k, v]) => [k, durationText(v, lang, t)]));
33
+ }
34
+ function field(s, fid, value, lang, invalid, describedBy) {
35
+ const d = s.def;
36
+ const aria = `${invalid ? ' aria-invalid="true"' : ""} aria-describedby="${describedBy}"`;
37
+ if (d.type === "choice") {
38
+ const opts = (d.choices ?? []).map((c) => `<option value="${esc(c.value)}"${c.value === value ? " selected" : ""}>${esc(phrase(c.label, lang))}</option>`).join("");
39
+ return `<select class="wb-settings-select" id="${fid}" name="value"${aria}>${opts}</select>`;
40
+ }
41
+ if (d.type === "text" && d.lines) {
42
+ return `<textarea class="wb-settings-input wb-settings-lines" id="${fid}" name="value" rows="4" maxlength="${textMax(d)}"${aria}>${esc(value)}</textarea>`;
43
+ }
44
+ const type = d.type === "email" ? "email" : d.type === "whole" ? "number" : "text";
45
+ const extra = d.type === "email"
46
+ ? ' autocomplete="email" spellcheck="false" maxlength="254"'
47
+ : d.type === "whole"
48
+ ? ` inputmode="numeric" step="1"${d.min !== undefined ? ` min="${d.min}"` : ""}${d.max !== undefined ? ` max="${d.max}"` : ""}`
49
+ : d.type === "money"
50
+ ? ' inputmode="decimal" autocomplete="off" maxlength="20"'
51
+ : d.type === "duration"
52
+ ? ' autocomplete="off" spellcheck="false" maxlength="10" placeholder="24h"'
53
+ : ` maxlength="${textMax(d)}"`;
54
+ return `<input class="wb-settings-input" id="${fid}" name="value" type="${type}" value="${esc(value)}"${extra}${aria}>`;
55
+ }
56
+ function source(s, lang, t, when) {
57
+ if (s.from === "owner")
58
+ return settingsWord("from.owner", lang, { by: s.changedBy ?? "", when: s.changedAt ? when(s.changedAt) : "" }, t);
59
+ return settingsWord(s.from === "answers" ? "from.answers" : "from.default", lang, {}, t);
60
+ }
61
+ const carryNote = (s, lang, t) => s.carry === "test_only" ? `<p class="wb-settings-carry">${esc(settingsWord("carry.test_only", lang, {}, t))}</p>` : "";
62
+ /** A map is set where it is chosen (design mode): here it is shown, with Put back. */
63
+ function mapItem(s, o, lang, when, fid, hidden) {
64
+ const t = o.t;
65
+ const entries = s.value && typeof s.value === "object" ? Object.entries(s.value) : [];
66
+ const list = entries.length
67
+ ? `<ul class="wb-settings-map" aria-labelledby="${fid}">${entries.map(([name, value]) => `<li class="wb-settings-map-item">${esc(name)}: ${esc(value)}</li>`).join("")}</ul>`
68
+ : `<p class="wb-settings-empty">${esc(settingsWord("map.empty", lang, {}, t))}</p>`;
69
+ return [
70
+ `<div class="wb-settings-setting"><form class="wb-settings-item" method="post" action="${esc(o.endpoint)}">`,
71
+ hidden,
72
+ `<p class="wb-settings-label" id="${fid}">${esc(phrase(s.def.label, lang))}</p>`,
73
+ s.def.help ? `<p class="wb-settings-help">${esc(phrase(s.def.help, lang))}</p>` : "",
74
+ list,
75
+ `<p class="wb-settings-source">${esc(source(s, lang, t, when))}</p>`,
76
+ carryNote(s, lang, t),
77
+ s.from === "owner" ? `<div class="wb-settings-actions"><button class="wb-settings-put-back" type="submit" name="action" value="put_back">${esc(settingsWord("put_back", lang, {}, t))}</button></div>` : "",
78
+ `</form></div>`,
79
+ ].join("");
80
+ }
81
+ function item(s, o, lang, when) {
82
+ const t = o.t;
83
+ const fid = `wb-settings-${s.tool}-${s.key}`.replace(/_/g, "-");
84
+ const mine = o.outcome && o.outcome.tool === s.tool && o.outcome.key === s.key ? o.outcome : undefined;
85
+ const problem = mine?.problem && !mine.notice && mine.problem.word.startsWith("problem.") ? mine.problem : undefined;
86
+ const value = problem && mine?.typed !== undefined ? mine.typed : s.value === null ? "" : s.def.type === "money" && typeof s.value === "number" ? formatMoney(s.value) : String(s.value);
87
+ const ids = [`${fid}-source`, ...(s.def.help ? [`${fid}-help`] : []), ...(problem ? [`${fid}-problem`] : [])].join(" ");
88
+ const extra = Object.entries(o.fields ?? {})
89
+ .map(([n, v]) => `<input type="hidden" name="${esc(n)}" value="${esc(v)}">`)
90
+ .join("");
91
+ const hidden = `${extra}<input type="hidden" name="tool" value="${esc(s.tool)}"><input type="hidden" name="key" value="${esc(s.key)}">`;
92
+ if (s.def.type === "map")
93
+ return mapItem(s, o, lang, when, fid, hidden);
94
+ const parts = [
95
+ `<form class="wb-settings-item" method="post" action="${esc(o.endpoint)}">`,
96
+ hidden,
97
+ `<label class="wb-settings-label" for="${fid}">${esc(phrase(s.def.label, lang))}</label>`,
98
+ s.def.help ? `<p class="wb-settings-help" id="${fid}-help">${esc(phrase(s.def.help, lang))}</p>` : "",
99
+ field(s, fid, value, lang, Boolean(problem), ids),
100
+ problem ? `<p class="wb-settings-field-problem" id="${fid}-problem" role="alert">${esc(settingsWord(problem.word, lang, readable(problem.word, problem.values, lang, t), t))}</p>` : "",
101
+ `<p class="wb-settings-source" id="${fid}-source">${esc(source(s, lang, t, when))}</p>`,
102
+ carryNote(s, lang, t),
103
+ `<div class="wb-settings-actions">`,
104
+ `<button class="wb-settings-save" type="submit" name="action" value="save">${esc(settingsWord("save", lang, {}, t))}</button>`,
105
+ s.from === "owner" ? `<button class="wb-settings-put-back" type="submit" name="action" value="put_back" formnovalidate>${esc(settingsWord("put_back", lang, {}, t))}</button>` : "",
106
+ `</div></form>`,
107
+ ];
108
+ if (s.pending) {
109
+ const cid = `${fid}-code`;
110
+ const codeProblem = mine?.problem && mine.problem.word.startsWith("code.") ? mine.problem : undefined;
111
+ parts.push(`<form class="wb-settings-pending" method="post" action="${esc(o.endpoint)}">`, hidden, `<p class="wb-settings-pending-note">${esc(settingsWord("pending.sent", lang, { value: String(s.pending.value) }, t))}</p>`, `<label class="wb-settings-label" for="${cid}">${esc(settingsWord("pending.code", lang, {}, t))}</label>`, `<input class="wb-settings-input wb-settings-code" id="${cid}" name="code" type="text" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required${codeProblem ? ` aria-invalid="true" aria-describedby="${cid}-problem"` : ""}>`, codeProblem ? `<p class="wb-settings-field-problem" id="${cid}-problem" role="alert">${esc(settingsWord(codeProblem.word, lang, codeProblem.values, t))}</p>` : "", `<div class="wb-settings-actions"><button class="wb-settings-save" type="submit" name="action" value="confirm">${esc(settingsWord("pending.confirm", lang, {}, t))}</button>`, `<button class="wb-settings-cancel" type="submit" name="action" value="cancel" formnovalidate>${esc(settingsWord("pending.cancel", lang, {}, t))}</button></div>`, `</form>`);
112
+ }
113
+ return `<div class="wb-settings-setting">${parts.join("")}</div>`;
114
+ }
115
+ function historyTable(rows, tools, lang, t, when) {
116
+ const head = `<h2 class="wb-settings-heading">${esc(settingsWord("history.title", lang, {}, t))}</h2>`;
117
+ if (!rows.length)
118
+ return `<section class="wb-settings-history">${head}<p class="wb-settings-empty">${esc(settingsWord("history.empty", lang, {}, t))}</p></section>`;
119
+ const label = (tool, key) => {
120
+ const d = tools.find((x) => x.tool === tool)?.settings.find((x) => x.key === key);
121
+ return d ? phrase(d.label, lang) : `${tool}.${key}`;
122
+ };
123
+ const defOf = (tool, key) => tools.find((x) => x.tool === tool)?.settings.find((x) => x.key === key);
124
+ const th = (k) => `<th class="wb-settings-th" scope="col">${esc(settingsWord(k, lang, {}, t))}</th>`;
125
+ const notSet = settingsWord("history.not_set", lang, {}, t);
126
+ const body = rows
127
+ .map((r) => {
128
+ const d = defOf(r.tool, r.key);
129
+ const from = r.before === null ? notSet : shown(r.before, lang, t, d);
130
+ const change = r.action === "put_back" ? `${settingsWord("history.put_back", lang, {}, t)} (${from})` : `${from} → ${shown(r.after, lang, t, d)}`;
131
+ return `<tr class="wb-settings-row"><td class="wb-settings-td">${esc(when(r.at))}</td><td class="wb-settings-td">${esc(r.by)}</td><td class="wb-settings-td">${esc(label(r.tool, r.key))}</td><td class="wb-settings-td">${esc(change)}</td></tr>`;
132
+ })
133
+ .join("");
134
+ return `<section class="wb-settings-history">${head}<table class="wb-settings-table"><thead><tr>${th("history.col.when")}${th("history.col.who")}${th("history.col.what")}${th("history.col.change")}</tr></thead><tbody>${body}</tbody></table></section>`;
135
+ }
136
+ /** The page's body, for the app's admin shell. */
137
+ export async function renderSettingsPage(settings, o) {
138
+ return drawSettingsPage(settings.tools, await settings.states(), o);
139
+ }
140
+ /**
141
+ * Draws the page from settings already read: the same body as
142
+ * renderSettingsPage, for samples and previews with made-up states.
143
+ */
144
+ export function drawSettingsPage(tools, states, o) {
145
+ const lang = o.lang ?? "en";
146
+ const t = o.t;
147
+ const when = o.when ?? defaultWhen(o.timeZone ?? "Australia/Sydney", lang);
148
+ const top = o.outcome?.notice
149
+ ? `<p class="wb-settings-notice" role="status">${esc(settingsWord(o.outcome.notice.word, lang, o.outcome.notice.values, t))}</p>`
150
+ : o.outcome?.status === 503 && o.outcome.problem
151
+ ? `<p class="wb-settings-problem" role="alert">${esc(settingsWord(o.outcome.problem.word, lang, o.outcome.problem.values, t))}</p>`
152
+ : "";
153
+ const sections = tools
154
+ .map((tool) => {
155
+ const items = states.filter((s) => s.tool === tool.tool).map((s) => item(s, o, lang, when));
156
+ return [
157
+ `<section class="wb-settings-section" aria-labelledby="wb-settings-${esc(tool.tool)}">`,
158
+ `<h2 class="wb-settings-heading" id="wb-settings-${esc(tool.tool)}">${esc(phrase(tool.title, lang))}</h2>`,
159
+ tool.about ? `<p class="wb-settings-about">${esc(phrase(tool.about, lang))}</p>` : "",
160
+ items.join(""),
161
+ `</section>`,
162
+ ].join("");
163
+ })
164
+ .join("");
165
+ return [
166
+ `<div class="wb-settings">`,
167
+ `<h1 class="wb-settings-title">${esc(settingsWord("title", lang, {}, t))}</h1>`,
168
+ `<p class="wb-settings-intro">${esc(settingsWord("intro", lang, {}, t))}</p>`,
169
+ top,
170
+ sections,
171
+ o.history ? historyTable(o.history, tools, lang, t, when) : "",
172
+ `</div>`,
173
+ ].join("");
174
+ }
175
+ /**
176
+ * Does what one of the page's forms asked: save, put back or confirm a code.
177
+ * Give it the posted fields and the signed-in admin's name or email (`by`),
178
+ * after the app's own sign-in and admin check. Render the page again with
179
+ * the outcome (renderSettingsPage's `outcome`) and its status.
180
+ */
181
+ export async function settingsAction(settings, fields, by, opts = {}) {
182
+ const get = (k) => (fields instanceof URLSearchParams ? fields.get(k) : fields[k]) ?? "";
183
+ const tool = get("tool");
184
+ const key = get("key");
185
+ const action = get("action");
186
+ const def = settings.tools.find((x) => x.tool === tool)?.settings.find((x) => x.key === key);
187
+ if (!def || !["save", "put_back", "confirm", "cancel"].includes(action))
188
+ return { status: 422, problem: { word: "problem.text" } };
189
+ const at = { tool, key };
190
+ try {
191
+ if (action === "put_back") {
192
+ await settings.putBack(tool, key, by);
193
+ return { status: 200, ...at, notice: { word: "put_back.done" } };
194
+ }
195
+ if (action === "cancel") {
196
+ await settings.cancel(tool, key);
197
+ return { status: 200, ...at, notice: { word: "pending.cancelled" } };
198
+ }
199
+ if (action === "confirm") {
200
+ const r = await settings.confirm(tool, key, get("code"), by);
201
+ if (r.status === "saved")
202
+ return { status: 200, ...at, notice: { word: "pending.confirmed", values: { value: String(r.value) } } };
203
+ if (r.status === "wrong")
204
+ return { status: 422, ...at, problem: { word: "code.wrong", values: { left: String(r.left) } } };
205
+ return { status: 422, ...at, problem: { word: `code.${r.status}` } };
206
+ }
207
+ const typed = get("value");
208
+ const r = await settings.save(tool, key, typed, by, opts);
209
+ if (r.status === "pending")
210
+ return { status: 200, ...at, notice: { word: "pending.sent", values: { value: String(r.value) } } };
211
+ if (r.status === "unchanged")
212
+ return { status: 200, ...at, notice: { word: "unchanged" } };
213
+ if (r.status === "saved" && r.value === null)
214
+ return { status: 200, ...at, notice: { word: "put_back.done" } };
215
+ return { status: 200, ...at, notice: { word: "saved" } };
216
+ }
217
+ catch (e) {
218
+ if (e instanceof SettingsError && e.code === "bad_value") {
219
+ const c = checkValue(def, get("value"));
220
+ const problem = c.ok
221
+ ? { word: "problem.text" }
222
+ : { word: c.problem, ...(c.words ? { values: { message: phrase(c.words, opts.lang ?? "en") } } : c.values ? { values: c.values } : {}) };
223
+ return { status: 422, ...at, typed: get("value"), problem };
224
+ }
225
+ const owned = { too_soon: "problem.too_soon", too_many: "problem.too_many", send_failed: "problem.send_failed", mailer_needed: "problem.mailer_needed" };
226
+ const word = e instanceof SettingsError ? owned[e.code] : undefined;
227
+ if (word)
228
+ return { status: 422, ...at, typed: get("value"), problem: { word } };
229
+ console.warn(JSON.stringify({ event: "settings_save_failed", tool, key, code: e instanceof SettingsError ? e.code : "unknown" }));
230
+ return { status: 503, ...at, problem: { word: "problem.failed" } };
231
+ }
232
+ }
@@ -0,0 +1,18 @@
1
+ /** One sample: a part of the tool, or one of its layouts. */
2
+ interface ToolSample {
3
+ id: string;
4
+ title: string;
5
+ layout?: string;
6
+ html: () => string;
7
+ }
8
+ /** Every sample of one tool (workbench-ui's ToolSamples). */
9
+ export interface ToolSamples {
10
+ format: 1;
11
+ package: string;
12
+ title: string;
13
+ prefix: string;
14
+ samples: readonly ToolSample[];
15
+ }
16
+ /** Every sample of the Settings page. */
17
+ export declare const SETTINGS_SAMPLES: ToolSamples;
18
+ export {};
@@ -0,0 +1,96 @@
1
+ // The Settings page's samples (docs/look-studio.md §5.1): every part it draws,
2
+ // with made-up settings, for the project's style guide, the look previewer
3
+ // and the visual check. Drawn by the page's own drawer (drawSettingsPage), so
4
+ // a sample can't drift from the real page.
5
+ import { designSettings } from "./design.js";
6
+ import { EMAIL_SETTINGS } from "./email.js";
7
+ import { drawSettingsPage } from "./page.js";
8
+ import { SETTINGS_STYLES } from "./styles.js";
9
+ const [replyTo, fromName] = EMAIL_SETTINGS.settings;
10
+ /** A made-up tool with a choice, so the sample shows a select. */
11
+ const CLASSES = {
12
+ format: 1,
13
+ tool: "classes",
14
+ title: { en: "Classes" },
15
+ about: { en: "How long people can book ahead." },
16
+ settings: [
17
+ {
18
+ key: "book_ahead",
19
+ type: "choice",
20
+ kind: "live",
21
+ label: { en: "Book ahead" },
22
+ help: { en: "How far ahead the timetable opens." },
23
+ choices: [
24
+ { value: "2w", label: { en: "Two weeks" } },
25
+ { value: "4w", label: { en: "Four weeks" } },
26
+ ],
27
+ default: "2w",
28
+ },
29
+ { key: "cancel_until", type: "duration", kind: "live", label: { en: "Cancel online until" }, help: { en: "How long before a class people can still cancel it themselves: 30m, 12h or 2d." }, default: "12h" },
30
+ { key: "drop_in", type: "money", kind: "live", currency: "AUD", min: 0, label: { en: "Drop-in price" }, default: 2500 },
31
+ { key: "opening_words", type: "text", lines: true, max: 2000, kind: "live", label: { en: "Opening hours" }, help: { en: "As your pages show them." } },
32
+ ],
33
+ };
34
+ const [bookAhead, cancelUntil, dropIn, openingWords] = CLASSES.settings;
35
+ const DESIGN = designSettings({
36
+ looks: [{ id: "clean", title: "Clean" }, { id: "calm", title: "Calm" }],
37
+ schemes: [{ id: "light", title: "Light" }, { id: "dark", title: "Dark" }],
38
+ toolLayouts: { bookings: ["list", "cards"], orders: ["grid", "list"] },
39
+ });
40
+ const [look, scheme, layouts] = DESIGN.settings;
41
+ const designed = [
42
+ { tool: "design", key: "look", def: look, value: "calm", from: "owner", changedBy: "maria@saltbush.example", changedAt: "2026-11-24T08:30:00.000Z", carry: "test_only" },
43
+ { tool: "design", key: "scheme", def: scheme, value: null, from: "default", carry: "carried" },
44
+ { tool: "design", key: "layouts", def: layouts, value: { bookings: "cards", "orders@/shop": "list" }, from: "owner", changedBy: "maria@saltbush.example", changedAt: "2026-11-24T08:31:00.000Z", carry: "test_only" },
45
+ ];
46
+ const page = { endpoint: "/admin/settings", timeZone: "Australia/Sydney" };
47
+ const waiting = [
48
+ { tool: "email", key: "reply_to", def: replyTo, value: "hello@saltbush.example", from: "answers", pending: { value: "bookings@saltbush.example", expiresAt: "2026-11-25T09:00:00.000Z" } },
49
+ { tool: "email", key: "from_name", def: fromName, value: "Saltbush Yoga Studio", from: "owner", changedBy: "maria@saltbush.example", changedAt: "2026-11-24T08:30:00.000Z" },
50
+ ];
51
+ const changes = [
52
+ { tool: "email", key: "from_name", action: "save", before: "Saltbush Yoga", after: "Saltbush Yoga Studio", by: "maria@saltbush.example", at: "2026-11-24T08:30:00.000Z" },
53
+ { tool: "email", key: "from_name", action: "put_back", before: "Saltbush", after: null, by: "sam@saltbush.example", at: "2026-11-20T02:15:00.000Z" },
54
+ ];
55
+ const problems = [
56
+ { tool: "email", key: "reply_to", def: replyTo, value: "hello@saltbush.example", from: "answers" },
57
+ { tool: "email", key: "from_name", def: fromName, value: null, from: "default" },
58
+ { tool: "classes", key: "book_ahead", def: bookAhead, value: "2w", from: "default" },
59
+ { tool: "classes", key: "cancel_until", def: cancelUntil, value: "12h", from: "default" },
60
+ { tool: "classes", key: "drop_in", def: dropIn, value: 2500, from: "default" },
61
+ { tool: "classes", key: "opening_words", def: openingWords, value: "Monday to Friday, 6am to 8pm\nSaturday, 7am to noon", from: "owner", changedBy: "maria@saltbush.example", changedAt: "2026-11-24T08:30:00.000Z" },
62
+ ];
63
+ /** Every sample of the Settings page. */
64
+ export const SETTINGS_SAMPLES = {
65
+ format: 1,
66
+ package: SETTINGS_STYLES.package,
67
+ title: "Settings",
68
+ prefix: SETTINGS_STYLES.prefix,
69
+ samples: [
70
+ {
71
+ id: "page",
72
+ title: "Settings, with a new address waiting for its code",
73
+ html: () => drawSettingsPage([EMAIL_SETTINGS], waiting, {
74
+ ...page,
75
+ outcome: { status: 422, tool: "email", key: "reply_to", problem: { word: "code.wrong", values: { left: "4" } } },
76
+ history: changes,
77
+ }),
78
+ },
79
+ {
80
+ id: "saved",
81
+ title: "Just saved, nothing changed yet",
82
+ html: () => drawSettingsPage([EMAIL_SETTINGS, CLASSES], problems, { ...page, outcome: { status: 200, tool: "classes", key: "book_ahead", notice: { word: "saved" } }, history: [] }),
83
+ },
84
+ {
85
+ id: "problems",
86
+ title: "Something to fix, and the store not answering",
87
+ html: () => drawSettingsPage([EMAIL_SETTINGS], problems, { ...page, outcome: { status: 422, tool: "email", key: "reply_to", problem: { word: "problem.email" }, typed: "hello@saltbush" } }) +
88
+ drawSettingsPage([CLASSES], problems, { ...page, outcome: { status: 503, problem: { word: "problem.failed" } } }),
89
+ },
90
+ {
91
+ id: "design",
92
+ title: "Design mode's choices, not yet on the live site",
93
+ html: () => drawSettingsPage([DESIGN], designed, page),
94
+ },
95
+ ],
96
+ };
@@ -0,0 +1,136 @@
1
+ import type { CarriedSetting, SettingChange, SettingsLang, SettingState, SettingValue, ToolSettings } from "./types.ts";
2
+ import { type SettingsStrings } from "./words.ts";
3
+ type DbError = {
4
+ message?: string;
5
+ code?: string;
6
+ details?: string;
7
+ } | null;
8
+ /** The part of a Supabase client settings need. Any supabase-js client fits; use the service client. */
9
+ export interface SettingsClient {
10
+ rpc(fn: string, args: Record<string, unknown>): PromiseLike<{
11
+ data: unknown;
12
+ error: DbError;
13
+ }>;
14
+ }
15
+ /** The part of workbench-email's createMailer(...) settings use, for the code email. */
16
+ export interface SettingsMailer {
17
+ send(mail: {
18
+ to: string | string[];
19
+ subject: string;
20
+ text: string;
21
+ template: string;
22
+ idempotencyKey?: string;
23
+ }): Promise<unknown>;
24
+ }
25
+ export interface SettingsOptions {
26
+ /** The service client. */
27
+ db: SettingsClient;
28
+ /** Every tool's declarations: EMAIL_SETTINGS and the others'. Checked here. */
29
+ tools: readonly ToolSettings[];
30
+ /**
31
+ * The project's answers, by tool: the values from workbench/<tool>.json
32
+ * that a declared setting's `answers` key reads, such as
33
+ * `{ email: { reply_to: "hello@harbour.example" } }`.
34
+ */
35
+ answers?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
36
+ /** createMailer(...), for a checked setting's code. Without it a checked setting can't be changed. */
37
+ mailer?: SettingsMailer;
38
+ /** The app's name, for the code email: "Harbour Physio". */
39
+ appName: string;
40
+ /**
41
+ * How long a read is kept before asking the database again. Default 60
42
+ * seconds: another isolate can use the old value for up to this long after
43
+ * a change.
44
+ */
45
+ cacheMs?: number;
46
+ now?: () => Date;
47
+ /** Six random digits. Only tests pass this. */
48
+ code?: () => string;
49
+ }
50
+ /** What a save did. */
51
+ export type SaveResult = {
52
+ status: "saved";
53
+ value: SettingValue | null;
54
+ } | {
55
+ status: "pending";
56
+ value: SettingValue;
57
+ expiresAt: string;
58
+ } | {
59
+ status: "unchanged";
60
+ };
61
+ /** What a code did. */
62
+ export type ConfirmResult = {
63
+ status: "saved";
64
+ value: SettingValue;
65
+ } | {
66
+ status: "wrong";
67
+ left: number;
68
+ } | {
69
+ status: "expired" | "locked" | "none";
70
+ };
71
+ export interface Settings {
72
+ readonly tools: readonly ToolSettings[];
73
+ /** The value in force: the owner's, else the project's answer, else the tool's default; null when none. */
74
+ get(tool: string, key: string): Promise<SettingValue | null>;
75
+ /** Every declared setting with its value, where it came from and any waiting change, in declaration order. */
76
+ states(): Promise<SettingState[]>;
77
+ /**
78
+ * Saves a value the owner typed. A checked setting emails a code to the new
79
+ * value and waits for confirm. Throws SettingsError bad_value, mailer_needed,
80
+ * too_soon (a code went less than a minute ago), too_many (five in a day) or
81
+ * send_failed (nothing is left waiting).
82
+ */
83
+ save(tool: string, key: string, raw: unknown, by: string, opts?: {
84
+ lang?: SettingsLang;
85
+ t?: SettingsStrings;
86
+ }): Promise<SaveResult>;
87
+ /** Uses a checked setting's waiting value when the code is right. */
88
+ confirm(tool: string, key: string, code: string, by: string): Promise<ConfirmResult>;
89
+ /** Drops a checked change waiting for its code. */
90
+ cancel(tool: string, key: string): Promise<{
91
+ cancelled: boolean;
92
+ }>;
93
+ /** Deletes the owner's value, so the project's answer is used again. */
94
+ putBack(tool: string, key: string, by: string): Promise<{
95
+ changed: boolean;
96
+ }>;
97
+ /** Recent changes, newest first. */
98
+ history(limit?: number): Promise<SettingChange[]>;
99
+ /** Once a day: drops changes older than 90 days and codes past their time. */
100
+ cleanup(): Promise<{
101
+ changes: number;
102
+ pending: number;
103
+ }>;
104
+ /** Forgets this isolate's cached read. */
105
+ forget(): void;
106
+ /**
107
+ * A carried tool's values on this site, to send to the live one: every
108
+ * declared key, with null where the owner hasn't changed it (so the live
109
+ * site puts it back). Run on the test site.
110
+ */
111
+ exportGroup(tool: string): Promise<CarriedSetting[]>;
112
+ /**
113
+ * Sets a carried tool's values from the test site's exportGroup: saves
114
+ * each changed one and puts back each null, recorded as `by`. Every value
115
+ * is checked first, and nothing is written if one fails. Run on the live
116
+ * site, after the owner approved the release.
117
+ */
118
+ importGroup(tool: string, rows: readonly CarriedSetting[], by: string): Promise<{
119
+ changed: number;
120
+ }>;
121
+ /**
122
+ * Records on the test site what the live site now holds (the rows
123
+ * importGroup took), so the page stops saying "On the test site only".
124
+ */
125
+ markCarried(tool: string, rows: readonly CarriedSetting[], by: string): Promise<void>;
126
+ }
127
+ export declare function createSettings(opts: SettingsOptions): Settings;
128
+ /**
129
+ * Gives a tool's `business` callback the owner's reply-to address: the
130
+ * address on the Settings page, else what `base` returns. Bookings, orders,
131
+ * progress, tracker and agreements take this shape.
132
+ */
133
+ export declare function withReplyTo<B extends object, A extends unknown[]>(settings: Settings, base: (...args: A) => B | Promise<B>): (...args: A) => Promise<B & {
134
+ replyTo?: string;
135
+ }>;
136
+ export {};