@sonordev/contracts 2.25.0 → 2.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.27.0
4
+
5
+ - Add the `booking-intake` entry: what a booking may ask a guest about their business. A booking type's step is `off`, `optional` or `required` (`parseBookingBusinessStep` reads anything unknown as `off`), and `checkBookingBusinessAnswers` is the one check the booking widget, the app's booking page and the API all run, with the guest-facing words in `BOOKING_BUSINESS_ERROR_TEXT`. `normalizeBookingCompany` removes control and format characters (bidi overrides, zero-width marks) and lone surrogates and never truncates; `normalizeGuestWebsite` returns a public `http` or `https` address with no query, fragment, port or credentials, keeps the path, and refuses IP addresses, the literal local names `localhost`, `.local` and `.internal`, and other schemes (it runs no DNS, so anything that fetches the address must check it itself, and the `url` must be HTML-escaped wherever it's rendered). A required company is refused for every source except `portal` with `verifiedMember: true`, which the API sets from its authenticated context and never from the request body; a missing or unknown source is held to the answers. `bookingBusinessDetails` is the one reader for the answers on every surface a host sees, and `BOOKING_INTAKE_JSON_SCHEMA` describes the three wire fields for an agent. The browser-safe part is its own module so the widget doesn't bundle the schema or the reader. `stripWww` moved into the `sites` leaf module and is still exported from `sites`.
6
+ - Let a qualified-lead goal count contacts who book. The reviewed objective and the native qualification witness can each name up to 100 `eligibleBookingTypeIds` beside the one managed form, and the two lists must match exactly, in any order or letter case. A witness that adds or drops a booking type, a duplicate or empty list, and booking types on any other goal source are refused. A goal without the field serializes and digests exactly as before.
7
+ - Add the `resonance-confirmation` entry: the one wire contract for the emailed code behind a budget approved on a person's word. It holds the two routes, the closed request and answer parsers, the six-key `on_their_word` evidence parser, the refusal table with its status codes, the code numbers (six digits, ten minutes, five tries, three an hour) and the marker that identifies the confirmation mail (subject tag and header). The shape of stored evidence is read here; whether a code was really redeemed stays the database's word. The receipt's `expiresAt` is the real deadline (the shorter of ten minutes and the prepared plan's own expiry), a prepared plan with under two minutes left is refused as `PLAN_EXPIRING` before any code is spent, a person is sent at most 3 codes an hour per project, 6 an hour and 15 a day across projects, and `attemptsLeft` travels under `data` (the one field the server's error filter forwards); a wrong code with no tries left reads as the lockout. The rate limits are `RESONANCE_CONFIRMATION_RATE_HOURLY` (3 an hour for a project, 6 an hour for a person) and `RESONANCE_CONFIRMATION_RATE_DAILY` (15 a day); the single `RESONANCE_CONFIRMATION_RATE` stays in the table because the first confirmation migration still answers with it. `RESONANCE_CONFIRMATION_PERSON_LOCKED` (429) is the answer when a person's agent has had three codes locked in a day. The rate-limit answers carry how long to wait as `retryAfterSeconds` under `error.data` (1 to 86,400), which `confirmationFailureOf` returns beside the failure kinds `rate_limited_daily` and `person_locked`, and `confirmationWaitWords` words it ("about 13 minutes", rounded up). `CONFIRMATION_LOCKS_PER_DAY` and `CONFIRMATION_RETRY_MAX_SECONDS` are the numbers.
8
+ - Add the `quote-screen` entry: the one screen for the quote a person's yes carries. A quote over 1,000 characters is refused before anything reads it, then provider keys, tokens, logins, passwords, PINs, card numbers (Luhn plus a brand prefix), IBANs (mod-97) and routing, account and social security numbers are refused, while campaign names written with words, abbreviations, all-caps or separators pass. Unseparated names of 24 or more characters are refused by design and listed as known limits.
9
+
10
+ ## 2.26.0
11
+
12
+ - Add positioning previews for exact Meta, Google Search and Broadcast draft targets. Current source witnesses and an independent consistency assessment support the owner's application checks.
13
+ - Add the property-interest entry with closed event and site report contracts. Exposure-normalized action rates, missing-session events and accepted tour inquiry evidence retain separate fields. The request matcher checks the exact site, window and explicit listing set.
14
+
3
15
  ## 2.25.0
4
16
 
5
17
  - Add guided Meta dataset selection and setup contracts, including exact verified dataset readback and a shared dataset name validator.
package/README.md CHANGED
@@ -45,6 +45,7 @@ pnpm add @sonordev/contracts
45
45
  | `@sonordev/contracts/resonance` | Campaign, consent, measurement, plan, mandate and command parsers, types and JSON schemas | Sites, APIs and the dashboard share the same wire rules |
46
46
  | `@sonordev/contracts/resonance-constants` | Small browser-safe measurement wire constants | Browser readers that don't need campaign schemas |
47
47
  | `@sonordev/contracts/signal-experiments` | Shared Signal experiment create and update validation | APIs and the dashboard use one experiment boundary |
48
+ | `@sonordev/contracts/booking-intake` | What a booking may ask a guest about their business: whether a type asks, how a company name and a website are cleaned and when they're refused, the guest-facing error text, and the one reader a host sees the answers through | The booking widget, the Sonor app's booking page, the booking API and everything that shows a booking to a host |
48
49
 
49
50
  ## Focus closing artwork
50
51
 
@@ -1521,6 +1522,17 @@ only `qualified_lead` with `unique_qualified_contact` and a 1–90 day window.
1521
1522
  Actual producer eligibility, permanent contact/destination deduplication and
1522
1523
  delivery remain server checks. Other goal profiles are unsupported.
1523
1524
 
1525
+ A qualified-lead goal can also count contacts who book. Its reviewed
1526
+ objective names up to 100 `eligibleBookingTypeIds` beside the one managed form,
1527
+ and the native witness (`resolvedQualificationRule`) must name exactly the same
1528
+ booking types, in any order or letter case. A witness that adds or drops a
1529
+ type, a duplicate or empty list, and booking types on any other goal source
1530
+ are refused, and a witness still names exactly one form. The field belongs to
1531
+ the reviewed objective, so the mandate and the Google delivery command bind it
1532
+ the way they bind the form. A goal that omits it parses and serializes exactly
1533
+ as before, with its existing digest. Which bookings qualify stays a server
1534
+ check.
1535
+
1524
1536
  The declaration's explicit statement is
1525
1537
  `DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING`; its category is `general`,
1526
1538
  `housing`, `employment` or `financial_products_services`. The server binds it
@@ -1774,6 +1786,61 @@ Use `@sonordev/contracts/resonance` to review audience setup for a saved draft b
1774
1786
  Only eligible visits from the active grant window can be considered for delivery. The native owner checks approval, current scope and consent before dispatch. The parsers validate wire shape and consistency. Campaign launch and spend require their own authorization.
1775
1787
 
1776
1788
 
1789
+ ### Positioning preview
1790
+
1791
+ Use `parseResonancePositioningPreviewRequest` to select a saved draft revision, site and exact Meta, Google Search or Broadcast target. A destination or offer can be absent while you're exploring. Applying a ready suggestion requires a current verified destination and any selected offer.
1792
+
1793
+ `parseResonancePositioningPreview` separates the buyer rationale, source references and suggested copy. A fictional bike shop might use a verified booking page to support a draft about choosing a drop-off location, while keeping its guess about walk-in demand labeled as a hypothesis. Provisional and no-fit results carry reasons and no application token.
1794
+
1795
+ `parseResonancePositioningApplyRequest` accepts the owner's application token. The owner rechecks the original scope and current evidence before updating a draft or passing the selected text to native Broadcast preparation. Publication and campaign launch follow their existing approval paths.
1796
+
1797
+ ### Property interest analytics
1798
+
1799
+ Use `@sonordev/contracts/property-interest` for property exposure and deliberate-action events. `parsePropertyInterestEvent` accepts the reserved category `real_estate_interest` and a native listing UUID, surface, and optional display ordinal. The API resolves the listing against the site's scope before admitting the event.
1800
+
1801
+ `parsePropertyInterestReportForRequest(response, request)` checks the site, time window and exact selected listing set. A broad report uses UUID pagination with at most 50 properties per page. Each property's collection and detail cohorts keep exposure sessions, eligible action sessions, unmatched action sessions and events without a session distinct. `propertyInterestRateBps` returns a rounded basis-point rate or `null` when there are no exposure sessions.
1802
+
1803
+ Accepted tour inquiries have explicit source availability. A verified zero remains different from unavailable evidence. These reports describe site activity. They establish no advertising audience, booking, qualified buyer or causal result.
1804
+
1805
+ ## Budget approved on a person's word
1806
+
1807
+ Added in 2.27.0: `@sonordev/contracts/resonance-confirmation` is the one wire contract between the agent side (Signal) and Sonor's API for the emailed code behind a budget a person approves in chat. `@sonordev/contracts/quote-screen` is the one screen for the quote that approval carries. Both are dependency-free.
1808
+
1809
+ ```ts
1810
+ import {
1811
+ confirmationRequestPath,
1812
+ confirmationRedeemPath,
1813
+ parseConfirmationRedeemRequest,
1814
+ parseOnTheirWordEvidence,
1815
+ confirmationFailureOf,
1816
+ } from '@sonordev/contracts/resonance-confirmation'
1817
+ import { refuseQuote } from '@sonordev/contracts/quote-screen'
1818
+
1819
+ refuseQuote('Yes, go ahead with Q4-BRAND-SEARCH-2026') // null: a campaign name is not a secret
1820
+ refuseQuote('yes, the Stripe key is sk_live_abcdefghijklmnop') // 'secret'
1821
+ ```
1822
+
1823
+ Two routes carry the whole flow: ask for a code (`confirmationRequestPath`), then redeem it for the exact request the agent filed (`confirmationRedeemPath`). The code goes to the person's verified login email and never back to the agent. The redeem body is exactly `confirmationId`, `ledgerActionId` and `code`. The evidence the Ledger keeps has six keys (`agent`, `quote`, `mandate_digest`, `review_digest`, `channel`, `confirmation`). `parseOnTheirWordEvidence` reads its shape only. Whether the code was really redeemed for that request is the database's word, and a stored quote is never screened again. `CONFIRMATION_REFUSALS` holds every refusal code with its status and words, and `confirmationFailureOf` turns any answer into one of them (anything unknown reads as unavailable, which approves nothing). The confirmation mail carries a subject tag and an `X-Sonor-Confirmation` header (`isConfirmationMail`), so a mailbox reader can keep it out of anything an agent reads.
1824
+
1825
+ `refuseQuote` checks the length first (1,000 characters, in constant time) and then reads the quote. It refuses provider keys, tokens, logins, passwords, PINs, payment card numbers, IBANs and bank or social security numbers. A campaign name written with words, abbreviations, capitals or separators passes. A single unbroken run of 24 or more letters and digits with no separator looks like a token and is refused; `QUOTE_KNOWN_LIMITS` lists examples, and the agent asks for the name with separators or its id instead.
1826
+
1827
+ ## Booking intake
1828
+
1829
+ Added in 2.27.0, `@sonordev/contracts/booking-intake` is the one rule for the "About your business" step a booking type can put between the guest picking a time and their contact details. It asks for a company name and, optionally, a website.
1830
+
1831
+ A type's step is `off`, `optional` or `required`. `parseBookingBusinessStep` reads anything unknown, null or missing as `off`, so an old row or an API that predates the column asks nothing. `optional` and `required` describe the company; the website is always optional, and a guest who ticks "we don't have a website yet" sends `noWebsite: true`, which wins over any website sent with it. The three wire fields are `company`, `website` and `noWebsite` (`BOOKING_GUEST_BUSINESS_FIELDS`), and `BOOKING_INTAKE_JSON_SCHEMA` describes them for an agent.
1832
+
1833
+ `checkBookingBusinessAnswers(step, { company, website, noWebsite }, { source, verifiedMember })` is the check the widget, the app's booking page and the API all run, and the API runs it again on the server. It always cleans what it's given, whatever the step:
1834
+
1835
+ - `normalizeBookingCompany` turns runs of whitespace into one space (the next-line control and the Unicode spaces included) and removes control and format characters (bidi overrides, zero-width marks, a byte-order mark) and lone surrogates, because the name ends up in a host's email, a calendar description and Echo's text. It never truncates; more than 120 characters is `too_long`.
1836
+ - `normalizeGuestWebsite` turns what a guest typed into `{ ok: true, url, host }`: `https://` when there's no scheme, no query, fragment, port or credentials, the path kept as the URL parser writes it, and `www.` kept in the `url` and dropped from the `host` when two or more labels remain. It's `null` when the box was empty and `{ ok: false, reason }` when it isn't an address. `reason` is `too_long` for more than 300 characters, or when the cleaned address is longer than the 300 characters a booking stores (an international host or a non-ASCII path grows when it's encoded), and `invalid` for everything else: another scheme, credentials, a port, an IP address, a host with no dot or no real top-level domain, and the literal local names `localhost`, `.local` and `.internal`. It never says why a host was refused. It runs no DNS and fetches nothing, so a name that only resolves to a private address passes: anything that later fetches the address, such as a site review, must resolve it and run its own DNS-pinned check first. The `url` is text a guest typed, so HTML-escape it wherever it's rendered, attributes included, and don't decode it.
1837
+
1838
+ It refuses (`ok: false`, with `errors` per field) whenever the type asks (`optional` or `required`), unless the caller is exempt. A `required` type refuses a missing company. The only exemption is `portal`, a Sonor member's or Echo's booking made for someone else, and only when the caller also passes `verifiedMember: true` (`bookingBusinessExempt`). A source is a string any caller can send, so the API sets `verifiedMember` from its authenticated context (the signed-in member or the service key) and never from the request body. A missing, empty or unknown source is held to the answers like any other. Where the type doesn't ask, or the caller is exempt, a value that doesn't fit is left out and reported in `value.dropped`, so a booking nobody asked a question on is never failed by a long CRM company or a malformed CRM website. `BOOKING_BUSINESS_ERROR_TEXT` holds the words a guest is told, and `describeBookingBusinessErrors` maps a refusal to them, so the widget, the app and the API's 400 say the same thing.
1839
+
1840
+ `bookingBusinessDetails(row, contact)` is the one reader for every surface a host sees the answers on. The booking row wins and the CRM contact only fills what the row lacks; a contact's website is read again and dropped if it isn't an address, and a guest who said they have no website is never contradicted by one the CRM has. `from` says where the answers came from.
1841
+
1842
+ The browser-safe part (the normalizers, the check and the error text) is its own module, `booking-intake-normalize`, so the booking widget doesn't bundle the agent schema or the host reader. Everything is also exported from `@sonordev/contracts/booking-intake`. The hold length and which hosts a site review skips are decisions of the API, not part of this contract.
1843
+
1777
1844
  ## Sales call preparation
1778
1845
 
1779
1846
  Added in 2.24.0, `@sonordev/contracts/sales-call-prep` provides pure request,
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Whether a booking type asks about the guest's business after they pick a time.
3
+ * `optional` and `required` describe the company field; the website is always
4
+ * optional.
5
+ */
6
+ export declare const BOOKING_BUSINESS_STEPS: readonly ['off', 'optional', 'required'];
7
+ export type BookingBusinessStep = (typeof BOOKING_BUSINESS_STEPS)[number];
8
+ /** Anything unknown, null or missing is `off`, so an old row or an API that predates the column reads as off. */
9
+ export declare function parseBookingBusinessStep(value: unknown): BookingBusinessStep;
10
+ /** True when the type puts the "About your business" step in front of the guest. */
11
+ export declare function bookingAsksBusiness(step: unknown): boolean;
12
+ /** The wire names on both booking create bodies (camelCase, like the rest of the booking body). */
13
+ export declare const BOOKING_GUEST_BUSINESS_FIELDS: {
14
+ readonly company: 'company';
15
+ readonly website: 'website';
16
+ readonly noWebsite: 'noWebsite';
17
+ };
18
+ /** The longest company name, in characters. */
19
+ export declare const BOOKING_COMPANY_MAX = 120;
20
+ /** The longest website a guest may type, in characters. */
21
+ export declare const BOOKING_WEBSITE_INPUT_MAX = 300;
22
+ /** The longest stored website, in characters: the booking row's length check, applied to the canonical address. */
23
+ export declare const BOOKING_WEBSITE_URL_MAX = 300;
24
+ /**
25
+ * A company name as it is stored and shown: runs of whitespace become one
26
+ * space, control and format characters and lone surrogates are removed (a bidi
27
+ * override in a name would reorder the line it lands in, in a host's email, a
28
+ * calendar description and Echo's text), and the result is trimmed. Null when
29
+ * nothing is left or the value isn't text. It never truncates: a name that is
30
+ * too long is an error (`checkBookingBusinessAnswers`), not a shorter name
31
+ * nobody typed.
32
+ *
33
+ * Format characters include the zero-width joiners some scripts use inside a
34
+ * word. A name that loses one is still readable; one that carried a bidi
35
+ * override would not be safe.
36
+ */
37
+ export declare function normalizeBookingCompany(value: unknown): string | null;
38
+ export type GuestWebsite = {
39
+ ok: true;
40
+ url: string;
41
+ host: string;
42
+ } | {
43
+ ok: false;
44
+ reason: 'invalid' | 'too_long';
45
+ };
46
+ /**
47
+ * What a guest typed into the website box, as an address a host can safely
48
+ * open. Pure: no network call, and it never says why a host was refused beyond
49
+ * `invalid`.
50
+ *
51
+ * - Empty or whitespace is `null` (not answered). More than 300 characters is
52
+ * `too_long`, and so is an address whose canonical form is (an IDN host or a
53
+ * non-ASCII path grows when it is encoded, and the stored value has the same
54
+ * limit).
55
+ * - No scheme means `https://`. An explicit scheme other than http or https
56
+ * (`javascript:`, `mailto:`, `ftp:`, `data:`) is invalid, and so is
57
+ * `user:pw@host`, which reads as a scheme.
58
+ * - Refused: credentials, a non-default port, whitespace, control and format
59
+ * characters, backslashes, a host without a dot or without a letter-only or
60
+ * `xn--` TLD, any IPv4 or IPv6 literal, and the literal local names
61
+ * `isBlockedPublicUrlHost` refuses (`localhost`, `.local`, `.internal`). A
62
+ * name that merely resolves to a private address is not caught: this runs no
63
+ * DNS, so anything that fetches the address must resolve and check it itself.
64
+ * - The canonical `url` is `scheme://host/path`: `www.` kept, the path kept as
65
+ * the URL parser writes it, a trailing slash trimmed, and no query,
66
+ * fragment, port or credentials. It is still text a guest typed. HTML-escape
67
+ * it wherever it is rendered, attributes included, and don't decode it.
68
+ * `host` is the address without `www.` (kept when stripping it would leave
69
+ * fewer than two labels), for display and for matching a company's domain.
70
+ */
71
+ export declare function normalizeGuestWebsite(value: unknown): null | GuestWebsite;
72
+ /**
73
+ * The only booking source that can be exempt from the answers a type asks for:
74
+ * `portal`, a Sonor member's or Echo's booking made for someone else. Every
75
+ * other source is held to the answers, and so is a missing, empty or unknown
76
+ * one, so a new source is held until it is deliberately listed here.
77
+ *
78
+ * A source is a string any caller can send, so naming it is not enough. The
79
+ * exemption also needs `verifiedMember`, which the API sets from its
80
+ * authenticated context (the signed-in member or the service key) and never
81
+ * from the request body.
82
+ */
83
+ export declare const BOOKING_BUSINESS_EXEMPT_SOURCES: readonly ['portal'];
84
+ /** True only for an exempt source asked for by a verified member. A missing, empty or unknown source, or any value but `true`, is not exempt. */
85
+ export declare function bookingBusinessExempt(source: unknown, verifiedMember?: unknown): boolean;
86
+ export interface BookingBusinessInput {
87
+ company?: unknown;
88
+ website?: unknown;
89
+ noWebsite?: unknown;
90
+ }
91
+ export interface BookingBusinessErrors {
92
+ company?: 'required' | 'too_long';
93
+ website?: 'invalid' | 'too_long';
94
+ }
95
+ /** An answer that was left out because the booking wasn't asking for it (see `checkBookingBusinessAnswers`). */
96
+ export interface BookingBusinessDropped {
97
+ company?: 'too_long';
98
+ website?: 'invalid' | 'too_long';
99
+ }
100
+ export interface BookingBusinessAnswers {
101
+ company: string | null;
102
+ /** The canonical address, or null. */
103
+ website: string | null;
104
+ noWebsite: boolean;
105
+ /** What was left out and why, so the caller can log it. Empty when nothing was. */
106
+ dropped: BookingBusinessDropped;
107
+ }
108
+ export type BookingBusinessCheck = {
109
+ ok: true;
110
+ value: BookingBusinessAnswers;
111
+ } | {
112
+ ok: false;
113
+ errors: BookingBusinessErrors;
114
+ };
115
+ /**
116
+ * The one check of a guest's business answers. The widget's Continue and
117
+ * submit, the app's booking page and the API's create all run it, and the
118
+ * server always runs it again.
119
+ *
120
+ * It always normalizes, whatever the step, because agents and the app send a
121
+ * company on types that don't ask. It refuses (`ok: false`) whenever the
122
+ * booking is asking (`optional` or `required`) unless the caller is exempt
123
+ * (`bookingBusinessExempt`: source `portal` and `verifiedMember` true, which the
124
+ * API sets from its authenticated context and never from the request body): a
125
+ * company that is too long, a website that isn't an address, and, when the
126
+ * step is `required`, a missing company. A missing, empty or unknown `source`
127
+ * is held to the answers like any other. Where the booking isn't asking (a
128
+ * type that doesn't), or the caller is exempt, a value that doesn't fit is
129
+ * dropped and reported in `dropped` instead of failing a booking nobody asked a
130
+ * question on.
131
+ *
132
+ * `noWebsite` true wins: the website becomes null.
133
+ */
134
+ export declare function checkBookingBusinessAnswers(step: unknown, input: BookingBusinessInput | null | undefined, opts?: {
135
+ source?: unknown;
136
+ verifiedMember?: boolean;
137
+ }): BookingBusinessCheck;
138
+ /**
139
+ * What a guest is told. The widget, the app's pages and the API's 400 message
140
+ * all use these words, so a refusal reads the same wherever it shows.
141
+ */
142
+ export declare const BOOKING_BUSINESS_ERROR_TEXT: {
143
+ readonly company_required: 'Please add your company name, or your own name if you work for yourself.';
144
+ readonly company_too_long: "That name's a little long. Please keep it to 120 characters or fewer.";
145
+ readonly website_invalid: "That doesn't look like a web address. Try something like yourcompany.com.";
146
+ readonly website_too_long: 'That address is too long. The main address is enough, like yourcompany.com.';
147
+ };
148
+ /** The guest-facing words for each refused field. */
149
+ export declare function describeBookingBusinessErrors(errors: BookingBusinessErrors): {
150
+ company?: string;
151
+ website?: string;
152
+ };
@@ -0,0 +1,68 @@
1
+ export { BOOKING_BUSINESS_STEPS, BOOKING_GUEST_BUSINESS_FIELDS, BOOKING_COMPANY_MAX, BOOKING_WEBSITE_INPUT_MAX, BOOKING_WEBSITE_URL_MAX, BOOKING_BUSINESS_EXEMPT_SOURCES, BOOKING_BUSINESS_ERROR_TEXT, parseBookingBusinessStep, bookingAsksBusiness, normalizeBookingCompany, normalizeGuestWebsite, bookingBusinessExempt, checkBookingBusinessAnswers, describeBookingBusinessErrors, } from './booking-intake-normalize';
2
+ export type { BookingBusinessStep, GuestWebsite, BookingBusinessInput, BookingBusinessErrors, BookingBusinessDropped, BookingBusinessAnswers, BookingBusinessCheck, } from './booking-intake-normalize';
3
+ /** Bump on a breaking change to the wire fields or to how the answers are read. */
4
+ export declare const BOOKING_INTAKE_CONTRACT_VERSION: 1;
5
+ /**
6
+ * Agent-native contract: JSON Schema for the three business fields on a
7
+ * booking's guest, so an agent can validate them without importing the code.
8
+ * Every field is optional here; whether a type requires the company is the
9
+ * booking type's `business_step`, read with `checkBookingBusinessAnswers`.
10
+ * `maxLength` counts characters the way the booking row's length checks do,
11
+ * on the cleaned company and the trimmed website.
12
+ */
13
+ export declare const BOOKING_INTAKE_JSON_SCHEMA: {
14
+ readonly $schema: 'http://json-schema.org/draft-07/schema#';
15
+ readonly $id: 'https://sonor.io/schemas/booking-intake.v1.json';
16
+ readonly title: 'BookingGuestBusinessAnswers';
17
+ readonly description: "What a guest tells a booking about their business: a company name (their own name if they work for themselves), a website address if they have one, and a flag for 'we don't have a website yet', which wins over any website sent with it.";
18
+ readonly type: 'object';
19
+ readonly properties: {
20
+ readonly company: {
21
+ readonly type: readonly ['string', 'null'];
22
+ readonly maxLength: 120;
23
+ readonly description: "Company name. Required when the booking type's business step is required. The length is measured after cleaning: extra whitespace and control characters don't count.";
24
+ };
25
+ readonly website: {
26
+ readonly type: readonly ['string', 'null'];
27
+ readonly maxLength: 300;
28
+ readonly description: 'A public http or https address, or a bare domain like example.com. Credentials, ports, IP addresses and the local names localhost, .local and .internal are refused. The query and fragment are dropped and the path is kept. The length is measured after trimming.';
29
+ };
30
+ readonly noWebsite: {
31
+ readonly type: readonly ['boolean', 'null'];
32
+ readonly description: "True when the guest has no website yet. A website sent with it is ignored.";
33
+ };
34
+ };
35
+ };
36
+ /** The booking columns that hold the answers. A Quo booking has none of its own and reads its contact. */
37
+ export interface BookingBusinessRow {
38
+ guest_company?: string | null;
39
+ guest_website?: string | null;
40
+ guest_no_website?: boolean | null;
41
+ }
42
+ /** The CRM contact a booking belongs to, whose company and website fill what the booking lacks. */
43
+ export interface BookingBusinessContact {
44
+ company?: string | null;
45
+ website?: string | null;
46
+ }
47
+ export interface BookingBusinessDetails {
48
+ company: string | null;
49
+ /** The canonical address, or null. */
50
+ website: string | null;
51
+ /** The address without `www.`, for display and for matching a company's domain. */
52
+ websiteHost: string | null;
53
+ /** The guest said they have no website yet, and no website is shown. */
54
+ noWebsite: boolean;
55
+ /** `booking` when the guest answered anything on this booking, `contact` when only the CRM contact supplied something, null when there is nothing. */
56
+ from: 'booking' | 'contact' | null;
57
+ }
58
+ /**
59
+ * The single reader for every host-facing surface: the host's email, the
60
+ * review email, the calendar description, the app's booking detail, the prep
61
+ * task, Signal's prep, and a Quo booking through its contact.
62
+ *
63
+ * The booking row wins; the contact only fills what the row lacks. A guest who
64
+ * ticked "we don't have a website yet" is not contradicted by a website the CRM
65
+ * has. Both sides are read again with the normalizers, because the CRM writes
66
+ * websites in mixed shapes: a website that isn't an address is dropped.
67
+ */
68
+ export declare function bookingBusinessDetails(row: BookingBusinessRow | null | undefined, contact?: BookingBusinessContact | null): BookingBusinessDetails;
@@ -0,0 +1,221 @@
1
+ 'use strict';
2
+
3
+ // src/contracts/sites-normalize.ts
4
+ function normalizeSiteHost(site) {
5
+ if (!site || typeof site !== "string") return null;
6
+ let s = site.trim().toLowerCase();
7
+ if (!s) return null;
8
+ s = s.replace(/^https?:\/\//, "");
9
+ const slash = s.indexOf("/");
10
+ if (slash >= 0) s = s.slice(0, slash);
11
+ const colon = s.indexOf(":");
12
+ if (colon >= 0) s = s.slice(0, colon);
13
+ s = s.replace(/\.+$/, "");
14
+ return s || null;
15
+ }
16
+
17
+ // src/contracts/public-url-host.ts
18
+ function isPrivateIpv4(a, b) {
19
+ return a === 127 || a === 10 || a === 0 || a === 192 && b === 168 || a === 172 && b >= 16 && b <= 31 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127 || a >= 224;
20
+ }
21
+ function ipv6Words(host) {
22
+ if (!host.includes(":") || !/^[a-f\d:.]+$/.test(host)) return null;
23
+ let canonical;
24
+ try {
25
+ canonical = new URL(`http://[${host}]/`).hostname.slice(1, -1);
26
+ } catch {
27
+ return null;
28
+ }
29
+ const sides = canonical.split("::");
30
+ const left = sides[0] ? sides[0].split(":") : [];
31
+ const right = sides.length > 1 && sides[1] ? sides[1].split(":") : [];
32
+ return [...left, ...Array(sides.length > 1 ? 8 - left.length - right.length : 0).fill("0"), ...right].map((word) => parseInt(word, 16));
33
+ }
34
+ function isBlockedPublicUrlHost(rawHost) {
35
+ const host = rawHost.toLowerCase().replace(/^\[|\]$/g, "");
36
+ const blockedName = host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal");
37
+ if (host.includes(":") && host.includes("%")) return true;
38
+ const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
39
+ const blockedIp = !!ipv4 && isPrivateIpv4(Number(ipv4[1]), Number(ipv4[2]));
40
+ const words = ipv6Words(host);
41
+ const blockedIpv6 = !!words && // Unspecified/loopback, unique-local, link-local, deprecated site-local
42
+ // and multicast destinations aren't public logo/webhook endpoints.
43
+ (words.every((word) => word === 0) || words.slice(0, 7).every((word) => word === 0) && words[7] === 1 || (words[0] & 65024) === 64512 || (words[0] & 65472) === 65152 || (words[0] & 65472) === 65216 || (words[0] & 65280) === 65280 || // IPv4-mapped and older IPv4-compatible forms carry an IPv4 destination.
44
+ words.slice(0, 5).every((word) => word === 0) && [0, 65535].includes(words[5]) && isPrivateIpv4(words[6] >> 8, words[6] & 255));
45
+ return blockedName || blockedIp || blockedIpv6;
46
+ }
47
+
48
+ // src/contracts/booking-intake-normalize.ts
49
+ var BOOKING_BUSINESS_STEPS = ["off", "optional", "required"];
50
+ function parseBookingBusinessStep(value) {
51
+ return BOOKING_BUSINESS_STEPS.includes(value) ? value : "off";
52
+ }
53
+ function bookingAsksBusiness(step) {
54
+ return parseBookingBusinessStep(step) !== "off";
55
+ }
56
+ var BOOKING_GUEST_BUSINESS_FIELDS = { company: "company", website: "website", noWebsite: "noWebsite" };
57
+ var BOOKING_COMPANY_MAX = 120;
58
+ var BOOKING_WEBSITE_INPUT_MAX = 300;
59
+ var BOOKING_WEBSITE_URL_MAX = 300;
60
+ var NAME_WHITESPACE = /[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+/gu;
61
+ var NAME_REMOVED = /[\p{Cc}\p{Cf}\p{Cs}]/gu;
62
+ var characters = (text) => Array.from(text).length;
63
+ function normalizeBookingCompany(value) {
64
+ if (typeof value !== "string") return null;
65
+ const text = value.replace(NAME_WHITESPACE, " ").replace(NAME_REMOVED, "").replace(/ {2,}/g, " ").trim();
66
+ return text || null;
67
+ }
68
+ var INVALID = { ok: false, reason: "invalid" };
69
+ var TOO_LONG = { ok: false, reason: "too_long" };
70
+ var PUBLIC_TLD = /^(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/;
71
+ var HOST_LABEL = /^[a-z0-9_-]{1,63}$/;
72
+ function normalizeGuestWebsite(value) {
73
+ if (value === null || value === void 0) return null;
74
+ if (typeof value !== "string") return INVALID;
75
+ const text = value.trim();
76
+ if (!text) return null;
77
+ if (characters(text) > BOOKING_WEBSITE_INPUT_MAX) return TOO_LONG;
78
+ if (/[\s\p{Cc}\p{Cf}\\]/u.test(text)) return INVALID;
79
+ let candidate;
80
+ const looksLikeScheme = /^[a-z][a-z0-9+.-]*:/i.test(text);
81
+ const hostWithPort = /^[^/?#@:]+:\d+(?:[/?#]|$)/.test(text);
82
+ if (looksLikeScheme && !hostWithPort) {
83
+ const explicit = /^https?:\/\/(.*)$/i.exec(text);
84
+ if (!explicit || explicit[1].startsWith("/")) return INVALID;
85
+ candidate = text;
86
+ } else {
87
+ if (text.startsWith("/")) return INVALID;
88
+ candidate = `https://${text}`;
89
+ }
90
+ let url;
91
+ try {
92
+ url = new URL(candidate);
93
+ } catch {
94
+ return INVALID;
95
+ }
96
+ if (url.protocol !== "http:" && url.protocol !== "https:") return INVALID;
97
+ if (url.username || url.password || url.port) return INVALID;
98
+ if (url.hostname.startsWith("[")) return INVALID;
99
+ const host = normalizeSiteHost(url.hostname);
100
+ if (!host || host.length > 253) return INVALID;
101
+ const labels = host.split(".");
102
+ if (labels.length < 2 || !labels.every((label) => HOST_LABEL.test(label))) return INVALID;
103
+ if (!PUBLIC_TLD.test(labels[labels.length - 1])) return INVALID;
104
+ if (isBlockedPublicUrlHost(host)) return INVALID;
105
+ const canonical = `${url.protocol}//${host}${url.pathname.replace(/\/+$/, "")}`;
106
+ if (canonical.length > BOOKING_WEBSITE_URL_MAX) return TOO_LONG;
107
+ const shown = labels[0] === "www" && labels.length > 2 ? labels.slice(1).join(".") : host;
108
+ return { ok: true, url: canonical, host: shown };
109
+ }
110
+ var BOOKING_BUSINESS_EXEMPT_SOURCES = ["portal"];
111
+ function bookingBusinessExempt(source, verifiedMember) {
112
+ return verifiedMember === true && typeof source === "string" && BOOKING_BUSINESS_EXEMPT_SOURCES.includes(source);
113
+ }
114
+ function checkBookingBusinessAnswers(step, input, opts = {}) {
115
+ const enforced = bookingAsksBusiness(step) && !bookingBusinessExempt(opts.source, opts.verifiedMember);
116
+ const required = enforced && parseBookingBusinessStep(step) === "required";
117
+ const errors = {};
118
+ const dropped = {};
119
+ let company = normalizeBookingCompany(input?.company);
120
+ if (company !== null && characters(company) > BOOKING_COMPANY_MAX) {
121
+ if (enforced) errors.company = "too_long";
122
+ else dropped.company = "too_long";
123
+ company = null;
124
+ } else if (company === null && required) {
125
+ errors.company = "required";
126
+ }
127
+ const noWebsite = input?.noWebsite === true;
128
+ let website = null;
129
+ if (!noWebsite) {
130
+ const parsed = normalizeGuestWebsite(input?.website);
131
+ if (parsed === null) website = null;
132
+ else if (parsed.ok) website = parsed.url;
133
+ else if (enforced) errors.website = parsed.reason;
134
+ else dropped.website = parsed.reason;
135
+ }
136
+ if (errors.company || errors.website) return { ok: false, errors };
137
+ return { ok: true, value: { company, website, noWebsite, dropped } };
138
+ }
139
+ var BOOKING_BUSINESS_ERROR_TEXT = {
140
+ company_required: "Please add your company name, or your own name if you work for yourself.",
141
+ company_too_long: `That name's a little long. Please keep it to ${BOOKING_COMPANY_MAX} characters or fewer.`,
142
+ website_invalid: "That doesn't look like a web address. Try something like yourcompany.com.",
143
+ website_too_long: "That address is too long. The main address is enough, like yourcompany.com."
144
+ };
145
+ function describeBookingBusinessErrors(errors) {
146
+ const text = {};
147
+ if (errors.company) text.company = errors.company === "required" ? BOOKING_BUSINESS_ERROR_TEXT.company_required : BOOKING_BUSINESS_ERROR_TEXT.company_too_long;
148
+ if (errors.website) text.website = errors.website === "invalid" ? BOOKING_BUSINESS_ERROR_TEXT.website_invalid : BOOKING_BUSINESS_ERROR_TEXT.website_too_long;
149
+ return text;
150
+ }
151
+
152
+ // src/contracts/booking-intake.ts
153
+ var BOOKING_INTAKE_CONTRACT_VERSION = 1;
154
+ var BOOKING_INTAKE_JSON_SCHEMA = {
155
+ $schema: "http://json-schema.org/draft-07/schema#",
156
+ $id: "https://sonor.io/schemas/booking-intake.v1.json",
157
+ title: "BookingGuestBusinessAnswers",
158
+ description: "What a guest tells a booking about their business: a company name (their own name if they work for themselves), a website address if they have one, and a flag for 'we don't have a website yet', which wins over any website sent with it.",
159
+ type: "object",
160
+ properties: {
161
+ company: {
162
+ type: ["string", "null"],
163
+ maxLength: BOOKING_COMPANY_MAX,
164
+ description: "Company name. Required when the booking type's business step is required. The length is measured after cleaning: extra whitespace and control characters don't count."
165
+ },
166
+ website: {
167
+ type: ["string", "null"],
168
+ maxLength: BOOKING_WEBSITE_INPUT_MAX,
169
+ description: "A public http or https address, or a bare domain like example.com. Credentials, ports, IP addresses and the local names localhost, .local and .internal are refused. The query and fragment are dropped and the path is kept. The length is measured after trimming."
170
+ },
171
+ noWebsite: {
172
+ type: ["boolean", "null"],
173
+ description: "True when the guest has no website yet. A website sent with it is ignored."
174
+ }
175
+ }
176
+ };
177
+ function bookingBusinessDetails(row, contact) {
178
+ const fromRow = {
179
+ company: normalizeBookingCompany(row?.guest_company),
180
+ website: readWebsite(row?.guest_website),
181
+ noWebsite: row?.guest_no_website === true
182
+ };
183
+ const fromContact = {
184
+ company: normalizeBookingCompany(contact?.company),
185
+ website: readWebsite(contact?.website)
186
+ };
187
+ const company = fromRow.company ?? fromContact.company;
188
+ const website = fromRow.website ?? (fromRow.noWebsite ? null : fromContact.website);
189
+ const noWebsite = fromRow.noWebsite && website === null;
190
+ const guestAnswered = fromRow.company !== null || fromRow.website !== null || fromRow.noWebsite;
191
+ const contactSupplied = fromRow.company === null && fromContact.company !== null || fromRow.website === null && website !== null;
192
+ return {
193
+ company,
194
+ website: website?.url ?? null,
195
+ websiteHost: website?.host ?? null,
196
+ noWebsite,
197
+ from: guestAnswered ? "booking" : contactSupplied ? "contact" : null
198
+ };
199
+ }
200
+ function readWebsite(value) {
201
+ const parsed = normalizeGuestWebsite(value);
202
+ return parsed && parsed.ok ? { url: parsed.url, host: parsed.host } : null;
203
+ }
204
+
205
+ exports.BOOKING_BUSINESS_ERROR_TEXT = BOOKING_BUSINESS_ERROR_TEXT;
206
+ exports.BOOKING_BUSINESS_EXEMPT_SOURCES = BOOKING_BUSINESS_EXEMPT_SOURCES;
207
+ exports.BOOKING_BUSINESS_STEPS = BOOKING_BUSINESS_STEPS;
208
+ exports.BOOKING_COMPANY_MAX = BOOKING_COMPANY_MAX;
209
+ exports.BOOKING_GUEST_BUSINESS_FIELDS = BOOKING_GUEST_BUSINESS_FIELDS;
210
+ exports.BOOKING_INTAKE_CONTRACT_VERSION = BOOKING_INTAKE_CONTRACT_VERSION;
211
+ exports.BOOKING_INTAKE_JSON_SCHEMA = BOOKING_INTAKE_JSON_SCHEMA;
212
+ exports.BOOKING_WEBSITE_INPUT_MAX = BOOKING_WEBSITE_INPUT_MAX;
213
+ exports.BOOKING_WEBSITE_URL_MAX = BOOKING_WEBSITE_URL_MAX;
214
+ exports.bookingAsksBusiness = bookingAsksBusiness;
215
+ exports.bookingBusinessDetails = bookingBusinessDetails;
216
+ exports.bookingBusinessExempt = bookingBusinessExempt;
217
+ exports.checkBookingBusinessAnswers = checkBookingBusinessAnswers;
218
+ exports.describeBookingBusinessErrors = describeBookingBusinessErrors;
219
+ exports.normalizeBookingCompany = normalizeBookingCompany;
220
+ exports.normalizeGuestWebsite = normalizeGuestWebsite;
221
+ exports.parseBookingBusinessStep = parseBookingBusinessStep;