From cbc1e32422e6d71c1efd6e3af3009050d15bbe49 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 12 Jul 2026 12:09:31 +0000 Subject: [PATCH 1/3] Lower jscpd minTokens to 22 and remove all resulting duplication Tightens the src/scripts/e2e jscpd config (.jscpd.json) from a 23-token to a 22-token minimum. Because jscpd seeds on a fixed window, that one-token drop surfaced 116 new near-duplicate spans that were previously just under the bar. This removes every one of them so the 0% threshold still holds. Most fixes fall into three shapes, matching how the duplication was really shaped: - Shared types: where two places repeated the same field list or the same function signature, they now share one `type`/`interface`/function-type alias (e.g. WriteInputs, StatementLinks, OrderSpan, SnapshotArgsFn, the settings-registry pruning shape). - Shared helpers/components: genuinely repeated logic was lifted into one plain-language helper or curried factory, and repeated markup into one small component (e.g. errorMessage, withLazyLogger, streamChunks, nonBlankLines, HeaderRow, LabelledParas, HiddenDetailRow, AgentHeader, moneyInto/moneyOutOf). - Import blocks: the few coincidental matches that were only shared import lines are wrapped in the sanctioned jscpd:ignore. Also unifies two overlaps the split surfaced: the duplicate-group form's inputs now reuse the shared TextField (via optional autofocus/required/duplicate flags) instead of a parallel DuplicateField, and admin list tables that lead with a Name column use a namedColumns helper so that column is declared once. No behaviour changes. Existing tests cover every extraction; the attendees hardcoded-string allowlist ratchets 5 -> 4 to reflect the smaller template. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01BaLTxRDzaxxQu7xm12khNK --- .jscpd.json | 2 +- e2e-payments/src/flow.ts | 23 +++-- e2e-payments/src/order-flow.ts | 32 +++---- scripts/bench/bunny-crypto-smoke.ts | 5 +- .../bench/cold-start/first-request-child.ts | 4 +- scripts/bench/cold-start/first-request.ts | 4 +- scripts/bench/cold-start/serve-root.ts | 12 +++ scripts/bunny-regions.ts | 9 +- scripts/edge-bundle-lib.ts | 56 ++++++------ scripts/mutation/isolation-state.ts | 19 ++-- scripts/mutation/isolation.ts | 31 +++---- scripts/mutation/runner.ts | 17 ++-- scripts/mutation/summary.ts | 29 +++++-- scripts/precommit/git.ts | 18 ++-- scripts/precommit/mutation-step.ts | 7 +- scripts/stream-lines.ts | 8 +- scripts/stripe-mock.ts | 3 +- scripts/stripe-mock/install.ts | 5 +- scripts/unit-tests-report-lib.ts | 69 ++++++++------- src/features/admin/actions.ts | 14 +-- src/features/admin/api.ts | 20 +++-- src/features/admin/attendee-form-routes.ts | 6 +- .../admin/attendee-logistics-routes.ts | 2 + src/features/admin/attendee-page-data.ts | 14 +-- src/features/admin/attendees-edit.ts | 2 + src/features/admin/attendees-merge.ts | 10 +-- src/features/admin/catalog-transfer/export.ts | 71 ++++++++------- src/features/admin/catalog-transfer/import.ts | 10 +-- src/features/admin/dashboard.ts | 6 +- src/features/admin/find-group.ts | 15 ++++ src/features/admin/groups.ts | 15 ++-- src/features/admin/listing-page-data.ts | 47 +++++----- src/features/admin/listing-qr.ts | 11 +-- src/features/admin/listings-edit.ts | 29 ++++--- src/features/admin/listings-view.ts | 2 +- src/features/admin/load-listing.ts | 21 +++++ src/features/admin/modifiers.ts | 7 +- src/features/admin/money-adjust.ts | 34 +++++--- src/features/admin/news.ts | 24 ++--- .../admin/settings-email-templates.ts | 70 ++++++++------- src/features/admin/settings-email.ts | 2 + src/features/admin/settings-sms.ts | 2 + src/features/admin/settings-statuses.ts | 34 +++++--- src/features/admin/site-content-create.ts | 43 +++++++++ src/features/admin/site-content.ts | 2 + src/features/admin/site-pages.ts | 28 +++--- src/features/api/helpers.ts | 5 +- src/features/api/json-body.ts | 6 ++ src/features/api/listings.ts | 2 + src/features/auth.ts | 30 +++++-- src/features/feeds.ts | 5 +- src/features/flash-for-page.ts | 11 +++ src/features/index.ts | 4 +- src/features/join.ts | 30 ++++--- src/features/public/discovery.ts | 3 +- src/features/public/ticket-page-url.ts | 7 ++ src/features/public/ticket-payment.ts | 17 ++-- src/features/public/ticket-submit.ts | 4 +- src/features/public/ticket-submit/paths.ts | 7 +- src/features/public/unsubscribe.ts | 7 +- src/shared/accounting/manual-entries.ts | 32 ++++--- src/shared/app-forms.ts | 15 ++-- src/shared/booking/capacity-tree.ts | 26 +++--- src/shared/booking/fold-tree.ts | 29 +++---- src/shared/booking/node-order.ts | 21 +++++ src/shared/booking/order-lines.ts | 19 ++-- src/shared/booking/order-span.ts | 10 +++ src/shared/booking/package-cap.ts | 17 ++-- src/shared/booking/price-tree.ts | 17 ++-- src/shared/bunny-cdn.ts | 18 ++-- src/shared/columns/attendee-columns.ts | 13 ++- src/shared/dates.ts | 13 ++- src/shared/db/attendees/balance.ts | 2 + src/shared/db/attendees/create.ts | 30 ++++--- src/shared/db/attributes.ts | 4 +- src/shared/db/client.ts | 13 +-- src/shared/db/groups.ts | 6 +- src/shared/db/holidays.ts | 5 +- src/shared/db/id-and-name-columns.ts | 13 +++ src/shared/db/listing-parents.ts | 6 +- src/shared/db/migrations.ts | 21 +++-- .../2026-06-14_rename_events_to_listings.ts | 3 + .../2026-06-18_contact_preferences.ts | 21 +++-- .../db/migrations/booking-slot-index.ts | 12 +-- src/shared/db/migrations/master-query.ts | 15 ++++ src/shared/db/migrations/rename-utils.ts | 13 +-- src/shared/db/migrations/schema-sync.ts | 26 +++--- src/shared/db/modifier-resolve.ts | 24 +++-- src/shared/db/news-posts.ts | 9 +- src/shared/db/query-log.ts | 9 +- .../db/questions/attendee-answers/save.ts | 47 +++++----- src/shared/db/settings.ts | 64 +++++++------- src/shared/db/settings/raw-writes.ts | 6 +- src/shared/db/site-pages.ts | 9 +- src/shared/db/slugged-content-input.ts | 13 +++ src/shared/db/system-notes.ts | 57 ++++++------ src/shared/db/users.ts | 22 +---- src/shared/deno-deploy-api.ts | 3 + src/shared/env.ts | 9 +- src/shared/error-message.ts | 10 +++ src/shared/flash-fields.ts | 9 ++ src/shared/forms.tsx | 25 +++--- src/shared/images/transcode.ts | 21 +++-- src/shared/lazy-logger.ts | 13 +++ src/shared/limits.ts | 41 +++++---- src/shared/lines.ts | 7 ++ src/shared/listing-attribute-filter.ts | 17 ++-- src/shared/listings-actions.ts | 16 +++- src/shared/listings-by-id.ts | 8 ++ src/shared/payment-helpers.ts | 36 +++++--- src/shared/payments.ts | 16 ++-- src/shared/refund-ledger.ts | 2 + src/shared/rest/crud-api.ts | 35 ++++---- src/shared/rest/resource.ts | 3 + src/shared/settings/registry.ts | 63 +++++--------- src/shared/square.ts | 12 ++- src/shared/storage.ts | 19 ++-- src/shared/stream-chunks.ts | 22 +++++ src/shared/stripe.ts | 26 +++--- src/shared/turso-api.ts | 3 + src/shared/webhook-verification.ts | 17 ++++ .../client/admin/markdown-editor-toolbar.ts | 5 +- src/ui/client/dom.ts | 14 +++ src/ui/client/order.ts | 9 +- src/ui/templates/admin/activityLog.tsx | 33 ++++--- src/ui/templates/admin/admin-page.tsx | 30 ++++--- src/ui/templates/admin/agent-header.tsx | 16 ++++ src/ui/templates/admin/api-keys.tsx | 58 +++++++------ src/ui/templates/admin/attendee-detail.tsx | 8 +- src/ui/templates/admin/attendee-form.tsx | 39 ++------- src/ui/templates/admin/attendees.tsx | 85 +++++++++--------- src/ui/templates/admin/builder.tsx | 15 ++-- src/ui/templates/admin/built-sites.tsx | 6 +- .../admin/built-sites/list-parts.tsx | 24 +++-- src/ui/templates/admin/bulk-actions.tsx | 87 +++++++++---------- src/ui/templates/admin/deliveries.tsx | 19 +--- src/ui/templates/admin/groups.tsx | 15 ++-- src/ui/templates/admin/hidden-row.tsx | 14 +++ src/ui/templates/admin/ledger.tsx | 20 ++--- src/ui/templates/admin/ledger/statement.tsx | 15 ++-- src/ui/templates/admin/listing-defaults.tsx | 10 ++- .../templates/admin/listings/aggregates.tsx | 17 ++-- src/ui/templates/admin/listings/details.tsx | 8 +- .../admin/listings/form-sections.tsx | 26 +++--- src/ui/templates/admin/listings/roster.tsx | 2 +- src/ui/templates/admin/logout.tsx | 14 +-- .../templates/admin/modifiers/aggregates.tsx | 22 ++--- src/ui/templates/admin/money-summary.tsx | 6 +- src/ui/templates/admin/nav.tsx | 13 +-- src/ui/templates/admin/privacy.tsx | 6 +- src/ui/templates/admin/recalculate-rows.ts | 23 +++++ src/ui/templates/attendee-table.tsx | 4 +- src/ui/templates/components/data-table.tsx | 11 ++- src/ui/templates/components/error.tsx | 7 +- src/ui/templates/components/header-row.tsx | 20 +++++ .../templates/components/heading-layout.tsx | 23 +++++ src/ui/templates/components/labelled-para.tsx | 29 +++++++ src/ui/templates/components/price-input.tsx | 7 +- src/ui/templates/components/prose-heading.tsx | 13 ++- .../components/success-complete-page.tsx | 7 +- src/ui/templates/components/text-field.tsx | 16 +++- src/ui/templates/payment.tsx | 17 ++-- .../public/reservations/contact-fields.ts | 24 +++-- .../public/reservations/listing-rows.ts | 46 +++++----- src/ui/templates/public/unsubscribe.tsx | 6 +- src/ui/templates/tickets.tsx | 8 +- test/lib/i18n-coverage.test.ts | 2 +- 167 files changed, 1811 insertions(+), 1233 deletions(-) create mode 100644 scripts/bench/cold-start/serve-root.ts create mode 100644 src/features/admin/find-group.ts create mode 100644 src/features/admin/load-listing.ts create mode 100644 src/features/admin/site-content-create.ts create mode 100644 src/features/api/json-body.ts create mode 100644 src/features/flash-for-page.ts create mode 100644 src/features/public/ticket-page-url.ts create mode 100644 src/shared/booking/node-order.ts create mode 100644 src/shared/booking/order-span.ts create mode 100644 src/shared/db/id-and-name-columns.ts create mode 100644 src/shared/db/migrations/master-query.ts create mode 100644 src/shared/db/slugged-content-input.ts create mode 100644 src/shared/error-message.ts create mode 100644 src/shared/flash-fields.ts create mode 100644 src/shared/lazy-logger.ts create mode 100644 src/shared/lines.ts create mode 100644 src/shared/listings-by-id.ts create mode 100644 src/shared/stream-chunks.ts create mode 100644 src/shared/webhook-verification.ts create mode 100644 src/ui/client/dom.ts create mode 100644 src/ui/templates/admin/agent-header.tsx create mode 100644 src/ui/templates/admin/hidden-row.tsx create mode 100644 src/ui/templates/admin/recalculate-rows.ts create mode 100644 src/ui/templates/components/header-row.tsx create mode 100644 src/ui/templates/components/heading-layout.tsx create mode 100644 src/ui/templates/components/labelled-para.tsx diff --git a/.jscpd.json b/.jscpd.json index d56e90afc2..404b35c5b0 100644 --- a/.jscpd.json +++ b/.jscpd.json @@ -23,7 +23,7 @@ "gitignore": true, "exitCode": 1, "minLines": 1, - "minTokens": 23, + "minTokens": 22, "path": [ "src", "e2e-payments", diff --git a/e2e-payments/src/flow.ts b/e2e-payments/src/flow.ts index e26ae3f2b0..8032044527 100644 --- a/e2e-payments/src/flow.ts +++ b/e2e-payments/src/flow.ts @@ -5,6 +5,7 @@ * confirm the booking is recorded as paid. */ +import type { Locator } from "playwright"; import type { BrowserSession } from "./browser.ts"; import { config } from "./config.ts"; import { log, step } from "./log.ts"; @@ -145,11 +146,7 @@ export const submitBooking = async ( const qty = page .locator('input[name^="quantity"], select[name^="quantity"]') .first(); - if (await qty.count()) { - const tag = await qty.evaluate((el) => el.tagName.toLowerCase()); - if (tag === "select") await qty.selectOption("1"); - else await qty.fill("1"); - } + if (await qty.count()) await setSelectOrInput(qty, "1"); const submit = page .getByRole("button", { name: /continue|book|pay|checkout|reserve/i }) @@ -167,6 +164,22 @@ const fillIfPresent = async ( if (await loc.count()) await loc.fill(value); }; +/** + * Set a quantity control that renders as either a `` (large caps): choose the option on a select, type the value + * into an input. Any Playwright options (force / timeout) apply to whichever + * action runs. + */ +export const setSelectOrInput = async ( + control: Locator, + value: string, + options?: { force?: boolean; timeout?: number }, +): Promise => { + const tag = await control.evaluate((el) => el.tagName.toLowerCase()); + if (tag === "select") await control.selectOption(value, options); + else await control.fill(value, options); +}; + /** * Before filling a hosted checkout, assert the booking actually left the app * for the provider. If payment-session creation fails server-side the app diff --git a/e2e-payments/src/order-flow.ts b/e2e-payments/src/order-flow.ts index 171ce06333..5aebae7d90 100644 --- a/e2e-payments/src/order-flow.ts +++ b/e2e-payments/src/order-flow.ts @@ -15,7 +15,12 @@ import type { BrowserSession } from "./browser.ts"; import { config } from "./config.ts"; -import { createListing, incomeLedgerText, waitForAppReturn } from "./flow.ts"; +import { + createListing, + incomeLedgerText, + setSelectOrInput, + waitForAppReturn, +} from "./flow.ts"; import { log, step } from "./log.ts"; /** The one catalog this journey builds and orders. Prices are minor units; @@ -138,23 +143,14 @@ const fillBookingPage = async (session: BrowserSession): Promise => { .selectOption("1", { force: true, timeout: config.actionTimeoutMs }); // A listing's quantity control renders as a for large ones — set whichever the row carries. - const setRowQty = async (name: string, value: string): Promise => { - const control = page - .locator(`.ticket-row:has-text("${name}") [name^="quantity_"]`) - .first(); - const tag = await control.evaluate((el) => el.tagName.toLowerCase()); - if (tag === "select") { - await control.selectOption(value, { - force: true, - timeout: config.actionTimeoutMs, - }); - } else { - await control.fill(value, { - force: true, - timeout: config.actionTimeoutMs, - }); - } - }; + const setRowQty = (name: string, value: string): Promise => + setSelectOrInput( + page + .locator(`.ticket-row:has-text("${name}") [name^="quantity_"]`) + .first(), + value, + { force: true, timeout: config.actionTimeoutMs }, + ); await setRowQty(MEMBER_A, "1"); await setRowQty(PLAIN, "2"); await session.fill("name", BUYER_NAME); diff --git a/scripts/bench/bunny-crypto-smoke.ts b/scripts/bench/bunny-crypto-smoke.ts index f1be42892f..78087a575f 100644 --- a/scripts/bench/bunny-crypto-smoke.ts +++ b/scripts/bench/bunny-crypto-smoke.ts @@ -13,6 +13,9 @@ const KEY = crypto.getRandomValues(new Uint8Array(32)); const SAMPLE = "attendee-pii-value-12345@example.com"; const ITERS = 2000; +/** A fresh random 12-byte AES-GCM nonce. */ +const randomIv = (): Uint8Array => crypto.getRandomValues(new Uint8Array(12)); + /** Run `body` ITERS times and return the elapsed milliseconds. */ const timeLoop = async (body: () => Promise | void): Promise => { const t0 = performance.now(); @@ -62,7 +65,7 @@ const run = async (): Promise => { // node:crypto helpers — match WebCrypto layout (tag appended to ciphertext) const nodeEnc = (pt: Uint8Array) => { - const iv = crypto.getRandomValues(new Uint8Array(12)); + const iv = randomIv(); const c = nc.createCipheriv("aes-256-gcm", KEY, iv); const body = Buffer.concat([c.update(pt), c.final()]); const ct = new Uint8Array(Buffer.concat([body, c.getAuthTag()])); diff --git a/scripts/bench/cold-start/first-request-child.ts b/scripts/bench/cold-start/first-request-child.ts index c8c4d33f60..1f5a856a5f 100644 --- a/scripts/bench/cold-start/first-request-child.ts +++ b/scripts/bench/cold-start/first-request-child.ts @@ -22,6 +22,7 @@ import { setBuildTimestampForTest, } from "#shared/update.ts"; import { serveHandler } from "#src/serve-app.ts"; +import { serveAndDrainRoot } from "./serve-root.ts"; // Keep stdout clean for the JSON result line the parent parses. setSuppressDebugLogs(true); @@ -131,8 +132,7 @@ setDb(wrapClient(createClient({ url: dbUrl }))); const timedRequest = async (): Promise<{ ms: number; status: number }> => { requestStart = performance.now(); - const response = await serveHandler(new Request("http://localhost/")); - await response.text(); + const response = await serveAndDrainRoot(serveHandler); return { ms: performance.now() - requestStart, status: response.status }; }; diff --git a/scripts/bench/cold-start/first-request.ts b/scripts/bench/cold-start/first-request.ts index a87c50e499..d72f258395 100644 --- a/scripts/bench/cold-start/first-request.ts +++ b/scripts/bench/cold-start/first-request.ts @@ -9,6 +9,7 @@ */ import { encodeBase64 } from "jsr:@std/encoding@^1.0.0/base64"; +import { serveAndDrainRoot } from "./serve-root.ts"; import { spawnChildJson } from "./spawn-child.ts"; const LATENCIES_MS = [0, 25, 50, 100]; @@ -52,8 +53,7 @@ const prepareDatabase = async (): Promise => { // One warm-up request so first-ever housekeeping (prune stamps, backfill // markers) lands in prep, not in a measured child. const { serveHandler } = await import("#src/serve-app.ts"); - const response = await serveHandler(new Request("http://localhost/")); - await response.text(); + const response = await serveAndDrainRoot(serveHandler); requireHealthyStatus(response.status, "database preparation request"); }; diff --git a/scripts/bench/cold-start/serve-root.ts b/scripts/bench/cold-start/serve-root.ts new file mode 100644 index 0000000000..b1a55a8351 --- /dev/null +++ b/scripts/bench/cold-start/serve-root.ts @@ -0,0 +1,12 @@ +/** Serve `GET /` through the production handler and drain the body, returning + * the response. `serve` is passed in so the parent can hand over its + * dynamically imported handler (nothing may read the environment before it sets + * it) while the child hands over its statically imported one. Both the parent's + * warm-up prep and the child's timed requests hit the root request one way. */ +export const serveAndDrainRoot = async ( + serve: (request: Request) => Promise, +): Promise => { + const response = await serve(new Request("http://localhost/")); + await response.text(); + return response; +}; diff --git a/scripts/bunny-regions.ts b/scripts/bunny-regions.ts index 9f1ae3b100..11233b8373 100644 --- a/scripts/bunny-regions.ts +++ b/scripts/bunny-regions.ts @@ -52,10 +52,11 @@ console.log(fmt(config.primary_regions)); console.log("\nReplica regions:"); console.log(fmt(config.replica_regions)); -const eu = (r: BunnyRegion) => r.group === "EU"; +const euIds = (rs: BunnyRegion[]) => + rs.filter((r) => r.group === "EU").map((r) => r.id); console.log("\nEuropean storage zone ids:"); -console.log(config.storage_region_available.filter(eu).map((r) => r.id)); +console.log(euIds(config.storage_region_available)); console.log("European primary region ids:"); -console.log(config.primary_regions.filter(eu).map((r) => r.id)); +console.log(euIds(config.primary_regions)); console.log("European replica region ids:"); -console.log(config.replica_regions.filter(eu).map((r) => r.id)); +console.log(euIds(config.replica_regions)); diff --git a/scripts/edge-bundle-lib.ts b/scripts/edge-bundle-lib.ts index 4ff65b7633..ad044313c3 100644 --- a/scripts/edge-bundle-lib.ts +++ b/scripts/edge-bundle-lib.ts @@ -118,6 +118,22 @@ globalThis.Buffer ??= Buffer; globalThis.global ??= globalThis; `; +// Swaps a real module for a generated one at build time: esbuild resolves any +// import matching `filter` into its own private namespace, then loads that +// namespace from the TypeScript source `buildContents` returns. +const inlineGeneratedModule = ( + build: Parameters[0], + filter: RegExp, + namespace: string, + buildContents: () => string, +): void => { + build.onResolve({ filter }, (args) => ({ namespace, path: args.path })); + build.onLoad({ filter: /.*/, namespace }, () => ({ + contents: buildContents(), + loader: "ts", + })); +}; + /** * Plugin to inline static assets and handle Deno-specific imports. * Replaces Deno.readTextFileSync calls with the pre-read content and the @@ -132,40 +148,22 @@ const inlineAssetsPlugin = ( name: "inline-assets", setup(build) { // Replace build-info module with actual build metadata - build.onResolve({ filter: /build-info\.ts$/ }, (args) => ({ - namespace: "inline-build-info", - path: args.path, - })); - build.onLoad({ filter: /.*/, namespace: "inline-build-info" }, () => ({ - contents: buildBuildInfoModule( - buildIso, - Deno.env.get("BUILD_COMMIT") ?? "", - ), - loader: "ts", - })); + inlineGeneratedModule(build, /build-info\.ts$/, "inline-build-info", () => + buildBuildInfoModule(buildIso, Deno.env.get("BUILD_COMMIT") ?? ""), + ); // Replace asset paths module with cache-busted version - build.onResolve({ filter: /asset-paths\.ts$/ }, (args) => ({ - namespace: "inline-asset-paths", - path: args.path, - })); - build.onLoad({ filter: /.*/, namespace: "inline-asset-paths" }, () => ({ - contents: buildAssetPathsModule(ASSET_DEFS, buildTs, published), - loader: "ts", - })); + inlineGeneratedModule(build, /asset-paths\.ts$/, "inline-asset-paths", () => + buildAssetPathsModule(ASSET_DEFS, buildTs, published), + ); // Replace the assets module with inlined content - build.onResolve( - { filter: /(features\/assets\.ts$|#routes\/assets\.ts$)/ }, - (args) => ({ - namespace: "inline-assets", - path: args.path, - }), + inlineGeneratedModule( + build, + /(features\/assets\.ts$|#routes\/assets\.ts$)/, + "inline-assets", + () => buildAssetsModule(ASSET_DEFS, staticAssets, published), ); - build.onLoad({ filter: /.*/, namespace: "inline-assets" }, () => ({ - contents: buildAssetsModule(ASSET_DEFS, staticAssets, published), - loader: "ts", - })); }, }); diff --git a/scripts/mutation/isolation-state.ts b/scripts/mutation/isolation-state.ts index d4a9a89743..a986d094f2 100644 --- a/scripts/mutation/isolation-state.ts +++ b/scripts/mutation/isolation-state.ts @@ -182,11 +182,15 @@ export const runsRoot = (root = projectRoot): string => export const runRoot = (id: string, root = projectRoot): string => join(runsRoot(root), id); -export const workRoot = (id: string, root = projectRoot): string => - join(runRoot(id, root), MUTATION_WORK_DIR); +/** Path to a named child (dir or file) inside a run's own folder. */ +const runChildPath = + (childName: string) => + (id: string, root = projectRoot): string => + join(runRoot(id, root), childName); -export const recordPath = (id: string, root = projectRoot): string => - join(runRoot(id, root), MUTATION_RECORD_FILE); +export const workRoot = runChildPath(MUTATION_WORK_DIR); + +export const recordPath = runChildPath(MUTATION_RECORD_FILE); export const runLockPath = (record: Pick): string => join(record.root, MUTATION_RUN_LOCK_FILE); @@ -332,11 +336,14 @@ export const rewriteProjectPathArg = ( return join(resolvedSnapshot, resolvedValue.slice(rootPrefix.length)); }; -export const rewriteMutationArgs = ( +/** Turn a run's arguments into the ones the child sees inside its snapshot. */ +export type SnapshotArgsFn = ( root: string, snapshotRoot: string, args: string[], -): string[] => +) => string[]; + +export const rewriteMutationArgs: SnapshotArgsFn = (root, snapshotRoot, args) => args.map((arg) => rewriteProjectPathArg(root, snapshotRoot, arg)); export const parseIsolationCommand = (args: string[]): IsolationCommand => { diff --git a/scripts/mutation/isolation.ts b/scripts/mutation/isolation.ts index f28655ffd2..793113cb11 100644 --- a/scripts/mutation/isolation.ts +++ b/scripts/mutation/isolation.ts @@ -6,6 +6,7 @@ */ import { relative } from "@std/path"; +import { errorMessage } from "#shared/error-message.ts"; import { processExists, stopProcess, stopProcessNow } from "../process.ts"; import { projectRoot } from "../project-root.ts"; import { @@ -31,11 +32,15 @@ import { rewriteMutationArgs, runLockIsHeld, runStartedRecently, + type SnapshotArgsFn, selectedRuns, withMutationRunLock, writeRunRecord, } from "./isolation-state.ts"; +/** Runs a mutation command from its argv and returns a process exit code. */ +type MutationCommandRunner = (args: string[], root?: string) => Promise; + const processBelongsToRun = async ( record: MutationRunRecord, ): Promise => { @@ -138,11 +143,7 @@ const childEnv = ( [MUTATION_WORK_ROOT_ENV]: snapshotRoot, }); -const childArgs = ( - root: string, - snapshotRoot: string, - args: string[], -): string[] => [ +const childArgs: SnapshotArgsFn = (root, snapshotRoot, args) => [ "run", "-A", "scripts/mutation.ts", @@ -170,10 +171,10 @@ const settleRecord = ( ): MutationRunRecord => interrupted ? markInterrupted(record) : markFinished(record, code); -export const runMutationInSnapshot = async ( - args: string[], +export const runMutationInSnapshot: MutationCommandRunner = async ( + args, root = projectRoot, -): Promise => { +) => { const id = createRunId(); let record = newRunRecord(id, args, root); await writeRunRecord(record); @@ -230,7 +231,7 @@ export const runMutationInSnapshot = async ( } catch { // A failed write should not mask the original error. } - console.error(error instanceof Error ? error.message : String(error)); + console.error(errorMessage(error)); } offTerminationSignals(stopChild); return exitCode; @@ -308,11 +309,7 @@ const removeMatchedRuns = async ( for (const record of removed) console.log(`Removed ${record.id}.`); for (const { error, record } of failed) { - console.error( - `Failed to remove ${record.id}: ${ - error instanceof Error ? error.message : String(error) - }`, - ); + console.error(`Failed to remove ${record.id}: ${errorMessage(error)}`); } for (const record of skipped) { console.error(`Skipped active isolated mutation run ${record.id}.`); @@ -330,10 +327,10 @@ const cleanRuns = (target: string, root = projectRoot): Promise => removeMatchedRuns(records, target), ); -export const runIsolatedMutationCommand = async ( - args: string[], +export const runIsolatedMutationCommand: MutationCommandRunner = async ( + args, root = projectRoot, -): Promise => { +) => { const command = parseIsolationCommand(args); if (command.kind === "invalid") { console.error(command.message); diff --git a/scripts/mutation/runner.ts b/scripts/mutation/runner.ts index 2219f4873e..e1e8fbea31 100644 --- a/scripts/mutation/runner.ts +++ b/scripts/mutation/runner.ts @@ -49,8 +49,10 @@ import { writeStepSummary, } from "./summary.ts"; -export interface MutationOptions { - batchJobs?: number; +/** The files and knobs that describe what to mutate and how — shared by the + * public {@link MutationOptions} and the internal {@link RunMutantsOptions} so + * the common fields are stated once. */ +interface MutationTargets { exhaustive: boolean; sourceFiles: string[]; testFiles: string[]; @@ -58,6 +60,10 @@ export interface MutationOptions { useHarness: boolean; } +export interface MutationOptions extends MutationTargets { + batchJobs?: number; +} + type Outcome = "failed" | "passed" | "timed-out"; const BASELINE_TIMEOUT = 120_000; @@ -415,19 +421,14 @@ const report = (results: MutantResult[]): number => { return summary.survived === 0 ? 0 : 1; }; -interface RunMutantsOptions { +interface RunMutantsOptions extends MutationTargets { abortSignal: AbortSignal; batchJobs: number; - exhaustive: boolean; ignoreList: IgnoreList; isAborted: () => boolean; originals: Map; restoreAll: () => void; results: MutantResult[]; - sourceFiles: string[]; - testFiles: string[]; - timeout: number; - useHarness: boolean; } /** diff --git a/scripts/mutation/summary.ts b/scripts/mutation/summary.ts index 58542782b3..96a7e8352a 100644 --- a/scripts/mutation/summary.ts +++ b/scripts/mutation/summary.ts @@ -125,10 +125,23 @@ const renderRow = (row: { }): string => ` ${row.color(row.label)}${" ".repeat(LABEL_WIDTH - row.label.length)}${row.value}`; -const survivorLine = (result: MutantResult): string => { - const { newOperator, operator } = result.mutant; - return ` ${survivorLocation(result)} ${bold(operator)} → ${bold(newOperator)}`; -}; +/** Build a "one survivor on a line" formatter from how it should wrap the + * location and the two operators. The terminal and Markdown reports show the + * same three pieces (location, old operator, new operator); only the + * surrounding text differs, so they share this one body. */ +const survivorFormatter = + ( + render: (location: string, operator: string, newOperator: string) => string, + ) => + (result: MutantResult): string => { + const { newOperator, operator } = result.mutant; + return render(survivorLocation(result), operator, newOperator); + }; + +const survivorLine = survivorFormatter( + (location, operator, newOperator) => + ` ${location} ${bold(operator)} → ${bold(newOperator)}`, +); /** The full terminal report as lines, ready for the runner to print. Pure. */ export const formatSummaryLines = (s: Summary): string[] => { @@ -168,10 +181,10 @@ export const formatSummaryLines = (s: Summary): string[] => { // --- GitHub step summary (Markdown) -------------------------------------- -const survivorRow = (result: MutantResult): string => { - const { newOperator, operator } = result.mutant; - return `| \`${survivorLocation(result)}\` | \`${operator}\` → \`${newOperator}\` |`; -}; +const survivorRow = survivorFormatter( + (location, operator, newOperator) => + `| \`${location}\` | \`${operator}\` → \`${newOperator}\` |`, +); const markdownSummary = (s: Summary): string => { if (s.total === 0) { diff --git a/scripts/precommit/git.ts b/scripts/precommit/git.ts index f83d204083..22307db593 100644 --- a/scripts/precommit/git.ts +++ b/scripts/precommit/git.ts @@ -17,11 +17,19 @@ export const splitCommand = ( return [command, args]; }; +/** Build a `Deno.Command` from a `[executable, ...args]` list plus the stdio + * wiring for this run. */ +const buildCommand = ( + cmd: string[], + options: Omit, +): Deno.Command => { + const [command, args] = splitCommand(cmd); + return new Deno.Command(command, { ...options, args }); +}; + /** Run a command, capturing its stdout/stderr as decoded strings. */ export const runCommand: RunCommand = async (cmd) => { - const [command, args] = splitCommand(cmd); - const output = await new Deno.Command(command, { - args, + const output = await buildCommand(cmd, { stderr: "piped", stdout: "piped", }).output(); @@ -37,9 +45,7 @@ export const runCommand: RunCommand = async (cmd) => { /** Run a command wired to the parent's stdio (for interactive steps). */ export const runInteractiveCommand: RunCommand = async (cmd) => { - const [command, args] = splitCommand(cmd); - const status = await new Deno.Command(command, { - args, + const status = await buildCommand(cmd, { stderr: "inherit", stdin: "inherit", stdout: "inherit", diff --git a/scripts/precommit/mutation-step.ts b/scripts/precommit/mutation-step.ts index abc6a88812..109a4d4c84 100644 --- a/scripts/precommit/mutation-step.ts +++ b/scripts/precommit/mutation-step.ts @@ -56,6 +56,7 @@ * `scripts/precommit-mutation.ts` wires in the real implementations. */ +import { nonBlankLines } from "#shared/lines.ts"; import type { RunCommand } from "./git.ts"; /** A changed-source count above this almost certainly means the local base ref @@ -139,11 +140,7 @@ export const changedFiles = async ( if (/no merge base/i.test(result.stderr)) return null; throw new Error(`git diff ${base}...HEAD failed: ${result.stderr.trim()}`); } - const paths = result.stdout - .split("\n") - .map((line) => line.trim()) - .filter((line) => line !== ""); - return partitionChanged(paths); + return partitionChanged(nonBlankLines(result.stdout)); }; /** diff --git a/scripts/stream-lines.ts b/scripts/stream-lines.ts index 7756e782ed..1e61dfdc0a 100644 --- a/scripts/stream-lines.ts +++ b/scripts/stream-lines.ts @@ -1,3 +1,5 @@ +import { streamChunks } from "#shared/stream-chunks.ts"; + /** * Read a byte stream to completion, decoding as UTF-8 and returning the full * text. When `onLine` is supplied, each newline-terminated line is delivered as @@ -8,7 +10,6 @@ export const readStream = async ( stream: ReadableStream, onLine?: (line: string) => void, ): Promise => { - const reader = stream.getReader(); const decoder = new TextDecoder(); let buffered = ""; let text = ""; @@ -28,14 +29,11 @@ export const readStream = async ( }; try { - while (true) { - const { done, value } = await reader.read(); - if (done) break; + for await (const value of streamChunks(stream)) { flush(decoder.decode(value, { stream: true }), false); } } finally { flush(decoder.decode(), true); - reader.releaseLock(); } return text; diff --git a/scripts/stripe-mock.ts b/scripts/stripe-mock.ts index 82330352e2..a028ab544f 100644 --- a/scripts/stripe-mock.ts +++ b/scripts/stripe-mock.ts @@ -13,6 +13,7 @@ import { defaultStripeMockPaths, downloadStripeMock, ensureBinDir, + type LockBody, type StripeMockCommands, type StripeMockInstallOptions, type StripeMockPaths, @@ -222,7 +223,7 @@ const stripeMockStartLockPath = (paths: StripeMockPaths): string => const withStripeMockStartLock = async ( paths: StripeMockPaths, - body: () => Promise, + body: LockBody, ): Promise => { const lockPath = stripeMockStartLockPath(paths); await ensureBinDir(paths); diff --git a/scripts/stripe-mock/install.ts b/scripts/stripe-mock/install.ts index 0a581d3c47..186a103ac5 100644 --- a/scripts/stripe-mock/install.ts +++ b/scripts/stripe-mock/install.ts @@ -24,6 +24,9 @@ export type StripeMockPaths = { binaryPath: string; }; +/** A task run while a lock is held, giving back its result. */ +export type LockBody = () => Promise; + /** Ensure the bin directory (and any parents) exists. */ export const ensureBinDir = (paths: StripeMockPaths): Promise => Deno.mkdir(paths.binDir, { recursive: true }); @@ -272,7 +275,7 @@ const acquireInstallLock = async ( const withInstallLock = async ( paths: StripeMockPaths, options: StripeMockInstallOptions, - body: () => Promise, + body: LockBody, ): Promise => { const lockPath = installLockPath(paths); const settings = installLockSettings(options); diff --git a/scripts/unit-tests-report-lib.ts b/scripts/unit-tests-report-lib.ts index eeeda8d17a..4f8427e340 100644 --- a/scripts/unit-tests-report-lib.ts +++ b/scripts/unit-tests-report-lib.ts @@ -298,39 +298,46 @@ const limitRows = (rows: T[], limit: number | null): T[] => const truncationNote = (shown: number, total: number): string[] => shown < total ? [` … and ${total - shown} more (use --all to list)`] : []; -const untestedLines = (report: Report, limit: number | null): string[] => { - if (report.untested.length === 0) - return [" (none — every source has a test)"]; - const shown = limitRows(report.untested, limit); - return [ - ...shown.map((s) => ` ${String(s.lines).padStart(5)} ${s.path}`), - ...truncationNote(shown.length, report.untested.length), - ]; -}; +/** + * Render one of the report's lists: a "none" note when it is empty, else the + * rows (with an optional header line on top) plus a "… and N more" note when + * the limit hid some. `pickRows` reads the list off the report so each list + * only names its own field once. + */ +const listSection = + ( + pickRows: (report: Report) => T[], + look: { whenEmpty: string; header?: string; renderRow: (row: T) => string }, + ) => + (report: Report, limit: number | null): string[] => { + const rows = pickRows(report); + if (rows.length === 0) return [look.whenEmpty]; + const shown = limitRows(rows, limit); + return [ + ...(look.header ? [look.header] : []), + ...shown.map(look.renderRow), + ...truncationNote(shown.length, rows.length), + ]; + }; -const rankedLines = (report: Report, limit: number | null): string[] => { - if (report.ranked.length === 0) return [" (none)"]; - const shown = limitRows(report.ranked, limit); - return [ - ` ${"ratio".padStart(6)} ${"src".padStart(5)} ${"test".padStart(5)} file`, - ...shown.map( - (s) => - ` ${formatRatio(s.ratio).padStart(6)} ${String(s.lines).padStart( - 5, - )} ${String(s.testLines).padStart(5)} ${s.path}`, - ), - ...truncationNote(shown.length, report.ranked.length), - ]; -}; +const untestedLines = listSection((report) => report.untested, { + renderRow: (s) => ` ${String(s.lines).padStart(5)} ${s.path}`, + whenEmpty: " (none — every source has a test)", +}); -const orphanLines = (report: Report, limit: number | null): string[] => { - if (report.orphanTests.length === 0) return [" (none)"]; - const shown = limitRows(report.orphanTests, limit); - return [ - ...shown.map((path) => ` ${path}`), - ...truncationNote(shown.length, report.orphanTests.length), - ]; -}; +const rankedLines = listSection((report) => report.ranked, { + header: ` ${"ratio".padStart(6)} ${"src".padStart(5)} ${"test".padStart(5)} file`, + renderRow: (s) => + ` ${formatRatio(s.ratio).padStart(6)} ${String(s.lines).padStart( + 5, + )} ${String(s.testLines).padStart(5)} ${s.path}`, + whenEmpty: " (none)", +}); + +const orphanLines = listSection((report) => report.orphanTests, { + renderRow: (path) => ` ${path}`, + whenEmpty: " (none)", +}); /** * Render the report as plain text lines. `limit` caps each list (null shows diff --git a/src/features/admin/actions.ts b/src/features/admin/actions.ts index 9722ea774d..eca2bdb481 100644 --- a/src/features/admin/actions.ts +++ b/src/features/admin/actions.ts @@ -124,6 +124,12 @@ export const listingAttendeesLoader = /** Error mapping: convert an Error into a redirect response */ export type ErrorMapper = (error: Error) => Response; +/** A string given directly, or computed from the session and the submitted form + * (and allowed to be async). Used for the flash/log message. */ +type SessionFormString = + | string + | ((session: TSession, form: FormParams) => string | Promise); + /** Configuration for createActionHandler */ export type ActionHandlerConfig = { /** Auth mode: "owner" requires owner role, "any" allows any authenticated user */ @@ -135,9 +141,7 @@ export type ActionHandlerConfig = { /** Optional listing/resource id for activity logging context */ listingId?: number | ((form: FormParams) => number | undefined); /** Message used for both flash and activity log */ - message: - | string - | ((session: TSession, form: FormParams) => string | Promise); + message: SessionFormString; /** Redirect URL on success */ successRedirect: string | ((session: TSession, form: FormParams) => string); /** Optional custom error mapping (falls back to errorRedirect with message) */ @@ -174,9 +178,7 @@ export const createActionHandler = ( }; const resolveString = async ( - value: - | string - | ((session: TSession, form: FormParams) => string | Promise), + value: SessionFormString, session: TSession, form: FormParams, ): Promise => diff --git a/src/features/admin/api.ts b/src/features/admin/api.ts index de5eb404e7..fdd6fe1757 100644 --- a/src/features/admin/api.ts +++ b/src/features/admin/api.ts @@ -7,6 +7,7 @@ * - Session cookie + x-csrf-token header */ +import { reduce } from "#fp"; import { groupApiRoutes } from "#routes/admin/api-groups.ts"; import { holidayApiRoutes } from "#routes/admin/api-holidays.ts"; import { verifyIdentifierOrJsonError } from "#routes/admin/confirmation.ts"; @@ -164,14 +165,17 @@ const optionalFields: FieldMapping[] = [ */ const parseDayPrices = (raw: unknown): Record => { if (typeof raw !== "object" || raw === null) return {}; - const result: Record = {}; - for (const [key, value] of Object.entries(raw)) { - const day = Number(key); - if (Number.isInteger(day) && day >= 1 && typeof value === "number") { - result[day] = value; - } - } - return result; + // Keep only positive whole day counts mapped to numeric prices; drop the rest. + return reduce( + (kept: Record, [key, value]: [string, unknown]) => { + const day = Number(key); + if (Number.isInteger(day) && day >= 1 && typeof value === "number") { + kept[day] = value; + } + return kept; + }, + {}, + )(Object.entries(raw)); }; /** Parse the optional `group_ids` array (group membership). An absent field diff --git a/src/features/admin/attendee-form-routes.ts b/src/features/admin/attendee-form-routes.ts index 592e1f6c82..446d130d55 100644 --- a/src/features/admin/attendee-form-routes.ts +++ b/src/features/admin/attendee-form-routes.ts @@ -44,6 +44,7 @@ import { loadPackagePaths, loadQuestionsForExisting, packagesByListingIdFrom, + type SelectedQuestionAnswers, } from "#routes/admin/attendee-page-data.ts"; import { AUTH_FORM, @@ -132,12 +133,9 @@ export const handleAttendeeNewGet: TypedRouteHandler< // --------------------------------------------------------------------------- /** Everything the submit handler needs about an attendee being edited. */ -type EditContext = { +type EditContext = SelectedQuestionAnswers & { attendee: Attendee | null; existingByKey: Map; - questions: QuestionWithAnswers[]; - selectedAnswerIds: number[]; - selectedTextAnswers: Map; }; /** Create mode has no attendee, lines, or questions to preload. */ diff --git a/src/features/admin/attendee-logistics-routes.ts b/src/features/admin/attendee-logistics-routes.ts index 992ef91a9d..bebe66da3c 100644 --- a/src/features/admin/attendee-logistics-routes.ts +++ b/src/features/admin/attendee-logistics-routes.ts @@ -28,9 +28,11 @@ import { loadAttendeeForEdit, } from "#routes/admin/attendee-page-data.ts"; import { AUTH_FORM, type AuthSession, withAuth } from "#routes/auth.ts"; +/* jscpd:ignore-start */ import { notFoundResponse, redirect } from "#routes/response.ts"; import type { TypedRouteHandler } from "#routes/router.ts"; import { logActivity } from "#shared/db/activityLog.ts"; +/* jscpd:ignore-end */ import { updateAttendeePII } from "#shared/db/attendees/update.ts"; import { setLogisticsAssignments } from "#shared/db/logistics.ts"; import { diff --git a/src/features/admin/attendee-page-data.ts b/src/features/admin/attendee-page-data.ts index 3fa7bf7bb4..e7ee8e6e9b 100644 --- a/src/features/admin/attendee-page-data.ts +++ b/src/features/admin/attendee-page-data.ts @@ -556,14 +556,18 @@ export const buildTemplateData = async ( * attendee's booked listings. The request's private key is only derived when * there are questions whose free-text answers need decrypting, so an attendee * with no questions never forces a key unwrap. */ -export const loadQuestionsForExisting = async ( - attendeeId: number, - existing: ExistingLine[], -): Promise<{ +/** A set of custom questions plus which answers the attendee has picked: the + * chosen option ids, and any free-text answers keyed by question id. */ +export type SelectedQuestionAnswers = { questions: QuestionWithAnswers[]; selectedAnswerIds: number[]; selectedTextAnswers: Map; -}> => { +}; + +export const loadQuestionsForExisting = async ( + attendeeId: number, + existing: ExistingLine[], +): Promise => { const listingIds = unique(existing.map((e) => e.booking.listing_id)); const data = await loadAttendeeQuestionData(listingIds, [attendeeId]); if (!data) { diff --git a/src/features/admin/attendees-edit.ts b/src/features/admin/attendees-edit.ts index 193018c774..b822f11137 100644 --- a/src/features/admin/attendees-edit.ts +++ b/src/features/admin/attendees-edit.ts @@ -11,9 +11,11 @@ import { chunk } from "#fp"; import { t } from "#i18n"; import { AUTH_FORM, withAuth } from "#routes/auth.ts"; +/* jscpd:ignore-start */ import { errorRedirect, htmlResponse, redirect } from "#routes/response.ts"; import type { TypedRouteHandler } from "#routes/router.ts"; import { logActivity } from "#shared/db/activityLog.ts"; +/* jscpd:ignore-end */ import type { ListingAttendeeRow } from "#shared/db/attendee-types.ts"; import { ATTENDEE_KIND } from "#shared/db/attendees/kind.ts"; import { decryptAttendeeOrNull } from "#shared/db/attendees/pii.ts"; diff --git a/src/features/admin/attendees-merge.ts b/src/features/admin/attendees-merge.ts index d921fdb210..42bb272efa 100644 --- a/src/features/admin/attendees-merge.ts +++ b/src/features/admin/attendees-merge.ts @@ -3,7 +3,7 @@ */ /* jscpd:ignore-start */ -import { filter, map, pipe } from "#fp"; +import { filter, map, pipe, unique } from "#fp"; import { createEntityRouteHandlers } from "#routes/admin/entity-handlers.ts"; import type { AttendeeRouteParams } from "#routes/entity.ts"; import { errorRedirect, redirect } from "#routes/response.ts"; @@ -111,12 +111,8 @@ const loadAttendeeBookings = ( const collectListingIds = ( targetBookings: ListingAttendeeRow[], sourceBookings: ListingAttendeeRow[], -): number[] => { - const ids = new Set(); - for (const b of targetBookings) ids.add(b.listing_id); - for (const b of sourceBookings) ids.add(b.listing_id); - return [...ids]; -}; +): number[] => + unique([...targetBookings, ...sourceBookings].map((b) => b.listing_id)); type MergeSource = NonNullable>>; type MergeSummary = Awaited>["summary"]; diff --git a/src/features/admin/catalog-transfer/export.ts b/src/features/admin/catalog-transfer/export.ts index 7ba392d773..813bf08cfa 100644 --- a/src/features/admin/catalog-transfer/export.ts +++ b/src/features/admin/catalog-transfer/export.ts @@ -27,6 +27,7 @@ import { listingsTable, } from "#shared/db/listings.ts"; import type { AdminLevel } from "#shared/types.ts"; +import { withGroupOrNull } from "../find-group.ts"; import { getListingGroupMemberships } from "./membership.ts"; import { CATALOG_TRANSFER_VERSION, @@ -184,40 +185,38 @@ export const exportListing = async ( * exist. Includes every member listing (by name) with its package override, * quantity, and per-day overrides. */ -export const exportGroup = async ( +export const exportGroup = ( id: number, -): Promise => { - const group = await groups.table.findById(id); - if (!group) return null; - - const groupData = parseExport( - GroupDataSchema, - groups.table.rowToInput(group, GROUP_EXPORT_EXCLUDED), - "group", - ); - if (groupData instanceof CatalogExportError) return groupData; - - const rows = await getGroupPackagePrices(id); - const [listingNames, dayPrices] = await Promise.all([ - getListingNamesByIds(rows.map((r) => r.listing_id)), - getGroupDayPrices(id), - ]); - - // Every package row references an existing listing (FK), and `listingNames` - // covers exactly those ids, so the name lookup always resolves. - const members: GroupMember[] = rows.map((row) => ({ - listing: listingNames.get(row.listing_id)!, - ...overrideFields( - row.package_price, - row.quantity, - dayPrices.get(row.listing_id), - ), - })); - - return { - group: groupData, - kind: "group", - members, - version: CATALOG_TRANSFER_VERSION, - }; -}; +): Promise => + withGroupOrNull(id, async (group) => { + const groupData = parseExport( + GroupDataSchema, + groups.table.rowToInput(group, GROUP_EXPORT_EXCLUDED), + "group", + ); + if (groupData instanceof CatalogExportError) return groupData; + + const rows = await getGroupPackagePrices(id); + const [listingNames, dayPrices] = await Promise.all([ + getListingNamesByIds(rows.map((r) => r.listing_id)), + getGroupDayPrices(id), + ]); + + // Every package row references an existing listing (FK), and `listingNames` + // covers exactly those ids, so the name lookup always resolves. + const members: GroupMember[] = rows.map((row) => ({ + listing: listingNames.get(row.listing_id)!, + ...overrideFields( + row.package_price, + row.quantity, + dayPrices.get(row.listing_id), + ), + })); + + return { + group: groupData, + kind: "group", + members, + version: CATALOG_TRANSFER_VERSION, + }; + }); diff --git a/src/features/admin/catalog-transfer/import.ts b/src/features/admin/catalog-transfer/import.ts index 81366e6919..88f3253450 100644 --- a/src/features/admin/catalog-transfer/import.ts +++ b/src/features/admin/catalog-transfer/import.ts @@ -56,10 +56,12 @@ import { edgeFieldError, } from "#shared/listing-parents-rules.ts"; import { + dayPriceFieldsFromInput, generateUniqueListingSlug, listingInputToEdge, validateListingInput, } from "#shared/listings-actions.ts"; +import { listingsById } from "#shared/listings-by-id.ts"; import { type AdminLevel, availableDayCounts, @@ -389,11 +391,7 @@ const importListing = async ( ); // A package day-price override must target a day count this listing offers — // the new listing itself is the member here, so validate against its own spans. - const newMember: DayPricedListing = { - customisable_days: input.customisableDays ?? false, - day_prices: input.dayPrices ?? {}, - duration_days: input.durationDays ?? 1, - }; + const newMember: DayPricedListing = dayPriceFieldsFromInput(input); for (let i = 0; i < memberships.length; i++) { if (!packageGroupIds.has(groupResolve.ids[i]!)) continue; const dayError = memberDayOverrideError( @@ -494,7 +492,7 @@ const importGroup = async (transfer: GroupTransfer): Promise => { const isPackage = group.isPackage ?? false; // Each member's day-price overrides must target a day count that member offers. if (isPackage) { - const listingById = new Map(listings.map((l) => [l.id, l])); + const listingById = listingsById(listings); for (let i = 0; i < members.length; i++) { const member = listingById.get(memberResolve.ids[i]!)!; const dayError = memberDayOverrideError( diff --git a/src/features/admin/dashboard.ts b/src/features/admin/dashboard.ts index f247c4f5d5..aae8185b5c 100644 --- a/src/features/admin/dashboard.ts +++ b/src/features/admin/dashboard.ts @@ -13,11 +13,10 @@ import { sessionPage, withSession, } from "#routes/auth.ts"; -import { applyFlash } from "#routes/csrf.ts"; +import { flashForPage } from "#routes/flash-for-page.ts"; import { htmlResponse, redirectResponse } from "#routes/response.ts"; /* jscpd:ignore-start */ import type { TypedRouteHandler } from "#routes/router.ts"; -import { signCsrfToken } from "#shared/csrf.ts"; import { type ActivityLogEntry, getAllActivityLog, @@ -64,9 +63,8 @@ export const loginResponse = async ( request: Request, status = 200, ): Promise => { - const flash = applyFlash(request); - await signCsrfToken(); // success (e.g. "Logged out") is rendered by the Layout backstop from context. + const flash = await flashForPage(request); return htmlResponse(adminLoginPage(flash.error), status); }; diff --git a/src/features/admin/find-group.ts b/src/features/admin/find-group.ts new file mode 100644 index 0000000000..b9c796946b --- /dev/null +++ b/src/features/admin/find-group.ts @@ -0,0 +1,15 @@ +import { groups } from "#shared/db/groups.ts"; + +/** The stored group row as loaded from the table. */ +type GroupRow = NonNullable>>; + +/** Load the group with `id` and hand it to `whenFound`. When no group has that + * id, skip the callback and return null — so a caller writes the found-group + * path once instead of repeating the "look it up, bail if missing" load. */ +export const withGroupOrNull = async ( + id: number, + whenFound: (group: GroupRow) => T | Promise, +): Promise => { + const group = await groups.table.findById(id); + return group ? whenFound(group) : null; +}; diff --git a/src/features/admin/groups.ts b/src/features/admin/groups.ts index f12aa1711f..32c576e8c0 100644 --- a/src/features/admin/groups.ts +++ b/src/features/admin/groups.ts @@ -56,6 +56,7 @@ import type { GroupFormValues, } from "#templates/fields/types.ts"; import { withEntityLoader } from "./entity-handlers.ts"; +import { withGroupOrNull } from "./find-group.ts"; import { groupPage } from "./group-page.ts"; import { createItemImageHandlers } from "./item-images.ts"; @@ -95,13 +96,13 @@ const validatePackageCompatibility = async ( * cards/rows, revealing the member names the hide flag concealed. Un-packaging * or deleting such a group is rejected until the operator clears the hide flag * first (an explicit reveal); a VISIBLE package still un-groups freely. */ -export const soldHiddenPackageError = async ( - id: number, -): Promise => { - const group = await groups.table.findById(id); - if (!group?.is_package || !group.hide_package_listings) return null; - return (await hasPackageBookings(id)) ? t("error.sold_hidden_package") : null; -}; +export const soldHiddenPackageError = (id: number): Promise => + withGroupOrNull(id, async (group) => { + if (!group.is_package || !group.hide_package_listings) return null; + return (await hasPackageBookings(id)) + ? t("error.sold_hidden_package") + : null; + }); /** Combined validation: slug uniqueness plus the package invariant. On create * (`id` undefined) the group has no members yet, so only the slug is checked. diff --git a/src/features/admin/listing-page-data.ts b/src/features/admin/listing-page-data.ts index dc1efe5ea2..43e47fb144 100644 --- a/src/features/admin/listing-page-data.ts +++ b/src/features/admin/listing-page-data.ts @@ -31,7 +31,6 @@ import { import { getAttendeesByListingIds, getListingAggregateRecalculation, - getListingWithCount, listingRevenueBreakdown, } from "#shared/db/listings.ts"; import { getAttendeeIdsWithPaymentReference } from "#shared/db/payment-references.ts"; @@ -59,7 +58,12 @@ import { import { ListingRosterPanel } from "#templates/admin/listings/roster.tsx"; import type { AttendeeFilter } from "#templates/admin/listings/types.ts"; import type { TableQuestionData } from "#templates/attendee-table.tsx"; -import { loadGroupContext, loadListingQuestionData } from "./listings-view.ts"; +import { + filterByDate, + loadGroupContext, + loadListingQuestionData, +} from "./listings-view.ts"; +import { loadListingOr } from "./load-listing.ts"; /** * The listing entity page's loaded row: the listing plus the derived flags any @@ -81,24 +85,21 @@ export type LoadedListing = { /** Load the listing and its cheap gating flags, or null when it is gone. * `hasEmailableAttendees` defaults to false here — the decrypt behind it is * deferred to the Actions tab, the only surface that reads it. */ -export const loadListingForPage = async ( - id: number, -): Promise => { - const listing = await getListingWithCount(id); - if (!listing) return null; - const [isChild, hiddenMemberIds] = await Promise.all([ - // A `bookable_alone` child keeps its standalone share / QR affordances, so - // gate on non-standalone children only (matches the public booking guard). - anyNonStandaloneChild([id]), - getHiddenPackageMemberIds([id]), - ]); - return { - hasEmailableAttendees: false, - isChild, - isHiddenPackageMember: hiddenMemberIds.size > 0, - listing, - }; -}; +export const loadListingForPage = (id: number): Promise => + loadListingOr(id, async (listing) => { + const [isChild, hiddenMemberIds] = await Promise.all([ + // A `bookable_alone` child keeps its standalone share / QR affordances, so + // gate on non-standalone children only (matches the public booking guard). + anyNonStandaloneChild([id]), + getHiddenPackageMemberIds([id]), + ]); + return { + hasEmailableAttendees: false, + isChild, + isHiddenPackageMember: hiddenMemberIds.size > 0, + listing, + }; + }); /** Whether the listing has at least one attendee with an email on file — the * same recipient resolution the bulk-email compose route uses, so the Email @@ -152,12 +153,6 @@ const loadDecryptedListingAttendees = async ( return decryptAttendees(attendeesRaw, privateKey); }; -/** Attendees filtered to a single date (daily listings), else the full set. */ -const filterByDate = ( - attendees: Attendee[], - date: string | null, -): Attendee[] => (date ? attendees.filter((a) => a.date === date) : attendees); - /** The distinct booking dates present on a daily listing, ascending, as the * roster's date-picker options; empty for a non-daily listing. */ const availableDatesFor = ( diff --git a/src/features/admin/listing-qr.ts b/src/features/admin/listing-qr.ts index fc33885b09..f62c36b6c3 100644 --- a/src/features/admin/listing-qr.ts +++ b/src/features/admin/listing-qr.ts @@ -40,6 +40,7 @@ import type { AdminListingQrValues, } from "#templates/admin/listing-qr.tsx"; import { adminListingQrPage } from "#templates/admin/listing-qr.tsx"; +import { loadListingOr } from "./load-listing.ts"; export const EMPTY_QR_VALUES: AdminListingQrValues = { customer_name: "", @@ -86,11 +87,11 @@ type QrContext = { listing: ListingWithCount; bookableDates: string[] }; /** Load a listing and its child-constrained bookable dates, or null when the * listing is missing. */ -const loadQrContext = async (id: number): Promise => { - const listing = await getListingWithCount(id); - if (!listing) return null; - return { bookableDates: await loadBookableDates(listing), listing }; -}; +const loadQrContext = (id: number): Promise => + loadListingOr(id, async (listing) => ({ + bookableDates: await loadBookableDates(listing), + listing, + })); /** The QR form's per-listing context: the child-constrained bookable dates it * offers and whether the listing can take a direct checkout. Shared by the diff --git a/src/features/admin/listings-edit.ts b/src/features/admin/listings-edit.ts index b5978b57ce..db7b9a26c3 100644 --- a/src/features/admin/listings-edit.ts +++ b/src/features/admin/listings-edit.ts @@ -100,14 +100,23 @@ export const handleNewListingGet: TypedRouteHandler< if (template?.requiresLogistics && !settings.hasLogistics) { return htmlResponse(adminListingPickerPage(session)); } - const allGroups = await groups.cache.getAll(); - return htmlResponse( - adminListingNewPage(allGroups, session, { - templateId: template?.id ?? "custom", - }), - ); + return renderNewListingPage(session, { + templateId: template?.id ?? "custom", + }); }); +/** Load every group and render the new-listing form. Shared by the empty-form + * GET and the rejected-create re-render, which both fetch the group list then + * hand it to {@link adminListingNewPage}. */ +const renderNewListingPage = async ( + session: AdminSession, + opts: Parameters[2], + status?: number, +): Promise => { + const allGroups = await groups.cache.getAll(); + return htmlResponse(adminListingNewPage(allGroups, session, opts), status); +}; + /** Build a DimensionSource from submitted form params. */ const formToDimensionSource = (form: FormParams) => ({ date: form.getString("date_date") || "", @@ -184,9 +193,9 @@ const renderCreateListingError = async ( error: string, templateId: string | null, ): Promise => { - const allGroups = await groups.cache.getAll(); - return htmlResponse( - adminListingNewPage(allGroups, session, { + return renderNewListingPage( + session, + { customiseOpen: form.getFlag("customise"), error, // The group checkboxes the operator submitted, so a rejected create @@ -194,7 +203,7 @@ const renderCreateListingError = async ( selectedGroupIds: parseGroupIds(form), templateId, values: Object.fromEntries(form.entries()), - }), + }, 400, ); }; diff --git a/src/features/admin/listings-view.ts b/src/features/admin/listings-view.ts index 0492e37b1d..61e8791580 100644 --- a/src/features/admin/listings-view.ts +++ b/src/features/admin/listings-view.ts @@ -22,7 +22,7 @@ import type { Attendee, ListingWithCount } from "#shared/types.ts"; import type { GroupContext } from "#templates/admin/listings/types.ts"; /** Filter attendees by date for daily listings */ -const filterByDate = ( +export const filterByDate = ( attendees: Attendee[], date: string | null, ): Attendee[] => diff --git a/src/features/admin/load-listing.ts b/src/features/admin/load-listing.ts new file mode 100644 index 0000000000..1964778106 --- /dev/null +++ b/src/features/admin/load-listing.ts @@ -0,0 +1,21 @@ +/** + * Shared "fetch a listing by id, then build something from it" loader. + * + * The entity page loader and the QR context loader both fetch a listing and + * return null when it is gone, then assemble their own shape from the row. This + * keeps that fetch-then-null-guard in one place. + */ + +import { getListingWithCount } from "#shared/db/listings.ts"; +import type { ListingWithCount } from "#shared/types.ts"; + +/** Load the listing with the given id and build a value from it, or null when + * no such listing exists. */ +export const loadListingOr = async ( + id: number, + build: (listing: ListingWithCount) => T | Promise, +): Promise => { + const listing = await getListingWithCount(id); + if (!listing) return null; + return build(listing); +}; diff --git a/src/features/admin/modifiers.ts b/src/features/admin/modifiers.ts index 1f6793bb18..3310c59768 100644 --- a/src/features/admin/modifiers.ts +++ b/src/features/admin/modifiers.ts @@ -34,6 +34,7 @@ import { childUnreachableAddOnError, type ListingGroupMembership, listingIdsInGroups, + reachablePageIds, toListingGroupMembership, } from "#shared/db/modifier-resolve.ts"; import { @@ -176,11 +177,7 @@ const childAddOnSaveError = async ( // ticket contexts load active listings only (`withActiveListings`), so an // inactive listing serves nothing. `childIds` here is the narrowed // non-standalone set, so a flagged child is neither suppressed nor excluded. - const reachableIds = new Set( - allListings - .filter((listing) => listing.active && !childIds.has(listing.id)) - .map((listing) => listing.id), - ); + const reachableIds = reachablePageIds(allListings, childIds); return childUnreachableAddOnError( { active: candidate.active, diff --git a/src/features/admin/money-adjust.ts b/src/features/admin/money-adjust.ts index 30602c3692..1324d1c84e 100644 --- a/src/features/admin/money-adjust.ts +++ b/src/features/admin/money-adjust.ts @@ -18,11 +18,15 @@ * overshooting the target. */ +/* jscpd:ignore-start */ import { OWNER_FORM, withAuth } from "#routes/auth.ts"; import { errorRedirect, notFoundResponse, redirect } from "#routes/response.ts"; import { logActivity } from "#shared/db/activityLog.ts"; +import type { FormParams } from "#shared/form-data.ts"; import { parseSignedMinorUnits } from "#shared/validation/money.ts"; +/* jscpd:ignore-end */ + /** Configuration for one entity's money-correction handler. */ type MoneyAdjustConfig = { /** Load the entity by id (existence check + log label), or null when missing. */ @@ -45,17 +49,25 @@ type MoneyAdjustConfig = { * entity, parses the new figure, posts the delta as a `writeoff` adjustment, logs * a neutral message, and redirects back to the edit page with a success flash. */ +const applyMoneyAdjust = async ( + config: MoneyAdjustConfig, + id: number, + form: FormParams, +): Promise => { + const entity = await config.load(id); + if (!entity) return notFoundResponse(); + const target = parseSignedMinorUnits(form.getString(config.field)); + if (target === null) { + return errorRedirect(config.editPath(id), "Enter a valid amount"); + } + await config.adjust(entity, target); + await logActivity(config.logMessage(entity)); + return redirect(config.editPath(id), config.successMessage, true); +}; + export const makeMoneyAdjustHandler = (config: MoneyAdjustConfig) => (request: Request, id: number): Promise => - withAuth(request, OWNER_FORM, async (_session, form) => { - const entity = await config.load(id); - if (!entity) return notFoundResponse(); - const target = parseSignedMinorUnits(form.getString(config.field)); - if (target === null) { - return errorRedirect(config.editPath(id), "Enter a valid amount"); - } - await config.adjust(entity, target); - await logActivity(config.logMessage(entity)); - return redirect(config.editPath(id), config.successMessage, true); - }); + withAuth(request, OWNER_FORM, (_session, form) => + applyMoneyAdjust(config, id, form), + ); diff --git a/src/features/admin/news.ts b/src/features/admin/news.ts index 0f7ba736c9..23ac5097e5 100644 --- a/src/features/admin/news.ts +++ b/src/features/admin/news.ts @@ -43,10 +43,10 @@ import { siteConfirmAuth, siteContentGet, siteContentPaths, - siteContentPost, siteEntityPost, validateContentFormOr, } from "./site-content.ts"; +import { siteCreatePost } from "./site-content-create.ts"; /* jscpd:ignore-end */ @@ -79,16 +79,18 @@ const renderList = siteContentGet(async (session) => const renderNew = siteContentGet((session) => adminNewsNewPage(session)); -const handleCreate = siteContentPost(async (form) => { - const fields = validateFields(form, paths.newPage); - if (!fields.ok) return fields.response; - const post = await createNewsPost(fields.input); - return savedContentResponse( - paths.edit(post.id), - `News post '${post.name}' created`, - t("news.created"), - ); -}); +const handleCreate = siteCreatePost( + paths.newPage, + validateFields, + async (fields) => { + const post = await createNewsPost(fields.input); + return { + flashMessage: t("news.created"), + logMessage: `News post '${post.name}' created`, + path: paths.edit(post.id), + }; + }, +); const handleUpdate = siteEntityPost(getNewsPostById)(async (post, form) => { const editPath = paths.edit(post.id); diff --git a/src/features/admin/settings-email-templates.ts b/src/features/admin/settings-email-templates.ts index e2b72b7051..0820c18965 100644 --- a/src/features/admin/settings-email-templates.ts +++ b/src/features/admin/settings-email-templates.ts @@ -13,6 +13,7 @@ import { renderTemplate, validateTemplate, } from "#shared/email-renderer.ts"; +import type { FormParams } from "#shared/form-data.ts"; import { type EmailTemplateType, isEmailTemplateFormat, @@ -151,38 +152,45 @@ const PREVIEW_BOOKINGS = [ const PREVIEW_CURRENCY = "GBP"; const PREVIEW_TICKET_URL = "https://example.com/t/SAMPLE123+SAMPLE456"; -/** Handle POST /admin/settings/email-templates/preview - render template with sample data */ -export const handleEmailTemplatePreviewPost = ( - request: Request, -): Promise => - withAuth(request, OWNER_FORM, async (_session, form) => { - const type = form.getString("type"); - const template = form.getString("template"); - const rawFormat = form.get("format") ?? "html"; +/** Render an email template with sample data (owner-only preview). */ +const renderEmailTemplatePreview = async ( + form: FormParams, +): Promise => { + const type = form.getString("type"); + const template = form.getString("template"); + const rawFormat = form.get("format") ?? "html"; - if (!isEmailTemplateType(type)) { - return jsonResponse({ error: "Invalid template type" }, 400); - } - if (!isEmailTemplateFormat(rawFormat)) { - return jsonResponse({ error: "Invalid template format" }, 400); - } - const format = rawFormat; + if (!isEmailTemplateType(type)) { + return jsonResponse({ error: "Invalid template type" }, 400); + } + if (!isEmailTemplateFormat(rawFormat)) { + return jsonResponse({ error: "Invalid template format" }, 400); + } + const format = rawFormat; - const error = validateTemplate(template); - if (error) { - return jsonResponse({ error: `Template syntax error: ${error}` }, 400); - } + const error = validateTemplate(template); + if (error) { + return jsonResponse({ error: `Template syntax error: ${error}` }, 400); + } - const sampleData = await buildTemplateData( - PREVIEW_BOOKINGS, - PREVIEW_CURRENCY, - PREVIEW_TICKET_URL, - ); + const sampleData = await buildTemplateData( + PREVIEW_BOOKINGS, + PREVIEW_CURRENCY, + PREVIEW_TICKET_URL, + ); - try { - const rendered = await renderTemplate(template, sampleData); - return jsonResponse({ format, rendered }); - } catch (err) { - return jsonResponse({ error: String(err) }, 400); - } - }); + try { + const rendered = await renderTemplate(template, sampleData); + return jsonResponse({ format, rendered }); + } catch (err) { + return jsonResponse({ error: String(err) }, 400); + } +}; + +/** Handle POST /admin/settings/email-templates/preview - render template with sample data */ +export const handleEmailTemplatePreviewPost = ( + request: Request, +): Promise => + withAuth(request, OWNER_FORM, (_session, form) => + renderEmailTemplatePreview(form), + ); diff --git a/src/features/admin/settings-email.ts b/src/features/admin/settings-email.ts index e0c0078184..c241572e0f 100644 --- a/src/features/admin/settings-email.ts +++ b/src/features/admin/settings-email.ts @@ -4,6 +4,7 @@ */ import { t } from "#i18n"; +/* jscpd:ignore-start */ import { advancedSettingsRoute, processSecretField, @@ -12,6 +13,7 @@ import { settingsHandler, } from "#routes/admin/settings-helpers.ts"; import { settings } from "#shared/db/settings.ts"; +/* jscpd:ignore-end */ import { getEmailConfig, isEmailProvider, diff --git a/src/features/admin/settings-sms.ts b/src/features/admin/settings-sms.ts index 7226728d04..81eda7d59c 100644 --- a/src/features/admin/settings-sms.ts +++ b/src/features/admin/settings-sms.ts @@ -6,6 +6,7 @@ * unchanged, an empty value clears it. */ +/* jscpd:ignore-start */ import { processSecretField, type SecretFieldResult, @@ -13,6 +14,7 @@ import { settingsHandler, } from "#routes/admin/settings-helpers.ts"; import { settings } from "#shared/db/settings.ts"; +/* jscpd:ignore-end */ import { SMS_PASSPHRASE_MIN_LENGTH } from "#shared/sms/e2e.ts"; import { validateSafeServerFetchUrl } from "#shared/url-safety.ts"; diff --git a/src/features/admin/settings-statuses.ts b/src/features/admin/settings-statuses.ts index c7018e512f..4755d43d3f 100644 --- a/src/features/admin/settings-statuses.ts +++ b/src/features/admin/settings-statuses.ts @@ -90,6 +90,16 @@ const parseStatusForm = (form: FormParams): ParseResult => { }; }; +// Parses the status form for a page whose form lives at `formPath`. Returns the +// valid data, or the redirect back to that form carrying the error message. +const parseStatusFormOr = ( + form: FormParams, + formPath: string, +): StatusFormData | Response => { + const parsed = parseStatusForm(form); + return parsed.ok ? parsed.data : errorRedirect(formPath, parsed.error); +}; + /** After a write, ensure at most one public-default and one paid-default. */ const clearOtherDefaults = async ( id: number, @@ -145,12 +155,12 @@ const editGet = ownerStatusPage((status, session) => const createPost = createAuthedHandler({ auth: OWNER_FORM, handle: async ({ form }) => { - const parsed = parseStatusForm(form); - if (!parsed.ok) return errorRedirect(`${LIST_PATH}/new`, parsed.error); - const status = await attendeeStatuses.table.insert(parsed.data); + const parsed = parseStatusFormOr(form, `${LIST_PATH}/new`); + if (parsed instanceof Response) return parsed; + const status = await attendeeStatuses.table.insert(parsed); await assignNextAttendeeStatusSortOrder(status.id); - await clearOtherDefaults(status.id, parsed.data); - await logActivity(`Attendee status '${parsed.data.name}' created`); + await clearOtherDefaults(status.id, parsed); + await logActivity(`Attendee status '${parsed.name}' created`); return redirect(LIST_PATH, "Status created", true); }, }); @@ -158,25 +168,25 @@ const createPost = createAuthedHandler({ const editPost = ownerFormById(async (id, _session, form) => { const existing = await getAttendeeStatus(id); if (!existing) return notFoundResponse(); - const parsed = parseStatusForm(form); - if (!parsed.ok) return errorRedirect(`${LIST_PATH}/${id}/edit`, parsed.error); + const parsed = parseStatusFormOr(form, `${LIST_PATH}/${id}/edit`); + if (parsed instanceof Response) return parsed; - if (existing.is_public_default && !parsed.data.isPublicDefault) { + if (existing.is_public_default && !parsed.isPublicDefault) { return errorRedirect( `${LIST_PATH}/${id}/edit`, "Choose another public default before clearing this one", ); } - if (existing.is_paid_default && !parsed.data.isPaidDefault) { + if (existing.is_paid_default && !parsed.isPaidDefault) { return errorRedirect( `${LIST_PATH}/${id}/edit`, "Choose another paid default before clearing this one", ); } - await attendeeStatuses.table.update(id, parsed.data); - await clearOtherDefaults(id, parsed.data); - await logActivity(`Attendee status '${parsed.data.name}' updated`); + await attendeeStatuses.table.update(id, parsed); + await clearOtherDefaults(id, parsed); + await logActivity(`Attendee status '${parsed.name}' updated`); return redirect(LIST_PATH, "Status updated", true); }); diff --git a/src/features/admin/site-content-create.ts b/src/features/admin/site-content-create.ts new file mode 100644 index 0000000000..ddd77f13e7 --- /dev/null +++ b/src/features/admin/site-content-create.ts @@ -0,0 +1,43 @@ +/** + * Shared "create from the New form" wiring for the Site tab's hand-wired + * editors (Pages, News). Both open the same way — validate the form, bounce + * back on error, otherwise write the record and flash the saved confirmation — + * so that flow lives here once instead of in each editor. + */ + +import type { FormParams } from "#shared/form-data.ts"; +import { savedContentResponse, siteContentPost } from "./site-content.ts"; + +/** A form check's outcome: the checked values, or the bounce-back response. */ +export type ContentCheck = + | ({ ok: true } & T) + | { ok: false; response: Response }; + +/** What a successful create tells the caller to flash and where to go next. */ +type SavedContent = { + path: string; + logMessage: string; + flashMessage: string; +}; + +/** Build the POST handler for a New form: check the form (bouncing back to + * `newPagePath` on error), otherwise create the record and flash the saved + * confirmation. */ +export const siteCreatePost = ( + newPagePath: string, + check: ( + form: FormParams, + errorPath: string, + ) => ContentCheck | Promise>, + create: (checked: T, form: FormParams) => Promise, +): ((request: Request) => Promise) => + siteContentPost(async (form) => { + const checked = await check(form, newPagePath); + if (!checked.ok) return checked.response; + const saved = await create(checked, form); + return savedContentResponse( + saved.path, + saved.logMessage, + saved.flashMessage, + ); + }); diff --git a/src/features/admin/site-content.ts b/src/features/admin/site-content.ts index 521a67b899..0c3f45ae59 100644 --- a/src/features/admin/site-content.ts +++ b/src/features/admin/site-content.ts @@ -5,6 +5,7 @@ * save completion (activity log + flash redirect). */ +/* jscpd:ignore-start */ import type { FormGuard } from "#routes/admin/confirmation.ts"; import { requireSiteOr, SITE_FORM, withAuth } from "#routes/auth.ts"; import { gatedEntityRoute } from "#routes/entity.ts"; @@ -13,6 +14,7 @@ import { logActivity } from "#shared/db/activityLog.ts"; import type { FormParams } from "#shared/form-data.ts"; import type { ValidationResult } from "#shared/forms.tsx"; import type { AdminSession } from "#shared/types.ts"; +/* jscpd:ignore-end */ /** Standard list/new/edit paths for a Site-tab collection under `base`. */ export const siteContentPaths = (base: string) => ({ diff --git a/src/features/admin/site-pages.ts b/src/features/admin/site-pages.ts index 020a387c63..6d9639bf0b 100644 --- a/src/features/admin/site-pages.ts +++ b/src/features/admin/site-pages.ts @@ -65,10 +65,10 @@ import { siteConfirmAuth, siteContentGet, siteContentPaths, - siteContentPost, siteEntityPost, validateContentFormOr, } from "./site-content.ts"; +import { siteCreatePost } from "./site-content-create.ts"; import { buildListModel, offerableListing } from "./site-pages-data.ts"; import { sitePageForm } from "./site-pages-form.ts"; import { sitePageEntityPage } from "./site-pages-page.ts"; @@ -165,18 +165,20 @@ const renderList = siteContentGet(async (session) => const renderNew = siteContentGet((session) => adminSitePageNewPage(session)); -const handleCreate = siteContentPost(async (form) => { - const fields = await validateFields(form, paths.newPage); - if (!fields.ok) return fields.response; - const page = await createSitePage( - contentFields(form, fields.name, fields.slug), - ); - return savedContentResponse( - editPath(page.id), - `Page '${fields.name}' created`, - t("site.pages.created"), - ); -}); +const handleCreate = siteCreatePost( + paths.newPage, + validateFields, + async (fields, form) => { + const page = await createSitePage( + contentFields(form, fields.name, fields.slug), + ); + return { + flashMessage: t("site.pages.created"), + logMessage: `Page '${fields.name}' created`, + path: editPath(page.id), + }; + }, +); const handleUpdate = siteEntityPost(getSitePageById)(async (page, form) => { const fields = await validateFields(form, editPath(page.id), page.id); diff --git a/src/features/api/helpers.ts b/src/features/api/helpers.ts index 861bddff56..70ce5644d7 100644 --- a/src/features/api/helpers.ts +++ b/src/features/api/helpers.ts @@ -1,4 +1,5 @@ import { apiError, apiResponse } from "#routes/api/cors.ts"; +import type { JsonBodyReader } from "#routes/api/json-body.ts"; import type { ServerContext } from "#routes/types.ts"; import { getClientIp } from "#routes/url.ts"; import { bookingError, parseCustomPrice } from "#shared/booking/form.ts"; @@ -94,9 +95,7 @@ export const findActiveListing = async ( }; /** Parse a JSON request body, returning a 400 API response on failure */ -export const parseApiJsonBody = async ( - request: Request, -): Promise | Response> => { +export const parseApiJsonBody: JsonBodyReader = async (request) => { try { return await request.json(); } catch { diff --git a/src/features/api/json-body.ts b/src/features/api/json-body.ts new file mode 100644 index 0000000000..4239e060be --- /dev/null +++ b/src/features/api/json-body.ts @@ -0,0 +1,6 @@ +/** Reads a request's body into a plain record, or returns a failure Response + * when the body is missing or malformed. Both the cookie-auth JSON parser and + * the public API JSON parser answer this one shape, so they spell it once. */ +export type JsonBodyReader = ( + request: Request, +) => Promise | Response>; diff --git a/src/features/api/listings.ts b/src/features/api/listings.ts index 8f84793be3..9de1e4dc83 100644 --- a/src/features/api/listings.ts +++ b/src/features/api/listings.ts @@ -7,12 +7,14 @@ import { toPublicListing, toResolvedPublicListing, } from "#routes/api/public-listing.ts"; +/* jscpd:ignore-start */ import { isRegistrationClosed } from "#routes/format.ts"; import { classifyForDiscovery, dropHiddenPackageMembers, loadBookablePackages, } from "#routes/public/discovery.ts"; +/* jscpd:ignore-end */ import { keepParentDailyDatesChildrenCanServe } from "#routes/public/ticket-payment.ts"; import { capacityDateFor } from "#shared/capacity-rules.ts"; import { getAvailableDates, getBookableStartDates } from "#shared/dates.ts"; diff --git a/src/features/auth.ts b/src/features/auth.ts index 5356f0cf80..0cf69b1cb2 100644 --- a/src/features/auth.ts +++ b/src/features/auth.ts @@ -2,6 +2,7 @@ * Authentication and session utilities */ +import type { JsonBodyReader } from "#routes/api/json-body.ts"; import { parseFormData } from "#routes/csrf.ts"; import { htmlResponse, @@ -326,6 +327,15 @@ export const SCANNER_JSON: AuthPolicy<"json"> = { csrfMaxAge: SCANNER_CSRF_MAX_AGE_S, }; +/** Get the current cookie session, or the channel's not-authenticated failure. */ +const cookieSessionOrFailure = async ( + request: Request, + channel: AuthChannel, +): Promise => { + const session = await getAuthenticatedSession(request); + return session ?? authFailure(channel, "not-authenticated"); +}; + /** * Core session + role gate. Returns the session on success, or a * channel-appropriate failure Response. @@ -336,8 +346,8 @@ const requireSessionFor = async ( role?: AdminLevel, roles?: readonly AdminLevel[], ): Promise => { - const session = await getAuthenticatedSession(request); - if (!session) return authFailure(channel, "not-authenticated"); + const session = await cookieSessionOrFailure(request, channel); + if (isResponse(session)) return session; if (!sessionRoleAllowed(session.adminLevel, role, roles)) { return authFailure(channel, "forbidden"); } @@ -499,11 +509,14 @@ export const authFailure = ( const isSafeMethod = (request: Request): boolean => request.method === "GET" || request.method === "HEAD"; +/** The request's Content-Type header, lowercased — HTTP header values are + * case-insensitive, so callers match casings uniformly. */ +export const lowerContentType = (request: Request): string => + (request.headers.get("content-type") ?? "").toLowerCase(); + /** Parse JSON body, returning empty object for non-JSON GET/HEAD requests */ -const parseJsonBody = async ( - request: Request, -): Promise | Response> => { - const contentType = (request.headers.get("content-type") ?? "").toLowerCase(); +const parseJsonBody: JsonBodyReader = async (request) => { + const contentType = lowerContentType(request); const bodyRequired = !isSafeMethod(request); if (!contentType.includes("application/json")) { @@ -599,9 +612,8 @@ const resolveSession = async ( if (s) return { authKind: "apiKey", session: s }; if (getBearerToken(request)) return authFailure(channel, "invalid-api-key"); } - const session = await getAuthenticatedSession(request); - if (!session) return authFailure(channel, "not-authenticated"); - return { authKind: "cookie", session }; + const session = await cookieSessionOrFailure(request, channel); + return isResponse(session) ? session : { authKind: "cookie", session }; }; /** Unified auth pipeline: authenticate, enforce role, validate CSRF, parse body. */ diff --git a/src/features/feeds.ts b/src/features/feeds.ts index c6056064e8..30277cc34a 100644 --- a/src/features/feeds.ts +++ b/src/features/feeds.ts @@ -5,12 +5,14 @@ import { map, pipe } from "#fp"; import { withAuth } from "#routes/auth.ts"; +/* jscpd:ignore-start */ import { isRegistrationClosed } from "#routes/format.ts"; import { classifyForDiscovery, dropHiddenPackageMembers, loadBookablePackages, } from "#routes/public/discovery.ts"; +/* jscpd:ignore-end */ import { icsResponse, redirectResponse, @@ -30,6 +32,7 @@ import { import { getNewsPostSummaries } from "#shared/db/news-posts.ts"; import { settings } from "#shared/db/settings.ts"; import { userAgents } from "#shared/db/user-agents.ts"; +import { listingsById } from "#shared/listings-by-id.ts"; import { getRequestPrivateKey } from "#shared/session-private-key.ts"; import { type ListingWithCount, @@ -341,7 +344,7 @@ const buildCalendarFeed = async (request: Request): Promise => { const privateKey = await getRequestPrivateKey(); if (!privateKey) return new Response("Forbidden", { status: 403 }); const listings = await getAllListings(); - const listingById = new Map(listings.map((l) => [l.id, l])); + const listingById = listingsById(listings); const rawAttendees = await getAttendeesByListingIds( listings.map((l) => l.id), // Operational ICS feed: exclude no-quantity sentinel lines. diff --git a/src/features/flash-for-page.ts b/src/features/flash-for-page.ts new file mode 100644 index 0000000000..542a17e36c --- /dev/null +++ b/src/features/flash-for-page.ts @@ -0,0 +1,11 @@ +import { applyFlash } from "#routes/csrf.ts"; +import { signCsrfToken } from "#shared/csrf.ts"; + +/** Read this request's flash message and refresh its CSRF token, ready to + * render a page. Returns the flash values (error/info/success) to show. Shared + * by the page handlers that open with this same two-step preamble. */ +export const flashForPage = async (request: Request) => { + const flash = applyFlash(request); + await signCsrfToken(); + return flash; +}; diff --git a/src/features/index.ts b/src/features/index.ts index f64e447034..b2e0e184e6 100644 --- a/src/features/index.ts +++ b/src/features/index.ts @@ -5,7 +5,7 @@ import { once, reduce } from "#fp"; import { parseAcceptLanguage, runWithLocale } from "#i18n"; -import { SessionKeyError } from "#routes/auth.ts"; +import { lowerContentType, SessionKeyError } from "#routes/auth.ts"; import { applySecurityHeaders, contentTypeRejectionResponse, @@ -577,7 +577,7 @@ const bufferRequestIfNeeded = async (request: Request): Promise => { // buffer gate accepts the same casings `isValidContentType` does — otherwise a // standards-compliant `Application/JSON` would be validated but skip buffering, // reopening the GC window for that casing. - const contentType = (request.headers.get("content-type") ?? "").toLowerCase(); + const contentType = lowerContentType(request); const needsBuffer = BUFFERED_POST_CONTENT_TYPES.some((type) => contentType.startsWith(type), ); diff --git a/src/features/join.ts b/src/features/join.ts index b732b331eb..0deca6a5d9 100644 --- a/src/features/join.ts +++ b/src/features/join.ts @@ -70,14 +70,25 @@ const validateInvite = async ( return { user, username: await decryptUsername(user) }; }; +// Runs once an invite code has been checked, with the code, the invited user, +// and their decrypted username. +type InviteHandler = ( + code: string, + user: User, + username: string, +) => Response | Promise; + +// The same, for a route: the incoming request comes first, then the checked +// invite details. +type RequestInviteHandler = ( + request: Request, + ...invite: Parameters +) => ReturnType; + /** Run handler with validated invite, returning error response if invalid */ const withValidInvite = async ( code: string, - handler: ( - code: string, - user: User, - username: string, - ) => Response | Promise, + handler: InviteHandler, ): Promise => { const result = await validateInvite(code); return result instanceof Response @@ -90,14 +101,7 @@ type InviteCodeParams = { code: string }; /** Create a join route handler that validates the invite code before running the callback */ const joinRoute = - ( - handler: ( - request: Request, - code: string, - user: User, - username: string, - ) => Response | Promise, - ) => + (handler: RequestInviteHandler) => (request: Request, { code }: InviteCodeParams): Promise => withValidInvite(code, (code, user, username) => handler(request, code, user, username), diff --git a/src/features/public/discovery.ts b/src/features/public/discovery.ts index 87aad932b7..6b80f10840 100644 --- a/src/features/public/discovery.ts +++ b/src/features/public/discovery.ts @@ -44,6 +44,7 @@ import { getNonStandaloneChildIds, getParentsForChildren, } from "#shared/db/listing-parents.ts"; +import { listingsById } from "#shared/listings-by-id.ts"; import { availableDayCounts, type Group, @@ -291,7 +292,7 @@ export const classifyForDiscovery = async ( getChildrenForParents(ids), getParentsForChildren(ids), ]); - const byId = new Map(listings.map((l) => [l.id, l])); + const byId = listingsById(listings); const everyChild = [...childrenByParent.values()].flat(); // Displayed children whose add-on label we are deciding (keys of parentsByChild // are among the displayed `ids`, so they are in `byId`). Their own group-remaining diff --git a/src/features/public/ticket-page-url.ts b/src/features/public/ticket-page-url.ts new file mode 100644 index 0000000000..f000f8d1f7 --- /dev/null +++ b/src/features/public/ticket-page-url.ts @@ -0,0 +1,7 @@ +import type { TicketCtx } from "./types.ts"; + +/** The URL a ticket page's form posts to, and falls back to on error. Uses the + * context's own action URL when set (renewal, order page), otherwise the plain + * ticket page for the chosen listing slugs. */ +export const ticketPageUrl = (ctx: TicketCtx): string => + ctx.actionUrl ?? `/ticket/${ctx.slugs.join("+")}`; diff --git a/src/features/public/ticket-payment.ts b/src/features/public/ticket-payment.ts index 27dd879ecf..62144c4c1f 100644 --- a/src/features/public/ticket-payment.ts +++ b/src/features/public/ticket-payment.ts @@ -2,7 +2,7 @@ * Payment flow, availability checks, and free registration */ -import { compact } from "#fp"; +import { compact, unique } from "#fp"; import { checkoutResponse } from "#routes/payment-response.ts"; import { errorRedirect, notFoundResponse } from "#routes/response.ts"; import { getBaseUrl } from "#routes/url.ts"; @@ -101,6 +101,7 @@ import { import { parsePositiveInt } from "#shared/validation/number.ts"; import { listingsWithQuantity } from "./ticket-form.ts"; import { buildTicketListingsWithGroupCapacity } from "./ticket-listings.ts"; +import { ticketPageUrl } from "./ticket-page-url.ts"; import type { AsyncHandler, ChildrenByParentId, @@ -258,8 +259,7 @@ export const handlePaymentFlow = ( `ticket items=${intent.items.length}`, request, (provider, baseUrl) => provider.createCheckoutSession(intent, baseUrl), - (msg) => - errorRedirect(ctx.actionUrl ?? `/ticket/${ctx.slugs.join("+")}`, msg), + (msg) => errorRedirect(ticketPageUrl(ctx), msg), ); const buildBookings = ( @@ -705,13 +705,10 @@ export const loadChildrenByParentId = async ( /** Distinct child listing ids across every parent's children. */ export const childListingIdsOf = ( childrenByParentId: ChildrenByParentId, -): number[] => { - const ids = new Set(); - for (const children of childrenByParentId.values()) { - for (const child of children) ids.add(child.listing.id); - } - return [...ids]; -}; +): number[] => + unique( + [...childrenByParentId.values()].flat().map((child) => child.listing.id), + ); /** Day counts the parent can pass to daily children. */ const parentDayCountsForChildren = (parent: ListingWithCount): number[] => { diff --git a/src/features/public/ticket-submit.ts b/src/features/public/ticket-submit.ts index 17a0443509..3a3f48c36a 100644 --- a/src/features/public/ticket-submit.ts +++ b/src/features/public/ticket-submit.ts @@ -53,6 +53,7 @@ import { ticketResponse, } from "./ticket-form.ts"; import { buildTicketListingsWithGroupCapacity } from "./ticket-listings.ts"; +import { ticketPageUrl } from "./ticket-page-url.ts"; import { checkAvailability, dropChildListings, @@ -220,8 +221,7 @@ const submitTicket = (request: Request, ctx: TicketCtx): Promise => // CSRF failures redirect with a flash (the token expired or was tampered // with — the page reloads with a fresh token). Field-level validation // errors instead re-render inline so the visitor keeps what they entered. - (message) => - errorRedirect(ctx.actionUrl ?? `/ticket/${ctx.slugs.join("+")}`, message), + (message) => errorRedirect(ticketPageUrl(ctx), message), (form) => { applyDemoOverrides(form, ATTENDEE_DEMO_FIELDS); return processSubmission(request, ctx, form); diff --git a/src/features/public/ticket-submit/paths.ts b/src/features/public/ticket-submit/paths.ts index 98d432a947..684bb476e2 100644 --- a/src/features/public/ticket-submit/paths.ts +++ b/src/features/public/ticket-submit/paths.ts @@ -6,6 +6,7 @@ */ import { redirectResponse } from "#routes/response.ts"; +import type { OrderSpan } from "#shared/booking/order-span.ts"; import type { ModifierApplication, PricedOrder, @@ -32,12 +33,8 @@ import { import type { TicketCtx } from "../types.ts"; import { type AnswerInfo, computeListingTextAnswerIdMap } from "./parse.ts"; -export type PathParams = { +export type PathParams = OrderSpan & { ctx: TicketCtx; - quantities: Map; - date: string | null; - dayCount: number; - hasCustomisable: boolean; contact: ReturnType; info: AnswerInfo; }; diff --git a/src/features/public/unsubscribe.ts b/src/features/public/unsubscribe.ts index 813880f08b..4df3fdc9ff 100644 --- a/src/features/public/unsubscribe.ts +++ b/src/features/public/unsubscribe.ts @@ -6,9 +6,9 @@ * on their own address via the capability in their link. */ -import { applyFlash, withCsrfForm } from "#routes/csrf.ts"; +import { withCsrfForm } from "#routes/csrf.ts"; +import { flashForPage } from "#routes/flash-for-page.ts"; import { htmlResponse, infoRedirect, redirect } from "#routes/response.ts"; -import { signCsrfToken } from "#shared/csrf.ts"; import { forgetContact, isHashUnsubscribed, @@ -24,8 +24,7 @@ const pagePath = (hash: string): string => export const handleUnsubscribeGet = async ( request: Request, ): Promise => { - const flash = applyFlash(request); - await signCsrfToken(); + const flash = await flashForPage(request); const hash = new URL(request.url).searchParams.get("email"); const unsubscribed = hash ? await isHashUnsubscribed(hash) : false; return htmlResponse( diff --git a/src/shared/accounting/manual-entries.ts b/src/shared/accounting/manual-entries.ts index c69ec3f2c9..19c082a6f9 100644 --- a/src/shared/accounting/manual-entries.ts +++ b/src/shared/accounting/manual-entries.ts @@ -61,16 +61,28 @@ export type ManualLedgerEntryOption = { readonly hintKey: string; }; +type TransferLegs = Pick; + type ManualEntrySpec = { readonly accountType: string; readonly labelKey: string; readonly hintKey: string; readonly descriptionKey: string; - readonly legs: ( - account: AccountRef, - ) => Pick; + readonly legs: (account: AccountRef) => TransferLegs; }; +/** Money arriving into the chosen account from a fixed source (WORLD for new + * money, WRITEOFF for money the business forgives). */ +const moneyInto = + (source: AccountRef) => + (account: AccountRef): TransferLegs => ({ destination: account, source }); + +/** Money leaving the chosen account to a fixed destination (WORLD when it + * leaves the business, WRITEOFF when the business absorbs it). */ +const moneyOutOf = + (destination: AccountRef) => + (account: AccountRef): TransferLegs => ({ destination, source: account }); + /** * One spec per entry type, keyed by the picklist so the Record is exhaustive by * construction — a new entry type is a compile error here, never a silent @@ -86,49 +98,49 @@ export const manualEntrySpecByType: Record< descriptionKey: "admin.ledger.human.manual_attendee_payment", hintKey: "admin.ledger.add.option.attendee_payment.hint", labelKey: "admin.ledger.add.option.attendee_payment.label", - legs: (account) => ({ destination: account, source: WORLD }), + legs: moneyInto(WORLD), }, [MANUAL_ATTENDEE_CHARGE]: { accountType: "attendee", descriptionKey: "admin.ledger.human.manual_attendee_charge", hintKey: "admin.ledger.add.option.attendee_charge.hint", labelKey: "admin.ledger.add.option.attendee_charge.label", - legs: (account) => ({ destination: WRITEOFF, source: account }), + legs: moneyOutOf(WRITEOFF), }, [MANUAL_ATTENDEE_WRITEOFF]: { accountType: "attendee", descriptionKey: "admin.ledger.human.manual_attendee_writeoff", hintKey: "admin.ledger.add.option.attendee_writeoff.hint", labelKey: "admin.ledger.add.option.attendee_writeoff.label", - legs: (account) => ({ destination: account, source: WRITEOFF }), + legs: moneyInto(WRITEOFF), }, [MANUAL_LISTING_INCOME]: { accountType: "revenue", descriptionKey: "admin.ledger.human.manual_listing_income", hintKey: "admin.ledger.add.option.listing_income.hint", labelKey: "admin.ledger.add.option.listing_income.label", - legs: (account) => ({ destination: account, source: WORLD }), + legs: moneyInto(WORLD), }, [MANUAL_LISTING_COST]: { accountType: "revenue", descriptionKey: "admin.ledger.human.manual_listing_cost", hintKey: "admin.ledger.add.option.listing_cost.hint", labelKey: "admin.ledger.add.option.listing_cost.label", - legs: (account) => ({ destination: WORLD, source: account }), + legs: moneyOutOf(WORLD), }, [MANUAL_MODIFIER_INCOME]: { accountType: "modifier", descriptionKey: "admin.ledger.human.manual_modifier_income", hintKey: "admin.ledger.add.option.modifier_income.hint", labelKey: "admin.ledger.add.option.modifier_income.label", - legs: (account) => ({ destination: account, source: WRITEOFF }), + legs: moneyInto(WRITEOFF), }, [MANUAL_MODIFIER_REDUCTION]: { accountType: "modifier", descriptionKey: "admin.ledger.human.manual_modifier_reduction", hintKey: "admin.ledger.add.option.modifier_reduction.hint", labelKey: "admin.ledger.add.option.modifier_reduction.label", - legs: (account) => ({ destination: WRITEOFF, source: account }), + legs: moneyOutOf(WRITEOFF), }, }; diff --git a/src/shared/app-forms.ts b/src/shared/app-forms.ts index 3ad8f75716..b3b75724e6 100644 --- a/src/shared/app-forms.ts +++ b/src/shared/app-forms.ts @@ -73,20 +73,15 @@ export const createAuthedHandler = // ── createAuthedFormRoute: adds schema validation on top ────────────── -type HandlerArgs = { - context: TContext; - form: FormParams; - params: TParams; - session: AuthSession; +type HandlerArgs = AuthedHandlerArgs< + TParams, + TContext +> & { values: TValues; }; -type InvalidArgs = { - context: TContext; +type InvalidArgs = AuthedHandlerArgs & { error: string; - form: FormParams; - params: TParams; - session: AuthSession; }; type FormRouteConfig = AuthedBase< diff --git a/src/shared/booking/capacity-tree.ts b/src/shared/booking/capacity-tree.ts index 9e9d8ed7ac..58cf8a433c 100644 --- a/src/shared/booking/capacity-tree.ts +++ b/src/shared/booking/capacity-tree.ts @@ -1,3 +1,4 @@ +import { sumByKey } from "#fp"; import { type TicketListing, ticketsThatFitInPool, @@ -31,17 +32,20 @@ export const packageQuantityLimit = ( }; const perMember = Math.min(...tree.nodes.map(ownLimit)); - const ticketsNeededByGroup = new Map(); - for (const node of tree.nodes) { - const q = perPackageQty(node); - for (const groupId of groupIdsByListingId.get(node.listingId) ?? []) { - if (!groupRemainingByGroupId.has(groupId)) continue; - ticketsNeededByGroup.set( - groupId, - (ticketsNeededByGroup.get(groupId) ?? 0) + q, - ); - } - } + // Every (group this member shares, tickets it needs there) pair, dropping + // groups with no remaining pool, then summed per group. + const groupTickets = tree.nodes.flatMap((node) => + (groupIdsByListingId.get(node.listingId) ?? []) + .filter((groupId) => groupRemainingByGroupId.has(groupId)) + .map((groupId) => ({ groupId, tickets: perPackageQty(node) })), + ); + const ticketsNeededByGroup = sumByKey< + { groupId: number; tickets: number }, + number + >( + (row) => row.groupId, + (row) => row.tickets, + )(groupTickets); let limit = perMember; for (const [groupId, ticketsNeeded] of ticketsNeededByGroup) { limit = Math.min( diff --git a/src/shared/booking/fold-tree.ts b/src/shared/booking/fold-tree.ts index 84b6cb009f..e5accdd0c5 100644 --- a/src/shared/booking/fold-tree.ts +++ b/src/shared/booking/fold-tree.ts @@ -10,6 +10,8 @@ import { childUsesSameDays, type TicketListing, } from "#shared/booking/model.ts"; +import { nodesDeepestFirst } from "#shared/booking/node-order.ts"; +import type { OrderSpan } from "#shared/booking/order-span.ts"; import { priceRuleByListingId } from "#shared/booking/price-tree.ts"; import type { BookingNode, @@ -115,12 +117,8 @@ export type FoldChildrenResult = /** The resolved inputs the fold needs beyond the tree: the page's date/day-count, * whether a page line was already customisable, the base quantity/custom-price * maps (page listings, before children fold in), and the active holidays. */ -export type FoldBase = { - quantities: Map; +export type FoldBase = OrderSpan & { customPrices: Map; - date: string | null; - dayCount: number; - hasCustomisable: boolean; }; /** A bookable child paired with the per-unit quantity chosen under one parent @@ -355,18 +353,15 @@ export const resolvedByNodeKey = ( ]), ); const resolved = new Map(); - const visit = (nodes: readonly BookingNode[]): void => { - for (const node of nodes) { - resolved.set( - node.nodeKey, - node.edgeRef.kind === "parent_child" - ? childByParent.get(node.edgeRef.parentId)!.get(node.listingId)! - : topById.get(node.listingId)!, - ); - visit(node.children); - } - }; - visit(tree.nodes); + // Each nodeKey is unique, so any full walk reaches them all — order is moot. + for (const node of nodesDeepestFirst(tree)) { + resolved.set( + node.nodeKey, + node.edgeRef.kind === "parent_child" + ? childByParent.get(node.edgeRef.parentId)!.get(node.listingId)! + : topById.get(node.listingId)!, + ); + } return resolved; }; diff --git a/src/shared/booking/node-order.ts b/src/shared/booking/node-order.ts new file mode 100644 index 0000000000..14067be53b --- /dev/null +++ b/src/shared/booking/node-order.ts @@ -0,0 +1,21 @@ +import type { BookingNode, BookingTree } from "#shared/booking/tree.ts"; + +/** + * Every node in the tree with the deepest children first and the top-level + * nodes last. Writing a listing-id-keyed map in this order lets a top-level + * node have the final say over a same-id child, because the top-level node is + * written after (and so overwrites) its descendants — the "top-level wins" + * rule the price-rule map relies on. Callers that don't care about order + * (unique keys) can walk it just to reach every node once. + */ +export const nodesDeepestFirst = (tree: BookingTree): BookingNode[] => { + const byDepth: BookingNode[][] = []; + const collect = (nodes: readonly BookingNode[], depth: number): void => { + const atDepth = byDepth[depth] ?? []; + byDepth[depth] = atDepth; + atDepth.push(...nodes); + for (const node of nodes) collect(node.children, depth + 1); + }; + collect(tree.nodes, 0); + return byDepth.reverse().flat(); +}; diff --git a/src/shared/booking/order-lines.ts b/src/shared/booking/order-lines.ts index f96546bc3c..3a37345822 100644 --- a/src/shared/booking/order-lines.ts +++ b/src/shared/booking/order-lines.ts @@ -1,3 +1,4 @@ +import { sumByKey } from "#fp"; import { effectivePrice } from "#shared/booking/price-tree.ts"; import { type BookingNode, @@ -53,13 +54,17 @@ export const aggregateNodeQuantities = ( tree: BookingTree, nodeQuantities: ReadonlyMap, ): Map => { - const totals = new Map(); - for (const node of tree.nodes) { - const quantity = nodeQuantities.get(node.nodeKey) ?? 0; - if (quantity <= 0) continue; - totals.set(node.listingId, (totals.get(node.listingId) ?? 0) + quantity); - } - return totals; + const booked = tree.nodes + .map((node) => ({ + listingId: node.listingId, + quantity: nodeQuantities.get(node.nodeKey) ?? 0, + })) + // Zero-total listings are omitted, matching the parsed-quantities convention. + .filter((line) => line.quantity > 0); + return sumByKey<{ listingId: number; quantity: number }, number>( + (line) => line.listingId, + (line) => line.quantity, + )(booked); }; /** One child node per child listing id (child facets are derived from the diff --git a/src/shared/booking/order-span.ts b/src/shared/booking/order-span.ts new file mode 100644 index 0000000000..7498195d61 --- /dev/null +++ b/src/shared/booking/order-span.ts @@ -0,0 +1,10 @@ +/** The parsed span of a submitted order that several stages pass along: the + * per-listing quantities, the chosen date (or null), the booked day count, and + * whether any line is priced by that day count. Both the child-fold input and + * the completion paths build on these same facts. */ +export type OrderSpan = { + quantities: Map; + date: string | null; + dayCount: number; + hasCustomisable: boolean; +}; diff --git a/src/shared/booking/package-cap.ts b/src/shared/booking/package-cap.ts index 6c20a8a909..3ba575753f 100644 --- a/src/shared/booking/package-cap.ts +++ b/src/shared/booking/package-cap.ts @@ -20,9 +20,14 @@ import { sharedGroupRemaining, } from "#shared/types.ts"; +/** Spots still free in each capacity group, keyed by group id. */ +type GroupRemaining = ReadonlyMap; +/** The group ids each listing belongs to, keyed by listing id. */ +type GroupIdsByListing = ReadonlyMap; + export type GroupCapacityInfo = { - groupRemainingByGroupId: ReadonlyMap; - groupIdsByListingId: ReadonlyMap; + groupRemainingByGroupId: GroupRemaining; + groupIdsByListingId: GroupIdsByListing; }; export type PackageLimitInfo = GroupCapacityInfo & { @@ -31,15 +36,15 @@ export type PackageLimitInfo = GroupCapacityInfo & { }; export const groupCapacityInfo = ( - groupRemainingByGroupId: ReadonlyMap, - groupIdsByListingId: ReadonlyMap, + groupRemainingByGroupId: GroupRemaining, + groupIdsByListingId: GroupIdsByListing, ): GroupCapacityInfo => ({ groupIdsByListingId, groupRemainingByGroupId }); export const packageLimitInfo = ( listings: readonly TicketListing[], childrenByParentId: ReadonlyMap | undefined, - groupRemainingByGroupId: ReadonlyMap, - groupIdsByListingId: ReadonlyMap, + groupRemainingByGroupId: GroupRemaining, + groupIdsByListingId: GroupIdsByListing, ): PackageLimitInfo => ({ childrenByParentId, listings, diff --git a/src/shared/booking/price-tree.ts b/src/shared/booking/price-tree.ts index aed4946c3b..1746d0c2e0 100644 --- a/src/shared/booking/price-tree.ts +++ b/src/shared/booking/price-tree.ts @@ -1,3 +1,4 @@ +import { nodesDeepestFirst } from "#shared/booking/node-order.ts"; import { type BookingNode, type BookingTree, @@ -260,14 +261,10 @@ export const packageBundleTotal = ( * pass. */ export const priceRuleByListingId = ( tree: BookingTree, -): Map => { - const map = new Map(); - // Set deeper (child) rules first, then shallower (top-level) rules, so a +): Map => + // Deepest (child) rules are written first and top-level rules last, so a // top-level node overwrites a same-id descendant — top-level wins. - const visit = (nodes: readonly BookingNode[]): void => { - for (const node of nodes) visit(node.children); - for (const node of nodes) map.set(node.listingId, node.priceRule); - }; - visit(tree.nodes); - return map; -}; + nodesDeepestFirst(tree).reduce((map, node) => { + map.set(node.listingId, node.priceRule); + return map; + }, new Map()); diff --git a/src/shared/bunny-cdn.ts b/src/shared/bunny-cdn.ts index d6fb90a73a..9cf6a5b1d0 100644 --- a/src/shared/bunny-cdn.ts +++ b/src/shared/bunny-cdn.ts @@ -156,6 +156,14 @@ const pullZonePost = async ( return okOrError(response, label); }; +/** A Bunny API request that carries only the AccessKey header and no body — + * the shared shape of the plain GET/DELETE calls. */ +const bunnyKeyRequest = (url: string, method: string): Promise => + fetchText(url, { + headers: { AccessKey: getBunnyApiKey() }, + method, + }); + /** Request a free Let's Encrypt certificate for a hostname on a pull zone. */ const loadFreeCertificate = async ( hostname: string, @@ -164,10 +172,7 @@ const loadFreeCertificate = async ( hostname, )}`; - const response = await fetchText(url, { - headers: { AccessKey: getBunnyApiKey() }, - method: "GET", - }); + const response = await bunnyKeyRequest(url, "GET"); return okOrError(response, "Load free certificate"); }; @@ -394,10 +399,7 @@ const deleteDnsRecordImpl = async ( ): Promise => { const url = `${BUNNY_API_BASE}/dnszone/${zoneId}/records/${recordId}`; logDebug("Domain", `Deleting DNS record: ${url}`); - const response = await fetchText(url, { - headers: { AccessKey: getBunnyApiKey() }, - method: "DELETE", - }); + const response = await bunnyKeyRequest(url, "DELETE"); return okOrError(response, "Delete DNS record"); }; diff --git a/src/shared/columns/attendee-columns.ts b/src/shared/columns/attendee-columns.ts index 01fcfaad43..470a674323 100644 --- a/src/shared/columns/attendee-columns.ts +++ b/src/shared/columns/attendee-columns.ts @@ -10,6 +10,7 @@ import { attendeeAdminPath } from "#shared/attendee-links.ts"; import type { ColumnDef, ColumnGenerators } from "#shared/column-order.ts"; import { formatDateLabel, formatDatetimeShort } from "#shared/dates.ts"; import { isServicing } from "#shared/db/attendees/kind.ts"; +import { nonBlankLines } from "#shared/lines.ts"; import { normalizePhone } from "#shared/phone.ts"; import { type AttendeeTableRow, hasTicketQuantity } from "#shared/types.ts"; import type { AttendeeColumnOpts } from "#templates/attendee-table.tsx"; @@ -200,14 +201,10 @@ const registered: AttendeeCol = { /** Format a multi-line address for inline display */ export const formatAddressInline = (addr: string): string => { if (!addr) return ""; - return addr - .split(/\r?\n/) - .map((line) => line.trim()) - .filter((line) => line) - .reduce((acc, line) => { - if (!acc) return line; - return acc.endsWith(",") ? `${acc} ${line}` : `${acc}, ${line}`; - }, ""); + return nonBlankLines(addr).reduce((acc, line) => { + if (!acc) return line; + return acc.endsWith(",") ? `${acc} ${line}` : `${acc}, ${line}`; + }, ""); }; /** Format multi-line instructions as single-line text */ diff --git a/src/shared/dates.ts b/src/shared/dates.ts index a02d9dda1e..a6e403589f 100644 --- a/src/shared/dates.ts +++ b/src/shared/dates.ts @@ -371,16 +371,21 @@ export const formatDateRangeLabelCompactEn = ( const sameDay = sameMonth && s.getUTCDate() === e.getUTCDate(); const sMonth = MONTH_NAMES[s.getUTCMonth()]; const eMonth = MONTH_NAMES[e.getUTCMonth()]; + // " " for one end of the range, e.g. "2 February 2027". + const dayMonthYear = (d: Date, month: string | undefined): string => + `${d.getUTCDate()} ${month} ${d.getUTCFullYear()}`; if (sameDay) { - return `${s.getUTCDate()} ${sMonth} ${s.getUTCFullYear()}`; + return dayMonthYear(s, sMonth); } if (sameMonth) { - return `${s.getUTCDate()}–${e.getUTCDate()} ${sMonth} ${s.getUTCFullYear()}`; + // Same month + year: share the month and year, e.g. "2–3 February 2027". + return `${s.getUTCDate()}–${dayMonthYear(e, sMonth)}`; } if (sameYear) { - return `${s.getUTCDate()} ${sMonth} – ${e.getUTCDate()} ${eMonth} ${s.getUTCFullYear()}`; + // Same year, different month: share only the year, from the end date. + return `${s.getUTCDate()} ${sMonth} – ${dayMonthYear(e, eMonth)}`; } - return `${s.getUTCDate()} ${sMonth} ${s.getUTCFullYear()} – ${e.getUTCDate()} ${eMonth} ${e.getUTCFullYear()}`; + return `${dayMonthYear(s, sMonth)} – ${dayMonthYear(e, eMonth)}`; }; /** diff --git a/src/shared/db/attendees/balance.ts b/src/shared/db/attendees/balance.ts index 3baecfeb9f..18fe3854ad 100644 --- a/src/shared/db/attendees/balance.ts +++ b/src/shared/db/attendees/balance.ts @@ -9,9 +9,11 @@ */ import type { InValue } from "@libsql/client"; +/* jscpd:ignore-start */ import { compact, mapParallel, sumOf } from "#fp"; import { attendeeAccount, WORLD } from "#shared/accounting/accounts.ts"; import { KIND } from "#shared/accounting/kinds.ts"; +/* jscpd:ignore-end */ import { attendeeOwedSubquery } from "#shared/accounting/projection-sql.ts"; import { eventGroup, legReference } from "#shared/accounting/refs.ts"; import { guardedInsertStatement } from "#shared/accounting/rows.ts"; diff --git a/src/shared/db/attendees/create.ts b/src/shared/db/attendees/create.ts index 0c7330cd8d..2ad41d42a4 100644 --- a/src/shared/db/attendees/create.ts +++ b/src/shared/db/attendees/create.ts @@ -50,7 +50,11 @@ import { batchFinalizeStatement } from "#shared/db/payment-finalize.ts"; import type { TransferInput } from "#shared/ledger/types.ts"; import { bestEffort } from "#shared/logger.ts"; import { nowIso } from "#shared/now.ts"; -import { type Attendee, normalizeDurationDays } from "#shared/types.ts"; +import { + type Attendee, + type ContactInfo, + normalizeDurationDays, +} from "#shared/types.ts"; /** * Enforce all-or-nothing semantics on a (greedy) create result. @@ -113,6 +117,16 @@ export const buildAttendeeInsert = ( ticket_token_index: enc.ticketTokenIndex, }); +/** The order's contact PII, with the optional fields defaulted to "" — the one + * shape both the encrypt step and the per-booking result read from an input. */ +const contactInfoFromInput = (input: AttendeeInput): ContactInfo => ({ + address: input.address ?? "", + email: input.email, + name: input.name, + phone: input.phone ?? "", + special_instructions: input.special_instructions ?? "", +}); + /** Build plain Attendee object from insert result */ const buildAttendeeResult = (input: BuildAttendeeInput): Attendee => ({ id: Number(input.insertId), @@ -373,13 +387,9 @@ const prepareAttendeeWrite = async ( // Use first booking's pricePaid for encryption (PII blob is shared) const enc = await encryptAttendeeFields({ - address: input.address ?? "", - email: input.email, - name: input.name, + ...contactInfoFromInput(input), paymentId, - phone: input.phone ?? "", pricePaid: bookings[0]!.pricePaid ?? 0, - special_instructions: input.special_instructions ?? "", }); if (!enc) { return { @@ -435,13 +445,7 @@ const finishAttendeeWrite = async ( enc: EncryptedAttendeeData, ): Promise => { const { bookings, source = "public" } = input; - const contactInfo = { - address: input.address ?? "", - email: input.email, - name: input.name, - phone: input.phone ?? "", - special_instructions: input.special_instructions ?? "", - }; + const contactInfo = contactInfoFromInput(input); const successfulBookings: Attendee[] = bookings.flatMap((booking, i) => written.flags[i] ? [ diff --git a/src/shared/db/attributes.ts b/src/shared/db/attributes.ts index 3f726d528d..b95059e015 100644 --- a/src/shared/db/attributes.ts +++ b/src/shared/db/attributes.ts @@ -15,6 +15,7 @@ import { queryAll, queryOne, } from "#shared/db/client.ts"; +import { idAndEncryptedName } from "#shared/db/id-and-name-columns.ts"; import { linkTableSide } from "#shared/db/link-table.ts"; import type { ListingOption } from "#shared/db/listings.ts"; import { swapSortOrder } from "#shared/db/query.ts"; @@ -55,8 +56,7 @@ export const attributesTable = defineTable({ name: "attributes", primaryKey: "id", schema: { - id: col.generated(), - name: col.encrypted(encrypt, decrypt), + ...idAndEncryptedName(), sort_order: col.withDefault(() => 0), }, }); diff --git a/src/shared/db/client.ts b/src/shared/db/client.ts index 27c58a6f54..7ccf0a64f1 100644 --- a/src/shared/db/client.ts +++ b/src/shared/db/client.ts @@ -220,10 +220,13 @@ const firstRowOrNull = (result: ResultSet): T | null => { return rows.length === 0 ? null : rows[0]!; }; +/** A read statement and its optional bound args — the shared parameters of + * {@link queryOne} and {@link queryAll}. */ +type ReadArgs = [sql: string, args?: InValue[]]; + /** Query single row, returning null if not found */ export const queryOne = async ( - sql: string, - args?: InValue[], + ...[sql, args]: ReadArgs ): Promise => firstRowOrNull(await execute(sql, args)); /** @@ -244,10 +247,8 @@ export const queryOnePrimary = async ( }; /** Query all rows, returning a typed array */ -export const queryAll = async ( - sql: string, - args?: InValue[], -): Promise => resultRows(await execute(sql, args)); +export const queryAll = async (...[sql, args]: ReadArgs): Promise => + resultRows(await execute(sql, args)); /** * True when the query returns at least one row. `sql` should be an existence diff --git a/src/shared/db/groups.ts b/src/shared/db/groups.ts index efdb377684..3e9316e48c 100644 --- a/src/shared/db/groups.ts +++ b/src/shared/db/groups.ts @@ -3,7 +3,6 @@ */ /* jscpd:ignore-start */ -import type { InValue } from "@libsql/client"; import { mapNotNullish } from "#fp"; import { decrypt, encrypt } from "#shared/crypto/encryption.ts"; import { hmacHash } from "#shared/crypto/hashing.ts"; @@ -14,6 +13,7 @@ import { inPlaceholders, queryAll, queryOne, + type SqlStatement, type TxScope, } from "#shared/db/client.ts"; import { @@ -580,7 +580,7 @@ export const cloneGroupMembershipStatement = (member: { groupSlugIndex: string; listingSlugIndex: string; quantity: number; -}): { sql: string; args: InValue[] } => ({ +}): SqlStatement => ({ args: [member.groupSlugIndex, member.listingSlugIndex, member.quantity], sql: `INSERT INTO group_listings (group_id, listing_id, quantity) SELECT (SELECT id FROM groups WHERE slug_index = ?), @@ -606,7 +606,7 @@ const listingGroupDiffStatements = ( ) => { const toRemove = [...current].filter((id) => !desired.has(id)); const toAdd = [...desired].filter((id) => !current.has(id)); - const statements: { args: InValue[]; sql: string }[] = []; + const statements: SqlStatement[] = []; // Set-based DELETEs + multi-row INSERT — at most three statements regardless of // how many groups change, so the transactional path (setListingGroupsTx) stays // well under the interactive round-trip guard even for a large group selection. diff --git a/src/shared/db/holidays.ts b/src/shared/db/holidays.ts index 051e6fee20..502dea6182 100644 --- a/src/shared/db/holidays.ts +++ b/src/shared/db/holidays.ts @@ -3,7 +3,7 @@ */ import { filter } from "#fp"; -import { decrypt, encrypt } from "#shared/crypto/encryption.ts"; +import { idAndEncryptedName } from "#shared/db/id-and-name-columns.ts"; import { settings } from "#shared/db/settings.ts"; import { col, defineCachedListTable } from "#shared/db/table.ts"; import { todayInTz } from "#shared/timezone.ts"; @@ -23,9 +23,8 @@ export const holidays = defineCachedListTable({ orderBy: "start_date ASC", primaryKey: "id", schema: { + ...idAndEncryptedName(), end_date: col.simple(), - id: col.generated(), - name: col.encrypted(encrypt, decrypt), start_date: col.simple(), }, }); diff --git a/src/shared/db/id-and-name-columns.ts b/src/shared/db/id-and-name-columns.ts new file mode 100644 index 0000000000..eb53a381de --- /dev/null +++ b/src/shared/db/id-and-name-columns.ts @@ -0,0 +1,13 @@ +import { decrypt, encrypt } from "#shared/crypto/encryption.ts"; +import { type ColumnDef, col } from "#shared/db/table.ts"; + +/** The two columns a simple named lookup table always shares: an auto-generated + * numeric id and an encrypted name. Spread it into the table's `schema` and add + * whatever extra columns that table needs. */ +export const idAndEncryptedName = (): { + id: ColumnDef; + name: ColumnDef; +} => ({ + id: col.generated(), + name: col.encrypted(encrypt, decrypt), +}); diff --git a/src/shared/db/listing-parents.ts b/src/shared/db/listing-parents.ts index dd1cc51ddd..db6eceaa77 100644 --- a/src/shared/db/listing-parents.ts +++ b/src/shared/db/listing-parents.ts @@ -180,12 +180,14 @@ export const edgeIdsTouchingMany = async ( getChildrenForParents(listingIds), getParentsForChildren(listingIds), ]); + const groupedIds = (byListing: Map, id: number) => + (byListing.get(id) ?? []).map((l) => l.id); return new Map( listingIds.map((id) => [ id, { - childIds: (childrenByParent.get(id) ?? []).map((l) => l.id), - parentIds: (parentsByChild.get(id) ?? []).map((l) => l.id), + childIds: groupedIds(childrenByParent, id), + parentIds: groupedIds(parentsByChild, id), }, ]), ); diff --git a/src/shared/db/migrations.ts b/src/shared/db/migrations.ts index 8fcdf557dc..287c2a3efe 100644 --- a/src/shared/db/migrations.ts +++ b/src/shared/db/migrations.ts @@ -14,8 +14,14 @@ import type { Client } from "@libsql/client"; import { lazyRef, once } from "#fp"; import { resetAllCaches } from "#shared/cache-registry.ts"; -import { executeBatch, getDb, inPlaceholders } from "#shared/db/client.ts"; +import { + executeBatch, + getDb, + inPlaceholders, + type SqlStatement, +} from "#shared/db/client.ts"; import { getEnv } from "#shared/env.ts"; +import { errorMessage } from "#shared/error-message.ts"; import { logDebug } from "#shared/logger.ts"; import { nowIso } from "#shared/now.ts"; import { sendNtfyError } from "#shared/ntfy.ts"; @@ -38,6 +44,7 @@ import { backfillModifierAggregates, createTableSql, fullSchemaCreateStatements, + noArgStatements, recreateTable, runMigration, syncCurrentSchema as syncCurrentSchemaBase, @@ -275,9 +282,7 @@ const initializeFreshSchema = async (): Promise => { */ export const rebuildWipedSchema = async (): Promise => { logDebug("Migration", "Rebuilding wiped database from current schema"); - await executeBatch( - fullSchemaCreateStatements().map((sql) => ({ args: [], sql })), - ); + await executeBatch(noArgStatements(fullSchemaCreateStatements())); // A compound CREATE TRIGGER … BEGIN … END body carries internal semicolons // that batch transports mis-split, so triggers run one by one, exactly as // syncTriggers sends them. @@ -305,7 +310,7 @@ const getAppliedMigrationIds = async (): Promise> => { const migrationMarkerStatement = ( migration: Migration, appliedAt: string, -): { sql: string; args: string[] } => ({ +): SqlStatement => ({ args: [migration.id, migration.description, appliedAt], sql: `INSERT OR REPLACE INTO ${SCHEMA_MIGRATIONS_TABLE} (id, description, applied_at) VALUES (?, ?, ?)`, }); @@ -443,9 +448,9 @@ export const applyMigrationWithRetry = async ( } catch (error) { logDebug( "Migration", - `verify ${migration.id} still failing after retries, re-running up(): ${ - error instanceof Error ? error.message : String(error) - }`, + `verify ${migration.id} still failing after retries, re-running up(): ${errorMessage( + error, + )}`, ); await migration.up(); await verifyMigrationWithRetry(migration); diff --git a/src/shared/db/migrations/2026-06-14_rename_events_to_listings.ts b/src/shared/db/migrations/2026-06-14_rename_events_to_listings.ts index 9da7c85f1c..e345ee0c7e 100644 --- a/src/shared/db/migrations/2026-06-14_rename_events_to_listings.ts +++ b/src/shared/db/migrations/2026-06-14_rename_events_to_listings.ts @@ -1,9 +1,12 @@ +/* jscpd:ignore-start */ import type { Migration, MigrationContext, SchemaRequirement, } from "./types.ts"; +/* jscpd:ignore-end */ + const requires: SchemaRequirement = { absentTables: ["events", "event_attendees", "event_questions"], columns: { diff --git a/src/shared/db/migrations/2026-06-18_contact_preferences.ts b/src/shared/db/migrations/2026-06-18_contact_preferences.ts index 242bbb3d67..172a23fcb9 100644 --- a/src/shared/db/migrations/2026-06-18_contact_preferences.ts +++ b/src/shared/db/migrations/2026-06-18_contact_preferences.ts @@ -1,12 +1,15 @@ import { countRows } from "#shared/db/client.ts"; import { nowMs } from "#shared/now.ts"; import { getExistingColumns, runMigration } from "./schema-sync.ts"; +/* jscpd:ignore-start */ import type { Migration, MigrationContext, SchemaRequirement, } from "./types.ts"; +/* jscpd:ignore-end */ + const requires: SchemaRequirement = { absentTables: ["email_preferences"], indexes: [ @@ -59,17 +62,23 @@ const renameLegacyTable = async (context: MigrationContext): Promise => { ); }; -const renameLegacyHashColumn = async (): Promise => { - const columns = await getExistingColumns("contact_preferences"); +// Reads the current columns of contact_preferences, then runs the given step +// with them. Keeps every column-check step from re-fetching the same list. +const withContactColumns = + (use: (columns: Set) => Promise) => async (): Promise => { + const columns = await getExistingColumns("contact_preferences"); + await use(columns); + }; + +const renameLegacyHashColumn = withContactColumns(async (columns) => { if (columns.has("email_hash") && !columns.has("contact_hash")) { await runMigration( "ALTER TABLE contact_preferences RENAME COLUMN email_hash TO contact_hash", ); } -}; +}); -const backfillAndDropCreated = async (): Promise => { - const columns = await getExistingColumns("contact_preferences"); +const backfillAndDropCreated = withContactColumns(async (columns) => { if (!columns.has("created")) return; if (columns.has("last_activity")) { const migratedAtMs = nowMs(); @@ -78,7 +87,7 @@ const backfillAndDropCreated = async (): Promise => { ); } await runMigration("ALTER TABLE contact_preferences DROP COLUMN created"); -}; +}); export default (context: MigrationContext): Migration => context.additive({ diff --git a/src/shared/db/migrations/booking-slot-index.ts b/src/shared/db/migrations/booking-slot-index.ts index 5ff774034d..152c3b279f 100644 --- a/src/shared/db/migrations/booking-slot-index.ts +++ b/src/shared/db/migrations/booking-slot-index.ts @@ -1,3 +1,4 @@ +import { queryRowsWithArg } from "./master-query.ts"; import { SCHEMA } from "./schema/index.ts"; import type { MigrationContext, SchemaRequirement } from "./types.ts"; @@ -38,11 +39,12 @@ export const slotIndexColumns = (): string[] => export const verifySlotIndex = ({ getDb }: Pick) => async (): Promise => { - const result = await getDb().execute({ - args: [SLOT_INDEX], - sql: "SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?", - }); - const live = result.rows.length > 0 ? String(result.rows[0]!.sql) : ""; + const rows = await queryRowsWithArg( + getDb(), + "SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?", + SLOT_INDEX, + ); + const live = rows.length > 0 ? String(rows[0]!.sql) : ""; const missing = slotIndexColumns().filter( (column) => !live.includes(column), ); diff --git a/src/shared/db/migrations/master-query.ts b/src/shared/db/migrations/master-query.ts new file mode 100644 index 0000000000..9712bc5f34 --- /dev/null +++ b/src/shared/db/migrations/master-query.ts @@ -0,0 +1,15 @@ +import type { Client, InValue, Row } from "@libsql/client"; + +/** + * Run a one-argument query on the given connection and hand back its rows. + * + * Shared by the migration helpers that read `sqlite_master` for a single table + * or index name. Takes the connection as an argument so callers that own their + * own `getDb` (the injected migration context) and callers that use the shared + * client both go through the same path. + */ +export const queryRowsWithArg = async ( + db: Client, + sql: string, + arg: InValue, +): Promise => (await db.execute({ args: [arg], sql })).rows; diff --git a/src/shared/db/migrations/rename-utils.ts b/src/shared/db/migrations/rename-utils.ts index f2b51c1a7f..8caee8814f 100644 --- a/src/shared/db/migrations/rename-utils.ts +++ b/src/shared/db/migrations/rename-utils.ts @@ -1,4 +1,5 @@ import { countRows, getDb } from "#shared/db/client.ts"; +import { queryRowsWithArg } from "./master-query.ts"; import { currentSchemaColumnsPresentIn, getExistingColumns, @@ -120,15 +121,15 @@ const dropProjectIndexesReferencingColumn = async ( table: string, column: string, ): Promise => { - const result = await getDb().execute({ - args: [table], - sql: - "SELECT name, sql FROM sqlite_master " + + const rows = await queryRowsWithArg( + getDb(), + "SELECT name, sql FROM sqlite_master " + "WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL", - }); + table, + ); const referencesColumn = sqlIdentifierPattern(column); - for (const row of result.rows) { + for (const row of rows) { const name = String(row.name); const sql = String(row.sql); if (name.startsWith("idx_") && referencesColumn.test(sql)) { diff --git a/src/shared/db/migrations/schema-sync.ts b/src/shared/db/migrations/schema-sync.ts index 3c17ae574f..8625522329 100644 --- a/src/shared/db/migrations/schema-sync.ts +++ b/src/shared/db/migrations/schema-sync.ts @@ -1,11 +1,12 @@ -import type { InValue } from "@libsql/client"; import { executeBatch, getDb, queryBatchPrimary, + type SqlStatement, withTransaction, } from "#shared/db/client.ts"; import { logDebug } from "#shared/logger.ts"; +import { queryRowsWithArg } from "./master-query.ts"; import { APP_SCHEMA, SCHEMA } from "./schema/index.ts"; import { TICKET_COUNTS_PREDICATE, @@ -44,11 +45,12 @@ export const getExistingColumns = async ( }; export const tableExists = async (table: string): Promise => { - const result = await getDb().execute({ - args: [table], - sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?", - }); - return result.rows.length > 0; + const rows = await queryRowsWithArg( + getDb(), + "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?", + table, + ); + return rows.length > 0; }; /** Live schema snapshot: every table's columns, every index, every trigger. */ @@ -176,9 +178,7 @@ const rebuildStatements = ({ export const rebuildTableWithColumns = async ( params: RebuildParams, ): Promise => { - await executeBatch( - rebuildStatements(params).map((sql) => ({ args: [], sql })), - ); + await executeBatch(noArgStatements(rebuildStatements(params))); }; const LISTING_AGGREGATE_TRIGGER_DEPENDENCIES = [ @@ -434,14 +434,18 @@ export const fullSchemaCreateStatements = (): string[] => ...(table.indexes ?? []).map((index) => createIndexSql(name, index)), ]); -const writeStatement = (sql: string): { args: InValue[]; sql: string } => ({ +const writeStatement = (sql: string): SqlStatement => ({ args: [], sql, }); +/** Turn a list of SQL strings into batch statements with no bound arguments. */ +export const noArgStatements = (sqls: string[]): SqlStatement[] => + sqls.map(writeStatement); + export const applySchemaChanges = async (): Promise => { const live = await snapshotLiveSchema(); - const statements: { args: InValue[]; sql: string }[] = []; + const statements: SqlStatement[] = []; for (const entry of SCHEMA) { const [name, table] = entry; const existing = live.tables.get(name); diff --git a/src/shared/db/modifier-resolve.ts b/src/shared/db/modifier-resolve.ts index 6e84088fd9..9c04c1f4b1 100644 --- a/src/shared/db/modifier-resolve.ts +++ b/src/shared/db/modifier-resolve.ts @@ -666,6 +666,22 @@ export const childUnreachableAddOnError = ( * page drops it from the reachable set and surfaces the dead end. Group scopes * resolve against `allListings` so a group-scoped add-on reflects the same set. */ +/** The ids of listings that can still offer an add-on to a booker: an active + * listing that isn't one of the suppressed children (only those serve their + * own public booking page). Shared by the in-memory save re-check and the + * modifier save guard. */ +export const reachablePageIds = ( + listings: ReadonlyArray<{ id: number; active?: boolean }>, + suppressedChildIds: Set, +): Set => + new Set( + listings + .filter( + (listing) => listing.active && !suppressedChildIds.has(listing.id), + ) + .map((listing) => listing.id), + ); + export const firstChildUnreachableAddOnForListings = async ( allListings: ListingGroupMembership[], childListingIds: Set, @@ -673,11 +689,7 @@ export const firstChildUnreachableAddOnForListings = async ( const { optional, scopes } = await optionalAddOnsWithScopes( inMemoryGroupScopeResolver(allListings), ); - const reachablePageIds = new Set( - allListings - .filter((listing) => listing.active && !childListingIds.has(listing.id)) - .map((listing) => listing.id), - ); + const reachable = reachablePageIds(allListings, childListingIds); for (const modifier of optional) { const error = childUnreachableAddOnError( { @@ -687,7 +699,7 @@ export const firstChildUnreachableAddOnForListings = async ( trigger: modifier.trigger, }, childListingIds, - reachablePageIds, + reachable, ); if (error) return error; } diff --git a/src/shared/db/news-posts.ts b/src/shared/db/news-posts.ts index 2c592a93a1..7862e85e62 100644 --- a/src/shared/db/news-posts.ts +++ b/src/shared/db/news-posts.ts @@ -33,6 +33,7 @@ import { clearImageUsesForItemStatement, imageFilenameSubqueries, } from "#shared/db/images.ts"; +import type { SluggedContentInput } from "#shared/db/slugged-content-input.ts"; import { col } from "#shared/db/table.ts"; import { nowIso } from "#shared/now.ts"; import { requestCache } from "#shared/request-cache.ts"; @@ -47,15 +48,9 @@ import type { /** Create/update input (camelCase keys → snake_case columns). `created`, `slug`, * and `slugIndex` are computed in {@link createNewsPost}, never posted by the * admin form (only restores and tests pin an explicit `created`). */ -export type NewsPostInput = { +export type NewsPostInput = SluggedContentInput & { created?: string; - slug: string; - slugIndex: BlindIndex; - name: string; - metaTitle?: string; - metaDescription?: string; snippet?: string; - content?: string; }; /** Table with CRUD — all free text (including the slug) encrypted; `created` diff --git a/src/shared/db/query-log.ts b/src/shared/db/query-log.ts index 597c83f19a..e3b61eb79f 100644 --- a/src/shared/db/query-log.ts +++ b/src/shared/db/query-log.ts @@ -16,6 +16,7 @@ import { AsyncLocalStorage } from "node:async_hooks"; import { lazyRef, map, pipe, reduce, sort } from "#fp"; +import { withLazyLogger } from "#shared/lazy-logger.ts"; import { shouldSuppressDebugLogs } from "#shared/log-settings.ts"; /** A single logged query */ @@ -190,10 +191,10 @@ const isReadSql = (sql: string): boolean => /^\s*(?:with|select)\b/i.test(sql); * the db client, which the logger transitively depends on, so a static import * would form a cycle. The dynamic import mirrors `env.ts`'s `isReadOnly`. */ -const notifyN1Violation = async (detail: string): Promise => { - const { ErrorCode, logError } = await import("#shared/logger.ts"); - logError({ code: ErrorCode.DB_QUERY, detail }); -}; +const notifyN1Violation = (detail: string): Promise => + withLazyLogger(({ ErrorCode, logError }) => + logError({ code: ErrorCode.DB_QUERY, detail }), + ); /** * Mirror the debug footer to the system logs: emit each SQL statement as it diff --git a/src/shared/db/questions/attendee-answers/save.ts b/src/shared/db/questions/attendee-answers/save.ts index d2bbb60732..bf908897cd 100644 --- a/src/shared/db/questions/attendee-answers/save.ts +++ b/src/shared/db/questions/attendee-answers/save.ts @@ -212,18 +212,15 @@ export const saveAttendeeAnswers = async ( // (one for choice answers, one for text answers) so the statement count // stays at a handful regardless of attendee count — the transaction // round-trip guard thresholds a chatty per-attendee loop would trip. + // One row of a pending INSERT: an attendee, a question, and the one value + // column that varies (a chosen answer id, or an interned text id). type AnswerRow = { attendeeId: number; questionId: number; - answerId: number; - }; - type TextRow = { - attendeeId: number; - questionId: number; - stringId: number; + valueId: number; }; const choiceRows: AnswerRow[] = []; - const textRows: TextRow[] = []; + const textRows: AnswerRow[] = []; for (const [ attendeeId, { answerIds, textAnswerIds, textAnswers }, @@ -234,9 +231,9 @@ export const saveAttendeeAnswers = async ( ); for (const id of dedupedAnswerIds) { choiceRows.push({ - answerId: id, attendeeId, questionId: questionIdsByAnswer.get(id)!, + valueId: id, }); } const resolvedTextAnswerIds = dedupeTextAnswerIdsByQuestion([ @@ -250,32 +247,28 @@ export const saveAttendeeAnswers = async ( textRows.push({ attendeeId, questionId: answer.questionId, - stringId: answer.stringId, + valueId: answer.stringId, }); } } - if (choiceRows.length > 0) { - const placeholders = choiceRows.map(() => "(?, ?, ?)").join(", "); - await tx.execute({ - args: choiceRows.flatMap((row) => [ - row.attendeeId, - row.questionId, - row.answerId, - ]), - sql: `INSERT INTO attendee_answers (attendee_id, question_id, answer_id) VALUES ${placeholders}`, - }); - } - if (textRows.length > 0) { - const placeholders = textRows.map(() => "(?, ?, ?)").join(", "); - await tx.execute({ - args: textRows.flatMap((row) => [ + // Emit one multi-row INSERT of answer rows into the given value column. + // Both answer kinds write the same three columns, so they share this body. + const insertAnswerRows = ( + valueColumn: "answer_id" | "string_id", + rows: AnswerRow[], + ): Promise => { + const placeholders = rows.map(() => "(?, ?, ?)").join(", "); + return tx.execute({ + args: rows.flatMap((row) => [ row.attendeeId, row.questionId, - row.stringId, + row.valueId, ]), - sql: `INSERT INTO attendee_answers (attendee_id, question_id, string_id) VALUES ${placeholders}`, + sql: `INSERT INTO attendee_answers (attendee_id, question_id, ${valueColumn}) VALUES ${placeholders}`, }); - } + }; + if (choiceRows.length > 0) await insertAnswerRows("answer_id", choiceRows); + if (textRows.length > 0) await insertAnswerRows("string_id", textRows); }); }; diff --git a/src/shared/db/settings.ts b/src/shared/db/settings.ts index d50860d943..f187d722a2 100644 --- a/src/shared/db/settings.ts +++ b/src/shared/db/settings.ts @@ -117,6 +117,18 @@ const withProperties = ( return target as T & P; }; +/** The card-provider getters shared by Stripe and SumUp: whether a secret key + * is set, and whether that key is a test or live key. `keyName` is the setting + * the provider's secret is stored under. */ +const providerKeyStatus = (keyName: "stripe_secret_key" | "sumup_api_key") => ({ + get hasKey(): boolean { + return snap(keyName) !== ""; + }, + get keyMode(): "test" | "live" | null { + return keyModeOf(snap(keyName)); + }, +}); + const settingsBase = { // --- Address lookup --- addressLookup: { @@ -294,39 +306,33 @@ const settingsBase = { }, // --- Stripe --- - stripe: { - get hasKey(): boolean { - return snap("stripe_secret_key") !== ""; - }, - get keyMode(): "test" | "live" | null { - return keyModeOf(snap("stripe_secret_key")); - }, - get secretKey(): string { - return snap("stripe_secret_key"); - }, - get webhookEndpointId(): string { - return snap("stripe_webhook_endpoint_id"); - }, - get webhookSecret(): string { - return snap("stripe_webhook_secret"); + stripe: withProperties( + { + get secretKey(): string { + return snap("stripe_secret_key"); + }, + get webhookEndpointId(): string { + return snap("stripe_webhook_endpoint_id"); + }, + get webhookSecret(): string { + return snap("stripe_webhook_secret"); + }, }, - }, + providerKeyStatus("stripe_secret_key"), + ), // --- SumUp --- - sumup: { - get apiKey(): string { - return snap("sumup_api_key"); - }, - get hasKey(): boolean { - return snap("sumup_api_key") !== ""; - }, - get keyMode(): "test" | "live" | null { - return keyModeOf(snap("sumup_api_key")); - }, - get merchantCode(): string { - return snap("sumup_merchant_code"); + sumup: withProperties( + { + get apiKey(): string { + return snap("sumup_api_key"); + }, + get merchantCode(): string { + return snap("sumup_merchant_code"); + }, }, - }, + providerKeyStatus("sumup_api_key"), + ), // --- Superuser --- get superuserChoice(): SuperuserChoice { diff --git a/src/shared/db/settings/raw-writes.ts b/src/shared/db/settings/raw-writes.ts index d88eae3f2b..c6a605614a 100644 --- a/src/shared/db/settings/raw-writes.ts +++ b/src/shared/db/settings/raw-writes.ts @@ -15,6 +15,7 @@ import { encrypt } from "#shared/crypto/encryption.ts"; import { executeBatchWithoutCacheInvalidation, executeWithoutCacheInvalidation, + type SqlStatement, } from "#shared/db/client.ts"; import { bumpSettingsVersion, @@ -36,10 +37,7 @@ const SETTINGS_UPSERT_SQL = "INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)"; /** Build a settings upsert as a batch statement (used by `completeSetup`). */ -export const settingUpsert = ( - key: string, - value: string, -): { sql: string; args: string[] } => ({ +export const settingUpsert = (key: string, value: string): SqlStatement => ({ args: [key, value], sql: SETTINGS_UPSERT_SQL, }); diff --git a/src/shared/db/site-pages.ts b/src/shared/db/site-pages.ts index d9fcc52d9f..651558593c 100644 --- a/src/shared/db/site-pages.ts +++ b/src/shared/db/site-pages.ts @@ -27,18 +27,13 @@ import { } from "#shared/db/common-schema.ts"; import { swapSortOrder } from "#shared/db/query.ts"; import { isSlugTakenAnywhere } from "#shared/db/slug-registry.ts"; +import type { SluggedContentInput } from "#shared/db/slugged-content-input.ts"; import { cachedTable, col } from "#shared/db/table.ts"; import type { SitePage, SitePageNavRow } from "#shared/types.ts"; /* jscpd:ignore-end */ /** Create/update input (camelCase keys → snake_case columns). */ -export type SitePageInput = { - slug: string; - slugIndex: BlindIndex; - name: string; - metaTitle?: string; - metaDescription?: string; - content?: string; +export type SitePageInput = SluggedContentInput & { sortOrder: number; }; diff --git a/src/shared/db/slugged-content-input.ts b/src/shared/db/slugged-content-input.ts new file mode 100644 index 0000000000..83bc3c6b9d --- /dev/null +++ b/src/shared/db/slugged-content-input.ts @@ -0,0 +1,13 @@ +import type { BlindIndex } from "#shared/crypto/sealed.ts"; + +/** The create/update fields shared by every slugged content record (site pages + * and news posts): its slug and slug blind-index, its name, and the optional + * SEO meta and main content. Each table adds its own extra fields on top. */ +export type SluggedContentInput = { + slug: string; + slugIndex: BlindIndex; + name: string; + metaTitle?: string; + metaDescription?: string; + content?: string; +}; diff --git a/src/shared/db/system-notes.ts b/src/shared/db/system-notes.ts index 790993d966..4613a71315 100644 --- a/src/shared/db/system-notes.ts +++ b/src/shared/db/system-notes.ts @@ -69,26 +69,30 @@ const insertNote = async ( await execute(sql, args); }; +/** Build a "record a note" function: it seals the text its own way, then stores + * the result under the given note type. The two note kinds differ only in how + * they seal, so they share this one body. */ +const noteCreatorVia = + ( + type: SystemNoteType, + seal: (note: string) => Promise, + ) => + async (attendeeId: number, note: string): Promise => + insertNote(attendeeId, type, await seal(note)); + /** * Record an auto-generated system note. The text MUST be PII-free: it is * encrypted with the symmetric DB key (recoverable from a DB dump + that key), * and exists so a system path with no owner session can write it. */ -export const createSystemNote = async ( - attendeeId: number, - note: string, -): Promise => insertNote(attendeeId, "system", await encrypt(note)); +export const createSystemNote = noteCreatorVia("system", (note) => + encrypt(note), +); /** Record an operator-authored note, encrypted with the owner public key. */ -export const createOwnerNote = async ( - attendeeId: number, - note: string, -): Promise => - insertNote( - attendeeId, - "owner", - await encryptWithOwnerKey(note, settings.publicKey), - ); +export const createOwnerNote = noteCreatorVia("owner", (note) => + encryptWithOwnerKey(note, settings.publicKey), +); /** Decrypt one note by its type. We do not guard this: a failure here can only * mean the data key itself is broken — in which case the attendee's own PII @@ -171,12 +175,16 @@ export const getNotesForAttendee = async ( * unwrap. Curried over the row-fetcher so the attendee-list and listing-scoped * loaders share one body. */ +/** A "load decrypted notes for " reader: takes the selector value and + * a lazy owner-private-key getter, and returns the decrypted notes. */ +type NotesLoader = ( + selector: A, + getPrivateKey: () => Promise, +) => Promise; + const notesLoaderVia = - (fetchRows: (selector: A) => Promise) => - async ( - selector: A, - getPrivateKey: () => Promise, - ): Promise => { + (fetchRows: (selector: A) => Promise): NotesLoader => + async (selector, getPrivateKey) => { const rows = await fetchRows(selector); return rows.length === 0 ? [] : decryptNotes(rows, await getPrivateKey()); }; @@ -185,20 +193,17 @@ const notesLoaderVia = * Decrypted notes for a set of attendees, oldest first, for an attendee-list * view. Returns [] when none have notes. */ -export const loadNotesForAttendees: ( - attendeeIds: number[], - getPrivateKey: () => Promise, -) => Promise = notesLoaderVia(getNoteRows); +export const loadNotesForAttendees: NotesLoader = + notesLoaderVia(getNoteRows); /** * Decrypted notes for every real attendee on one listing, oldest first — * scoped in SQL (see {@link getNoteRowsForListing}). Returns [] when none have * notes, so the Overview's key unwrap is skipped for a note-free listing. */ -export const loadNotesForListing: ( - listingId: number, - getPrivateKey: () => Promise, -) => Promise = notesLoaderVia(getNoteRowsForListing); +export const loadNotesForListing: NotesLoader = notesLoaderVia( + getNoteRowsForListing, +); /** Group decrypted notes by attendee id (input order preserved within a group). */ export const groupNotesByAttendee = ( diff --git a/src/shared/db/users.ts b/src/shared/db/users.ts index b8304a4d0e..fabddbe9b9 100644 --- a/src/shared/db/users.ts +++ b/src/shared/db/users.ts @@ -176,7 +176,7 @@ const activatedUserOpts = ( passwordHash: PasswordHash | "", wrappedDataKey: WrappedKey | null, adminLevel: AdminLevel, - kekVersion: number, + kekVersion = 2, ): InsertUserOpts => ({ adminLevel, inviteCodeHash: null, @@ -195,24 +195,8 @@ const activatedUserOpts = ( */ const consumeActivatedUserInsert = (consume: (built: BuiltUserInsert) => T | Promise) => - async ( - username: string, - passwordHash: PasswordHash | "", - wrappedDataKey: WrappedKey | null, - adminLevel: AdminLevel, - kekVersion = 2, - ): Promise => - consume( - await buildUserInsert( - activatedUserOpts( - username, - passwordHash, - wrappedDataKey, - adminLevel, - kekVersion, - ), - ), - ); + async (...args: Parameters): Promise => + consume(await buildUserInsert(activatedUserOpts(...args))); /** * Create a new (already-activated) user with encrypted fields. Activated users diff --git a/src/shared/deno-deploy-api.ts b/src/shared/deno-deploy-api.ts index a464bbcca2..4917cf2378 100644 --- a/src/shared/deno-deploy-api.ts +++ b/src/shared/deno-deploy-api.ts @@ -6,6 +6,7 @@ * Auth: Authorization: Bearer {DENO_DEPLOY_TOKEN} */ +/* jscpd:ignore-start */ import { getDenoDeployOrgId, getDenoDeployToken, @@ -14,6 +15,8 @@ import { import { type ApiResult, fetchText, parseApiError } from "#shared/fetch.ts"; import type { HostingProviderApi } from "#shared/provider-types.ts"; +/* jscpd:ignore-end */ + const DENO_API_BASE = "https://api.deno.com/v2"; interface CreateAppResponse { diff --git a/src/shared/env.ts b/src/shared/env.ts index ab144ed530..a1a0509d91 100644 --- a/src/shared/env.ts +++ b/src/shared/env.ts @@ -11,6 +11,8 @@ * and writes too. */ +import { withLazyLogger } from "#shared/lazy-logger.ts"; + declare const Deno: | { env: { get(key: string): string | undefined } } | undefined; @@ -76,13 +78,12 @@ export const isReadOnly = (): boolean => { const cutoff = getEnv("READ_ONLY_FROM"); if (!cutoff) return false; if (Number.isNaN(Date.parse(cutoff))) { - void (async () => { - const { ErrorCode, logError } = await import("#shared/logger.ts"); + void withLazyLogger(({ ErrorCode, logError }) => logError({ code: ErrorCode.DATA_INVALID, detail: `READ_ONLY_FROM unparseable: ${cutoff}`, - }); - })(); + }), + ); return false; } return isReadOnlyFromCutoff(Date.now(), cutoff); diff --git a/src/shared/error-message.ts b/src/shared/error-message.ts new file mode 100644 index 0000000000..7aab11fb1f --- /dev/null +++ b/src/shared/error-message.ts @@ -0,0 +1,10 @@ +/** + * The human-readable message for a caught value. + * + * `catch` hands back `unknown`: a real `Error` carries a `.message`, but a + * thrown string, number, or object does not. This reads the message when there + * is one and falls back to the value's string form otherwise, so a log line + * always has something useful to show. + */ +export const errorMessage = (error: unknown): string => + error instanceof Error ? error.message : String(error); diff --git a/src/shared/flash-fields.ts b/src/shared/flash-fields.ts new file mode 100644 index 0000000000..0c2880c861 --- /dev/null +++ b/src/shared/flash-fields.ts @@ -0,0 +1,9 @@ +/** The three optional flash messages a page or form can show — an error, a + * success note, or a neutral info note. Present only when there is a message. + * Shared by the {@link Flash} component and any page data that carries its own + * flash straight into that component. */ +export type FlashFields = { + error?: string | undefined; + success?: string | undefined; + info?: string | undefined; +}; diff --git a/src/shared/forms.tsx b/src/shared/forms.tsx index 422154ee42..d943fcc3c7 100644 --- a/src/shared/forms.tsx +++ b/src/shared/forms.tsx @@ -12,6 +12,7 @@ import { getFlash, getFlashFormId, } from "#shared/flash-context.ts"; +import type { FlashFields } from "#shared/flash-fields.ts"; import type { FormParams } from "#shared/form-data.ts"; import { appendIframeParam } from "#shared/iframe.ts"; import { escapeHtml } from "#shared/jsx/jsx-runtime.ts"; @@ -545,15 +546,7 @@ export const defineForm = < * second time. This is what lets a page render its flash inline — or not at all * — without ever double-rendering or dropping it. */ -export const Flash = ({ - error, - success, - info, -}: { - error?: string | undefined; - success?: string | undefined; - info?: string | undefined; -}): JSX.Element => { +export const Flash = ({ error, success, info }: FlashFields): JSX.Element => { if (error || success || info) consumeFlash(); return ( <> @@ -745,6 +738,18 @@ export const hiddenInputs = ( )); +/** Hidden field that carries where to send the visitor after the form runs. + * Renders nothing when there is no return URL. */ +export const ReturnUrlField = ({ + returnUrl, +}: { + returnUrl?: string | undefined; +}): JSX.Element => ( + <> + {returnUrl && } + +); + export const ConfirmForm = ({ action, name, @@ -771,7 +776,7 @@ export const ConfirmForm = ({ }): JSX.Element => ( {children &&
{children}
} - {returnUrl && } + {hiddenFields && hiddenInputs(Object.entries(hiddenFields))} {confirmName && (