Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 31 additions & 9 deletions scripts/mutation/equivalent-mutants.txt
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ src/shared/checkout-ledger.ts:35:72 ?? → || # find(...)?.amount: number|und
src/features/settings-bundles.ts:264:40 ?? → || # bundle is a readonly string[] or undefined; every present array, including [], is truthy
src/shared/db/attendees/balance.ts:223:22 ?? → || # attendee status ids are positive integers when present, so the value is always truthy or nullish
src/shared/accounting/queries.ts:162:26 || → && # transferActivityBounds: MIN(occurred_at) and MAX(occurred_at) over one table are NULL together (both iff the table is empty), so either-null and both-null coincide
src/shared/admin-features.ts:95:58 ?? → || # find(): AdminFeatureDefinition|undefined; a feature object is always truthy
src/shared/admin-features.ts:121:58 ?? → || # find(): AdminFeatureDefinition|undefined; a feature object is always truthy
src/shared/db/admin-features.ts:50:10 __required_setting_condition__ → "" # the placeholder key is never stored: a failed condition always aborts on its NULL value
src/shared/db/admin-features.ts:50:10 __required_setting_condition__ → "__required_setting_condition__ mutated" # same as above; no successful statement exposes this key
src/shared/db/admin-features.ts:76:49 ?? → || # inUseSql: a non-empty SQL string|undefined, so only undefined reaches the fallback
Expand Down Expand Up @@ -103,13 +103,13 @@ src/fp.ts:449:49 ?? → || # items?.length is undefined or a non-negative int
# undefined, paired null checks already reject both nullish values, optional
# conditions/dependencies are objects or arrays, and non-generated primary keys
# are overwritten from the input-column fold in either initial-row branch.
src/shared/db/table.ts:282:17 === → == # queryOne returns StoredRow|null, never undefined
src/shared/db/table.ts:349:25 !== → != # paired checks reject both null and undefined before applying a write transform
src/shared/db/table.ts:501:24 ?: → consequent only # generated keys use the consequent; non-generated keys are overwritten by their input-column value
src/shared/db/table.ts:541:28 ?? → || # condition?.args is an array or undefined, and every array is truthy
src/shared/db/table.ts:667:59 ?? → || # dependsOn is a readonly array or undefined, and every array is truthy
src/shared/db/table.ts:694:32 ?? → || # dependsOn is a readonly array or undefined, and every array is truthy
src/shared/db/table.ts:715:6 === → == # wrapNullable constrains T to exclude undefined, so v is T|null
src/shared/db/table.ts:283:17 === → == # queryOne returns StoredRow|null, never undefined
src/shared/db/table.ts:350:25 !== → != # paired checks reject both null and undefined before applying a write transform
src/shared/db/table.ts:502:24 ?: → consequent only # generated keys use the consequent; non-generated keys are overwritten by their input-column value
src/shared/db/table.ts:542:28 ?? → || # condition?.args is an array or undefined, and every array is truthy
src/shared/db/table.ts:667:21 ?? → || # dependsOn is a readonly array or undefined, and every array is truthy
src/shared/db/table.ts:700:32 ?? → || # dependsOn is a readonly array or undefined, and every array is truthy
src/shared/db/table.ts:721:6 === → == # wrapNullable constrains T to exclude undefined, so v is T|null

# Login attempt rows store an integer count. For undefined, null, zero, or any
# non-zero integer, `(attempts ?? 0) + 1` and `(attempts || 0) + 1` agree.
Expand Down Expand Up @@ -241,7 +241,29 @@ src/shared/db/attendees/capacity/groups.ts:166:55 ?? → || # membership.get(
src/shared/db/attendees/capacity/groups.ts:178:39 ?? → || # membership.get(): number[]|undefined — an array is always truthy

# v2 signed metadata (Phase 2d).
src/shared/payment-helpers.ts:159:24 ?? → || # toBookingItems intent.allocations: ChildAllocation[]|undefined — an array is always truthy, undefined→[] either way
src/shared/payment-helpers.ts:168:24 ?? → || # toBookingItems intent.allocations: ChildAllocation[]|undefined — an array is always truthy, undefined→[] either way
src/shared/payment-helpers.ts:539:16 || → && # parsed JSON null/falsy primitives return {} in both forms; truthy primitives expose none of PACKED_KEYS and also produce {}
src/shared/payment-helpers.ts:598:40 ?? → || # metadata field length is undefined or a non-negative integer; 0 and undefined both use 0

# Built-site form writes cannot change assignment/renewal state, so omitted raw
# inputs preserve the same defaults/current values. Blob strings are either
# truthy or have the same falsy fallback.
src/shared/db/built-sites.ts:163:57 ?? → || # assigned IDs are positive generated IDs or null; renewal indexes are non-empty HMAC strings or null
src/shared/db/built-sites.ts:178:15 assignedAttendeeId → "" # not in BuiltSiteFormInput; inserts default null and form updates preserve the existing raw value
src/shared/db/built-sites.ts:186:15 assignedListingId → "" # not in BuiltSiteFormInput; inserts default null and form updates preserve the existing raw value
src/shared/db/built-sites.ts:194:15 readOnlyFrom → "" # not in BuiltSiteFormInput; inserts default "" and form updates preserve the existing raw value
src/shared/db/built-sites.ts:202:15 renewalTokenIndex → "" # not in BuiltSiteFormInput; inserts default null and form updates preserve the existing raw value
src/shared/db/built-sites.ts:377:71 ?? → || # blob input strings use "" as their fallback, providers are non-empty, and renewalToken uses null
src/shared/db/built-sites.ts:391:54 ?? → || # validated optional strings use "" as their fallback, providers are non-empty, and renewalToken is null or non-empty

# Admin listing API fallbacks receive only objects, arrays, positive ids, or
# nullish values, so no valid request can distinguish these operators.
src/features/admin/api.ts:342:66 ?? → || # stored listing lookup returns a ListingWithCount object or null; listing objects are truthy
src/features/admin/api.ts:373:25 ?? → || # parsed group ids are an array or undefined; every array, including [], is truthy
src/features/admin/api.ts:492:30 1 → 0 # the mutation changes sentinel -1 to -0; positive listing ids match neither value
src/features/admin/api.ts:534:19 ?? → || # groupIds is an array or undefined; every array, including [], is truthy
src/features/admin/api.ts:547:43 ?? → || # an existing listing id is positive and truthy, otherwise optional access yields undefined
src/features/admin/api.ts:549:38 ?? → || # groupIds is an array or undefined; every array, including [], is truthy

# Settings registry: readOnly is optional but can only be true when present, so
# `"readOnly" in accessor && accessor.readOnly` and `... || accessor.readOnly`
Expand Down
38 changes: 36 additions & 2 deletions src/features/admin/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
*/

/* jscpd:ignore-start */
import * as v from "valibot";
import { mapById, reduce } from "#fp";
import { groupApiRoutes } from "#routes/admin/api-groups.ts";
import { holidayApiRoutes } from "#routes/admin/api-holidays.ts";
Expand Down Expand Up @@ -157,6 +158,38 @@ const optionalFields: FieldMapping[] = [
["bookable_alone", "bookableAlone", "boolean"],
];

interface ApiBodyFieldRule {
apiKey: string;
error: string;
schema: v.GenericSchema;
}

const API_BODY_FIELD_RULES: ApiBodyFieldRule[] = [
{
apiKey: "bookable_days",
error: "bookable_days must contain only text",
schema: v.array(v.string()),
},
{
apiKey: "duration_days",
error: "duration_days must be a safe integer",
schema: v.pipe(v.number(), v.safeInteger()),
},
];

/** Reject malformed mapped values before they can reach domain or storage code. */
const validateApiBodyFields = (
body: Record<string, unknown>,
): ParseResult<undefined> => {
const invalid = API_BODY_FIELD_RULES.find(
({ apiKey, schema }) =>
body[apiKey] !== undefined && !v.is(schema, body[apiKey]),
);
return invalid
? { error: invalid.error, ok: false }
: { input: undefined, ok: true };
};

/**
* Parse a day_prices object from a JSON body into DayPrices. Keeps only
* positive-integer day counts mapped to numeric prices; everything else is
Expand Down Expand Up @@ -249,12 +282,13 @@ const existingToDefaults = (existing: ListingWithCount): FieldRecord =>
// Body → ListingInput converters
// =============================================================================

/** Parse the request's group ids, then either bail with the parse error or hand
* the ids to `build` to finish producing the listing input. */
/** Validate mapped fields and group ids before building the listing input. */
const withParsedGroupIds = (
body: Record<string, unknown>,
build: (groupIds: number[] | undefined) => Promise<ParseResult<ListingInput>>,
): Promise<ParseResult<ListingInput>> => {
const fields = validateApiBodyFields(body);
if (!fields.ok) return Promise.resolve(fields);
const groups = parseGroupIds(body.group_ids);
return groups.ok ? build(groups.input) : Promise.resolve(groups);
};
Expand Down
4 changes: 2 additions & 2 deletions src/features/admin/attendee-form-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ import type { FormParams } from "#shared/form-data.ts";
import { START_DATE_FIELD } from "#shared/order-select.ts";
import {
type ContactInfo,
clampDurationDays,
type ListingWithCount,
normalizeDurationDays,
} from "#shared/types.ts";
import { isIsoDate } from "#shared/validation/date.ts";
import {
Expand Down Expand Up @@ -256,7 +256,7 @@ export const attendeeBookingsFromLines = (

/** Clamp a submitted day count to the valid range; blank defaults to 1. */
const clampDayCount = (raw: number | null): number =>
normalizeDurationDays(raw ?? 1);
clampDurationDays(raw ?? 1);

/**
* The status an attendee resolves to: their submitted choice, or the public
Expand Down
6 changes: 3 additions & 3 deletions src/features/admin/attendees.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,9 @@ const buildCreateAttendeeInput = (
const { name, email, phone, address, special_instructions, quantity, date } =
values;
const isDaily = listing.listing_type === "daily";
// Customisable daily bookings span the admin's chosen day count (a required,
// options-constrained field; any odd value is clamped downstream by
// normalizeDurationDays); other daily bookings use the fixed duration.
// Customisable daily bookings span the admin's chosen day count. The shared
// boundary clamps whole numbers outside its range and rejects malformed
// numbers. Other daily bookings use the fixed duration.
const durationDays = listing.customisable_days
? Number(values.day_count)
: listing.duration_days;
Expand Down
4 changes: 2 additions & 2 deletions src/features/admin/catalog-transfer/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@ import { seenBefore } from "#shared/seen-before.ts";
import {
type AdminLevel,
availableDayCounts,
clampDurationDays,
type DayPricedListing,
type Group,
type Listing,
type ListingType,
type ListingWithCount,
normalizeDurationDays,
parseDayPrices,
} from "#shared/types.ts";
import { childAddOnError } from "../listings-parents.ts";
Expand Down Expand Up @@ -229,7 +229,7 @@ const listingDataToInput = (
const listingToEdge = (listing: Listing): EdgeListing => ({
customisable_days: listing.customisable_days,
day_prices: listing.day_prices,
duration_days: normalizeDurationDays(listing.duration_days),
duration_days: clampDurationDays(listing.duration_days),
id: listing.id,
listing_type: listing.listing_type,
months_per_unit: listing.months_per_unit,
Expand Down
11 changes: 5 additions & 6 deletions src/features/admin/catalog-transfer/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
ListingTypeSchema,
MAX_DURATION_DAYS,
} from "#shared/types.ts";
import { integerAtLeast } from "#shared/validation/number.ts";

/**
* True when `value` is storable in a datetime column: empty (no value), or a
Expand Down Expand Up @@ -88,16 +89,14 @@ export const CATALOG_TRANSFER_VERSION = 1;
* so an out-of-safe-range magnitude like `1e100` — which `Number.isInteger`
* accepts — is a field error here rather than being rounded or throwing a raw
* error at the storage layer, matching the form's money parser. */
const intAtLeast = (min: number) =>
v.pipe(v.number(), v.safeInteger(), v.minValue(min));
/** A whole non-negative integer (counts, day windows, minor-unit prices). */
const NonNegativeIntSchema = intAtLeast(0);
const NonNegativeIntSchema = integerAtLeast(0);
/** A whole positive integer (durations, quantities). */
const PositiveIntSchema = intAtLeast(1);
const PositiveIntSchema = integerAtLeast(1);
/** A booking duration in whole days: 1..MAX_DURATION_DAYS, matching the listing
* form's cap so an over-limit blob is a field error, not silently clamped. */
const DurationDaysSchema = v.pipe(
intAtLeast(1),
integerAtLeast(1),
v.maxValue(MAX_DURATION_DAYS, `must be at most ${MAX_DURATION_DAYS} days`),
);
/** A single valid contact-field name (email/phone/address/…). */
Expand All @@ -122,7 +121,7 @@ const FieldsSchema = v.pipe(
* rather than a day that never matches an availability check. */
const BookableDaySchema = v.picklist(VALID_DAY_NAMES);
/** A minor-unit price — a non-negative integer. */
const PriceSchema = intAtLeast(0);
const PriceSchema = integerAtLeast(0);
/** A required, trimmed, non-empty name reference. */
const NameRefSchema = v.pipe(v.string(), v.trim(), v.minLength(1));
/** A day-count JSON key: a positive whole number within the bookable range, so a
Expand Down
4 changes: 2 additions & 2 deletions src/features/public/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ import { requirePublicSite } from "#shared/public-site.ts";
import type { ResponseHandler } from "#shared/response-steps.ts";
import { loadSortedListings } from "#shared/sort-listings.ts";
import {
clampDurationDays,
type GroupWithMembers,
type ListingWithCount,
normalizeDurationDays,
} from "#shared/types.ts";
import { parseEmail } from "#shared/validation/email.ts";
import {
Expand Down Expand Up @@ -81,7 +81,7 @@ export const handleHome: ResponseHandler = () =>
* fixed daily listing books its whole duration. Mirrors
* {@link getBookableStartDates}'s span. */
const cardSpanDays = (listing: ListingWithCount): number =>
listing.customisable_days ? 1 : normalizeDurationDays(listing.duration_days);
listing.customisable_days ? 1 : clampDurationDays(listing.duration_days);

/** The daily listings NOT bookable on `date`: outside their bookable calendar,
* or without capacity for their span starting that day. One remaining query
Expand Down
7 changes: 6 additions & 1 deletion src/shared/address-lookup/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,12 @@ export type AddressLookupProvider = Exclude<AddressLookupSetting, "none">;

/** One matching address: its ready-to-display line, plus the provider's
* latitude/longitude when it knows them ("" when it doesn't). */
export type AddressMatch = { line: string; lat: string; lng: string };
export const AddressMatchSchema = v.strictObject({
lat: v.string(),
line: v.string(),
lng: v.string(),
});
export type AddressMatch = v.InferOutput<typeof AddressMatchSchema>;

/** A successful search: one match per address the provider found. */
export type AddressLookupResult = { addresses: AddressMatch[] };
Expand Down
9 changes: 7 additions & 2 deletions src/shared/admin-features.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as v from "valibot";
import { defineStoredJson } from "#shared/validation/stored-json.ts";

/**
* The admin features operators can choose to show. This one registry drives the
Expand Down Expand Up @@ -81,6 +82,7 @@ const EnabledFeaturesSchema = v.pipe(
"Every admin feature must have an enabled value",
),
);
const enabledFeaturesJson = defineStoredJson(EnabledFeaturesSchema);

const DEFAULT_ENABLED_FEATURES = Object.freeze(
Object.fromEntries(FEATURE_KEYS.map((key) => [key, false])),
Expand All @@ -91,10 +93,13 @@ const DEFAULT_ENABLED_FEATURES = Object.freeze(
export const parseEnabledFeatures = (value: string): EnabledFeatures =>
value === ""
? DEFAULT_ENABLED_FEATURES
: (v.parse(EnabledFeaturesSchema, JSON.parse(value)) as EnabledFeatures);
: (enabledFeaturesJson.read(
value,
"settings.enabled_features",
) as EnabledFeatures);

export const serializeEnabledFeatures = (features: EnabledFeatures): string =>
JSON.stringify(v.parse(EnabledFeaturesSchema, features));
enabledFeaturesJson.write(features, "settings.enabled_features");

export const setFeatureEnabled = (
features: EnabledFeatures,
Expand Down
8 changes: 4 additions & 4 deletions src/shared/booking-date-fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

import { capacityDateFor } from "#shared/capacity-rules.ts";
import type { ListingWithCount } from "#shared/types.ts";
import { normalizeDurationDays } from "#shared/types.ts";
import { clampDurationDays } from "#shared/types.ts";

/** The listing facts the row builder reads to derive a booking's date and
* duration. Narrower than the full listing so the helper stays pure over the
Expand All @@ -30,7 +30,7 @@ export type BookingDateSource = Pick<
* - A non-customisable `daily` listing spans its fixed `duration_days`.
* - A `standard` listing spans one dateless day (no range column).
*
* `dayCount` defaults to `1`, and {@link normalizeDurationDays} clamps
* `dayCount` defaults to `1`, and {@link clampDurationDays} clamps
* non-finite input back to `1`, so a genuinely optional `dayCount` (a legacy
* signed session without `day_count`, modelled as `undefined` on
* `BookingIntent`) flows through that default unchanged — missing day count
Expand All @@ -45,8 +45,8 @@ export const bookingDateFields = (
): { date: string | null; durationDays: number } => ({
date: capacityDateFor(listing.listing_type, date),
durationDays: listing.customisable_days
? normalizeDurationDays(dayCount)
? clampDurationDays(dayCount)
: listing.listing_type === "daily"
? normalizeDurationDays(listing.duration_days)
? clampDurationDays(listing.duration_days)
: 1,
});
10 changes: 5 additions & 5 deletions src/shared/booking/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { getBookableStartDates, isBookingRangeValid } from "#shared/dates.ts";
import {
ascending,
availableDayCounts,
clampDurationDays,
dayPriceFor,
type Holiday,
type ListingWithCount,
normalizeDurationDays,
PARENT_CHILD_GROUP_UNITS,
type SharedGroupCapacity,
} from "#shared/types.ts";
Expand Down Expand Up @@ -84,7 +84,7 @@ export const childUsesSameDays =
(child: TicketListing): boolean =>
child.listing.customisable_days ||
child.listing.listing_type !== "daily" ||
normalizeDurationDays(child.listing.duration_days) === days;
clampDurationDays(child.listing.duration_days) === days;

/** The order's resolved date is valid for a daily child's own calendar. */
export const childDateOk =
Expand Down Expand Up @@ -145,7 +145,7 @@ export const childDaysFromParent = <T extends number | null>(
): T => {
if (parent.customisable_days) return customisableValue;
if (parent.listing_type === "daily") {
return normalizeDurationDays(parent.duration_days) as T;
return clampDurationDays(parent.duration_days) as T;
}
return standardValue;
};
Expand All @@ -160,7 +160,7 @@ export const fixedParentDays = (
childDaysFromParent<number | null>(
parent,
null,
normalizeDurationDays(parent.duration_days),
clampDurationDays(parent.duration_days),
);

/** Keeps options that at least one child can support. */
Expand Down Expand Up @@ -251,7 +251,7 @@ export const dayCountsChildSupports = (
): number[] | null => {
if (child.listing.customisable_days) return availableDayCounts(child.listing);
if (child.listing.listing_type === "daily") {
return [normalizeDurationDays(child.listing.duration_days)];
return [clampDurationDays(child.listing.duration_days)];
}
return null;
};
Expand Down
Loading