@peektravel/app-utilities 0.1.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/gateway-endpoints.ts","../src/internal/account-users/account-user-converter.ts","../src/internal/account-users/account-user-queries.ts","../src/internal/account-users/account-user-service.ts","../src/internal/availability/availability-queries.ts","../src/internal/availability/availability-service.ts","../src/models/product.ts","../src/internal/bookings/booking-converter.ts","../src/internal/bookings/booking-guest-converter.ts","../src/internal/bookings/payments-on-file-converter.ts","../src/internal/bookings/addon-queries.ts","../src/internal/bookings/addon-converter.ts","../src/internal/bookings/booking-queries.ts","../src/internal/bookings/booking-service.ts","../src/internal/daily-notes/daily-note-converter.ts","../src/internal/daily-notes/daily-note-queries.ts","../src/internal/daily-notes/daily-note-service.ts","../src/errors.ts","../src/internal/graphql-client.ts","../src/internal/memberships/membership-converter.ts","../src/internal/memberships/membership-queries.ts","../src/internal/memberships/membership-service.ts","../src/internal/resellers/channel-converter.ts","../src/internal/resellers/channel-queries.ts","../src/internal/resellers/reseller-service.ts","../src/internal/resource-pools/resource-pool-converter.ts","../src/internal/resource-pools/resource-pool-queries.ts","../src/internal/resource-pools/resource-pool-service.ts","../src/internal/timeslots/timeslot-converter.ts","../src/internal/timeslots/guide-matcher.ts","../src/internal/timeslots/resource-allocation-queries.ts","../src/internal/timeslots/timeslot-queries.ts","../src/internal/timeslots/timeslot-service.ts","../src/internal/products/product-converter.ts","../src/internal/products/product-queries.ts","../src/internal/products/product-service.ts","../src/internal/promo-codes/promo-code-queries.ts","../src/internal/promo-codes/promo-code-service.ts","../src/internal/token-manager.ts","../src/logger.ts","../src/peek-access-service.ts"],"names":["DEFAULT_PAGE_SIZE","CREATE_QUOTE_V2_MUTATION","randomUUID"],"mappings":";;;;AAKO,IAAM,cAAA,GAAiB,OAAA;;;ACG9B,IAAM,aAAA,GAAgB,QAAA;AAMf,SAAS,oBACd,IAAA,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AAK,MAAM,CAAA;AAAA,IAC1D;AACA,IAAA,OAAO,IAAA,CAAK,gBAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,sBAAA,GAA8C;AAC5C,IAAA,IAAI,CAAC,KAAK,mBAAA,EAAqB;AAC7B,MAAA,IAAA,CAAK,mBAAA,GAAsB,IAAI,mBAAA,CAAoB,IAAA,CAAK,MAAM,CAAA;AAAA,IAChE;AACA,IAAA,OAAO,IAAA,CAAK,mBAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,oBAAA,GAA0C;AACxC,IAAA,IAAI,CAAC,KAAK,iBAAA,EAAmB;AAC3B,MAAA,IAAA,CAAK,iBAAA,GAAoB,IAAI,iBAAA,CAAkB,IAAA,CAAK,MAAM,CAAA;AAAA,IAC5D;AACA,IAAA,OAAO,IAAA,CAAK,iBAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,iBAAA,GAAoC;AAClC,IAAA,IAAI,CAAC,KAAK,cAAA,EAAgB;AACxB,MAAA,IAAA,CAAK,cAAA,GAAiB,IAAI,cAAA,CAAe,IAAA,CAAK,MAAA,EAAQ;AAAA,QACpD,cAAA,EAAgB,KAAK,iBAAA;AAAkB,OACxC,CAAA;AAAA,IACH;AACA,IAAA,OAAO,IAAA,CAAK,cAAA;AAAA,EACd;AACF;AAEA,SAAS,eAAA,CAAgB,OAAe,IAAA,EAAoB;AAC1D,EAAA,IAAI,CAAC,KAAA,EAAO;AACV,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,oBAAA,EAAuB,IAAI,CAAA,aAAA,CAAe,CAAA;AAAA,EAC5D;AACF","file":"index.js","sourcesContent":["/**\n * Path segments for the backoffice GraphQL gateway. Every current operation\n * routes through the `sales` endpoint; this constant is shared across resources\n * so the value lives in exactly one place.\n */\nexport const SALES_ENDPOINT = \"sales\";\n","/**\n * Pure functions mapping raw account-user nodes into the clean\n * {@link AccountUser} model. Inactive users are dropped (mapped to `null`).\n */\nimport type { AccountUser } from \"../../models/account-user.js\";\nimport type { AccountUserNode } from \"./account-user-queries.js\";\n\n/** Only users in this status are surfaced. */\nconst ACTIVE_STATUS = \"ACTIVE\";\n\n/**\n * Converts a single node into an {@link AccountUser}, or `null` when the node is\n * missing or the user is not active.\n */\nexport function fromAccountUserNode(\n node: AccountUserNode | null | undefined,\n): AccountUser | null {\n if (!node || node.status !== ACTIVE_STATUS) {\n return null;\n }\n\n return {\n id: node.id,\n name: node.name,\n email: node.email,\n phone: node.phone,\n assignedActivities: (node.assignedActivities ?? []).map((activity) => ({\n id: activity.id,\n name: activity.name,\n })),\n };\n}\n\n/** Converts a list of nodes into active {@link AccountUser}s, dropping the rest. */\nexport function fromAccountUserNodes(\n nodes: Array<AccountUserNode | null | undefined>,\n): AccountUser[] {\n const users: AccountUser[] = [];\n for (const node of nodes) {\n const user = fromAccountUserNode(node);\n if (user) {\n users.push(user);\n }\n }\n return users;\n}\n","/**\n * Raw Peek GraphQL queries and response shapes for account users. Internal —\n * not re-exported from the public entry point.\n */\n\n/** Fetches a cursor-paginated page of account users. */\nexport const USER_QUERY = `\n query Sales($first: Int, $after: String) {\n accountUsers(first: $first, after: $after) {\n pageInfo {\n endCursor\n hasNextPage\n }\n edges {\n cursor\n node {\n id\n name\n email\n phone\n status\n assignedActivities {\n id\n name\n }\n }\n }\n }\n }\n`;\n\n/** Fetches account users matching a filter (e.g. by id). */\nexport const USER_BY_FILTER_QUERY = `\n query Sales($first: Int, $filter: AccountUsersFilter) {\n accountUsers(first: $first, filter: $filter) {\n edges {\n cursor\n node {\n id\n name\n email\n phone\n status\n assignedActivities {\n id\n name\n }\n }\n }\n }\n }\n`;\n\n/** A single account-user node as returned by the account-user queries. */\nexport interface AccountUserNode {\n id: string;\n name: string;\n email: string;\n phone: string;\n status: string;\n assignedActivities: Array<{ id: string; name: string }>;\n}\n\n/** The `data` payload of the account-user queries. */\nexport interface AccountUsersResponse {\n accountUsers: {\n pageInfo?: { endCursor: string | null; hasNextPage: boolean };\n edges: Array<{ cursor: string; node: AccountUserNode }>;\n };\n}\n","/**\n * Account-user operations against the Peek gateway.\n *\n * Obtain an instance via {@link PeekAccessService.getAccountUserService}. Only\n * active users are returned.\n */\nimport { SALES_ENDPOINT } from \"../gateway-endpoints.js\";\nimport type { GraphQLBody, GraphQLClient } from \"../graphql-client.js\";\nimport type { AccountUser } from \"../../models/account-user.js\";\nimport {\n fromAccountUserNode,\n fromAccountUserNodes,\n} from \"./account-user-converter.js\";\nimport {\n USER_BY_FILTER_QUERY,\n USER_QUERY,\n type AccountUsersResponse,\n} from \"./account-user-queries.js\";\n\n/** Default page size for cursor-paginated account users. */\nconst DEFAULT_PAGE_SIZE = 50;\n\n/** Tuning options for an {@link AccountUserService}. */\nexport interface AccountUserServiceOptions {\n /** Page size for cursor pagination. Default: 50. */\n pageSize?: number;\n}\n\nexport class AccountUserService {\n private readonly pageSize: number;\n\n constructor(\n private readonly client: GraphQLClient,\n options: AccountUserServiceOptions = {},\n ) {\n this.pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;\n }\n\n /**\n * Returns all active account users, walking the cursor pagination to the end.\n * Inactive users are omitted.\n */\n async getAll(): Promise<AccountUser[]> {\n const users: AccountUser[] = [];\n let after: string | null = null;\n\n for (;;) {\n const body: GraphQLBody<AccountUsersResponse> =\n await this.client.request<AccountUsersResponse>(SALES_ENDPOINT, USER_QUERY, {\n first: this.pageSize,\n after,\n });\n\n const connection = body.data?.accountUsers;\n const edges = connection?.edges ?? [];\n if (edges.length === 0) {\n break;\n }\n\n users.push(...fromAccountUserNodes(edges.map((edge) => edge.node)));\n\n const pageInfo = connection?.pageInfo;\n if (pageInfo?.hasNextPage && pageInfo.endCursor) {\n after = pageInfo.endCursor;\n } else {\n break;\n }\n }\n\n return users;\n }\n\n /**\n * Returns a single active account user by id, or `null` when no active user\n * matches.\n */\n async getById(userId: string): Promise<AccountUser | null> {\n const body: GraphQLBody<AccountUsersResponse> =\n await this.client.request<AccountUsersResponse>(\n SALES_ENDPOINT,\n USER_BY_FILTER_QUERY,\n { first: this.pageSize, filter: { ids: [userId] } },\n );\n\n const firstEdge = (body.data?.accountUsers?.edges ?? [])[0];\n if (!firstEdge) {\n return null;\n }\n return fromAccountUserNode(firstEdge.node);\n }\n}\n","/**\n * Raw Peek GraphQL query and response shape for availability times. Internal.\n * The node matches the public {@link AvailabilityTime} model one-to-one.\n */\nimport type { AvailabilityTime } from \"../../models/availability-time.js\";\n\n/** Fetches availability times for an activity/date and resource-option quantities. */\nexport const AVAILABILITY_TIMES_QUERY = `\n query Sales($activityId: ID!, $resourceOptionQuantities: [ResourceOptionQuantityData!]!, $date: Date!) {\n availabilityTimes(activityId: $activityId, resourceOptionQuantities: $resourceOptionQuantities, date: $date) {\n id\n time\n from\n end\n duration {\n name\n length {\n amount\n unit\n }\n }\n status\n availability {\n qty\n taken\n resourceOptionId\n }\n }\n }\n`;\n\n/** The `data` payload of {@link AVAILABILITY_TIMES_QUERY}. */\nexport interface AvailabilityTimesResponse {\n availabilityTimes: AvailabilityTime[];\n}\n","/**\n * Availability-times operations against the Peek gateway.\n *\n * Obtain an instance via {@link PeekAccessService.getAvailabilityService}.\n */\nimport { SALES_ENDPOINT } from \"../gateway-endpoints.js\";\nimport type { GraphQLBody, GraphQLClient } from \"../graphql-client.js\";\nimport type {\n AvailabilityTime,\n AvailabilityTimesQuery,\n} from \"../../models/availability-time.js\";\nimport {\n AVAILABILITY_TIMES_QUERY,\n type AvailabilityTimesResponse,\n} from \"./availability-queries.js\";\n\nexport class AvailabilityService {\n constructor(private readonly client: GraphQLClient) {}\n\n /** Returns the availability times for an activity/date and requested quantities. */\n async getAvailabilityTimes(\n query: AvailabilityTimesQuery,\n ): Promise<AvailabilityTime[]> {\n const body: GraphQLBody<AvailabilityTimesResponse> =\n await this.client.request<AvailabilityTimesResponse>(\n SALES_ENDPOINT,\n AVAILABILITY_TIMES_QUERY,\n {\n activityId: query.activityId,\n resourceOptionQuantities: query.resourceOptionQuantities,\n date: query.date,\n },\n );\n return body.data?.availabilityTimes ?? [];\n }\n}\n","/**\n * The clean, transport-agnostic data model for a Peek Pro product.\n *\n * This is the shape consumers of the package work with. It is intentionally\n * decoupled from the underlying Peek GraphQL schema — the raw GraphQL types and\n * the conversion logic live inside the package and are never exposed here.\n */\n\n/**\n * A bookable product in a Peek Pro account.\n *\n * `PeekAccessService.getAllProducts()` returns a single flat list that combines\n * two distinct Peek concepts into one uniform shape:\n *\n * - **Activities** — the primary bookable experiences (tours, rentals, classes,\n * etc.). Their {@link Product.type} is whatever Peek reports for the activity.\n * - **Add-ons** — optional item options offered alongside activities. They are\n * grouped under their parent item and always carry the\n * {@link ADD_ON_PRODUCT_TYPE} (`\"ADD-ON\"`) type, so callers can tell the two\n * apart with a single field check.\n */\nexport interface Product {\n /**\n * Stable unique identifier for the product.\n *\n * - Activities: the primary GraphQL `id` (falls back to the `legacyId`).\n * - Add-ons: the id of the parent item the options belong to.\n */\n productId: string;\n\n /** Human-readable display name. */\n name: string;\n\n /**\n * Product type.\n *\n * For activities this is the type reported by Peek; for add-ons it is always\n * {@link ADD_ON_PRODUCT_TYPE}.\n */\n type: string;\n\n /**\n * Display color as a hex string (e.g. `\"#1A2B3C\"`).\n *\n * Add-ons default to white (`\"#FFFFFF\"`). Empty string when no color is set.\n */\n color: string;\n\n /**\n * The bookable sub-options of this product.\n *\n * - Activities: the activity's resource options.\n * - Add-ons: each individual item option grouped under the parent item.\n */\n tickets: ProductTicket[];\n}\n\n/** A single bookable sub-option (resource option or add-on item option). */\nexport interface ProductTicket {\n /** Unique identifier of the ticket / option. */\n id: string;\n /** Human-readable name of the ticket / option. */\n name: string;\n}\n\n/**\n * The {@link Product.type} value assigned to add-on products.\n *\n * Exposed so callers can filter add-ons out of (or in to) the combined list\n * returned by {@link Product} queries without hard-coding the string.\n */\nexport const ADD_ON_PRODUCT_TYPE = \"ADD-ON\";\n","/**\n * Pure functions mapping a raw booking node into the clean {@link Booking}\n * model. Ported from the connector's BookingConverter.\n */\nimport type {\n Booking,\n CustomQuestionAnswer,\n Guest,\n GuestMetadata,\n Price,\n ResourcePoolAssignment,\n Ticket,\n} from \"../../models/booking.js\";\nimport type { BookingGuestNode, BookingNode } from \"./booking-queries.js\";\n\nconst UNKNOWN = \"unknown\";\n\nconst SOURCE_SOURCE_MAP: Record<string, string> = {\n APP_REGISTRY: \"app\",\n BOOKING_IMPORTER_FUTURE: \"importer\",\n BOOKING_IMPORTER_HISTORIC: \"importer\",\n EXPEDIA: \"expedia\",\n GROUPON: \"groupon\",\n GYG: \"getyourguide\",\n HOOK: \"internal\",\n INTERNAL_TOOLS: \"internal\",\n IOS_PP: \"ios\",\n OCTO: \"octo\",\n PDC: \"peekcom\",\n PEEK_PLUS: \"peekcom\",\n PP: \"backend\",\n RWG: \"rwg\",\n SELF_SERVE: \"internal\",\n SYSTEM: \"internal\",\n VIATOR: \"viator\",\n WIDGET: \"website\",\n YELP: \"yelp\",\n};\n\nconst SOURCE_DESC_MAP: Record<string, string> = {\n APP_REGISTRY: \"App Store App\",\n BOOKING_IMPORTER_FUTURE: \"Booking Importer\",\n BOOKING_IMPORTER_HISTORIC: \"Booking Importer\",\n EXPEDIA: \"Expedia\",\n GROUPON: \"Groupon\",\n GYG: \"GetYourGuide\",\n HOOK: \"Internal\",\n INTERNAL_TOOLS: \"Internal\",\n IOS_PP: \"Peek Pro: iOS App\",\n OCTO: \"OCTO\",\n PDC: \"Peek.com\",\n PEEK_PLUS: \"Peek.com\",\n PP: \"Peek Pro: Backend\",\n RWG: \"Reserve with Google\",\n SELF_SERVE: \"Internal\",\n SYSTEM: \"Internal\",\n VIATOR: \"Viator\",\n WIDGET: \"Website Booking Flow\",\n YELP: \"Yelp\",\n};\n\n/** Converts a raw booking node into a {@link Booking}. */\nexport function fromBookingNode(\n node: BookingNode | null | undefined,\n includeGuests = false,\n includePriceBreakdown = false,\n): Booking {\n const data = node ?? {};\n const ticketQuantities = data.ticketQuantities ?? [];\n const app = data.order?.initialQuote?.source?.actor?.app ?? null;\n\n const customQuestionAnswers: CustomQuestionAnswer[] = (data.questionAnswers ?? []).map(\n (answer) => {\n const base: CustomQuestionAnswer = {\n question: answer.questionText,\n answer: answer.answer,\n };\n const location = answer.questionLocationSnapshot;\n if (location && location.latitude && location.longitude) {\n base.latitude = location.latitude;\n base.longitude = location.longitude;\n }\n return base;\n },\n );\n\n const customGuestQuestionAnswers: CustomQuestionAnswer[] = Array.isArray(data.tickets)\n ? data.tickets.flatMap((ticket) =>\n Array.isArray(ticket?.questionAnswers)\n ? ticket.questionAnswers\n .filter((qa) => qa && qa.answer !== undefined && qa.questionText !== undefined)\n .map((qa) => ({ question: qa.questionText, answer: qa.answer }))\n : [],\n )\n : [];\n\n return {\n bookingId: data.id || \"\",\n displayId: data.displayId || \"\",\n\n source: sourceFromApp(app),\n sourceApp: app || UNKNOWN,\n sourceDescription: sourceDescriptionFromApp(app),\n\n customerName: data.primaryGuest?.name || \"\",\n customerEmail: data.primaryGuest?.email || null,\n customerPhone: data.primaryGuest?.phone || null,\n\n productId: data.activitySnapshot?.id || UNKNOWN,\n productName: data.activitySnapshot?.name || UNKNOWN,\n isRentalProduct: data.activitySnapshot?.type === \"RENTAL\",\n\n timeslotId: data.timeSnapshot?.legacyId || null,\n totalTickets: ticketQuantity(ticketQuantities),\n ticketDescription: formatTickets(ticketQuantities),\n tickets: ticketsToTicketArray(ticketQuantities),\n\n isCanceled: data.reservationStatus === \"CANCELED\",\n isNoShow: data.fulfillmentStatusOverride?.status === \"NO_SHOW\",\n isCheckedIn: data.checkinStatus !== \"NONE\",\n isReturned: data.returnStatus !== \"NONE\",\n\n purchasedAt: data.purchasedAt || null,\n purchasedAtUtc: data.purchasedAtUtc || null,\n startsAt: data.startsAt || null,\n startsAtUtc: data.startsAtUtc || null,\n endsAt: data.endsAt || null,\n endsAtUtc: data.endsAtUtc || null,\n durationMin: durationInMin(data.startsAt || null, data.endsAt || null),\n availabilityTimeId: data.availabilityTimeId || null,\n\n portalUrl: data.bookingPortalUrl || null,\n notes: data.operatorNotes || \"\",\n\n valueDisplay: data.value?.total?.formatted || \"\",\n valueAmount: data.value?.total?.amount || \"\",\n\n outstandingBalanceAmount: data.balance?.total?.amount || \"\",\n outstandingBalanceDisplay: data.balance?.total?.formatted || \"\",\n promoCodes: data.order?.promoCodes?.map((promo) => promo.code) ?? [],\n tips: (data.tips ?? []).map((tip) => ({\n display: tip.price?.formatted || \"\",\n amount: tip.price?.amount || \"\",\n })),\n\n customQuestionAnswers,\n customGuestQuestionAnswers,\n\n resources: (data.resourcePoolAssignments ?? []).map((resource) => ({\n quantity: resource.quantity || 0,\n name: resource.resourcePool?.name || \"\",\n shortName: resource.resourcePool?.shortName || \"\",\n })),\n\n resourcePoolAssignments: mapResourcePoolAssignments(data.resourcePoolAssignments),\n\n resellerId: data.order?.channelSnapshot?.id || null,\n resellerName: resellerNameFromChannelSnapshot(data.order?.channelSnapshot),\n\n orderId: data.order?.id || \"\",\n\n convenienceFee: includePriceBreakdown ? mapPrice(data.value?.convenienceFee) : undefined,\n deposit: includePriceBreakdown ? mapPrice(data.value?.deposit) : undefined,\n discount: includePriceBreakdown ? mapPrice(data.value?.discount) : undefined,\n discountedPrice: includePriceBreakdown ? mapPrice(data.value?.discountedPrice) : undefined,\n fees: includePriceBreakdown ? mapPrice(data.value?.fees) : undefined,\n flatPartnerFee: includePriceBreakdown ? mapPrice(data.value?.flatPartnerFee) : undefined,\n price: includePriceBreakdown ? mapPrice(data.value?.price) : undefined,\n retailPrice: includePriceBreakdown ? mapPrice(data.value?.retailPrice) : undefined,\n taxes: includePriceBreakdown ? mapPrice(data.value?.taxes) : undefined,\n tipsBreakdown: includePriceBreakdown ? mapPrice(data.value?.tips) : undefined,\n\n guests: includeGuests ? convertGuests(data) : undefined,\n };\n}\n\n/** Merges a booking node's `bookingGuests` + `primaryGuest` into a guest list. */\nexport function convertGuests(data: BookingNode): Guest[] {\n const bookingGuestsNodes = Array.isArray(data.bookingGuests) ? data.bookingGuests : [];\n const primaryGuestNode = data.primaryGuest;\n const primaryId = primaryGuestNode?.id;\n\n const guests: Guest[] = [];\n for (const guestNode of bookingGuestsNodes) {\n guests.push(mapGuestNode(guestNode, primaryId ? guestNode.id === primaryId : false));\n }\n\n const hasPrimaryInGuests = primaryId\n ? bookingGuestsNodes.some((guest) => guest.id === primaryId)\n : false;\n if (!hasPrimaryInGuests && primaryGuestNode?.id) {\n guests.push(mapGuestNode(primaryGuestNode, true));\n }\n\n return guests;\n}\n\n/** Maps a single raw guest node into a {@link Guest}. */\nexport function mapGuestNode(guestNode: BookingGuestNode, isPrimary: boolean): Guest {\n const fieldResponses = Array.isArray(guestNode.fieldResponses) ? guestNode.fieldResponses : [];\n const metadata: GuestMetadata[] = fieldResponses.map((response) => ({\n id: response.id,\n name: response.fieldLocation?.field?.name ?? \"\",\n value: response.text ?? \"\",\n }));\n\n return {\n id: guestNode.id,\n name: guestNode.name ?? null,\n country: guestNode.country ?? null,\n dateOfBirth: guestNode.dateOfBirth ? new Date(guestNode.dateOfBirth) : null,\n phone: guestNode.phone ?? null,\n email: guestNode.email ?? null,\n isGdpr: Boolean(guestNode.isGdpr),\n isParticipant: Boolean(guestNode.isParticipant),\n isPrimary,\n optinSms: Boolean(guestNode.optinSms),\n optinMarketing: Boolean(guestNode.optinMarketing),\n postalCode: guestNode.postalCode ?? null,\n metadata,\n };\n}\n\nfunction sourceFromApp(app: string | null): string {\n if (!app) return UNKNOWN;\n return SOURCE_SOURCE_MAP[app] ?? UNKNOWN;\n}\n\nfunction sourceDescriptionFromApp(app: string | null): string {\n if (!app) return UNKNOWN;\n return SOURCE_DESC_MAP[app] ?? UNKNOWN;\n}\n\nfunction resellerNameFromChannelSnapshot(\n channelSnapshot: { name?: string; agent?: { name?: string } | null } | null | undefined,\n): string | null {\n if (!channelSnapshot) return null;\n let out = channelSnapshot.name ?? \"\";\n if (channelSnapshot.agent?.name) {\n out += \" - \" + channelSnapshot.agent.name;\n }\n return out;\n}\n\nfunction ticketsToTicketArray(\n ticketQuantities: BookingNode[\"ticketQuantities\"],\n): Ticket[] {\n if (!ticketQuantities || ticketQuantities.length === 0) return [];\n return ticketQuantities.map((ticket) => ({\n name: ticket.resourceOptionSnapshot?.name || \"Unknown\",\n quantity: ticket.quantity || 0,\n ticketId: ticket.resourceOptionSnapshot?.id || \"unknown\",\n }));\n}\n\nfunction durationInMin(startsAt: string | null, endsAt: string | null): number {\n if (!startsAt || !endsAt) return 0;\n const duration = new Date(endsAt).getTime() - new Date(startsAt).getTime();\n return Math.floor(duration / 1000 / 60);\n}\n\nfunction ticketQuantity(ticketQuantities: BookingNode[\"ticketQuantities\"]): number {\n if (!ticketQuantities || ticketQuantities.length === 0) return 0;\n return ticketQuantities.reduce((acc, ticket) => acc + (ticket.quantity || 0), 0);\n}\n\nfunction formatTickets(ticketQuantities: BookingNode[\"ticketQuantities\"]): string {\n if (!ticketQuantities || ticketQuantities.length === 0) return \"\";\n return ticketQuantities\n .map((ticket) => `${ticket.quantity || 0}x ${ticket.resourceOptionSnapshot?.name || \"Unknown\"}`)\n .join(\", \");\n}\n\nfunction mapResourcePoolAssignments(\n poolAssignments: BookingNode[\"resourcePoolAssignments\"],\n): ResourcePoolAssignment[] {\n if (!poolAssignments || poolAssignments.length === 0) return [];\n return poolAssignments.flatMap((pool) =>\n (pool.resourceAssignments ?? []).map((assignment) => ({\n id: assignment.resource?.id || \"\",\n name: assignment.resource?.name || \"\",\n })),\n );\n}\n\nfunction mapPrice(\n priceData: { amount?: string; formatted?: string } | undefined,\n): Price | undefined {\n if (!priceData || (!priceData.amount && !priceData.formatted)) {\n return undefined;\n }\n return {\n amount: priceData.amount || \"0\",\n display: priceData.formatted || \"\",\n };\n}\n","/**\n * Resolves the dedicated guests query into a merged guest list (booking guests\n * plus the primary guest when not already present).\n */\nimport type { Guest } from \"../../models/booking.js\";\nimport { mapGuestNode } from \"./booking-converter.js\";\nimport type { BookingGuestsResponse } from \"./booking-queries.js\";\n\n/** Maps a booking-guests response into a {@link Guest} list. */\nexport function fromBookingGuestsResponse(\n response: BookingGuestsResponse | undefined,\n): Guest[] {\n const firstEdge = (response?.sales?.edges ?? [])[0];\n if (!firstEdge) {\n return [];\n }\n\n const bookingNode = firstEdge.node;\n const primaryGuestNode = bookingNode.primaryGuest;\n const bookingGuestsNodes = Array.isArray(bookingNode.bookingGuests)\n ? bookingNode.bookingGuests\n : [];\n const primaryId = primaryGuestNode?.id;\n\n const guests: Guest[] = [];\n for (const guestNode of bookingGuestsNodes) {\n guests.push(mapGuestNode(guestNode, primaryId ? guestNode.id === primaryId : false));\n }\n\n const hasPrimaryInGuests = primaryId\n ? bookingGuestsNodes.some((guest) => guest.id === primaryId)\n : false;\n if (!hasPrimaryInGuests && primaryGuestNode) {\n guests.push(mapGuestNode(primaryGuestNode, true));\n }\n\n return guests;\n}\n","/**\n * Aggregates a booking's raw order payments + payment sources into the clean\n * {@link BookingPaymentsOnFile} model, grouping payments under their source.\n */\nimport type {\n BookingPaymentsOnFile,\n Payment,\n PaymentSource,\n} from \"../../models/booking-payment.js\";\nimport type { BookingPaymentsOnFileResponse } from \"./booking-queries.js\";\n\n/**\n * Maps a payments-on-file response into the aggregated result, or null when the\n * booking is not found.\n */\nexport function fromPaymentsOnFileResponse(\n response: BookingPaymentsOnFileResponse | undefined,\n bookingId: string,\n): BookingPaymentsOnFile | null {\n const firstEdge = (response?.sales?.edges ?? [])[0];\n if (!firstEdge) {\n return null;\n }\n\n const order = firstEdge.node.order;\n const orderId = order?.id ?? \"\";\n const rawPaymentSources = order?.paymentSources ?? [];\n const rawPayments = order?.payments ?? [];\n\n const paymentsBySourceId = new Map<string, Payment[]>();\n for (const payment of rawPayments) {\n const sourceId = payment.paymentSource?.id;\n if (!sourceId) continue;\n const mapped: Payment = {\n id: payment.id,\n paidAt: dateOnly(payment.appliedAt),\n currentAmount: payment.currentAmount,\n refundableAmount: payment.refundableAmount,\n };\n const existing = paymentsBySourceId.get(sourceId);\n if (existing) {\n existing.push(mapped);\n } else {\n paymentsBySourceId.set(sourceId, [mapped]);\n }\n }\n\n const paymentsOnFile: PaymentSource[] = rawPaymentSources.map((source) => {\n const payments = paymentsBySourceId.get(source.id);\n return {\n description: source.description,\n id: source.id,\n type: source.type,\n ...(payments ? { payments } : {}),\n };\n });\n\n return { bookingId, orderId, paymentsOnFile };\n}\n\nfunction dateOnly(iso: string): string {\n /* v8 ignore next -- split always yields at least one element */\n return iso.split(\"T\")[0] ?? iso;\n}\n","/**\n * Raw Peek GraphQL query, variables, and response shapes for listing the\n * add-ons (items + item options) attached to a single booking. Internal.\n *\n * The `SALES_ADDONS_QUERY` runs the `sales` query filtered by a booking's\n * display id (`filter.searchString`) and returns every item on the booking\n * together with its item options, refids, and reservation statuses — the\n * detail needed both to surface add-ons and to build add/cancel mutations.\n */\n\n/** Reservation status for a live (confirmed) item or option. */\nexport const RESERVATION_STATUS_CONFIRMED = \"CONFIRMED\";\n/** Reservation status marking an item or option as canceled. */\nexport const ADDON_OPTION_STATUS_CANCELED = \"CANCELED\";\n\n/** Page size for the sales add-ons query (a single booking, so one page). */\nconst SALES_ADDONS_PAGE_SIZE = 100;\n\n/**\n * GraphQL query fetching the items and item options for a single booking\n * matched by `filter.searchString` (the booking display id).\n */\nexport const SALES_ADDONS_QUERY = `\n query Sales($after: String, $first: Int, $filter: SalesFilter!, $orderBy: SalesOrdering) {\n sales(after: $after, first: $first, filter: $filter, orderBy: $orderBy) {\n pageInfo { endCursor hasNextPage }\n edges {\n node {\n order { id displayId }\n ... on Booking {\n displayId\n id\n refid\n reservationStatus\n items {\n id\n refid\n value { total { amount currency formatted } }\n reservationStatus\n options {\n refid\n reservationStatus\n price { amount currency formatted }\n itemOptionSnapshot { id name }\n itemSnapshot { id name }\n }\n }\n }\n }\n }\n }\n }\n`;\n\n/** Variables for {@link SALES_ADDONS_QUERY}. */\nexport interface SalesAddonsVariables {\n first: number;\n after: string | null;\n orderBy: { direction: string; field: string };\n filter: { searchString: string };\n}\n\n/** Builds the variables for the sales add-ons query from a booking display id. */\nexport function buildSalesAddonsVariables(searchString: string): SalesAddonsVariables {\n return {\n first: SALES_ADDONS_PAGE_SIZE,\n after: null,\n orderBy: { direction: \"DESC\", field: \"STARTS_AT\" },\n filter: { searchString },\n };\n}\n\n/** Raw money shape returned by the `sales` add-ons query. */\nexport interface AddonGqlPrice {\n amount: string;\n currency: string;\n formatted: string;\n}\n\nexport interface SalesAddonItemOptionNode {\n refid: string;\n reservationStatus: string;\n price: AddonGqlPrice | null;\n itemOptionSnapshot: { id: string; name: string } | null;\n itemSnapshot: { id: string; name: string } | null;\n}\n\nexport interface SalesAddonItemNode {\n id: string;\n refid: string;\n value: { total: AddonGqlPrice | null } | null;\n reservationStatus: string;\n options: SalesAddonItemOptionNode[] | null;\n}\n\nexport interface SalesAddonBookingNode {\n id: string;\n displayId: string;\n refid: string;\n reservationStatus: string;\n order: { id: string; displayId: string } | null;\n items: SalesAddonItemNode[] | null;\n}\n\nexport interface SalesAddonsResponse {\n sales: {\n pageInfo: { endCursor: string | null; hasNextPage: boolean };\n edges: Array<{ node: SalesAddonBookingNode }>;\n };\n}\n","/**\n * Pure mappers between the raw `sales` add-ons response and the add-on models.\n *\n * `parseSaleNode` produces the internal, detail-rich {@link AddonItem} model\n * (refids + reservation statuses) that the service uses to build add/cancel\n * mutations. `toBookingAddon` collapses one internal item into the clean,\n * public {@link BookingAddon}. The internal model is intentionally not exported\n * from the package's public entry point.\n */\nimport type { BookingAddon, BookingAddonOption } from \"../../models/booking-addon.js\";\nimport {\n ADDON_OPTION_STATUS_CANCELED,\n type AddonGqlPrice,\n type SalesAddonBookingNode,\n} from \"./addon-queries.js\";\n\nconst ERROR_INCONSISTENT_ADDON_ITEM_ID =\n \"Add-on group contains options with mismatched item IDs\";\n\n/** One add-on option on a booking, with the refids/statuses needed to mutate it. */\nexport interface AddonItemOption {\n itemId: string;\n optionId: string;\n itemName: string;\n optionName: string;\n optionRefid: string;\n optionReservationStatus: string;\n itemReservationStatus: string;\n itemRefid: string;\n}\n\n/** One add-on item on a booking (internal; grouped by add-on item). */\nexport interface AddonItem {\n bookingId: string;\n displayId: string;\n orderId: string;\n total: AddonGqlPrice | null;\n bookingQuoteRefid: string;\n bookingQuoteReservationStatus: string;\n addonItemOptions: AddonItemOption[];\n}\n\n/**\n * Converts a single booking node into the internal {@link AddonItem}[] model.\n * Booking-level identifiers (bookingId, displayId, orderId) are repeated on\n * each item for convenience.\n */\nexport function parseSaleNode(node: SalesAddonBookingNode): AddonItem[] {\n const bookingId = node.id || \"\";\n const displayId = node.displayId || \"\";\n const orderId = node.order?.id || \"\";\n const bookingQuoteRefid = node.refid || \"\";\n const bookingQuoteReservationStatus = node.reservationStatus || \"\";\n const items = Array.isArray(node.items) ? node.items : [];\n\n return items.map((item) => {\n const options = Array.isArray(item.options) ? item.options : [];\n const addonItemOptions: AddonItemOption[] = options.map((opt) => ({\n itemId: opt.itemSnapshot?.id || \"\",\n optionId: opt.itemOptionSnapshot?.id || \"\",\n itemName: opt.itemSnapshot?.name || \"\",\n optionName: opt.itemOptionSnapshot?.name || \"\",\n optionRefid: opt.refid || \"\",\n optionReservationStatus: opt.reservationStatus || \"\",\n itemReservationStatus: item.reservationStatus || \"\",\n itemRefid: item.refid || \"\",\n }));\n\n return {\n bookingId,\n displayId,\n orderId,\n total: item.value?.total ?? null,\n bookingQuoteRefid,\n bookingQuoteReservationStatus,\n addonItemOptions,\n };\n });\n}\n\n/**\n * Collapses one internal {@link AddonItem} (already grouped by add-on item id)\n * into a clean public {@link BookingAddon}. All of the item's options must\n * share the same item id (a data-integrity invariant); a mismatch throws.\n * Canceled options are dropped and the rest are combined by option id with a\n * quantity count. Returns `null` when no live options remain, so the caller\n * can omit the add-on entirely.\n */\nexport function toBookingAddon(item: AddonItem): BookingAddon | null {\n const options = item.addonItemOptions || [];\n if (options.length === 0) {\n return null;\n }\n\n const addonId = options[0]!.itemId;\n const addonName = options[0]!.itemName;\n\n if (options.some((opt) => opt.itemId !== addonId)) {\n throw new Error(ERROR_INCONSISTENT_ADDON_ITEM_ID);\n }\n\n const grouped = new Map<string, BookingAddonOption>();\n options\n .filter((opt) => opt.optionReservationStatus !== ADDON_OPTION_STATUS_CANCELED)\n .forEach((opt) => {\n const existing = grouped.get(opt.optionId);\n if (existing) {\n existing.quantity += 1;\n } else {\n grouped.set(opt.optionId, {\n addonOptionId: opt.optionId,\n addonOptionName: opt.optionName,\n quantity: 1,\n });\n }\n });\n\n const addonOptions = Array.from(grouped.values());\n if (addonOptions.length === 0) {\n return null;\n }\n\n return { addonId, addonName, total: item.total, addonOptions };\n}\n","/**\n * Raw Peek GraphQL fields, queries, mutations, variables, and response shapes\n * for bookings. Internal.\n */\nimport type { BookingSearchBy } from \"../../models/booking.js\";\n\nexport const SEARCH_BY_PURCHASE_DATE: BookingSearchBy = \"purchaseDate\";\nexport const SEARCH_BY_ACTIVITY_DATE: BookingSearchBy = \"activityDate\";\n\n/** Normalizes a booking id to the gateway's expected form. */\nexport function normalizeBookingId(bookingId: string): string {\n return bookingId.toLowerCase().replace(/-/g, \"_\");\n}\n\nconst guestFields = `\n id\n name\n country\n dateOfBirth\n email\n isGdpr\n isParticipant\n optinSms\n optinMarketing\n phone\n postalCode\n fieldResponses {\n id\n text\n fieldLocation {\n field {\n name\n }\n }\n }\n`;\n\nconst bookingGuestsFields = `\n bookingGuests {\n ${guestFields}\n }\n primaryGuest {\n ${guestFields}\n }\n`;\n\nconst bookingQueryFields = `\n displayId\n id\n primaryGuest {\n name\n email\n phone\n optinMarketing\n optinSms\n isGdpr\n postalCode\n }\n activitySnapshot {\n type\n name\n id\n }\n ticketQuantities {\n quantity\n resourceOptionSnapshot {\n name\n id\n }\n }\n reservationStatus\n checkinStatus\n returnStatus\n fulfillmentStatusOverride {\n status\n }\n timeSnapshot {\n id\n legacyId\n }\n purchasedAt\n purchasedAtUtc\n startsAt\n startsAtUtc\n endsAt\n endsAtUtc\n availabilityTimeId\n bookingPortalUrl\n operatorNotes\n value {\n total {\n formatted\n amount\n }\n }\n balance {\n total {\n amount\n formatted\n }\n }\n tips {\n price {\n amount\n formatted\n }\n }\n order {\n displayId\n id\n promoCodes {\n code\n }\n channelSnapshot {\n id\n name\n agent {\n name\n }\n }\n initialQuote {\n source {\n actor {\n app\n }\n }\n }\n }\n questionAnswers {\n answer\n questionText\n questionLocationSnapshot {\n latitude\n longitude\n }\n }\n tickets {\n questionAnswers {\n answer\n questionText\n }\n }\n resourcePoolAssignments {\n quantity\n resourcePool {\n name\n shortName\n resources {\n name\n }\n }\n resourceAssignments {\n resource {\n id\n name\n }\n }\n }\n`;\n\nconst PRICE_BREAKDOWN_FIELDS = `\n convenienceFee { amount formatted }\n deposit { amount formatted }\n discount { amount formatted }\n discountedPrice { amount formatted }\n fees { amount formatted }\n flatPartnerFee { amount formatted }\n price { amount formatted }\n retailPrice { amount formatted }\n taxes { amount formatted }\n tips { amount formatted }\n`;\n\n/** Builds the bookings listing query, optionally including guests and price breakdown. */\nexport function buildBookingsListingQuery(\n includeGuests: boolean,\n includePriceBreakdown: boolean,\n): string {\n const guestsSection = includeGuests ? bookingGuestsFields : \"\";\n const fields = includePriceBreakdown\n ? bookingQueryFields.replace(\"value {\", `value { ${PRICE_BREAKDOWN_FIELDS}`)\n : bookingQueryFields;\n\n return `\n query Sales($after: String, $first: Int, $filter: SalesFilter!, $orderBy: SalesOrdering) {\n sales(after: $after, first: $first, filter: $filter, orderBy: $orderBy) {\n pageInfo { endCursor hasNextPage }\n edges {\n node {\n ... on Booking {\n ${fields}\n ${guestsSection}\n }\n }\n }\n }\n }\n `;\n}\n\n/** Query fetching the guests for a booking. */\nexport const BOOKING_GUESTS_QUERY = `\n query Sales($after: String, $first: Int, $filter: SalesFilter!, $orderBy: SalesOrdering) {\n sales(after: $after, first: $first, filter: $filter, orderBy: $orderBy) {\n pageInfo { endCursor hasNextPage }\n edges {\n node {\n ... on Booking {\n displayId\n id\n ${bookingGuestsFields}\n }\n }\n }\n }\n }\n`;\n\n/** Query fetching a booking's order payments + payment sources. */\nexport const BOOKING_PAYMENTS_ON_FILE_QUERY = `\n query Sales($after: String, $first: Int, $filter: SalesFilter!, $orderBy: SalesOrdering) {\n sales(after: $after, first: $first, filter: $filter, orderBy: $orderBy) {\n pageInfo { endCursor hasNextPage }\n edges {\n node {\n order {\n payments {\n id\n paymentSource { id }\n appliedAt\n currentAmount { amount currency }\n refundableAmount { amount currency }\n }\n id\n displayId\n paymentSources { description type id }\n }\n ... on Booking {\n displayId\n id\n }\n }\n }\n }\n }\n`;\n\nexport const UPDATE_OPERATOR_NOTES_MUTATION = `\n mutation Account($input: UpdateOperatorNotesForBookingInput!) {\n updateOperatorNotesForBooking(input: $input) {\n booking { operatorNotes }\n }\n }\n`;\n\nexport const UPDATE_BOOKING_CHECKIN_MUTATION = `\n mutation Account($input: UpdateBookingCheckInInput!) {\n updateBookingCheckIn(input: $input) {\n booking { checkinStatus }\n }\n }\n`;\n\nexport const CANCEL_BOOKING_MUTATION = `\n mutation Account($input: CancelBookingInput!) {\n cancelBooking(input: $input) {\n booking { id displayId reservationStatus }\n }\n }\n`;\n\nexport const APPLY_PAYMENT_TO_ORDER_MUTATION = `\n mutation ApplyPaymentToOrder($input: ApplyPaymentToOrderInput!) {\n applyPaymentToOrder(input: $input) {\n transactionId\n errors { code detail value }\n }\n }\n`;\n\nexport const APPLY_REFUND_TO_ORDER_MUTATION = `\n mutation ApplyRefundToOrder($input: ApplyRefundToOrderInput!) {\n applyRefundToOrder(input: $input) {\n transactionId\n errors { code detail value }\n }\n }\n`;\n\nexport const CREATE_INVOICE_LINK_MUTATION = `\n mutation CreateInvoiceLink($input: CreateInvoiceLinkInput!) {\n createInvoiceLink(input: $input) {\n invoiceLink { status url }\n errors { code detail value __typename }\n }\n }\n`;\n\n/** A payment/refund/invoice error entry. */\nexport interface PaymentMutationError {\n code: string;\n detail: string;\n value: string | null;\n}\n\nexport interface ApplyPaymentToOrderResponse {\n applyPaymentToOrder: { transactionId: string | null; errors: PaymentMutationError[] | null };\n}\n\nexport interface ApplyRefundToOrderResponse {\n applyRefundToOrder: { transactionId: string | null; errors: PaymentMutationError[] | null };\n}\n\nexport interface CreateInvoiceLinkResponse {\n createInvoiceLink: {\n invoiceLink: { status: string; url: string } | null;\n errors: PaymentMutationError[] | null;\n };\n}\n\nexport const CREATE_QUOTE_FROM_ORDER_MUTATION = `\n mutation CreateQuoteFromOrder($input: CreateQuoteFromOrderInput!) {\n createQuoteFromOrder(input: $input) {\n errors { detail value code }\n quote {\n id\n saleQuotes { refid reservationStatus }\n }\n }\n }\n`;\n\nexport const UPDATE_QUOTE_V2_MUTATION = `\n mutation UpdateQuoteV2($input: UpdateQuoteV2Input!) {\n updateQuoteV2(input: $input) {\n errors { detail value code }\n quote { id }\n }\n }\n`;\n\nexport const AMEND_ORDER_MUTATION = `\n mutation AmendOrder($input: AmendOrderInput!) {\n amendOrder(input: $input) {\n errors { code detail value }\n order { id }\n }\n }\n`;\n\nexport interface CreateQuoteFromOrderResponse {\n createQuoteFromOrder: {\n errors: PaymentMutationError[] | null;\n quote: { id: string; saleQuotes: Array<{ refid: string; reservationStatus: string }> } | null;\n };\n}\n\nexport interface UpdateQuoteV2Response {\n updateQuoteV2: { errors: PaymentMutationError[] | null; quote: { id: string } | null };\n}\n\nexport interface AmendOrderResponse {\n amendOrder: { errors: PaymentMutationError[] | null; order: { id: string } | null };\n}\n\nexport const CREATE_QUOTE_V2_MUTATION = `\n mutation CreateQuoteV2($input: CreateQuoteV2Input!) {\n createQuoteV2(input: $input) {\n errors { detail value code }\n quote { id }\n }\n }\n`;\n\nexport const CREATE_ORDER_FROM_QUOTE_MUTATION = `\n mutation CreateOrderFromQuote($input: CreateOrderFromQuoteInput!) {\n createOrderFromQuote(input: $input) {\n errors { code detail value }\n order {\n id\n sales {\n id\n displayId\n ... on Booking {\n balance { total { amount currency formatted } }\n }\n }\n }\n }\n }\n`;\n\nexport interface CreateQuoteV2Response {\n createQuoteV2: { errors: PaymentMutationError[] | null; quote: { id: string } | null };\n}\n\nexport interface CreateOrderFromQuoteResponse {\n createOrderFromQuote: {\n errors: PaymentMutationError[] | null;\n order: {\n id: string;\n sales: Array<{\n id: string;\n displayId: string;\n balance?: { total: { amount: string; currency: string; formatted: string } } | null;\n }>;\n } | null;\n };\n}\n\n/** Builds the variables for the bookings/guests/payments sales queries. */\nexport function buildBookingsVariables(params: {\n pageSize: number;\n after: string | null;\n startDateTime?: string;\n endDateTime?: string;\n timeslotId?: string;\n searchBy?: BookingSearchBy;\n productId?: string;\n bookingId?: string;\n email?: string;\n searchString?: string;\n}): object {\n const filter: Record<string, unknown> = {};\n const bookingFilter: Record<string, unknown> = {};\n\n if (params.bookingId) {\n bookingFilter.ids = [normalizeBookingId(params.bookingId)];\n } else if (params.timeslotId) {\n bookingFilter.timeslotRefid = params.timeslotId;\n } else {\n if (params.searchBy === SEARCH_BY_ACTIVITY_DATE) {\n bookingFilter.overlapsRange = `[${params.startDateTime},${params.endDateTime}]`;\n } else if (params.searchBy === SEARCH_BY_PURCHASE_DATE) {\n filter.purchasedAtRangeUtc = `[${params.startDateTime},${params.endDateTime}]`;\n }\n if (params.productId) {\n bookingFilter.activityIds = [params.productId];\n }\n }\n\n if (params.email) {\n filter.primaryGuestEmail = params.email;\n }\n if (params.searchString && params.searchString.length > 0) {\n filter.searchString = params.searchString;\n }\n if (Object.keys(bookingFilter).length > 0) {\n filter.bookingFilter = bookingFilter;\n }\n\n return {\n first: params.pageSize,\n after: params.after,\n orderBy: { direction: \"ASC\", field: \"STARTS_AT\" },\n filter,\n };\n}\n\n// ---- Raw response shapes -------------------------------------------------\n\nexport interface BookingNode {\n displayId?: string;\n id?: string;\n // Base bookings query selects name/email/phone; when guests are requested the\n // full guest fields (id, fieldResponses, …) are merged in as well.\n primaryGuest?: BookingGuestNode | null;\n activitySnapshot?: { type?: string; name?: string; id?: string } | null;\n ticketQuantities?: Array<{\n quantity?: number;\n resourceOptionSnapshot?: { name?: string; id?: string } | null;\n }>;\n reservationStatus?: string;\n checkinStatus?: string;\n returnStatus?: string;\n fulfillmentStatusOverride?: { status?: string } | null;\n timeSnapshot?: { id?: string; legacyId?: string | null } | null;\n purchasedAt?: string;\n purchasedAtUtc?: string;\n startsAt?: string;\n startsAtUtc?: string;\n endsAt?: string;\n endsAtUtc?: string;\n availabilityTimeId?: string;\n bookingPortalUrl?: string;\n operatorNotes?: string | null;\n value?: Record<string, { amount?: string; formatted?: string } | undefined> & {\n total?: { amount?: string; formatted?: string };\n };\n balance?: { total?: { amount?: string; formatted?: string } } | null;\n tips?: Array<{ price?: { amount?: string; formatted?: string } }>;\n order?: {\n id?: string;\n promoCodes?: Array<{ code: string }>;\n channelSnapshot?: { id?: string; name?: string; agent?: { name?: string } | null } | null;\n initialQuote?: { source?: { actor?: { app?: string } | null } | null } | null;\n } | null;\n questionAnswers?: Array<{\n answer: string;\n questionText: string;\n questionLocationSnapshot?: { latitude?: string; longitude?: string } | null;\n }>;\n tickets?: Array<{\n questionAnswers?: Array<{ answer: string; questionText: string }> | null;\n }> | null;\n resourcePoolAssignments?: Array<{\n quantity?: number;\n resourcePool?: { name?: string; shortName?: string } | null;\n resourceAssignments?: Array<{ resource?: { id?: string; name?: string } | null }>;\n }>;\n // Present when guests are requested.\n bookingGuests?: BookingGuestNode[];\n}\n\nexport interface BookingsResponse {\n sales: {\n pageInfo: { endCursor: string | null; hasNextPage: boolean };\n edges: Array<{ node: BookingNode }>;\n };\n}\n\nexport interface BookingGuestFieldResponse {\n id: string;\n text: string | null;\n fieldLocation?: { field?: { name?: string } | null } | null;\n}\n\nexport interface BookingGuestNode {\n id: string;\n name?: string | null;\n country?: string | null;\n dateOfBirth?: string | null;\n phone?: string | null;\n email?: string | null;\n isGdpr?: boolean;\n isParticipant?: boolean;\n optinSms?: boolean;\n optinMarketing?: boolean;\n postalCode?: string | null;\n fieldResponses?: BookingGuestFieldResponse[];\n}\n\nexport interface BookingGuestsResponse {\n sales: {\n edges: Array<{\n node: {\n displayId: string;\n id: string;\n bookingGuests?: BookingGuestNode[];\n primaryGuest?: BookingGuestNode | null;\n };\n }>;\n };\n}\n\nexport interface BookingPaymentsOnFileResponse {\n sales: {\n edges: Array<{\n node: {\n order?: {\n id?: string;\n displayId?: string;\n payments?: Array<{\n id: string;\n paymentSource?: { id?: string } | null;\n appliedAt: string;\n currentAmount: { amount: string; currency: string };\n refundableAmount: { amount: string; currency: string };\n }>;\n paymentSources?: Array<{ description: string; id: string; type: string }>;\n } | null;\n };\n }>;\n };\n}\n","/**\n * Booking operations against the Peek gateway.\n *\n * Obtain an instance via {@link PeekAccessService.getBookingService}.\n */\nimport { randomUUID } from \"node:crypto\";\n\nimport { SALES_ENDPOINT } from \"../gateway-endpoints.js\";\nimport type { GraphQLBody, GraphQLClient } from \"../graphql-client.js\";\nimport type { ProductService } from \"../products/product-service.js\";\nimport type {\n Booking,\n BookingReadOptions,\n BookingTimeRangeSearch,\n CreateBookingInput,\n CreatedBooking,\n Guest,\n NoteMode,\n} from \"../../models/booking.js\";\nimport { ADD_ON_PRODUCT_TYPE } from \"../../models/product.js\";\nimport type {\n BookingPaymentsOnFile,\n InvoiceLinkResult,\n MakePaymentInput,\n MakePaymentResult,\n RefundInput,\n RefundResult,\n} from \"../../models/booking-payment.js\";\nimport type {\n BookingAddons,\n BookingAddonsMutationResult,\n} from \"../../models/booking-addon.js\";\nimport { fromBookingNode } from \"./booking-converter.js\";\nimport { fromBookingGuestsResponse } from \"./booking-guest-converter.js\";\nimport { fromPaymentsOnFileResponse } from \"./payments-on-file-converter.js\";\nimport {\n type AddonItem,\n parseSaleNode,\n toBookingAddon,\n} from \"./addon-converter.js\";\nimport {\n ADDON_OPTION_STATUS_CANCELED,\n RESERVATION_STATUS_CONFIRMED,\n SALES_ADDONS_QUERY,\n buildSalesAddonsVariables,\n type SalesAddonsResponse,\n} from \"./addon-queries.js\";\nimport {\n AMEND_ORDER_MUTATION,\n APPLY_PAYMENT_TO_ORDER_MUTATION,\n APPLY_REFUND_TO_ORDER_MUTATION,\n BOOKING_GUESTS_QUERY,\n BOOKING_PAYMENTS_ON_FILE_QUERY,\n CANCEL_BOOKING_MUTATION,\n CREATE_INVOICE_LINK_MUTATION,\n CREATE_ORDER_FROM_QUOTE_MUTATION,\n CREATE_QUOTE_FROM_ORDER_MUTATION,\n CREATE_QUOTE_V2_MUTATION,\n SEARCH_BY_PURCHASE_DATE,\n UPDATE_BOOKING_CHECKIN_MUTATION,\n UPDATE_OPERATOR_NOTES_MUTATION,\n UPDATE_QUOTE_V2_MUTATION,\n buildBookingsListingQuery,\n buildBookingsVariables,\n normalizeBookingId,\n type AmendOrderResponse,\n type ApplyPaymentToOrderResponse,\n type ApplyRefundToOrderResponse,\n type BookingGuestsResponse,\n type BookingPaymentsOnFileResponse,\n type BookingsResponse,\n type CreateInvoiceLinkResponse,\n type CreateOrderFromQuoteResponse,\n type CreateQuoteFromOrderResponse,\n type CreateQuoteV2Response,\n type UpdateQuoteV2Response,\n} from \"./booking-queries.js\";\n\n/** Default page size for cursor-paginated bookings. */\nconst DEFAULT_PAGE_SIZE = 50;\n/** Default note used when cancelling without an explicit reason. */\nconst DEFAULT_CANCEL_NOTE = \"Canceled\";\n/** Default customer message attached to a charge. */\nconst DEFAULT_CUSTOMER_MESSAGE = \"Charge initiated via API\";\n\nconst BOOKING_ID_PREFIX = \"b_\";\nconst PAYMENT_SOURCE_PREFIX = \"ps_\";\nconst PAYMENT_ID_PREFIX = \"pmt_\";\nconst ALLOWED_PAYMENT_SOURCE_IDS = [\"cash/cash\", \"custom/other\", \"custom/voucher\"];\nconst CURRENCY_CODE_REGEX = /^[A-Z]{3}$/;\n\n/** Result of cancelling a booking. */\nexport interface CancelBookingResult {\n id: string;\n displayId: string;\n reservationStatus: string;\n}\n\ninterface CancelBookingResponse {\n cancelBooking?: { booking?: CancelBookingResult | null } | null;\n}\n\n/** Tuning options for a {@link BookingService}. */\nexport interface BookingServiceOptions {\n /** Page size for cursor pagination. Default: 50. */\n pageSize?: number;\n}\n\n/** Dependencies the {@link BookingService} composes for add-on resolution. */\nexport interface BookingServiceDeps {\n productService: ProductService;\n}\n\n/** Input for adding or removing an add-on on a booking. */\nexport interface AddAddonInput {\n /** The add-on (item option) id. */\n addonOptionId?: string;\n /**\n * @deprecated Use `addonOptionId`. Still accepted for backwards\n * compatibility; treated as `addonOptionId` when `addonOptionId` is absent.\n */\n addonId?: string;\n /** Quantity as a positive integer string. */\n quantity: string;\n}\n\nconst ERROR_ADDON_OPTION_ID_REQUIRED = \"addonOptionId is required\";\nconst ERROR_QUANTITY_INVALID = \"quantity must be a positive integer string\";\nconst ERROR_BOOKING_ID_REQUIRED = \"bookingId is required\";\nconst ERROR_BOOKING_NOT_FOUND = \"Booking not found\";\nconst ERROR_MULTIPLE_BOOKINGS_FOUND =\n \"Expected exactly one booking for the provided bookingId\";\nconst ERROR_NO_ADDON_OPTION_TO_REMOVE =\n \"No confirmed add-on option matching addonOptionId was found on the booking\";\nconst ERROR_CREATE_QUOTE_FAILED = \"Failed to create quote from order\";\nconst ERROR_UPDATE_QUOTE_FAILED = \"Failed to update quote with add-on\";\nconst ERROR_AMEND_ORDER_FAILED = \"Failed to amend order with add-on\";\n\nexport class BookingService {\n private readonly pageSize: number;\n\n constructor(\n private readonly client: GraphQLClient,\n private readonly deps: BookingServiceDeps,\n options: BookingServiceOptions = {},\n ) {\n this.pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;\n }\n\n /**\n * Returns a single booking by id, or null when not found. The `bookingId` is\n * normalized internally (lowercased, `-` → `_`), so `B-ABC123` and `b_abc123`\n * resolve to the same booking.\n *\n * @example\n * ```ts\n * const bookings = peek.getBookingService();\n * const booking = await bookings.getById(\"b_abc123\", {\n * includeGuests: true,\n * includePriceBreakdown: true,\n * });\n * if (booking) console.log(booking.displayId, booking.outstandingBalanceAmount);\n * ```\n */\n async getById(\n bookingId: string,\n options: BookingReadOptions = {},\n ): Promise<Booking | null> {\n const includeGuests = options.includeGuests ?? false;\n const includePriceBreakdown = options.includePriceBreakdown ?? false;\n\n const body: GraphQLBody<BookingsResponse> =\n await this.client.request<BookingsResponse>(\n SALES_ENDPOINT,\n buildBookingsListingQuery(includeGuests, includePriceBreakdown),\n buildBookingsVariables({\n pageSize: this.pageSize,\n after: null,\n bookingId: normalizeBookingId(bookingId),\n }),\n );\n\n const firstEdge = (body.data?.sales?.edges ?? [])[0];\n if (!firstEdge) {\n return null;\n }\n return fromBookingNode(firstEdge.node, includeGuests, includePriceBreakdown);\n }\n\n /** Returns all bookings matching a time range (paginated). */\n async searchByTimeRange(input: BookingTimeRangeSearch): Promise<Booking[]> {\n const includeGuests = input.includeGuests ?? false;\n const includePriceBreakdown = input.includePriceBreakdown ?? false;\n\n return this.fetchPaginated(\n buildBookingsListingQuery(includeGuests, includePriceBreakdown),\n {\n startDateTime: input.start,\n endDateTime: input.end,\n searchBy: input.searchBy ?? SEARCH_BY_PURCHASE_DATE,\n productId: input.productId,\n email: input.email,\n searchString: input.searchString,\n },\n includeGuests,\n includePriceBreakdown,\n );\n }\n\n /** Returns all bookings on a timeslot (paginated). */\n async searchByTimeslot(\n timeslotId: string,\n options: BookingReadOptions = {},\n ): Promise<Booking[]> {\n const includeGuests = options.includeGuests ?? false;\n const includePriceBreakdown = options.includePriceBreakdown ?? false;\n\n return this.fetchPaginated(\n buildBookingsListingQuery(includeGuests, includePriceBreakdown),\n { timeslotId },\n includeGuests,\n includePriceBreakdown,\n );\n }\n\n /** Returns the guests on a booking (primary guest included). */\n async getGuests(bookingId: string): Promise<Guest[]> {\n const body: GraphQLBody<BookingGuestsResponse> =\n await this.client.request<BookingGuestsResponse>(\n SALES_ENDPOINT,\n BOOKING_GUESTS_QUERY,\n buildBookingsVariables({\n pageSize: this.pageSize,\n after: null,\n bookingId: normalizeBookingId(bookingId),\n }),\n );\n return fromBookingGuestsResponse(body.data);\n }\n\n /** Returns the payments on file for a booking, or null when not found. */\n async getPaymentsOnFile(bookingId: string): Promise<BookingPaymentsOnFile | null> {\n const normalized = normalizeBookingId(bookingId);\n const body: GraphQLBody<BookingPaymentsOnFileResponse> =\n await this.client.request<BookingPaymentsOnFileResponse>(\n SALES_ENDPOINT,\n BOOKING_PAYMENTS_ON_FILE_QUERY,\n buildBookingsVariables({ pageSize: this.pageSize, after: null, bookingId: normalized }),\n );\n return fromPaymentsOnFileResponse(body.data, normalized);\n }\n\n /**\n * Appends to (or overwrites) a booking's operator notes. Returns the updated\n * booking, or null when the booking is not found.\n */\n async appendNote(\n bookingId: string,\n note: string,\n mode: NoteMode = \"append\",\n ): Promise<Booking | null> {\n const normalized = normalizeBookingId(bookingId);\n const booking = await this.getById(normalized);\n if (!booking) {\n return null;\n }\n\n const newNote =\n mode === \"overwrite\" || !booking.notes ? note : `${booking.notes}\\n${note}`;\n\n await this.client.request(SALES_ENDPOINT, UPDATE_OPERATOR_NOTES_MUTATION, {\n input: { id: normalized, operatorNotes: newNote },\n });\n\n booking.notes = newNote;\n return booking;\n }\n\n /**\n * Sets a booking's check-in status. Returns the refreshed booking, or null\n * when not found.\n */\n async setCheckinStatus(\n bookingId: string,\n checkedIn: boolean,\n ): Promise<Booking | null> {\n const normalized = normalizeBookingId(bookingId);\n const checkedInAt = checkedIn ? new Date().toISOString() : null;\n\n await this.client.request(SALES_ENDPOINT, UPDATE_BOOKING_CHECKIN_MUTATION, {\n input: { id: normalized, checkedInAt },\n });\n\n return this.getById(normalized);\n }\n\n /** Cancels a booking and returns its id/displayId/status. */\n async cancel(\n bookingId: string,\n notes: string = DEFAULT_CANCEL_NOTE,\n ): Promise<CancelBookingResult> {\n const body: GraphQLBody<CancelBookingResponse> =\n await this.client.request<CancelBookingResponse>(\n SALES_ENDPOINT,\n CANCEL_BOOKING_MUTATION,\n { input: { bookingId: normalizeBookingId(bookingId), notes } },\n );\n\n const booking = body.data?.cancelBooking?.booking;\n if (!booking) {\n throw new Error(\"No booking data returned from cancelBooking\");\n }\n return {\n id: booking.id,\n displayId: booking.displayId,\n reservationStatus: booking.reservationStatus,\n };\n }\n\n /**\n * Charges a booking. Validates input, resolves the order + payment source via\n * payments-on-file, then applies the payment. The `idempotencyKey` is passed\n * through to Peek.\n *\n * @example\n * ```ts\n * const result = await peek.getBookingService().makePayment({\n * bookingId: \"b_abc123\",\n * paymentSourceId: \"custom/other\", // or a \"ps_…\" source on file\n * amount: \"25.00\",\n * currency: \"USD\",\n * idempotencyKey: crypto.randomUUID(),\n * });\n * console.log(result.transactionId);\n * ```\n *\n * @throws {Error} when `paymentSourceId` is missing or not a `ps_…` id / one\n * of `cash/cash`, `custom/other`, `custom/voucher`; when `amount` is not a\n * valid number; when `currency` is not a 3-letter uppercase code; when\n * `idempotencyKey` is empty; when `bookingId` does not resolve to a `b_…` id;\n * when the booking or payment source is not found; or when the charge fails.\n */\n async makePayment(input: MakePaymentInput): Promise<MakePaymentResult> {\n const normalized = normalizeBookingId(input.bookingId);\n this.validatePaymentInput(input, normalized);\n\n const onFile = await this.getPaymentsOnFile(normalized);\n if (!onFile) {\n throw new Error(\"Booking not found\");\n }\n if (!onFile.paymentsOnFile.some((source) => source.id === input.paymentSourceId)) {\n throw new Error(\"paymentSourceId not found for this booking\");\n }\n\n const customerMessage = input.customerMessage\n ? `${DEFAULT_CUSTOMER_MESSAGE} (${input.customerMessage})`\n : DEFAULT_CUSTOMER_MESSAGE;\n\n const body: GraphQLBody<ApplyPaymentToOrderResponse> =\n await this.client.request<ApplyPaymentToOrderResponse>(\n SALES_ENDPOINT,\n APPLY_PAYMENT_TO_ORDER_MUTATION,\n {\n input: {\n amount: { amount: input.amount, currency: input.currency },\n orderId: onFile.orderId,\n paymentSourceId: input.paymentSourceId,\n idempotencyKey: input.idempotencyKey,\n customerMessage,\n scopedTo: [normalized],\n },\n },\n );\n\n const result = body.data?.applyPaymentToOrder;\n if (result?.errors && result.errors.length > 0) {\n throw new Error(`Payment failed: ${result.errors[0]!.detail}`);\n }\n\n return {\n transactionId: result?.transactionId ?? \"\",\n bookingId: normalized,\n orderId: onFile.orderId,\n amount: input.amount,\n currency: input.currency,\n paymentSourceId: input.paymentSourceId,\n };\n }\n\n /**\n * Refunds a booking payment. Validates input, resolves the order + payment via\n * payments-on-file, then applies the refund.\n */\n async refund(input: RefundInput): Promise<RefundResult> {\n const normalized = normalizeBookingId(input.bookingId);\n this.validateRefundInput(input, normalized);\n\n const onFile = await this.getPaymentsOnFile(normalized);\n if (!onFile) {\n throw new Error(\"Booking not found\");\n }\n const paymentExists = onFile.paymentsOnFile.some((source) =>\n (source.payments ?? []).some((payment) => payment.id === input.paymentId),\n );\n if (!paymentExists) {\n throw new Error(\"paymentId not found for this booking\");\n }\n\n const body: GraphQLBody<ApplyRefundToOrderResponse> =\n await this.client.request<ApplyRefundToOrderResponse>(\n SALES_ENDPOINT,\n APPLY_REFUND_TO_ORDER_MUTATION,\n {\n input: {\n amount: { amount: input.amount, currency: input.currency },\n orderId: onFile.orderId,\n paymentId: input.paymentId,\n idempotencyKey: input.idempotencyKey,\n scopedTo: [normalized],\n },\n },\n );\n\n const result = body.data?.applyRefundToOrder;\n if (result?.errors && result.errors.length > 0) {\n throw new Error(`Refund failed: ${result.errors[0]!.detail}`);\n }\n\n return {\n transactionId: result?.transactionId ?? \"\",\n bookingId: normalized,\n orderId: onFile.orderId,\n amount: input.amount,\n currency: input.currency,\n paymentId: input.paymentId,\n };\n }\n\n /** Creates an invoice link for a booking's order. */\n async createInvoiceLink(bookingId: string): Promise<InvoiceLinkResult> {\n if (!bookingId || bookingId.trim().length === 0) {\n throw new Error(\"bookingId is required\");\n }\n const normalized = normalizeBookingId(bookingId);\n\n const booking = await this.getById(normalized);\n if (!booking || !booking.orderId) {\n throw new Error(\"Booking not found\");\n }\n const orderId = normalizeBookingId(booking.orderId);\n\n const body: GraphQLBody<CreateInvoiceLinkResponse> =\n await this.client.request<CreateInvoiceLinkResponse>(\n SALES_ENDPOINT,\n CREATE_INVOICE_LINK_MUTATION,\n { input: { orderId } },\n );\n\n const url = body.data?.createInvoiceLink?.invoiceLink?.url;\n if (!url) {\n throw new Error(\"Failed to create invoice link\");\n }\n return { bookingId: normalized, orderId, invoiceLink: url };\n }\n\n /** Returns the add-ons on a booking, grouped by add-on item (clean model). */\n async listAddons(bookingId: string): Promise<BookingAddons> {\n const { items, displayId, orderId, normalizedBookingId } =\n await this.fetchBookingSale(bookingId);\n\n const addons = items\n .map((item) => toBookingAddon(item))\n .filter((addon): addon is NonNullable<typeof addon> => addon !== null);\n\n return {\n bookingId: items[0]?.bookingId || normalizedBookingId,\n displayId: items[0]?.displayId || displayId,\n orderId: items[0]?.orderId || orderId,\n addons,\n };\n }\n\n /**\n * Adds an add-on to a booking via createQuoteFromOrder → updateQuoteV2 →\n * amendOrder. Lists the booking's add-ons first to derive the order id and\n * reuse an existing add-on refid; resolves the add-on's parent item via the\n * product service. Returns the booking's add-ons after the change.\n *\n * `quantity` is a **positive-integer string** (\"1\", \"2\", …); one add-on\n * itemOption is created per unit. `addonOptionId` is the add-on's item-option\n * id (a ticket id on an `ADD_ON_PRODUCT_TYPE` product from\n * {@link ProductService.getAllProducts}).\n *\n * @example\n * ```ts\n * const result = await peek.getBookingService().addAddon(\"b_abc123\", {\n * addonOptionId: \"io_helmet\",\n * quantity: \"2\",\n * });\n * console.log(result.updatedBookingAddons.addons);\n * ```\n *\n * @throws {Error} when `addonOptionId` is missing, `quantity` is not a\n * positive-integer string, the add-on is not found on any product, or any of\n * the underlying quote/order mutations fail.\n */\n async addAddon(\n bookingId: string,\n input: AddAddonInput,\n ): Promise<BookingAddonsMutationResult> {\n const addonOptionId = (input?.addonOptionId || input?.addonId || \"\").trim();\n if (!addonOptionId) {\n throw new Error(ERROR_ADDON_OPTION_ID_REQUIRED);\n }\n const quantity = parseQuantity(input?.quantity);\n if (quantity === null) {\n throw new Error(ERROR_QUANTITY_INVALID);\n }\n\n // List the booking's existing add-ons first — this yields the order id (no\n // separate lookup) and lets us reuse an existing add-on refid instead of\n // minting a new one. Resolve the add-on's parent item in parallel.\n const [sale, parentItemId] = await Promise.all([\n this.fetchBookingSale(bookingId),\n this.resolveParentItemId(addonOptionId),\n ]);\n\n const normalizedOrderId = normalizeBookingId(sale.orderId);\n\n // Reuse the bookingQuote item refid when this parent item is already on the\n // booking under a non-canceled add-on; otherwise mint a fresh refid.\n const existingItemRefid = sale.items\n .filter(\n (item) => item.bookingQuoteReservationStatus !== ADDON_OPTION_STATUS_CANCELED,\n )\n .flatMap((item) => item.addonItemOptions)\n .find((opt) => opt.itemId === parentItemId)?.itemRefid;\n const addonRefid = existingItemRefid || randomUUID();\n\n // Step 1 — create a quote from the order.\n const { quoteId, saleQuoteRefid } =\n await this.createQuoteFromOrderOrThrow(normalizedOrderId);\n if (!saleQuoteRefid) {\n throw new Error(ERROR_CREATE_QUOTE_FAILED);\n }\n\n // Step 2 — add the add-on to the quote (one new itemOption per unit).\n const itemOptions = Array.from({ length: quantity }, () => ({\n itemOptionId: addonOptionId,\n reservationStatus: RESERVATION_STATUS_CONFIRMED,\n refid: randomUUID(),\n }));\n await this.updateQuoteOrThrow(quoteId, {\n bookingQuotes: [\n {\n refid: saleQuoteRefid,\n addons: [\n {\n itemOptions,\n itemId: parentItemId,\n reservationStatus: RESERVATION_STATUS_CONFIRMED,\n refid: addonRefid,\n },\n ],\n reservationStatus: RESERVATION_STATUS_CONFIRMED,\n },\n ],\n });\n\n // Step 3 — amend the order with the updated quote.\n await this.amendOrderOrThrow(quoteId, normalizedOrderId);\n\n return { updatedBookingAddons: await this.listAddons(bookingId) };\n }\n\n /**\n * Removes (cancels) add-on options from a booking. Lists the booking's\n * add-ons first to get the order id and the existing item/option refids, then\n * issues the same three mutations as {@link addAddon} but with cancellation\n * variables. Returns the booking's add-ons after the change.\n */\n async removeAddon(\n bookingId: string,\n input: AddAddonInput,\n ): Promise<BookingAddonsMutationResult> {\n const addonOptionId = (input?.addonOptionId || input?.addonId || \"\").trim();\n if (!addonOptionId) {\n throw new Error(ERROR_ADDON_OPTION_ID_REQUIRED);\n }\n const quantity = parseQuantity(input?.quantity);\n if (quantity === null) {\n throw new Error(ERROR_QUANTITY_INVALID);\n }\n\n const sale = await this.fetchBookingSale(bookingId);\n const normalizedOrderId = normalizeBookingId(sale.orderId);\n\n const { bookingQuotes, canceledCount } = buildCancellation(\n sale.items,\n addonOptionId,\n quantity,\n );\n if (canceledCount === 0) {\n throw new Error(ERROR_NO_ADDON_OPTION_TO_REMOVE);\n }\n\n // Step 1 — create a quote from the order (only the quote id is needed; the\n // refids come from the existing booking, not the quote).\n const { quoteId } = await this.createQuoteFromOrderOrThrow(normalizedOrderId);\n\n // Step 2 — update the quote, canceling the selected options.\n await this.updateQuoteOrThrow(quoteId, { bookingQuotes });\n\n // Step 3 — amend the order.\n await this.amendOrderOrThrow(quoteId, normalizedOrderId);\n\n return { updatedBookingAddons: await this.listAddons(bookingId) };\n }\n\n /**\n * Runs the sales add-ons query for a booking, validates that exactly one\n * booking matched, and parses the node into the internal model.\n */\n private async fetchBookingSale(bookingId: string): Promise<{\n items: AddonItem[];\n displayId: string;\n orderId: string;\n normalizedBookingId: string;\n }> {\n const searchString = (bookingId || \"\").trim();\n if (!searchString) {\n throw new Error(ERROR_BOOKING_ID_REQUIRED);\n }\n\n const body: GraphQLBody<SalesAddonsResponse> =\n await this.client.request<SalesAddonsResponse>(\n SALES_ENDPOINT,\n SALES_ADDONS_QUERY,\n buildSalesAddonsVariables(searchString),\n );\n\n const edges = body.data?.sales?.edges ?? [];\n if (edges.length === 0) {\n throw new Error(ERROR_BOOKING_NOT_FOUND);\n }\n if (edges.length > 1) {\n throw new Error(ERROR_MULTIPLE_BOOKINGS_FOUND);\n }\n\n const node = edges[0]!.node;\n return {\n items: parseSaleNode(node),\n displayId: node.displayId || \"\",\n orderId: node.order?.id || \"\",\n normalizedBookingId: node.id || \"\",\n };\n }\n\n /**\n * Runs `createQuoteFromOrder` and validates the response, returning the new\n * quote id and the first sale quote refid (empty string when absent).\n */\n private async createQuoteFromOrderOrThrow(\n normalizedOrderId: string,\n ): Promise<{ quoteId: string; saleQuoteRefid: string }> {\n const body: GraphQLBody<CreateQuoteFromOrderResponse> =\n await this.client.request<CreateQuoteFromOrderResponse>(\n SALES_ENDPOINT,\n CREATE_QUOTE_FROM_ORDER_MUTATION,\n { input: { orderId: normalizedOrderId, quoteInput: {} } },\n );\n\n const created = body.data?.createQuoteFromOrder;\n const quote = created?.quote;\n if ((created?.errors && created.errors.length > 0) || !quote?.id) {\n throw new Error(ERROR_CREATE_QUOTE_FAILED);\n }\n return { quoteId: quote.id, saleQuoteRefid: quote.saleQuotes?.[0]?.refid || \"\" };\n }\n\n /** Runs `updateQuoteV2` with the given quoteInput and validates the response. */\n private async updateQuoteOrThrow(\n quoteId: string,\n quoteInput: Record<string, unknown>,\n ): Promise<void> {\n const body: GraphQLBody<UpdateQuoteV2Response> =\n await this.client.request<UpdateQuoteV2Response>(\n SALES_ENDPOINT,\n UPDATE_QUOTE_V2_MUTATION,\n { input: { quoteId, quoteInput } },\n );\n const updated = body.data?.updateQuoteV2;\n if ((updated?.errors && updated.errors.length > 0) || !updated?.quote) {\n throw new Error(ERROR_UPDATE_QUOTE_FAILED);\n }\n }\n\n /** Runs `amendOrder` and validates the response. */\n private async amendOrderOrThrow(\n quoteId: string,\n normalizedOrderId: string,\n ): Promise<void> {\n const body: GraphQLBody<AmendOrderResponse> =\n await this.client.request<AmendOrderResponse>(\n SALES_ENDPOINT,\n AMEND_ORDER_MUTATION,\n { input: { quoteId, orderId: normalizedOrderId } },\n );\n const amended = body.data?.amendOrder;\n if ((amended?.errors && amended.errors.length > 0) || !amended?.order) {\n throw new Error(ERROR_AMEND_ORDER_FAILED);\n }\n }\n\n /**\n * Creates a booking via createQuoteV2 → createOrderFromQuote, optionally\n * marking it paid. IDs must be pre-resolved (no free-text matching) — resolve\n * `activityId` + ticket `resourceOptionId`s from {@link ProductService} and\n * `availabilityTimeId` from {@link AvailabilityService.getAvailabilityTimes}.\n *\n * @example\n * ```ts\n * const created = await peek.getBookingService().create({\n * activityId: \"a_kayak_tour\",\n * availabilityTimeId: \"at_2026_06_20_0900\",\n * tickets: [{ resourceOptionId: \"ro_adult\", quantity: 2 }],\n * guest: { name: \"Sam Rivera\", email: \"sam@example.com\" },\n * markAsPaid: true,\n * idempotencyKey: crypto.randomUUID(),\n * });\n * console.log(created.bookingId, created.displayId, created.balanceFormatted);\n * ```\n *\n * @throws {Error} when `activityId`, `availabilityTimeId`, a ticket\n * `resourceOptionId`/positive `quantity`, or the guest `name` is missing; when\n * `markAsPaid` is set without an `idempotencyKey`; or when the quote/order\n * mutations fail.\n */\n async create(input: CreateBookingInput): Promise<CreatedBooking> {\n validateCreateInput(input);\n\n const tickets = input.tickets.flatMap((ticket) =>\n Array.from({ length: ticket.quantity }, () => ({\n resourceOptionId: ticket.resourceOptionId,\n reservationStatus: \"CONFIRMED\",\n refid: randomUUID(),\n })),\n );\n\n const bookingQuote: Record<string, unknown> = {\n tickets,\n activityId: input.activityId,\n availabilityTimeId: input.availabilityTimeId,\n refid: randomUUID(),\n skipCustomerEmail: input.skipCustomerEmail ?? false,\n guest: {\n name: input.guest.name,\n email: input.guest.email ?? null,\n phone: input.guest.phone ?? null,\n optinMarketing: input.guest.optinMarketing ?? false,\n optinSms: input.guest.optinSms ?? false,\n postalCode: input.guest.postalCode ?? null,\n country: input.guest.country ?? null,\n },\n };\n if (input.operatorNotes) {\n bookingQuote.operatorNotes = input.operatorNotes;\n }\n\n const quoteInput: Record<string, unknown> = { bookingQuotes: [bookingQuote] };\n if (input.parentOrderId) {\n quoteInput.source = { clonedFromId: input.parentOrderId };\n }\n\n // Step 1 — create the quote.\n const quoteBody: GraphQLBody<CreateQuoteV2Response> =\n await this.client.request<CreateQuoteV2Response>(SALES_ENDPOINT, CREATE_QUOTE_V2_MUTATION, {\n input: { quoteInput },\n });\n const quoteResult = quoteBody.data?.createQuoteV2;\n if ((quoteResult?.errors && quoteResult.errors.length > 0) || !quoteResult?.quote?.id) {\n throw new Error(\"Failed to create quote\");\n }\n const quoteId = quoteResult.quote.id;\n\n // Step 2 — create the order from the quote.\n const orderBody: GraphQLBody<CreateOrderFromQuoteResponse> =\n await this.client.request<CreateOrderFromQuoteResponse>(\n SALES_ENDPOINT,\n CREATE_ORDER_FROM_QUOTE_MUTATION,\n { input: { quoteId } },\n );\n const orderResult = orderBody.data?.createOrderFromQuote;\n if (orderResult?.errors && orderResult.errors.length > 0) {\n throw new Error(\"Failed to create order from quote\");\n }\n const order = orderResult?.order;\n const sale = order?.sales?.[0];\n if (!order || !sale) {\n throw new Error(\"Order created but no sales found\");\n }\n\n const created: CreatedBooking = {\n orderId: order.id,\n bookingId: sale.id,\n displayId: sale.displayId,\n balanceAmount: sale.balance?.total?.amount ?? \"0.00\",\n balanceCurrency: sale.balance?.total?.currency ?? \"USD\",\n balanceFormatted: sale.balance?.total?.formatted ?? \"$0.00\",\n };\n\n // Step 3 — optionally mark the booking paid.\n if (input.markAsPaid) {\n created.transactionId = await this.markCreatedBookingPaid(created, input);\n }\n\n return created;\n }\n\n private async markCreatedBookingPaid(\n booking: CreatedBooking,\n input: CreateBookingInput,\n ): Promise<string> {\n const parsedPartial = input.markAsPaidAmount ? parseFloat(input.markAsPaidAmount) : NaN;\n const amount =\n !Number.isNaN(parsedPartial) && parsedPartial > 0\n ? parsedPartial.toFixed(2)\n : booking.balanceAmount;\n\n const body: GraphQLBody<ApplyPaymentToOrderResponse> =\n await this.client.request<ApplyPaymentToOrderResponse>(\n SALES_ENDPOINT,\n APPLY_PAYMENT_TO_ORDER_MUTATION,\n {\n input: {\n amount: { amount, currency: booking.balanceCurrency },\n orderId: booking.orderId,\n paymentSourceId: \"custom/other\",\n idempotencyKey: input.idempotencyKey,\n customerMessage: \"Marked as paid\",\n scopedTo: [booking.bookingId],\n },\n },\n );\n\n const result = body.data?.applyPaymentToOrder;\n if ((result?.errors && result.errors.length > 0) || !result?.transactionId) {\n throw new Error(\"Failed to mark booking as paid\");\n }\n return result.transactionId;\n }\n\n /** Finds the parent item id of an add-on by matching its option id. */\n private async resolveParentItemId(addonOptionId: string): Promise<string> {\n const products = await this.deps.productService.getAllProducts();\n const matched = products.find(\n (product) =>\n product.type === ADD_ON_PRODUCT_TYPE &&\n product.tickets.some((ticket) => ticket.id === addonOptionId),\n );\n if (!matched) {\n throw new Error(\"Add-on not found for the provided addonOptionId\");\n }\n return matched.productId;\n }\n\n private validatePaymentInput(input: MakePaymentInput, normalizedBookingId: string): void {\n if (\n !input.paymentSourceId ||\n (!input.paymentSourceId.startsWith(PAYMENT_SOURCE_PREFIX) &&\n !ALLOWED_PAYMENT_SOURCE_IDS.includes(input.paymentSourceId))\n ) {\n throw new Error(\n \"paymentSourceId is required and must start with 'ps_' or be one of \" +\n \"'cash/cash', 'custom/other', 'custom/voucher'\",\n );\n }\n assertAmount(input.amount);\n assertCurrency(input.currency);\n assertIdempotencyKey(input.idempotencyKey);\n assertBookingId(normalizedBookingId);\n }\n\n private validateRefundInput(input: RefundInput, normalizedBookingId: string): void {\n if (!input.paymentId || !input.paymentId.startsWith(PAYMENT_ID_PREFIX)) {\n throw new Error(\"paymentId is required and must start with 'pmt_'\");\n }\n assertAmount(input.amount);\n assertCurrency(input.currency);\n assertIdempotencyKey(input.idempotencyKey);\n assertBookingId(normalizedBookingId);\n }\n\n private async fetchPaginated(\n query: string,\n baseParams: {\n startDateTime?: string;\n endDateTime?: string;\n timeslotId?: string;\n searchBy?: BookingTimeRangeSearch[\"searchBy\"];\n productId?: string;\n email?: string;\n searchString?: string;\n },\n includeGuests: boolean,\n includePriceBreakdown: boolean,\n ): Promise<Booking[]> {\n const bookings: Booking[] = [];\n let after: string | null = null;\n\n for (;;) {\n const body: GraphQLBody<BookingsResponse> =\n await this.client.request<BookingsResponse>(\n SALES_ENDPOINT,\n query,\n buildBookingsVariables({ ...baseParams, pageSize: this.pageSize, after }),\n );\n\n const sales = body.data?.sales;\n for (const edge of sales?.edges ?? []) {\n bookings.push(fromBookingNode(edge.node, includeGuests, includePriceBreakdown));\n }\n\n const pageInfo = sales?.pageInfo;\n if (pageInfo?.hasNextPage && pageInfo.endCursor) {\n after = pageInfo.endCursor;\n } else {\n break;\n }\n }\n\n return bookings;\n }\n}\n\nfunction assertAmount(amount: string): void {\n if (!amount || Number.isNaN(Number(amount))) {\n throw new Error(\"amount is required and must be a valid number\");\n }\n}\n\nfunction assertCurrency(currency: string): void {\n if (!currency || !CURRENCY_CODE_REGEX.test(currency)) {\n throw new Error(\"currency is required and must be a 3-letter uppercase code\");\n }\n}\n\nfunction assertIdempotencyKey(idempotencyKey: string): void {\n if (!idempotencyKey) {\n throw new Error(\"idempotencyKey is required\");\n }\n}\n\nfunction assertBookingId(normalizedBookingId: string): void {\n if (!normalizedBookingId.startsWith(BOOKING_ID_PREFIX)) {\n throw new Error(\"bookingId is required and must start with 'b_' or 'B-'\");\n }\n}\n\nfunction validateCreateInput(input: CreateBookingInput): void {\n if (!input.activityId) throw new Error(\"activityId is required\");\n if (!input.availabilityTimeId) throw new Error(\"availabilityTimeId is required\");\n if (!input.tickets || input.tickets.length === 0) {\n throw new Error(\"at least one ticket is required\");\n }\n if (input.tickets.some((ticket) => !ticket.resourceOptionId || !(ticket.quantity > 0))) {\n throw new Error(\"each ticket requires a resourceOptionId and a positive quantity\");\n }\n if (!input.guest || !input.guest.name) {\n throw new Error(\"guest name is required\");\n }\n if (input.markAsPaid && !input.idempotencyKey) {\n throw new Error(\"idempotencyKey is required when markAsPaid is set\");\n }\n}\n\nfunction parseQuantity(value: unknown): number | null {\n if (typeof value !== \"string\" && typeof value !== \"number\") {\n return null;\n }\n const str = String(value).trim();\n if (!/^\\d+$/.test(str)) {\n return null;\n }\n const num = parseInt(str, 10);\n if (!Number.isFinite(num) || num <= 0) {\n return null;\n }\n return num;\n}\n\n/**\n * Builds the `bookingQuotes` cancellation payload for `updateQuoteV2`. Selects\n * up to `quantity` options across the booking where the item and the option are\n * both still `CONFIRMED` and `optionId === addonOptionId`, grouped by booking\n * item. Each selected option becomes a CANCELED itemOptions entry (by its\n * `optionRefid`); the parent add-on is marked CANCELED only when every one of\n * its options ends up canceled.\n */\nfunction buildCancellation(\n items: AddonItem[],\n addonOptionId: string,\n quantity: number,\n): { bookingQuotes: Array<Record<string, unknown>>; canceledCount: number } {\n let budget = quantity;\n // bookingQuoteRefid -> (itemRefid -> { item, canceledOptionRefids })\n const byBookingQuote = new Map<\n string,\n Map<string, { item: AddonItem; canceledOptionRefids: string[] }>\n >();\n\n for (const item of items) {\n if (budget <= 0) break;\n for (const opt of item.addonItemOptions) {\n if (budget <= 0) break;\n // Only cancel options that are themselves still confirmed — an item can\n // hold a mix of already-canceled and confirmed options for the same\n // optionId, and we must skip the canceled ones.\n if (\n opt.itemReservationStatus !== RESERVATION_STATUS_CONFIRMED ||\n opt.optionReservationStatus !== RESERVATION_STATUS_CONFIRMED ||\n opt.optionId !== addonOptionId\n ) {\n continue;\n }\n\n let itemMap = byBookingQuote.get(item.bookingQuoteRefid);\n if (!itemMap) {\n itemMap = new Map();\n byBookingQuote.set(item.bookingQuoteRefid, itemMap);\n }\n let entry = itemMap.get(opt.itemRefid);\n if (!entry) {\n entry = { item, canceledOptionRefids: [] };\n itemMap.set(opt.itemRefid, entry);\n }\n entry.canceledOptionRefids.push(opt.optionRefid);\n budget -= 1;\n }\n }\n\n const canceledCount = quantity - budget;\n\n const bookingQuotes = Array.from(byBookingQuote.entries()).map(\n ([bookingQuoteRefid, itemMap]) => ({\n refid: bookingQuoteRefid,\n addons: Array.from(itemMap.entries()).map(\n ([itemRefid, { item, canceledOptionRefids }]) => {\n const canceledSet = new Set(canceledOptionRefids);\n const itemOptions = canceledOptionRefids.map((refid) => ({\n reservationStatus: ADDON_OPTION_STATUS_CANCELED,\n refid,\n }));\n\n // Mark the add-on canceled only if every option ends up canceled.\n const allCanceled = item.addonItemOptions.every(\n (o) =>\n o.optionReservationStatus === ADDON_OPTION_STATUS_CANCELED ||\n canceledSet.has(o.optionRefid),\n );\n\n const addon: Record<string, unknown> = { itemOptions, refid: itemRefid };\n if (allCanceled) {\n addon.reservationStatus = ADDON_OPTION_STATUS_CANCELED;\n }\n return addon;\n },\n ),\n }),\n );\n\n return { bookingQuotes, canceledCount };\n}\n","/**\n * Pure functions resolving the daily-note GraphQL unions into the clean\n * {@link DailyNote} model. A not-found / missing note maps to `null`.\n */\nimport type { DailyNote } from \"../../models/daily-note.js\";\nimport type {\n DailyNoteResponse,\n UpsertDailyNoteResponse,\n} from \"./daily-note-queries.js\";\n\n/** Resolves a daily-note query response into a {@link DailyNote}, or null. */\nexport function toDailyNote(\n response: DailyNoteResponse | undefined,\n): DailyNote | null {\n const union = response?.dailyNote;\n if (!union) {\n return null;\n }\n // Success branch carries a nested `dailyNote`; the not-found branch carries `message`.\n if (\"dailyNote\" in union) {\n return cleanNote(union.dailyNote);\n }\n return null;\n}\n\n/** Resolves an upsert response into the saved {@link DailyNote}, or null. */\nexport function fromUpsertResponse(\n response: UpsertDailyNoteResponse | undefined,\n): DailyNote | null {\n return cleanNote(response?.upsertDailyNote?.dailyNote);\n}\n\nfunction cleanNote(note: DailyNote | null | undefined): DailyNote | null {\n if (!note || typeof note.note !== \"string\") {\n return null;\n }\n return { note: note.note };\n}\n","/**\n * Raw Peek GraphQL query/mutation and response shapes for the daily note.\n * Internal.\n */\nimport type { DailyNote } from \"../../models/daily-note.js\";\n\n/** The global-note type for the dashboard daily note. */\nexport const GLOBAL_NOTE_TYPE = \"DASHBOARD\";\n\n/** Fetches today's daily note. */\nexport const DAILY_NOTE_TODAY_QUERY = `\n query dailyNote($type: GlobalNoteType!) {\n dailyNote(type: $type) {\n ... on DailyNoteSuccess {\n dailyNote {\n note\n }\n }\n ... on NotFoundError {\n message\n }\n }\n }\n`;\n\n/** Upserts the daily note. */\nexport const UPSERT_DAILY_NOTE_MUTATION = `\n mutation Account($input: UpsertDailyNoteInput!) {\n upsertDailyNote(input: $input) {\n ... on UpsertDailyNoteSuccess {\n dailyNote {\n note\n }\n }\n }\n }\n`;\n\n/** `data` payload of {@link DAILY_NOTE_TODAY_QUERY} (a success/not-found union). */\nexport interface DailyNoteResponse {\n dailyNote: { dailyNote: DailyNote | null } | { message: string };\n}\n\n/** `data` payload of {@link UPSERT_DAILY_NOTE_MUTATION}. */\nexport interface UpsertDailyNoteResponse {\n upsertDailyNote: { dailyNote: DailyNote | null };\n}\n\n/** Builds the variables for {@link UPSERT_DAILY_NOTE_MUTATION}. */\nexport function buildUpsertDailyNoteVariables(note: string): {\n input: { type: string; note: string };\n} {\n return { input: { type: GLOBAL_NOTE_TYPE, note } };\n}\n","/**\n * Daily-note operations against the Peek gateway.\n *\n * Obtain an instance via {@link PeekAccessService.getDailyNoteService}.\n */\nimport { SALES_ENDPOINT } from \"../gateway-endpoints.js\";\nimport type { GraphQLBody, GraphQLClient } from \"../graphql-client.js\";\nimport type { DailyNote } from \"../../models/daily-note.js\";\nimport { fromUpsertResponse, toDailyNote } from \"./daily-note-converter.js\";\nimport {\n DAILY_NOTE_TODAY_QUERY,\n GLOBAL_NOTE_TYPE,\n UPSERT_DAILY_NOTE_MUTATION,\n buildUpsertDailyNoteVariables,\n type DailyNoteResponse,\n type UpsertDailyNoteResponse,\n} from \"./daily-note-queries.js\";\n\nexport class DailyNoteService {\n constructor(private readonly client: GraphQLClient) {}\n\n /** Returns today's daily note, or null when none is set. */\n async getToday(): Promise<DailyNote | null> {\n const body: GraphQLBody<DailyNoteResponse> =\n await this.client.request<DailyNoteResponse>(SALES_ENDPOINT, DAILY_NOTE_TODAY_QUERY, {\n type: GLOBAL_NOTE_TYPE,\n });\n return toDailyNote(body.data);\n }\n\n /** Upserts the daily note and returns the saved note, or null. */\n async update(note: string): Promise<DailyNote | null> {\n const body: GraphQLBody<UpsertDailyNoteResponse> =\n await this.client.request<UpsertDailyNoteResponse>(\n SALES_ENDPOINT,\n UPSERT_DAILY_NOTE_MUTATION,\n buildUpsertDailyNoteVariables(note),\n );\n return fromUpsertResponse(body.data);\n }\n}\n","/**\n * Typed errors thrown by the package. Each mirrors a failure mode of the Peek\n * GraphQL gateway so callers can branch on the error type rather than parsing\n * messages.\n */\n\n/**\n * Thrown when the gateway responds with HTTP 418, indicating the install is not\n * permitted to perform the request because an admin account is required.\n */\nexport class AdminAccountRequiredError extends Error {\n /** The HTTP status that triggered this error. */\n public readonly statusCode = 418;\n\n constructor(message = \"Admin account required\") {\n super(message);\n this.name = \"AdminAccountRequiredError\";\n }\n}\n\n/**\n * Thrown when the gateway responds with HTTP 429 and all configured retries\n * have been exhausted.\n */\nexport class RateLimitError extends Error {\n /** The HTTP status that triggered this error. */\n public readonly statusCode = 429;\n\n constructor(message = \"Rate limit exceeded\") {\n super(message);\n this.name = \"RateLimitError\";\n }\n}\n\n/**\n * Thrown when a GraphQL response contains an `errors` array. The raw errors are\n * preserved on {@link PeekGraphQLError.graphqlErrors} for inspection.\n */\nexport class PeekGraphQLError extends Error {\n /** The raw `errors` array returned by the GraphQL endpoint. */\n public readonly graphqlErrors: unknown[];\n\n constructor(graphqlErrors: unknown[], message = \"GraphQL request failed\") {\n super(message);\n this.name = \"PeekGraphQLError\";\n this.graphqlErrors = graphqlErrors;\n }\n}\n","/**\n * Thin GraphQL-over-HTTP transport built on the global `fetch`. Handles\n * endpoint construction, auth headers, query whitespace collapsing, HTTP 429\n * retry/backoff, and mapping known failure modes to typed errors.\n */\nimport {\n AdminAccountRequiredError,\n PeekGraphQLError,\n RateLimitError,\n} from \"../errors.js\";\nimport type { Logger } from \"../logger.js\";\n\nconst RATE_LIMIT_STATUS = 429;\nconst ADMIN_ACCOUNT_REQUIRED_STATUS = 418;\n\n/** The raw body of a GraphQL HTTP response. */\nexport interface GraphQLBody<T> {\n data?: T;\n errors?: unknown[];\n}\n\nexport interface GraphQLClientOptions {\n /** Base URL of the backoffice GraphQL gateway (no trailing slash). */\n baseUrl: string;\n /** Peek app ID, used in the endpoint path. */\n appId: string;\n /** API gateway key sent as the `pk-api-key` header. */\n gatewayKey: string;\n /** Supplies a valid bearer token for each request. */\n getToken: () => string;\n /** Backoff delays (ms) applied on successive HTTP 429 responses. */\n retryDelaysMs: number[];\n /** Diagnostics sink. */\n logger: Logger;\n /** `fetch` implementation to use. */\n fetchFn: typeof fetch;\n}\n\nconst sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\nexport class GraphQLClient {\n constructor(private readonly options: GraphQLClientOptions) {}\n\n /**\n * Executes a GraphQL query against the named endpoint and returns the raw\n * response body. Retries on HTTP 429 per the configured backoff.\n */\n async request<T>(\n endpointName: string,\n query: string,\n variables: object,\n ): Promise<GraphQLBody<T>> {\n const { retryDelaysMs, logger, fetchFn } = this.options;\n const url = this.endpoint(endpointName);\n const collapsedQuery = query.replace(/\\s+/g, \" \").trim();\n\n logger.info(\"Making GraphQL request\", { url, endpointName });\n\n for (let attempt = 0; attempt <= retryDelaysMs.length; attempt++) {\n const response = await fetchFn(url, {\n method: \"POST\",\n headers: this.buildHeaders(),\n body: JSON.stringify({ query: collapsedQuery, variables }),\n });\n\n if (response.status === ADMIN_ACCOUNT_REQUIRED_STATUS) {\n logger.warn(`Admin account required for ${endpointName} (HTTP 418)`, { url });\n throw new AdminAccountRequiredError();\n }\n\n if (response.status === RATE_LIMIT_STATUS) {\n const delay = retryDelaysMs[attempt];\n if (delay !== undefined) {\n logger.warn(\n `Rate limited on ${endpointName}, retrying in ${delay}ms ` +\n `(attempt ${attempt + 1}/${retryDelaysMs.length})`,\n );\n await sleep(delay);\n continue;\n }\n logger.error(`Rate limit exceeded for ${endpointName}`, { url });\n throw new RateLimitError();\n }\n\n const body = (await response.json()) as GraphQLBody<T>;\n\n if (body.errors) {\n logger.error(`GraphQL errors for ${endpointName}`, {\n url,\n graphqlErrors: JSON.stringify(body.errors),\n });\n throw new PeekGraphQLError(body.errors);\n }\n\n if (!response.ok) {\n logger.error(`GraphQL request failed with HTTP ${response.status}`, { url });\n throw new Error(`GraphQL request failed with HTTP ${response.status}`);\n }\n\n return body;\n }\n\n /* istanbul ignore next -- unreachable: the 429 branch always returns/throws */\n throw new RateLimitError();\n }\n\n private endpoint(endpointName: string): string {\n return `${this.options.baseUrl}/${this.options.appId}/${endpointName}`;\n }\n\n private buildHeaders(): Record<string, string> {\n return {\n \"X-Peek-Auth\": `Bearer ${this.options.getToken()}`,\n \"pk-api-key\": this.options.gatewayKey,\n \"Content-Type\": \"application/json\",\n };\n }\n}\n","/**\n * Pure function flattening raw membership nodes into the clean\n * {@link Membership} model — one record per variant.\n */\nimport type { Membership } from \"../../models/membership.js\";\nimport type { MembershipsResponse } from \"./membership-queries.js\";\n\n/** Flattens a memberships response into one {@link Membership} per variant. */\nexport function fromMembershipsResponse(\n response: MembershipsResponse | undefined,\n): Membership[] {\n return (response?.memberships ?? []).flatMap((membership) =>\n (membership.membershipVariants ?? []).map((variant) => ({\n id: membership.id,\n membershipVariantId: variant.id,\n description: variant.description ?? null,\n externalName: variant.externalName,\n imageUrl: variant.imageUrl ?? null,\n internalName: variant.internalName,\n displayName: membership.name,\n })),\n );\n}\n","/**\n * Raw Peek GraphQL query and response shape for memberships. Internal.\n */\n\n/** Fetches all memberships with their variants. */\nexport const MEMBERSHIPS_QUERY = `\n query Sales {\n memberships {\n name\n id\n membershipVariants {\n id\n description\n imageUrl\n externalName\n internalName\n }\n }\n }\n`;\n\n/** A single membership variant node. */\nexport interface MembershipVariantNode {\n id: string;\n description: string | null;\n imageUrl: string | null;\n externalName: string;\n internalName: string;\n}\n\n/** A single membership node as returned by {@link MEMBERSHIPS_QUERY}. */\nexport interface MembershipNode {\n name: string;\n id: string;\n membershipVariants: MembershipVariantNode[];\n}\n\n/** The `data` payload of {@link MEMBERSHIPS_QUERY}. */\nexport interface MembershipsResponse {\n memberships: MembershipNode[];\n}\n\n/** Creates a quote (used here to start a membership purchase). */\nexport const CREATE_QUOTE_V2_MUTATION = `\n mutation CreateQuoteV2($input: CreateQuoteV2Input!) {\n createQuoteV2(input: $input) {\n errors { detail value code }\n quote { id }\n }\n }\n`;\n\n/** Creates a membership order from a quote. */\nexport const CREATE_MEMBERSHIP_ORDER_FROM_QUOTE_MUTATION = `\n mutation CreateOrderFromQuote($input: CreateOrderFromQuoteInput!) {\n createOrderFromQuote(input: $input) {\n errors { code detail value }\n order {\n id\n sales {\n id\n displayId\n ... on SoldMembership {\n id\n displayId\n primaryMember { name id }\n balance { total { amount currency formatted } }\n }\n }\n }\n }\n }\n`;\n\n/** Member details attached to a membership quote. */\nexport interface MembershipMember {\n email: string;\n country?: string;\n formattedAddress?: string;\n membershipCode?: string;\n name?: string;\n phone?: string;\n}\n\ninterface MutationError {\n code: string;\n detail: string;\n value: string | null;\n}\n\n/** `data` payload of {@link CREATE_QUOTE_V2_MUTATION}. */\nexport interface CreateQuoteV2Response {\n createQuoteV2: { errors: MutationError[] | null; quote: { id: string } | null };\n}\n\n/** A sold membership returned by the order mutation. */\nexport interface SoldMembershipSale {\n id: string;\n displayId: string;\n primaryMember?: { id: string; name: string } | null;\n balance?: { total: { amount: string; currency: string; formatted: string } } | null;\n}\n\n/** `data` payload of {@link CREATE_MEMBERSHIP_ORDER_FROM_QUOTE_MUTATION}. */\nexport interface CreateMembershipOrderResponse {\n createOrderFromQuote: {\n errors: MutationError[] | null;\n order: { id: string; sales: SoldMembershipSale[] } | null;\n };\n}\n","/**\n * Membership operations against the Peek gateway.\n *\n * Obtain an instance via {@link PeekAccessService.getMembershipService}.\n */\nimport { randomUUID } from \"node:crypto\";\n\nimport { SALES_ENDPOINT } from \"../gateway-endpoints.js\";\nimport type { GraphQLBody, GraphQLClient } from \"../graphql-client.js\";\nimport type {\n Membership,\n MembershipPurchaseInput,\n PurchasedMembership,\n} from \"../../models/membership.js\";\nimport { fromMembershipsResponse } from \"./membership-converter.js\";\nimport {\n CREATE_MEMBERSHIP_ORDER_FROM_QUOTE_MUTATION,\n CREATE_QUOTE_V2_MUTATION,\n MEMBERSHIPS_QUERY,\n type CreateMembershipOrderResponse,\n type CreateQuoteV2Response,\n type MembershipMember,\n type MembershipsResponse,\n} from \"./membership-queries.js\";\n\nconst QUOTE_STATUS_CONFIRMED = \"CONFIRMED\";\nconst DEFAULT_BALANCE_AMOUNT = \"0.00\";\nconst DEFAULT_BALANCE_CURRENCY = \"USD\";\nconst DEFAULT_BALANCE_FORMATTED = \"$0.00\";\nconst EMAIL_REGEX = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst COUNTRY_REGEX = /^[A-Z]{2}$/i;\nconst PHONE_REGEX = /^[0-9+\\s()\\-.]+$/;\n\nexport class MembershipService {\n constructor(private readonly client: GraphQLClient) {}\n\n /** Returns all membership variants, flattened into {@link Membership} records. */\n async getAll(): Promise<Membership[]> {\n const body: GraphQLBody<MembershipsResponse> =\n await this.client.request<MembershipsResponse>(SALES_ENDPOINT, MEMBERSHIPS_QUERY, {});\n return fromMembershipsResponse(body.data);\n }\n\n /**\n * Purchases a membership via the two-step quote → order flow. Throws on\n * invalid input or when Peek returns errors.\n */\n async purchase(input: MembershipPurchaseInput): Promise<PurchasedMembership> {\n validatePurchaseInput(input);\n\n const quoteBody: GraphQLBody<CreateQuoteV2Response> =\n await this.client.request<CreateQuoteV2Response>(\n SALES_ENDPOINT,\n CREATE_QUOTE_V2_MUTATION,\n {\n input: {\n quoteInput: {\n membershipQuotes: [\n {\n member: buildMember(input),\n membershipVariantId: input.membershipVariantId,\n refid: randomUUID(),\n status: QUOTE_STATUS_CONFIRMED,\n },\n ],\n },\n },\n },\n );\n\n const quoteResult = quoteBody.data?.createQuoteV2;\n if (quoteResult?.errors && quoteResult.errors.length > 0) {\n throw new Error(`Failed to create membership quote: ${quoteResult.errors[0]!.detail}`);\n }\n const quoteId = quoteResult?.quote?.id;\n if (!quoteId) {\n throw new Error(\"Membership quote created but missing quote id\");\n }\n\n const orderBody: GraphQLBody<CreateMembershipOrderResponse> =\n await this.client.request<CreateMembershipOrderResponse>(\n SALES_ENDPOINT,\n CREATE_MEMBERSHIP_ORDER_FROM_QUOTE_MUTATION,\n { input: { quoteId } },\n );\n\n const orderResult = orderBody.data?.createOrderFromQuote;\n if (orderResult?.errors && orderResult.errors.length > 0) {\n throw new Error(`Failed to create membership order: ${orderResult.errors[0]!.detail}`);\n }\n\n const order = orderResult?.order;\n const sale = order?.sales?.[0];\n if (!order || !sale) {\n throw new Error(\"Membership order created but no sales found\");\n }\n\n return {\n orderId: order.id,\n membershipId: sale.id,\n displayId: sale.displayId,\n primaryMemberId: sale.primaryMember?.id ?? null,\n primaryMemberName: sale.primaryMember?.name ?? null,\n balanceAmount: sale.balance?.total?.amount ?? DEFAULT_BALANCE_AMOUNT,\n balanceCurrency: sale.balance?.total?.currency ?? DEFAULT_BALANCE_CURRENCY,\n balanceFormatted: sale.balance?.total?.formatted ?? DEFAULT_BALANCE_FORMATTED,\n };\n }\n}\n\n/** Builds the GraphQL member, including only non-empty optional fields. */\nfunction buildMember(input: MembershipPurchaseInput): MembershipMember {\n const member: MembershipMember = { email: input.email };\n if (input.country?.trim()) member.country = input.country;\n if (input.formattedAddress?.trim()) member.formattedAddress = input.formattedAddress;\n if (input.membershipCode?.trim()) member.membershipCode = input.membershipCode;\n if (input.name?.trim()) member.name = input.name;\n if (input.phone?.trim()) member.phone = input.phone;\n return member;\n}\n\nfunction validatePurchaseInput(input: MembershipPurchaseInput): void {\n const errors: string[] = [];\n\n if (!input.membershipVariantId || input.membershipVariantId.trim().length === 0) {\n errors.push(\"membershipVariantId is required\");\n }\n if (!input.email || input.email.trim().length === 0) {\n errors.push(\"email is required\");\n } else if (!EMAIL_REGEX.test(input.email)) {\n errors.push(\"email is invalid\");\n }\n if (input.country && !COUNTRY_REGEX.test(input.country)) {\n errors.push(\"country is invalid\");\n }\n if (input.phone && !PHONE_REGEX.test(input.phone)) {\n errors.push(\"phone is invalid\");\n }\n\n if (errors.length > 0) {\n throw new Error(errors.join(\", \"));\n }\n}\n","/**\n * Pure functions mapping raw channel nodes into the clean {@link Channel}\n * model, flattening the agents edge/node structure.\n */\nimport type { Channel } from \"../../models/channel.js\";\nimport type { ChannelNode, ChannelsResponse } from \"./channel-queries.js\";\n\n/** Converts a channels response into {@link Channel}s. */\nexport function fromChannelsResponse(\n response: ChannelsResponse | undefined,\n): Channel[] {\n return (response?.channels ?? []).map(fromChannelNode);\n}\n\nfunction fromChannelNode(node: ChannelNode): Channel {\n return {\n id: node.id,\n name: node.name,\n notes: node.notes,\n pricingModel: node.pricingModel,\n state: node.state,\n type: node.type,\n agents: (node.agents?.edges ?? []).map((edge) => ({\n email: edge.node.email,\n name: edge.node.name,\n internalNotes: edge.node.internalNotes,\n phone: edge.node.phone,\n })),\n };\n}\n","/**\n * Raw Peek GraphQL query and response shape for reseller channels. Internal.\n *\n * Channels themselves are returned in full; `$first` limits the number of\n * agents fetched per channel.\n */\n\n/** Fetches reseller channels with up to `$first` agents each. */\nexport const CHANNELS_QUERY = `\n query Sales($first: Int) {\n channels {\n id\n agents(first: $first) {\n edges {\n node {\n email\n name\n internalNotes\n phone\n }\n }\n }\n name\n notes\n state\n type\n pricingModel\n }\n }\n`;\n\n/** A single agent node. */\nexport interface AgentNode {\n email: string | null;\n name: string;\n internalNotes: string | null;\n phone: string | null;\n}\n\n/** A single channel node as returned by {@link CHANNELS_QUERY}. */\nexport interface ChannelNode {\n id: string;\n name: string;\n notes: string | null;\n pricingModel: string;\n state: string;\n type: string;\n agents: { edges: Array<{ node: AgentNode }> } | null;\n}\n\n/** The `data` payload of {@link CHANNELS_QUERY}. */\nexport interface ChannelsResponse {\n channels: ChannelNode[];\n}\n","/**\n * Reseller-channel operations against the Peek gateway.\n *\n * Obtain an instance via {@link PeekAccessService.getResellerService}.\n */\nimport { SALES_ENDPOINT } from \"../gateway-endpoints.js\";\nimport type { GraphQLBody, GraphQLClient } from \"../graphql-client.js\";\nimport type { Channel } from \"../../models/channel.js\";\nimport { fromChannelsResponse } from \"./channel-converter.js\";\nimport { CHANNELS_QUERY, type ChannelsResponse } from \"./channel-queries.js\";\n\n/** Default number of agents fetched per channel. */\nconst DEFAULT_AGENTS_PER_CHANNEL = 10;\n\nexport class ResellerService {\n constructor(private readonly client: GraphQLClient) {}\n\n /**\n * Returns all reseller channels, each with up to `agentsPerChannel` agents\n * (default 10).\n */\n async getAllChannels(\n agentsPerChannel: number = DEFAULT_AGENTS_PER_CHANNEL,\n ): Promise<Channel[]> {\n const body: GraphQLBody<ChannelsResponse> =\n await this.client.request<ChannelsResponse>(SALES_ENDPOINT, CHANNELS_QUERY, {\n first: agentsPerChannel,\n });\n return fromChannelsResponse(body.data);\n }\n}\n","/**\n * Pure functions mapping raw resource-pool nodes into the clean\n * {@link ResourcePool} model.\n */\nimport type {\n ResourcePool,\n ResourcePoolAccountUser,\n} from \"../../models/resource-pool.js\";\nimport type {\n ResourcePoolNode,\n ResourcePoolsResponse,\n} from \"./resource-pool-queries.js\";\n\n/** Converts a resource-pools response into {@link ResourcePool}s. */\nexport function fromResourcePoolsResponse(\n response: ResourcePoolsResponse | undefined,\n): ResourcePool[] {\n return (response?.resourcePools ?? []).map(fromResourcePoolNode);\n}\n\nfunction fromResourcePoolNode(pool: ResourcePoolNode): ResourcePool {\n return {\n id: pool.id || \"\",\n name: pool.name || \"\",\n imageUrl: pool.imageUrl ?? null,\n mode: pool.mode || \"\",\n colorHex: pool.colorHex ?? null,\n quantity: pool.quantity ?? null,\n category: pool.category || \"\",\n capacity: pool.capacity ?? null,\n resourceTrackingMode: pool.resourceTrackingMode ?? null,\n accountUser: fromAccountUser(pool.accountUser),\n };\n}\n\nfunction fromAccountUser(\n accountUser: { id: string; name: string } | null | undefined,\n): ResourcePoolAccountUser | null {\n if (!accountUser) {\n return null;\n }\n return {\n id: accountUser.id || \"\",\n name: accountUser.name || \"\",\n };\n}\n","/**\n * Raw Peek GraphQL query and response shape for resource pools. Internal.\n */\n\n/** Fetches resource pools matching a mode filter. */\nexport const RESOURCE_POOLS_QUERY = `\n query Sales($filter: ResourcePoolsFilter) {\n resourcePools(filter: $filter) {\n id\n name\n imageUrl\n mode\n colorHex\n quantity\n category\n capacity\n resourceTrackingMode\n accountUser {\n id\n name\n }\n }\n }\n`;\n\n/** A single resource-pool node as returned by {@link RESOURCE_POOLS_QUERY}. */\nexport interface ResourcePoolNode {\n id: string;\n name: string;\n imageUrl: string | null;\n mode: string;\n colorHex: string | null;\n quantity: number | null;\n category: string;\n capacity: number | null;\n resourceTrackingMode: string | null;\n accountUser: { id: string; name: string } | null;\n}\n\n/** The `data` payload of {@link RESOURCE_POOLS_QUERY}. */\nexport interface ResourcePoolsResponse {\n resourcePools: ResourcePoolNode[];\n}\n","/**\n * Resource-pool operations against the Peek gateway.\n *\n * Obtain an instance via {@link PeekAccessService.getResourcePoolService}.\n */\nimport { SALES_ENDPOINT } from \"../gateway-endpoints.js\";\nimport type { GraphQLBody, GraphQLClient } from \"../graphql-client.js\";\nimport type {\n ResourcePool,\n ResourcePoolMode,\n} from \"../../models/resource-pool.js\";\nimport { fromResourcePoolsResponse } from \"./resource-pool-converter.js\";\nimport {\n RESOURCE_POOLS_QUERY,\n type ResourcePoolsResponse,\n} from \"./resource-pool-queries.js\";\n\n/** Default mode filter (matches the connector). */\nconst DEFAULT_MODE: ResourcePoolMode = \"ALL\";\n\nexport class ResourcePoolService {\n constructor(private readonly client: GraphQLClient) {}\n\n /**\n * Returns all resource pools for the given mode filter (defaults to `\"ALL\"`).\n */\n async getAll(mode: ResourcePoolMode = DEFAULT_MODE): Promise<ResourcePool[]> {\n const body: GraphQLBody<ResourcePoolsResponse> =\n await this.client.request<ResourcePoolsResponse>(\n SALES_ENDPOINT,\n RESOURCE_POOLS_QUERY,\n { filter: { mode } },\n );\n return fromResourcePoolsResponse(body.data);\n }\n}\n","/**\n * Pure functions mapping raw timeslot nodes into the clean {@link Timeslot}\n * model.\n */\nimport type { AssignedResource, Timeslot } from \"../../models/timeslot.js\";\nimport type {\n TimeslotNode,\n TimeslotResourceAllocationNode,\n} from \"./timeslot-queries.js\";\n\n/** Converts a list of timeslot nodes for the given activity into {@link Timeslot}s. */\nexport function fromTimeslotNodes(\n nodes: Array<TimeslotNode | null>,\n productId: string,\n): Timeslot[] {\n if (!Array.isArray(nodes) || nodes.length === 0) {\n return [];\n }\n return nodes.map((node) => fromTimeslotNode(node, productId));\n}\n\n/** Converts a single timeslot node into a {@link Timeslot}. A missing node yields a zeroed timeslot. */\nexport function fromTimeslotNode(\n node: TimeslotNode | null | undefined,\n productId: string,\n): Timeslot {\n if (!node) {\n return {\n id: \"\",\n productId,\n totalCapacity: 0,\n availableCapacity: 0,\n maxPartySize: 0,\n bookingCount: 0,\n checkedInCount: 0,\n status: \"\",\n notes: null,\n durationMin: 0,\n date: \"\",\n startTime: null,\n assignedResources: [],\n };\n }\n\n return {\n id: node.id || \"\",\n productId,\n totalCapacity: node.totalCapacity ?? 0,\n availableCapacity: node.availableSpots ?? 0,\n maxPartySize: node.maxPartySize ?? 0,\n bookingCount: node.bookingCount ?? 0,\n checkedInCount: node.checkedInCount ?? 0,\n status: node.status || \"\",\n notes: node.manifestNotes ?? null,\n durationMin: node.minuteLength ?? 0,\n date: node.date || \"\",\n startTime: node.start ?? null,\n assignedResources: mapAssignedResources(node.resourceAllocations),\n };\n}\n\nfunction mapAssignedResources(\n allocations: TimeslotResourceAllocationNode[] | null | undefined,\n): AssignedResource[] {\n if (!Array.isArray(allocations) || allocations.length === 0) {\n return [];\n }\n\n return allocations.map((allocation) => {\n const pool = allocation.resourcePool;\n return {\n id: pool?.id || \"\",\n name: pool?.name || \"\",\n capacity: pool?.capacity ?? 0,\n category: pool?.category || \"\",\n quantity: allocation.quantity ?? 0,\n accountUserId: pool?.accountUser?.id ?? null,\n };\n });\n}\n","/**\n * Pure guide-matching logic: resolves a caller-supplied guide identifier to a\n * resource-pool id. A guide may be referenced by resource-pool id, by backing\n * account-user id, or by name (directly or via an account user).\n */\nimport type { ResourcePool } from \"../../models/resource-pool.js\";\n\n/**\n * Resolves a `guideId` to a resource-pool id using `guideResourcePools`\n * (resource pools already filtered to the guide category) and `accountUsers`.\n * Returns the matched pool id, or `null` when nothing matches.\n */\nexport function matchGuideToResourcePool(\n guideId: string,\n guideResourcePools: ResourcePool[],\n accountUsers: Array<{ id: string; name: string }>,\n): string | null {\n // Direct resource-pool id match.\n const directIdMatch = guideResourcePools.find((pool) => pool.id === guideId);\n if (directIdMatch) {\n return directIdMatch.id;\n }\n\n // Match by backing account-user id.\n const accountUserMatch = guideResourcePools.find(\n (pool) => pool.accountUser?.id === guideId,\n );\n if (accountUserMatch) {\n return accountUserMatch.id;\n }\n\n // Match by pool name.\n const nameMatch = guideResourcePools.find((pool) => pool.name === guideId);\n if (nameMatch) {\n return nameMatch.id;\n }\n\n // Resolve via an account user, then match its pool by id or name.\n const matchedUser = accountUsers.find((user) => user.id === guideId);\n if (matchedUser) {\n const userIdMatch = guideResourcePools.find(\n (pool) => pool.accountUser?.id === matchedUser.id,\n );\n /* v8 ignore next 3 -- unreachable: the earlier account-user id match already\n returns when a pool's accountUser.id equals the guideId; kept for source parity. */\n if (userIdMatch) {\n return userIdMatch.id;\n }\n\n const userNameMatch = guideResourcePools.find(\n (pool) => pool.name === matchedUser.name,\n );\n if (userNameMatch) {\n return userNameMatch.id;\n }\n }\n\n return null;\n}\n","/**\n * Raw Peek GraphQL mutation and shapes for bulk resource-allocation requests\n * (used by guide assignment). Internal.\n */\n\n/** Bulk-(un)assigns resources (e.g. guides) to timeslots. */\nexport const RESOURCE_ALLOCATION_BULK_REQUEST_MUTATION = `\n mutation ResourceAllocationBulkRequest($input: ResourceAllocationBulkRequestInput!) {\n resourceAllocationBulkRequest(input: $input) {\n __typename\n ... on ResourceAllocationRequest {\n id\n }\n ... on GenericError {\n __typename\n message\n }\n }\n }\n`;\n\n/** Allocation status: assigning (`ACTIVE`) or unassigning (`REMOVAL`). */\nexport type ResourceAllocationStatus = \"ACTIVE\" | \"REMOVAL\";\n\n/** `data` payload of {@link RESOURCE_ALLOCATION_BULK_REQUEST_MUTATION}. */\nexport interface ResourceAllocationBulkRequestResponse {\n resourceAllocationBulkRequest:\n | { __typename: \"ResourceAllocationRequest\"; id: string }\n | { __typename: \"GenericError\"; message: string };\n}\n\n/** Builds the variables for {@link RESOURCE_ALLOCATION_BULK_REQUEST_MUTATION}. */\nexport function buildResourceAllocationVariables(\n timeslotIds: string[],\n resourcePoolIds: string[],\n status: ResourceAllocationStatus,\n): { input: { timeslotIds: string[]; resourcePoolIds: string[]; status: ResourceAllocationStatus } } {\n return { input: { timeslotIds, resourcePoolIds, status } };\n}\n","/**\n * Raw Peek GraphQL queries/mutations and response shapes for timeslots.\n * Internal.\n */\nimport type { TimeslotFilter } from \"../../models/timeslot.js\";\n\n/** Fetches timeslots for an activity/date via a filter. */\nexport const TIMESLOTS_QUERY = `\n query Sales($params: TimeslotsFilter!) {\n timeslots(filter: $params) {\n ... on TimeslotsSuccess {\n timeslots {\n id\n bookingCount\n availableSpots\n maxPartySize\n totalCapacity\n checkedInCount\n manifestNotes\n minuteLength\n status\n date\n resourceAllocations {\n quantity\n resourcePool {\n id\n name\n category\n capacity\n accountUser {\n id\n }\n }\n }\n ... on VariableTimeslot {\n start\n }\n ... on FixedTimeslot {\n start\n }\n }\n }\n }\n }\n`;\n\n/** Fetches a single timeslot by id. */\nexport const TIMESLOT_BY_ID_QUERY = `\n query Sales($id: ID!) {\n timeslot(id: $id) {\n ... on ActivityTimeslotSuccess {\n timeslot {\n id\n bookingCount\n availableSpots\n maxPartySize\n totalCapacity\n checkedInCount\n manifestNotes\n minuteLength\n status\n date\n resourceAllocations {\n quantity\n resourcePool {\n id\n name\n category\n capacity\n accountUser {\n id\n }\n }\n }\n ... on VariableTimeslot {\n start\n }\n ... on FixedTimeslot {\n start\n }\n }\n }\n }\n }\n`;\n\n/** Updates a timeslot's manifest notes and/or status. */\nexport const UPDATE_TIMESLOT_MUTATION = `\n mutation Account($input: UpdateTimeslotInput!) {\n updateTimeslot(input: $input) {\n ... on UpdateTimeslotSuccess {\n timeslot {\n id\n manifestNotes\n status\n }\n }\n }\n }\n`;\n\n/** A single resource allocation on a timeslot node. */\nexport interface TimeslotResourceAllocationNode {\n quantity: number | null;\n resourcePool: {\n id: string;\n name: string;\n category: string;\n capacity: number | null;\n accountUser: { id: string } | null;\n } | null;\n}\n\n/** A single timeslot node as returned by the timeslot queries. */\nexport interface TimeslotNode {\n id: string;\n bookingCount: number | null;\n availableSpots: number | null;\n maxPartySize: number | null;\n totalCapacity: number | null;\n checkedInCount: number | null;\n manifestNotes: string | null;\n minuteLength: number | null;\n status: string | null;\n date: string | null;\n start?: string | null;\n resourceAllocations: TimeslotResourceAllocationNode[] | null;\n}\n\n/** `data` payload of {@link TIMESLOTS_QUERY}. */\nexport interface TimeslotsResponse {\n timeslots: { timeslots: TimeslotNode[] };\n}\n\n/** `data` payload of {@link TIMESLOT_BY_ID_QUERY}. */\nexport interface SingleTimeslotResponse {\n timeslot: { timeslot: TimeslotNode | null } | null;\n}\n\n/** `data` payload of {@link UPDATE_TIMESLOT_MUTATION}. */\nexport interface UpdateTimeslotResponse {\n updateTimeslot: {\n timeslot: { id: string; manifestNotes: string | null; status: string | null };\n };\n}\n\n/** Input for {@link UPDATE_TIMESLOT_MUTATION}. */\nexport interface UpdateTimeslotInput {\n id: string;\n manifestNotes?: string;\n status?: string;\n}\n\n/** Builds the variables for {@link TIMESLOTS_QUERY}. */\nexport function buildTimeslotVariables(\n productId: string,\n date: string,\n filter: TimeslotFilter,\n): { params: { activityIds: string[]; dateRange: string; hasBookings?: boolean } } {\n const params: {\n activityIds: string[];\n dateRange: string;\n hasBookings?: boolean;\n } = {\n activityIds: [productId],\n dateRange: `[${date},${date}]`,\n };\n\n if (filter === \"withBookings\") {\n params.hasBookings = true;\n } else if (filter === \"withoutBookings\") {\n params.hasBookings = false;\n }\n\n return { params };\n}\n","/**\n * Timeslot operations against the Peek gateway.\n *\n * Obtain an instance via {@link PeekAccessService.getTimeslotService}. The\n * `assignGuide` operation composes the resource-pool and account-user services\n * to resolve guides before issuing the allocation request.\n */\nimport type { AccountUserService } from \"../account-users/account-user-service.js\";\nimport { SALES_ENDPOINT } from \"../gateway-endpoints.js\";\nimport type { GraphQLBody, GraphQLClient } from \"../graphql-client.js\";\nimport type { ResourcePoolService } from \"../resource-pools/resource-pool-service.js\";\nimport type {\n AssignGuideResult,\n GuideAssignment,\n Timeslot,\n TimeslotFilter,\n UpdateTimeslotResult,\n} from \"../../models/timeslot.js\";\nimport { fromTimeslotNode, fromTimeslotNodes } from \"./timeslot-converter.js\";\nimport { matchGuideToResourcePool } from \"./guide-matcher.js\";\nimport {\n RESOURCE_ALLOCATION_BULK_REQUEST_MUTATION,\n buildResourceAllocationVariables,\n type ResourceAllocationBulkRequestResponse,\n type ResourceAllocationStatus,\n} from \"./resource-allocation-queries.js\";\nimport {\n TIMESLOTS_QUERY,\n TIMESLOT_BY_ID_QUERY,\n UPDATE_TIMESLOT_MUTATION,\n buildTimeslotVariables,\n type SingleTimeslotResponse,\n type TimeslotsResponse,\n type UpdateTimeslotInput,\n type UpdateTimeslotResponse,\n} from \"./timeslot-queries.js\";\n\nconst GUIDE_CATEGORY = \"guide\";\nconst ERROR_MISSING_TIMESLOTS_OR_GUIDES =\n \"At least one timeslot and one guide are required\";\nconst ERROR_INVALID_ACTION = \"Invalid action. Must be either assign or unassign\";\nconst ERROR_GUIDE_NOT_FOUND = \"Guide not found\";\n\n/** Dependencies the {@link TimeslotService} composes for guide assignment. */\nexport interface TimeslotServiceDeps {\n resourcePoolService: ResourcePoolService;\n accountUserService: AccountUserService;\n}\n\nexport class TimeslotService {\n constructor(\n private readonly client: GraphQLClient,\n private readonly deps: TimeslotServiceDeps,\n ) {}\n\n /** Returns the timeslots for an activity on a given date. */\n async getForDay(\n productId: string,\n date: string,\n filter: TimeslotFilter = \"all\",\n ): Promise<Timeslot[]> {\n const normalizedDate = normalizeDate(date);\n const body: GraphQLBody<TimeslotsResponse> =\n await this.client.request<TimeslotsResponse>(\n SALES_ENDPOINT,\n TIMESLOTS_QUERY,\n buildTimeslotVariables(productId, normalizedDate, filter),\n );\n\n return fromTimeslotNodes(body.data?.timeslots?.timeslots ?? [], productId);\n }\n\n /** Returns a single timeslot by id, or null when not found. */\n async getById(timeslotId: string): Promise<Timeslot | null> {\n const body: GraphQLBody<SingleTimeslotResponse> =\n await this.client.request<SingleTimeslotResponse>(\n SALES_ENDPOINT,\n TIMESLOT_BY_ID_QUERY,\n { id: timeslotId },\n );\n\n const node = body.data?.timeslot?.timeslot;\n if (!node) {\n return null;\n }\n return fromTimeslotNode(node, extractProductId(timeslotId));\n }\n\n /** Sets the timeslot's status (e.g. open/closed). */\n async setAvailability(\n timeslotId: string,\n status: string,\n ): Promise<UpdateTimeslotResult> {\n return this.updateTimeslot({ id: timeslotId, status });\n }\n\n /** Sets the timeslot's manifest notes. */\n async setNotes(\n timeslotId: string,\n manifestNotes: string,\n ): Promise<UpdateTimeslotResult> {\n return this.updateTimeslot({ id: timeslotId, manifestNotes });\n }\n\n /**\n * Assigns or unassigns guides across timeslots. Guides are resolved to\n * resource pools (by pool id, account-user id, or name) before the bulk\n * allocation request is issued.\n *\n * @example\n * ```ts\n * await peek.getTimeslotService().assignGuide({\n * timeslotIds: [\"ts_2026_06_20_0900\"],\n * guideIds: [\"Alex Guide\"], // pool id, account-user id, or name\n * action: \"assign\",\n * });\n * ```\n */\n async assignGuide(assignment: GuideAssignment): Promise<AssignGuideResult> {\n const { timeslotIds, guideIds, action } = assignment;\n\n if (!timeslotIds?.length || !guideIds?.length) {\n throw new Error(ERROR_MISSING_TIMESLOTS_OR_GUIDES);\n }\n if (action !== \"assign\" && action !== \"unassign\") {\n throw new Error(ERROR_INVALID_ACTION);\n }\n\n const [allPools, accountUsers] = await Promise.all([\n this.deps.resourcePoolService.getAll(),\n this.deps.accountUserService.getAll(),\n ]);\n const guidePools = allPools.filter((pool) => pool.category === GUIDE_CATEGORY);\n\n const resourcePoolIds = guideIds.map((guideId) => {\n const matched = matchGuideToResourcePool(guideId, guidePools, accountUsers);\n if (!matched) {\n throw new Error(`${ERROR_GUIDE_NOT_FOUND}: ${guideId}`);\n }\n return matched;\n });\n\n const status: ResourceAllocationStatus =\n action === \"assign\" ? \"ACTIVE\" : \"REMOVAL\";\n\n const body: GraphQLBody<ResourceAllocationBulkRequestResponse> =\n await this.client.request<ResourceAllocationBulkRequestResponse>(\n SALES_ENDPOINT,\n RESOURCE_ALLOCATION_BULK_REQUEST_MUTATION,\n buildResourceAllocationVariables(timeslotIds, resourcePoolIds, status),\n );\n\n const result = body.data?.resourceAllocationBulkRequest;\n if (result?.__typename === \"ResourceAllocationRequest\") {\n return {\n status: \"success\",\n resourceAllocationRequestId: result.id,\n errors: null,\n };\n }\n\n return {\n status: \"error\",\n resourceAllocationRequestId: null,\n errors: [{ message: result?.message ?? \"Unknown error\" }],\n };\n }\n\n private async updateTimeslot(\n input: UpdateTimeslotInput,\n ): Promise<UpdateTimeslotResult> {\n const body: GraphQLBody<UpdateTimeslotResponse> =\n await this.client.request<UpdateTimeslotResponse>(\n SALES_ENDPOINT,\n UPDATE_TIMESLOT_MUTATION,\n { input },\n );\n\n const timeslot = body.data?.updateTimeslot?.timeslot;\n return {\n manifestNotes: timeslot?.manifestNotes ?? null,\n status: timeslot?.status ?? null,\n };\n }\n}\n\n/** Activity timeslot ids are `\"<activityId>|...\"`; the activity id is the product id. */\nfunction extractProductId(timeslotId: string): string {\n /* v8 ignore next -- split always yields at least one element */\n return timeslotId.split(\"|\")[0] ?? \"\";\n}\n\n/** Timeslot day queries expect a `YYYY-MM-DD` date; drop any time component. */\nfunction normalizeDate(date: string): string {\n /* v8 ignore next -- split always yields at least one element */\n return date.split(\"T\")[0] ?? date;\n}\n","/**\n * Pure functions that map raw Peek GraphQL nodes into the clean {@link Product}\n * model. No I/O — straightforward, testable transformations.\n */\nimport { ADD_ON_PRODUCT_TYPE, type Product } from \"../../models/product.js\";\nimport type { ActivityNode, ItemOptionNode } from \"./product-queries.js\";\n\n/** Default display color applied to add-on products. */\nconst ADD_ON_COLOR = \"#FFFFFF\";\n\n/** Converts the activities from a products response into {@link Product}s. */\nexport function fromActivities(activities: ActivityNode[]): Product[] {\n return activities.map(fromActivity);\n}\n\n/** Converts a single activity node into a {@link Product}. */\nfunction fromActivity(activity: ActivityNode): Product {\n return {\n // Prefer the primary GraphQL ID for stable product identity.\n productId: activity.id || activity.legacyId || \"\",\n name: activity.name,\n type: activity.type,\n color: activity.colorHex || \"\",\n tickets: (activity.resourceOptions ?? []).map((option) => ({\n id: option.id,\n name: option.name,\n })),\n };\n}\n\n/**\n * Converts a flat list of item option nodes into add-on {@link Product}s by\n * grouping each option under its parent item. The parent item id becomes the\n * `productId` and its name becomes the product `name`; each option becomes a\n * ticket.\n */\nexport function fromItemOptionNodes(nodes: ItemOptionNode[]): Product[] {\n const grouped = new Map<string, Product>();\n\n for (const node of nodes) {\n const itemId = node.item?.id;\n if (!itemId) continue;\n\n let product = grouped.get(itemId);\n if (!product) {\n product = {\n productId: itemId,\n name: node.item.name,\n type: ADD_ON_PRODUCT_TYPE,\n color: ADD_ON_COLOR,\n tickets: [],\n };\n grouped.set(itemId, product);\n }\n product.tickets.push({ id: node.id, name: node.name });\n }\n\n return Array.from(grouped.values());\n}\n","/**\n * Raw Peek GraphQL queries and response shapes for products. These are an\n * internal implementation detail of the package and are deliberately not\n * re-exported from the public entry point.\n */\n\n/** Fetches all activities (primary bookable products). */\nexport const PRODUCTS_QUERY = `\n query Sales {\n activities {\n name\n legacyId\n id\n deletedAt\n type\n colorHex\n resourceOptions {\n id\n name\n }\n }\n }\n`;\n\n/** A single activity node as returned by {@link PRODUCTS_QUERY}. */\nexport interface ActivityNode {\n name: string;\n legacyId?: string;\n id: string;\n deletedAt?: string | null;\n type: string;\n colorHex: string;\n resourceOptions: Array<{ id: string; name: string }>;\n}\n\n/** The `data` payload of {@link PRODUCTS_QUERY}. */\nexport interface ProductsResponse {\n activities: ActivityNode[];\n}\n\n/** Fetches a single cursor-paginated page of item options (add-ons). */\nexport const ITEM_OPTIONS_QUERY = `\n query GetItemOptions($first: Int, $after: String) {\n itemOptions(first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n name\n description\n item {\n id\n name\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n`;\n\n/** A single item option node as returned by {@link ITEM_OPTIONS_QUERY}. */\nexport interface ItemOptionNode {\n id: string;\n name: string;\n description: string | null;\n item: {\n id: string;\n name: string;\n };\n}\n\n/** The `data` payload of {@link ITEM_OPTIONS_QUERY}. */\nexport interface ItemOptionsData {\n itemOptions: {\n edges: Array<{ cursor: string; node: ItemOptionNode }>;\n pageInfo: {\n hasNextPage: boolean;\n endCursor: string | null;\n };\n };\n}\n","/**\n * Product-related operations against the Peek gateway.\n *\n * Obtain an instance via {@link PeekAccessService.getProductService} rather than\n * constructing it directly — the access service wires in the authenticated,\n * shared transport. This class is where product-specific business logic lives.\n */\nimport { SALES_ENDPOINT } from \"../gateway-endpoints.js\";\nimport type { GraphQLBody, GraphQLClient } from \"../graphql-client.js\";\nimport type { Product } from \"../../models/product.js\";\nimport { fromActivities, fromItemOptionNodes } from \"./product-converter.js\";\nimport {\n ITEM_OPTIONS_QUERY,\n PRODUCTS_QUERY,\n type ItemOptionNode,\n type ItemOptionsData,\n type ProductsResponse,\n} from \"./product-queries.js\";\n\n/** Default page size for cursor-paginated item options. */\nconst DEFAULT_ITEM_OPTIONS_PAGE_SIZE = 50;\n\n/** Tuning options for a {@link ProductService}. */\nexport interface ProductServiceOptions {\n /** Page size for cursor-paginated item options. Default: 50. */\n itemOptionsPageSize?: number;\n}\n\nexport class ProductService {\n private readonly itemOptionsPageSize: number;\n\n constructor(\n private readonly client: GraphQLClient,\n options: ProductServiceOptions = {},\n ) {\n this.itemOptionsPageSize =\n options.itemOptionsPageSize ?? DEFAULT_ITEM_OPTIONS_PAGE_SIZE;\n }\n\n /**\n * Returns every product as a single flat list: activities plus add-ons (the\n * latter tagged with the add-on type). Add-ons are gathered across all\n * cursor-paginated pages.\n *\n * @example Split activities from add-ons\n * ```ts\n * import { ADD_ON_PRODUCT_TYPE } from \"@peektravel/app-utilities\";\n *\n * const products = await peek.getProductService().getAllProducts();\n * const activities = products.filter((p) => p.type !== ADD_ON_PRODUCT_TYPE);\n * const addons = products.filter((p) => p.type === ADD_ON_PRODUCT_TYPE);\n * ```\n */\n async getAllProducts(): Promise<Product[]> {\n const [activities, itemOptionNodes] = await Promise.all([\n this.fetchActivities(),\n this.fetchAllItemOptionNodes(),\n ]);\n\n return [...fromActivities(activities), ...fromItemOptionNodes(itemOptionNodes)];\n }\n\n private async fetchActivities(): Promise<ProductsResponse[\"activities\"]> {\n const body: GraphQLBody<ProductsResponse> =\n await this.client.request<ProductsResponse>(\n SALES_ENDPOINT,\n PRODUCTS_QUERY,\n {},\n );\n return body.data?.activities ?? [];\n }\n\n private async fetchAllItemOptionNodes(): Promise<ItemOptionNode[]> {\n const all: ItemOptionNode[] = [];\n let after: string | null = null;\n\n for (;;) {\n const body: GraphQLBody<ItemOptionsData> =\n await this.client.request<ItemOptionsData>(\n SALES_ENDPOINT,\n ITEM_OPTIONS_QUERY,\n { first: this.itemOptionsPageSize, after },\n );\n\n const connection = body.data?.itemOptions;\n for (const edge of connection?.edges ?? []) {\n all.push(edge.node);\n }\n\n const pageInfo = connection?.pageInfo;\n if (pageInfo?.hasNextPage && pageInfo.endCursor) {\n after = pageInfo.endCursor;\n } else {\n break;\n }\n }\n\n return all;\n }\n}\n","/**\n * Raw Peek GraphQL query/mutation and response shapes for promo codes.\n * Internal. The promo-code node matches the public {@link PromoCode} model\n * one-to-one, so no converter is needed.\n */\nimport type { PromoCode } from \"../../models/promo-code.js\";\n\n/** Fetches a cursor-paginated page of promo codes. */\nexport const PROMO_CODES_QUERY = `\n query Sales($first: Int, $after: String) {\n promoCodes(first: $first, after: $after) {\n edges {\n node {\n id\n name\n percentAmount\n perTicketDiscount\n redemptionCode\n fixedAmount {\n amount\n currency\n formatted\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n`;\n\n/** Creates a promo code. Returns the new code's id/name or an InvalidDataError. */\nexport const CREATE_PROMO_CODE_MUTATION = `\n mutation Sales($input: CreatePromoCodeInput!) {\n createPromoCode(input: $input) {\n ... on InvalidDataError {\n message\n }\n ... on PromoCode {\n id\n name\n }\n }\n }\n`;\n\n/** `data` payload of {@link PROMO_CODES_QUERY}. */\nexport interface PromoCodesResponse {\n promoCodes: {\n edges: Array<{ node: PromoCode }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n}\n\n/** `data` payload of {@link CREATE_PROMO_CODE_MUTATION}. */\nexport interface CreatePromoCodeResponse {\n createPromoCode: { message: string } | { id: string; name: string };\n}\n\n/** Variables for {@link CREATE_PROMO_CODE_MUTATION}. */\nexport interface CreatePromoCodeVariables {\n input: {\n code: string;\n name: string;\n maxRedeemCount?: number;\n fixedAmount?: { amount: string; currency: string };\n percentAmount?: string;\n };\n}\n","/**\n * Promo-code operations against the Peek gateway.\n *\n * Obtain an instance via {@link PeekAccessService.getPromoCodeService}.\n */\nimport { SALES_ENDPOINT } from \"../gateway-endpoints.js\";\nimport type { GraphQLBody, GraphQLClient } from \"../graphql-client.js\";\nimport type {\n CreatePromoCodeInput,\n CreatedPromoCode,\n PromoCode,\n} from \"../../models/promo-code.js\";\nimport {\n CREATE_PROMO_CODE_MUTATION,\n PROMO_CODES_QUERY,\n type CreatePromoCodeResponse,\n type CreatePromoCodeVariables,\n type PromoCodesResponse,\n} from \"./promo-code-queries.js\";\n\n/** Default page size for cursor-paginated promo codes. */\nconst DEFAULT_PAGE_SIZE = 50;\n/** Default currency for fixed-amount discounts. */\nconst DEFAULT_CURRENCY = \"USD\";\n/** ISO currency codes are three uppercase letters. */\nconst CURRENCY_PATTERN = /^[A-Z]{3}$/;\n\n/** Tuning options for a {@link PromoCodeService}. */\nexport interface PromoCodeServiceOptions {\n /** Page size for cursor pagination. Default: 50. */\n pageSize?: number;\n}\n\nexport class PromoCodeService {\n private readonly pageSize: number;\n\n constructor(\n private readonly client: GraphQLClient,\n options: PromoCodeServiceOptions = {},\n ) {\n this.pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;\n }\n\n /** Returns all promo codes, walking the cursor pagination to the end. */\n async getAll(): Promise<PromoCode[]> {\n const all: PromoCode[] = [];\n let after: string | null = null;\n\n for (;;) {\n const body: GraphQLBody<PromoCodesResponse> =\n await this.client.request<PromoCodesResponse>(SALES_ENDPOINT, PROMO_CODES_QUERY, {\n first: this.pageSize,\n after,\n });\n\n const connection = body.data?.promoCodes;\n for (const edge of connection?.edges ?? []) {\n all.push(edge.node);\n }\n\n const pageInfo = connection?.pageInfo;\n if (pageInfo?.hasNextPage && pageInfo.endCursor) {\n after = pageInfo.endCursor;\n } else {\n break;\n }\n }\n\n return all;\n }\n\n /**\n * Creates a promo code. Throws on invalid input or when Peek returns an\n * InvalidDataError.\n */\n async create(input: CreatePromoCodeInput): Promise<CreatedPromoCode> {\n if (!input.name) throw new Error(\"name is required\");\n if (!input.code) throw new Error(\"code is required\");\n if (!input.amount) throw new Error(\"amount is required\");\n if (!input.discountType) throw new Error(\"discountType is required\");\n if (input.discountType !== \"percent\" && input.discountType !== \"fixed\") {\n throw new Error(\"discountType must be either 'percent' or 'fixed'\");\n }\n if (Number.isNaN(parseFloat(input.amount))) {\n throw new Error(\"amount must be a valid number\");\n }\n const currency = input.currency || DEFAULT_CURRENCY;\n if (!CURRENCY_PATTERN.test(currency)) {\n throw new Error(\"currency must be 3 uppercase letters\");\n }\n\n const variables: CreatePromoCodeVariables = {\n input: {\n code: input.code,\n name: input.name,\n maxRedeemCount: input.maxRedemptions\n ? parseInt(String(input.maxRedemptions), 10)\n : undefined,\n },\n };\n if (input.discountType === \"fixed\") {\n variables.input.fixedAmount = { amount: input.amount, currency };\n } else {\n variables.input.percentAmount = input.amount;\n }\n\n const body: GraphQLBody<CreatePromoCodeResponse> =\n await this.client.request<CreatePromoCodeResponse>(\n SALES_ENDPOINT,\n CREATE_PROMO_CODE_MUTATION,\n variables,\n );\n\n const result = body.data?.createPromoCode;\n if (result && \"message\" in result) {\n throw new Error(result.message);\n }\n if (!result) {\n throw new Error(\"createPromoCode returned no data\");\n }\n return { id: result.id, name: result.name };\n }\n}\n","/**\n * Mints and caches the short-lived JWT used to authenticate with the Peek\n * gateway. The token is signed on demand and reused until it nears expiry.\n */\nimport * as jwt from \"jsonwebtoken\";\n\nexport interface TokenManagerOptions {\n /** HMAC secret used to sign the JWT. */\n secret: string;\n /** JWT issuer (the app name). */\n issuer: string;\n /** JWT subject (the install ID). */\n installId: string;\n /** Token lifetime in seconds. */\n ttlSeconds: number;\n /** Re-mint the cached token this many seconds before its expiry. */\n leewaySeconds: number;\n}\n\nexport class TokenManager {\n private cached?: { token: string; expiresAtMs: number };\n\n constructor(private readonly options: TokenManagerOptions) {}\n\n /**\n * Returns a valid bearer token, reusing the cached one until it is within\n * `leewaySeconds` of expiring, at which point a fresh token is minted.\n */\n getToken(): string {\n const now = Date.now();\n if (this.cached && now < this.cached.expiresAtMs) {\n return this.cached.token;\n }\n\n const { secret, issuer, installId, ttlSeconds, leewaySeconds } = this.options;\n const token = jwt.sign({}, secret, {\n expiresIn: ttlSeconds,\n issuer,\n subject: installId,\n });\n\n this.cached = {\n token,\n expiresAtMs: now + (ttlSeconds - leewaySeconds) * 1000,\n };\n return token;\n }\n}\n","/**\n * Minimal structured logger interface the package can write diagnostics to.\n *\n * Consumers may supply their own implementation (e.g. wrapping an existing\n * application logger). When none is provided the package stays completely\n * silent via {@link noopLogger}.\n */\nexport interface Logger {\n info(message: string, context?: Record<string, unknown>): void;\n warn(message: string, context?: Record<string, unknown>): void;\n error(message: string, context?: Record<string, unknown>): void;\n}\n\n/** A {@link Logger} that discards everything. Used as the default. */\nexport const noopLogger: Logger = {\n info() {},\n warn() {},\n error() {},\n};\n","/**\n * Authenticated root entry point to the Peek backoffice GraphQL gateway.\n *\n * Configure one instance per install with everything needed to authenticate and\n * reach the gateway. The access service owns the shared, authenticated\n * transport (it mints and caches tokens on demand) and hands out per-resource\n * service objects — e.g. {@link PeekAccessService.getProductService} — that\n * carry the resource-specific business logic.\n */\nimport { AccountUserService } from \"./internal/account-users/account-user-service.js\";\nimport { AvailabilityService } from \"./internal/availability/availability-service.js\";\nimport { BookingService } from \"./internal/bookings/booking-service.js\";\nimport { DailyNoteService } from \"./internal/daily-notes/daily-note-service.js\";\nimport { GraphQLClient } from \"./internal/graphql-client.js\";\nimport { MembershipService } from \"./internal/memberships/membership-service.js\";\nimport { ResellerService } from \"./internal/resellers/reseller-service.js\";\nimport { ResourcePoolService } from \"./internal/resource-pools/resource-pool-service.js\";\nimport { TimeslotService } from \"./internal/timeslots/timeslot-service.js\";\nimport {\n ProductService,\n type ProductServiceOptions,\n} from \"./internal/products/product-service.js\";\nimport { PromoCodeService } from \"./internal/promo-codes/promo-code-service.js\";\nimport { TokenManager } from \"./internal/token-manager.js\";\nimport { noopLogger, type Logger } from \"./logger.js\";\n\n/** Default backoffice GraphQL gateway base URL. */\nconst DEFAULT_BASE_URL = \"https://apps.peekapis.com/backoffice-gql\";\n/** Default JWT lifetime (1 hour). */\nconst DEFAULT_TOKEN_TTL_SECONDS = 3600;\n/** Default leeway before expiry at which a cached token is re-minted. */\nconst DEFAULT_TOKEN_REFRESH_LEEWAY_SECONDS = 60;\n/** Default HTTP 429 retry backoff. */\nconst DEFAULT_RETRY_DELAYS_MS = [1000, 2000, 4000];\n\n/** Configuration for a {@link PeekAccessService} instance. */\nexport interface PeekAccessServiceConfig {\n /** Peek install ID. Becomes the JWT subject. */\n installId: string;\n /** HMAC secret used to sign the JWT (the Peek internal secret). */\n jwtSecret: string;\n /** JWT issuer — the app name. */\n issuer: string;\n /** Peek app ID, used in the gateway endpoint path. */\n appId: string;\n /** API gateway key, sent as the `pk-api-key` header. */\n gatewayKey: string;\n\n /** Override the gateway base URL. Default: Peek production gateway. */\n baseUrl?: string;\n /** JWT lifetime in seconds. Default: 3600. */\n tokenTtlSeconds?: number;\n /** Re-mint the cached token this many seconds before expiry. Default: 60. */\n tokenRefreshLeewaySeconds?: number;\n /** Backoff delays (ms) for HTTP 429 retries. Default: [1000, 2000, 4000]. */\n retryDelaysMs?: number[];\n /** Optional logger. Default: no-op (silent). */\n logger?: Logger;\n /** Custom `fetch` implementation. Default: the global `fetch`. */\n fetch?: typeof fetch;\n /** Page size for cursor-paginated item options. Default: 50. */\n itemOptionsPageSize?: number;\n}\n\n/**\n * Authenticated root entry point to the Peek backoffice GraphQL gateway.\n *\n * Construct one instance per install, then call the `get<Resource>Service()`\n * accessors to reach the resource-specific operations. Each accessor returns a\n * memoized service bound to the shared, authenticated transport — the access\n * service mints and caches a short-lived JWT on demand.\n *\n * @example Configure once, then call resource services\n * ```ts\n * import { PeekAccessService, type Product } from \"@peektravel/app-utilities\";\n *\n * const peek = new PeekAccessService({\n * installId: \"install-123\", // JWT subject\n * jwtSecret: process.env.PEEK_INTERNAL_SECRET!, // signs the JWT\n * issuer: process.env.APP_NAME!, // JWT issuer\n * appId: process.env.PEEK_APP_ID!, // gateway path segment\n * gatewayKey: process.env.PEEK_GATEWAY_KEY!, // pk-api-key header\n * });\n *\n * const products: Product[] = await peek.getProductService().getAllProducts();\n * const booking = await peek.getBookingService().getById(\"b_abc123\");\n * ```\n *\n * @throws {Error} from the constructor when any required config field\n * (`installId`, `jwtSecret`, `issuer`, `appId`, `gatewayKey`) is empty.\n */\nexport class PeekAccessService {\n private readonly client: GraphQLClient;\n private readonly productServiceOptions: ProductServiceOptions;\n private productService?: ProductService;\n private accountUserService?: AccountUserService;\n private resourcePoolService?: ResourcePoolService;\n private timeslotService?: TimeslotService;\n private resellerService?: ResellerService;\n private promoCodeService?: PromoCodeService;\n private dailyNoteService?: DailyNoteService;\n private availabilityService?: AvailabilityService;\n private membershipService?: MembershipService;\n private bookingService?: BookingService;\n\n constructor(config: PeekAccessServiceConfig) {\n requireNonEmpty(config.installId, \"installId\");\n requireNonEmpty(config.jwtSecret, \"jwtSecret\");\n requireNonEmpty(config.issuer, \"issuer\");\n requireNonEmpty(config.appId, \"appId\");\n requireNonEmpty(config.gatewayKey, \"gatewayKey\");\n\n const logger = config.logger ?? noopLogger;\n const tokens = new TokenManager({\n secret: config.jwtSecret,\n issuer: config.issuer,\n installId: config.installId,\n ttlSeconds: config.tokenTtlSeconds ?? DEFAULT_TOKEN_TTL_SECONDS,\n leewaySeconds:\n config.tokenRefreshLeewaySeconds ?? DEFAULT_TOKEN_REFRESH_LEEWAY_SECONDS,\n });\n\n this.client = new GraphQLClient({\n baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,\n appId: config.appId,\n gatewayKey: config.gatewayKey,\n getToken: () => tokens.getToken(),\n retryDelaysMs: config.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS,\n logger,\n fetchFn: config.fetch ?? globalThis.fetch,\n });\n\n this.productServiceOptions = {\n itemOptionsPageSize: config.itemOptionsPageSize,\n };\n }\n\n /**\n * Returns the {@link ProductService} for this install, bound to the shared\n * authenticated transport. The instance is created lazily and reused.\n */\n getProductService(): ProductService {\n if (!this.productService) {\n this.productService = new ProductService(\n this.client,\n this.productServiceOptions,\n );\n }\n return this.productService;\n }\n\n /**\n * Returns the {@link AccountUserService} for this install, bound to the shared\n * authenticated transport. The instance is created lazily and reused.\n */\n getAccountUserService(): AccountUserService {\n if (!this.accountUserService) {\n this.accountUserService = new AccountUserService(this.client);\n }\n return this.accountUserService;\n }\n\n /**\n * Returns the {@link ResourcePoolService} for this install, bound to the\n * shared authenticated transport. The instance is created lazily and reused.\n */\n getResourcePoolService(): ResourcePoolService {\n if (!this.resourcePoolService) {\n this.resourcePoolService = new ResourcePoolService(this.client);\n }\n return this.resourcePoolService;\n }\n\n /**\n * Returns the {@link TimeslotService} for this install, bound to the shared\n * authenticated transport. The instance is created lazily and reused; its\n * guide assignment composes the resource-pool and account-user services.\n */\n getTimeslotService(): TimeslotService {\n if (!this.timeslotService) {\n this.timeslotService = new TimeslotService(this.client, {\n resourcePoolService: this.getResourcePoolService(),\n accountUserService: this.getAccountUserService(),\n });\n }\n return this.timeslotService;\n }\n\n /**\n * Returns the {@link ResellerService} for this install, bound to the shared\n * authenticated transport. The instance is created lazily and reused.\n */\n getResellerService(): ResellerService {\n if (!this.resellerService) {\n this.resellerService = new ResellerService(this.client);\n }\n return this.resellerService;\n }\n\n /**\n * Returns the {@link PromoCodeService} for this install, bound to the shared\n * authenticated transport. The instance is created lazily and reused.\n */\n getPromoCodeService(): PromoCodeService {\n if (!this.promoCodeService) {\n this.promoCodeService = new PromoCodeService(this.client);\n }\n return this.promoCodeService;\n }\n\n /**\n * Returns the {@link DailyNoteService} for this install, bound to the shared\n * authenticated transport. The instance is created lazily and reused.\n */\n getDailyNoteService(): DailyNoteService {\n if (!this.dailyNoteService) {\n this.dailyNoteService = new DailyNoteService(this.client);\n }\n return this.dailyNoteService;\n }\n\n /**\n * Returns the {@link AvailabilityService} for this install, bound to the\n * shared authenticated transport. The instance is created lazily and reused.\n */\n getAvailabilityService(): AvailabilityService {\n if (!this.availabilityService) {\n this.availabilityService = new AvailabilityService(this.client);\n }\n return this.availabilityService;\n }\n\n /**\n * Returns the {@link MembershipService} for this install, bound to the shared\n * authenticated transport. The instance is created lazily and reused.\n */\n getMembershipService(): MembershipService {\n if (!this.membershipService) {\n this.membershipService = new MembershipService(this.client);\n }\n return this.membershipService;\n }\n\n /**\n * Returns the {@link BookingService} for this install, bound to the shared\n * authenticated transport. The instance is created lazily and reused.\n */\n getBookingService(): BookingService {\n if (!this.bookingService) {\n this.bookingService = new BookingService(this.client, {\n productService: this.getProductService(),\n });\n }\n return this.bookingService;\n }\n}\n\nfunction requireNonEmpty(value: string, name: string): void {\n if (!value) {\n throw new Error(`PeekAccessService: \"${name}\" is required`);\n }\n}\n"]}