@inploi/sdk 2.10.0 → 3.0.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.
- package/README.md +20 -4
- package/cdn/index.js +1 -1
- package/dist/index.d.mts +98 -73
- package/dist/index.d.ts +98 -73
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sdk.logger.ts","../src/sdk.plugins.ts","../../core/src/common/common.utils.ts","../../core/src/common/common.currency.ts","../../core/src/common/common.datetime.ts","../../core/src/common/common.address-region.ts","../../core/src/common/common.address-shadow.ts","../../core/src/common/common.geo.ts","../src/sdk.api.ts","../package.json","../src/sdk.constants.ts","../src/sdk.uuid.ts","../src/sdk.analytics.ts","../src/sdk.rpc.ts","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/enums.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/pagination.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/candidate.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/application.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/_shared.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/interview.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/http/identify.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/http/applications.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/http/candidates.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/http/metrics.js","../src/sdk.talent-bank.ts","../src/sdk.ts","../src/sdk.consent.ts","../src/ready.ts","../src/sdk.job-alerts.ts","../src/sdk.countries.ts"],"sourcesContent":["export const CONSOLE_PREFIX = '%c[inploi SDK]';\nexport const CONSOLE_STYLE = 'color: #65BC67; font-weight: bold;';\n\ntype LogMessage = (...data: any[]) => void;\nexport type Logger = {\n\twarn: LogMessage;\n\terror: LogMessage;\n\tinfo: LogMessage;\n\tlog: LogMessage;\n};\n\nexport const inploiBrandedLogger: Logger = {\n\twarn: (...args) => console.warn(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\terror: (...args) => console.error(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\tinfo: (...args) => console.info(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\tlog: (...args) => console.log(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n};\n\nexport const noLogging: Logger = { info: () => void 0, error: () => void 0, log: () => void 0, warn: () => void 0 };\n","import { AnalyticsService } from './sdk.analytics';\nimport { ApiClient } from './sdk.api';\nimport { InploiSdkEnvironment } from './sdk.constants';\nimport { Logger } from './sdk.logger';\nimport { InploiRpcClient } from './sdk.rpc';\n\nexport type PluginParams = {\n\tapiClient: ApiClient;\n\tlogger: Logger;\n};\n\nexport type Plugin<T extends string, P extends Record<string, unknown>> = {\n\tpluginName: T;\n\tpure_createActions: (params: PluginParams) => P;\n};\n\ntype PluginDependencies = {\n\tapiClient: ApiClient;\n\trpcClient: InploiRpcClient;\n\tlogger: Logger;\n\tanalytics: AnalyticsService;\n\t/** The publishable key used to initialise the SDK (available when registered via initialiseSdk) */\n\tpublishableKey?: string;\n\t/** The environment the SDK was initialised with — plugins can use this to select the correct service URL */\n\tenv?: InploiSdkEnvironment;\n};\n\nexport type InploiSdkPlugin = (dependencies: PluginDependencies) => any;\n\nexport const createPlugin = <T extends InploiSdkPlugin>(pluginFn: T) => pluginFn;\n","export const exhaustive = (value: never) => {\n\tthrow new Error(`Unhandled discriminated union member: ${JSON.stringify(value)}`);\n};\n\nexport function invariant(condition: any, message?: string): asserts condition {\n\tif (condition) {\n\t\treturn;\n\t}\n\n\tthrow new Error(message);\n}\n\nexport const uniqueOrThrow = <T>(array: T[]) => {\n\tconst uniqueValues = new Set(array);\n\n\tif (array.length !== uniqueValues.size) {\n\t\tthrow new Error('Duplicate values found');\n\t}\n\treturn true;\n};\n\nexport const uniqueByPropertyOrThrow =\n\t<T extends PropertyKey>(propertyKey: T) =>\n\t(array: { [K in T]: any }[]) => {\n\t\tconst values = array.map(item => item[propertyKey]);\n\t\tconst uniqueValues = new Set(values);\n\n\t\tif (values.length !== uniqueValues.size) {\n\t\t\tthrow new Error(`Duplicate values found for property: ${propertyKey.toString()}`);\n\t\t}\n\t\treturn true;\n\t};\n\n/**\n * A destructive way to ensure an object has a property.\n * This is useful when working with unknowns.\n */\nexport function hasProp<K extends PropertyKey>(data: object, prop: K): data is Record<K, unknown> {\n\treturn prop in data;\n}\n\n/**\n * A sort of type-safe way to check whether a key exists in an object.\n */\nexport function isKeyInObj<O extends Record<string, unknown>>(key: PropertyKey, obj: O): key is keyof O {\n\treturn key in obj;\n}\n","type TFunction = (key: 'competitive' | 'invalid_salary' | 'from' | 'up_to') => string;\n\ninterface SalaryParams {\n\tpay: string | null;\n\tpay_min: string | null;\n\tpay_mask: boolean;\n\tpay_max: string | null;\n\tpay_type: 'ANNUALLY' | 'HOURLY' | 'MONTHLY' | 'WEEKLY' | 'DAILY' | null;\n\tpay_currency: string;\n\tpay_display: boolean;\n}\n\nconst payPeriods: Record<NonNullable<SalaryParams['pay_type']>, string> = {\n\tANNUALLY: 'per year',\n\tDAILY: 'per day',\n\tHOURLY: 'per hour',\n\tMONTHLY: 'per month',\n\tWEEKLY: 'per week',\n};\n\nexport const getSalaryAsText = (params: {\n\tsalary: SalaryParams;\n\tconfig: { locales: string | string[] | undefined };\n\tt?: TFunction;\n}) => {\n\tconst { salary, config, t = s => s } = params;\n\tconst numberFormatter = new Intl.NumberFormat(config.locales, {\n\t\tstyle: 'currency',\n\t\tcurrency: salary.pay_currency,\n\t\ttrailingZeroDisplay: 'stripIfInteger',\n\t});\n\tif (salary.pay_display === false) return undefined;\n\tif (salary.pay === null && salary.pay_min === null && salary.pay_max === null) return undefined;\n\tif (salary.pay_mask) return t('competitive');\n\n\tif (salary.pay_max && Number.isNaN(+salary.pay_max)) return t('invalid_salary');\n\tif (salary.pay_min && Number.isNaN(+salary.pay_min)) return t('invalid_salary');\n\tif (salary.pay && Number.isNaN(+salary.pay)) return t('invalid_salary');\n\n\tconst period = salary.pay_type && salary.pay_type in payPeriods ? payPeriods[salary.pay_type] : undefined;\n\n\tif (salary.pay) return [numberFormatter.format(+salary.pay), period].filter(Boolean).join(' ');\n\n\tif (salary.pay_max && salary.pay_min)\n\t\treturn [numberFormatter.formatRange(+salary.pay_min, +salary.pay_max), period].filter(Boolean).join(' ') || '';\n\n\tif (salary.pay_max)\n\t\treturn `${t('up_to')} ${[numberFormatter.format(+salary.pay_max), period].filter(Boolean).join(' ')}`;\n\tif (salary.pay_min)\n\t\treturn `${t('from')} ${[numberFormatter.format(+salary.pay_min), period].filter(Boolean).join(' ')}`;\n\treturn t('invalid_salary');\n};\n","type TFunction = (key: 'today' | 'over_30_days_ago' | 'in_over_30_days') => string;\n\ntype Params = {\n\tfrom?: Date;\n\tto: string | number | Date;\n\tformatter?: Intl.RelativeTimeFormat;\n\tt?: TFunction;\n};\n\nconst DEFAULT_FORMATTER = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });\n/** From a date, calculates the relative time difference from now */\nexport const getRelativeTimeDifference = ({\n\tfrom = new Date(),\n\tto,\n\tformatter = DEFAULT_FORMATTER,\n\tt = s => s,\n}: Params) => {\n\tconst then = to instanceof Date ? to : new Date(to);\n\tconst diff = then.getTime() - from.getTime();\n\n\tconst diffIn = {\n\t\tdays: Math.round(diff / 1000 / 60 / 60 / 24),\n\t\tmonths: Math.round(diff / 1000 / 60 / 60 / 24 / 30),\n\t};\n\n\tif (diffIn.days === 0) return t('today');\n\tif (Math.abs(diffIn.days) < 30) return formatter.format(diffIn.days, 'days');\n\tif (Math.abs(diffIn.days) < 3) return formatter.format(diffIn.months, 'months');\n\treturn diffIn.months < 0 ? t('over_30_days_ago') : t('in_over_30_days');\n};\n","export const POSTCODE_PATTERN =\n\t/\\b(?:GIR\\s*0AA|[a-z]{1,2}\\d[\\da-z]?\\s*\\d[a-z]{2}|[a-z](?:\\d{2}|\\d[a-z])\\s*[\\da-z]{4})\\b/i;\nexport const UK_POSTCODE_PATTERN = /^(?:GIR0AA|[A-Z]{1,2}\\d[\\dA-Z]?\\d[A-Z]{2})$/;\nexport const EIRCODE_PATTERN = /^[A-Z](?:\\d{2}|\\d[A-Z])[\\dA-Z]{4}$/;\n\n/** Classify only the answered address; a company's country filter never determines its region. */\nexport const addressRegion = ({\n\tpostcode,\n\tlabel = '',\n\tstate,\n\tcountry,\n}: {\n\tpostcode?: string;\n\tlabel?: string;\n\tstate?: string;\n\tcountry?: string;\n}): 'gb' | 'ni' | 'ie' | null => {\n\tconst code = (postcode?.trim() || label.match(POSTCODE_PATTERN)?.[0] || '').replace(/\\s/g, '').toUpperCase();\n\tif (UK_POSTCODE_PATTERN.test(code)) return code.startsWith('BT') ? 'ni' : 'gb';\n\tif (EIRCODE_PATTERN.test(code)) return 'ie';\n\tconst normalise = (value: string) =>\n\t\tvalue\n\t\t\t.normalize('NFD')\n\t\t\t.replace(/[\\u0300-\\u036f]/g, '')\n\t\t\t.toLowerCase()\n\t\t\t.replace(/\\s+/g, ' ')\n\t\t\t.trim();\n\tif (\n\t\tnormalise(state ?? '') === 'northern ireland' ||\n\t\tlabel.split(',').some(part => normalise(part) === 'northern ireland')\n\t)\n\t\treturn 'ni';\n\tconst name = (country?.trim() || label.split(',').at(-1)?.trim())?.toLowerCase();\n\tif (name === 'united kingdom' || name === 'gb') return 'gb';\n\tif (name === 'ireland' || name === 'ie') return 'ie';\n\treturn null;\n};\n","import { EIRCODE_PATTERN, POSTCODE_PATTERN, UK_POSTCODE_PATTERN, addressRegion } from './common.address-region';\n\nconst ADDRESS_SHADOW_URL = 'https://maps.inploi.com/address';\n\nexport type AddressShadowComparison = {\n\thit: boolean;\n\trank: number | null;\n\tresults: number;\n\tsource: 'photon' | 'mapbox';\n\tfallback: string | null;\n\tms: number | null;\n\tregion: 'gb' | 'ni' | 'ie' | null;\n};\n\nconst normaliseAddress = (value: string) =>\n\tvalue\n\t\t.normalize('NFD')\n\t\t.replace(/[\\u0300-\\u036f]/g, '')\n\t\t.toLowerCase()\n\t\t.replace(/\\s+/g, ' ')\n\t\t.trim();\n\nconst addressComponents = (label: string) =>\n\tlabel.split(',').map(part =>\n\t\tnormaliseAddress(part)\n\t\t\t.replace(/^\\d+[a-z]?(?:\\s*[-/]\\s*\\d+[a-z]?)?(?:\\s+|$)/, '')\n\t\t\t.trim(),\n\t);\n\nconst postcodeArea = (postcode: string) =>\n\tUK_POSTCODE_PATTERN.test(postcode) ? `gb:${postcode.slice(0, -3)}`\n\t: EIRCODE_PATTERN.test(postcode) ? `ie:${postcode.slice(0, 3)}`\n\t: null;\n\n/** Approximate street coverage: exact components plus a postcode area or town, never a street alone. */\nconst shadowAddressRank = (pickedLabel: string, pickedPostcode: string, labels: string[]): number | null => {\n\tconst [street = '', townPart = ''] = addressComponents(pickedLabel);\n\tconst area = postcodeArea(pickedPostcode);\n\tconst town = townPart.replace(POSTCODE_PATTERN, '').trim();\n\tconst hasTown =\n\t\ttown && !['united kingdom', 'ireland', 'england', 'scotland', 'wales', 'northern ireland'].includes(town);\n\tif (!street || (!area && !hasTown)) return null;\n\tconst index = labels.slice(0, 3).findIndex(label => {\n\t\tconst components = addressComponents(label);\n\t\tif (!components.includes(street)) return false;\n\t\tconst shadowPostcode = label.match(POSTCODE_PATTERN)?.[0].replace(/\\s/g, '').toUpperCase() ?? '';\n\t\tconst shadowArea = postcodeArea(shadowPostcode);\n\t\tif (area && shadowArea) return area === shadowArea;\n\t\treturn Boolean(hasTown && components.some(part => part.replace(POSTCODE_PATTERN, '').trim() === town));\n\t});\n\treturn index === -1 ? null : index + 1;\n};\n\n/** Best-effort shadow telemetry. Call without awaiting it; no result or failure changes the candidate's pick. */\nexport const shadowAddressPick = async ({\n\tquery,\n\tcountry,\n\tpickedLabel,\n\tpickedPostcode,\n\tpickedCountry,\n\tpickedState,\n\tlog,\n}: {\n\tquery: string;\n\tcountry: string | undefined;\n\tpickedLabel: string;\n\tpickedPostcode?: string;\n\tpickedCountry?: string;\n\tpickedState?: string;\n\tlog: (properties: AddressShadowComparison) => unknown;\n}): Promise<void> => {\n\tif (!country || !country.split(',').every(code => /^(gb|ie)$/i.test(code.trim()))) return;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\ttry {\n\t\tconst controller = new AbortController();\n\t\ttimer = setTimeout(() => controller.abort(), 1500);\n\t\tconst url = new URL(ADDRESS_SHADOW_URL);\n\t\turl.search = new URLSearchParams({ q: query, country, limit: '5' }).toString();\n\t\tconst response = await fetch(url.href, { signal: controller.signal });\n\t\tif (!response.ok) return;\n\t\tconst data: unknown = await response.json();\n\t\tif (\n\t\t\ttypeof data !== 'object' ||\n\t\t\tdata === null ||\n\t\t\t!('results' in data) ||\n\t\t\t!Array.isArray(data.results) ||\n\t\t\t!('source' in data) ||\n\t\t\t(data.source !== 'photon' && data.source !== 'mapbox')\n\t\t)\n\t\t\treturn;\n\t\tconst results: unknown[] = data.results;\n\t\tconst labels: string[] = [];\n\t\tfor (const result of results) {\n\t\t\tif (typeof result !== 'object' || result === null || !('label' in result) || typeof result.label !== 'string')\n\t\t\t\treturn;\n\t\t\tlabels.push(result.label);\n\t\t}\n\t\tconst postcode = (pickedPostcode?.trim() || pickedLabel.match(POSTCODE_PATTERN)?.[0] || '')\n\t\t\t.replace(/\\s/g, '')\n\t\t\t.toUpperCase();\n\t\tconst rank = shadowAddressRank(pickedLabel, postcode, labels);\n\t\tconst duration = response.headers.get('Server-Timing')?.match(/(?:^|,)\\s*lookup\\s*;\\s*dur=([\\d.]+)/)?.[1];\n\t\tconst ms = duration === undefined ? null : Number(duration);\n\t\tconst fallback = response.headers.get('X-Geo-Fallback');\n\t\tconst region = addressRegion({\n\t\t\tpostcode: pickedPostcode,\n\t\t\tlabel: pickedLabel,\n\t\t\tstate: pickedState,\n\t\t\tcountry: pickedCountry,\n\t\t});\n\t\tawait log({\n\t\t\thit: rank !== null,\n\t\t\trank,\n\t\t\tresults: labels.length,\n\t\t\tsource: data.source,\n\t\t\t// Only machine codes are telemetry: never forward arbitrary response text.\n\t\t\tfallback: fallback && /^[a-z0-9_-]{1,64}$/i.test(fallback) ? fallback : null,\n\t\t\tms: ms !== null && Number.isFinite(ms) ? ms : null,\n\t\t\tregion,\n\t\t});\n\t} catch {\n\t\t// Optional telemetry must stay silent on timeout, bad responses, network or analytics failure.\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n};\n","import type { AddressOptions, SearchOptions } from './common.geo-transport';\n\nexport type GeoArm = 'inploi' | 'mapbox' | 'direct';\nexport type GeoSource = 'photon' | 'mapbox' | 'places' | 'direct';\nexport type GeoSurface = 'candidate' | 'chatbot' | 'forms' | 'job-search';\nexport type GeoLookup = { arm: GeoArm; source: GeoSource };\nexport type GeoSearchResult<T> = GeoLookup & { results: T[] };\nexport type GeoAddressSuggestion = {\n\tid: string;\n\tlabel: string;\n\tcountry: string | undefined;\n\taddress: Partial<Record<'line1' | 'line2' | 'line3' | 'city' | 'state' | 'postcode' | 'country', string>>;\n};\nexport type GeoPlace = {\n\tkind: 'place' | 'postcode';\n\tname: string;\n\tlabel: string;\n\tcountry: string;\n\tlat: number;\n\tlng: number;\n};\n\nconst GEO_ORIGIN = 'https://maps.inploi.com';\n\n/** Chunk loading and the Worker response share one deadline; only caller cancellation skips direct fallback. */\nconst geoLookup = async <T>(\n\tlookup: (signal: AbortSignal) => Promise<GeoSearchResult<T> | undefined>,\n\tsignal?: AbortSignal,\n\tdeadline = Date.now() + 2500,\n): Promise<GeoSearchResult<T> | undefined> => {\n\tsignal?.throwIfAborted();\n\tconst controller = new AbortController();\n\tconst abort = () => controller.abort(signal?.reason);\n\tsignal?.addEventListener('abort', abort, { once: true });\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\ttry {\n\t\tconst expired = new Promise<never>((_, reject) => {\n\t\t\tcontroller.signal.addEventListener('abort', () => reject(controller.signal.reason), { once: true });\n\t\t\ttimer = setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));\n\t\t});\n\t\tconst result = await Promise.race([lookup(controller.signal), expired]);\n\t\tsignal?.throwIfAborted();\n\t\treturn result;\n\t} catch {\n\t\tsignal?.throwIfAborted();\n\t\treturn;\n\t} finally {\n\t\tclearTimeout(timer);\n\t\tsignal?.removeEventListener('abort', abort);\n\t}\n};\n\nexport const geoAddressSearch = async (\n\toptions: AddressOptions,\n\tfallback: () => Promise<GeoAddressSuggestion[]>,\n\tdeadline?: number,\n): Promise<GeoSearchResult<GeoAddressSuggestion>> => {\n\tconst result = await geoLookup(\n\t\tasync signal => {\n\t\t\tconst { lookupAddress } = await import('./common.geo-transport');\n\t\t\tsignal.throwIfAborted();\n\t\t\treturn lookupAddress({ ...options, signal });\n\t\t},\n\t\toptions.signal,\n\t\tdeadline,\n\t);\n\treturn result ?? { results: await fallback(), arm: 'direct', source: 'direct' };\n};\n\nexport const geoPlacesSearch = async <T>(\n\toptions: SearchOptions & { surface: 'job-search' },\n\tmap: (place: GeoPlace) => T,\n\tfallback: () => Promise<T[]>,\n): Promise<GeoSearchResult<T>> => {\n\tconst result = await geoLookup(async signal => {\n\t\tconst { lookupPlaces } = await import('./common.geo-transport');\n\t\tsignal.throwIfAborted();\n\t\treturn lookupPlaces({ ...options, signal });\n\t}, options.signal);\n\treturn result ?\n\t\t\t{ ...result, results: result.results.map(map) }\n\t\t:\t{ results: await fallback(), arm: 'direct', source: 'direct' };\n};\n\n/** Codes only: explicitly list fields so neither query nor address text can enter the outcome URL. */\nexport const geoOutcome = (\n\toutcome: GeoLookup & {\n\t\tkind: 'address' | 'places';\n\t\tsurface: GeoSurface;\n\t\tpicked: boolean;\n\t\tedited?: boolean;\n\t\tregion?: 'gb' | 'ni' | 'ie' | 'other' | null;\n\t},\n): void => {\n\ttry {\n\t\tconst url = new URL('/outcome', GEO_ORIGIN);\n\t\turl.search = new URLSearchParams({\n\t\t\tkind: outcome.kind,\n\t\t\tsurface: outcome.surface,\n\t\t\tarm: outcome.arm,\n\t\t\tpicked: outcome.picked ? '1' : '0',\n\t\t}).toString();\n\t\turl.searchParams.set('source', outcome.source);\n\t\tif (outcome.picked && outcome.edited !== undefined) url.searchParams.set('edited', outcome.edited ? '1' : '0');\n\t\tif (outcome.region) url.searchParams.set('region', outcome.region);\n\t\tvoid fetch(url.href, { keepalive: true }).catch(() => {});\n\t} catch {\n\t\t// Optional telemetry never delays or prevents an answer, including synchronous fetch failures.\n\t}\n};\n","import { hasProp } from '@inploi/core/common';\nimport { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport const unauthenticatedMessage = 'Unauthenticated';\nexport const unauthorisedMessage = 'This action is unauthorized.';\n\nexport class ErrorWithStatus extends Error {\n\tpublic status?: number;\n\tconstructor(message?: string, status?: number) {\n\t\tsuper(message);\n\t\tthis.status = status;\n\t\tthis.name = 'ErrorWithStatus';\n\t}\n}\n\nexport class NotFoundError extends ErrorWithStatus {\n\tconstructor(message?: string) {\n\t\tsuper(message ?? 'Not found');\n\t\tthis.name = 'NotFoundError';\n\t\tthis.status = 404;\n\t}\n}\n\nexport class UnauthorisedError extends ErrorWithStatus {\n\tconstructor(message?: string, status?: number) {\n\t\tsuper(message ?? 'You are not authorised to perform this action.');\n\t\tthis.name = 'UnauthorisedError';\n\t\tthis.status = status ?? 401;\n\t}\n}\n\nexport class SchemaValidationError extends ErrorWithStatus {\n\tconstructor(\n\t\tpublic issues: readonly StandardSchemaV1.Issue[],\n\t\tpublic source?: 'body' | 'searchParams' | 'response',\n\t) {\n\t\tconst sourceText = source ? ` in ${source}` : '';\n\t\tsuper(`Schema validation failed${sourceText}`);\n\t\tthis.name = 'SchemaValidationError';\n\t\tthis.status = 400;\n\t}\n}\n\nexport class ApiError extends ErrorWithStatus {\n\tconstructor(\n\t\tmessage: string,\n\t\tstatus?: number,\n\t\tpublic data?: unknown,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'ApiError';\n\t\tthis.status = status ?? 500;\n\t}\n}\n\nexport const isApiErrorWithData = (error: unknown): error is ApiError & { data: unknown } =>\n\terror instanceof ApiError && error.data !== undefined;\n\nexport class JsonParsingError extends ErrorWithStatus {\n\tpublic contentType?: string;\n\n\tconstructor(public response?: Response) {\n\t\tsuper('Error parsing response into JSON.');\n\t\tthis.name = 'ParsingError';\n\t\tthis.status = response && response.status >= 300 ? response.status : 500;\n\t\tthis.contentType = new Headers(response?.headers).get('content-type') ?? undefined;\n\t}\n}\n\n/** @deprecated - use `JsonParsingError` instead */\nexport class ParsingError extends JsonParsingError {}\n\nexport type ApiClient = {\n\tfetch: (pathname: string, options?: RequestInit) => Promise<unknown>;\n};\n\nexport async function parseJsonResponse(response: Response): Promise<unknown> {\n\tconst contentType = new Headers(response.headers).get('content-type');\n\tconst mediaType = contentType?.replace(/;.*/, '').trim().toLowerCase();\n\tif (mediaType && mediaType !== 'application/json' && !mediaType.endsWith('+json')) {\n\t\tthrow new JsonParsingError(response);\n\t}\n\n\treturn response.json().catch(() => {\n\t\tthrow new JsonParsingError(response);\n\t});\n}\n\nconst ERROR_MESSAGE_KEYS = ['message', 'error', 'errors', 'exception', 'exceptions'] as const;\nfunction getErrorMessageFromJson(json: unknown): string {\n\tconst messages: string[] = [];\n\tif (typeof json === 'object' && json !== null) {\n\t\tfor (const key of ERROR_MESSAGE_KEYS) {\n\t\t\tif (hasProp(json, key)) {\n\t\t\t\tconst value = json[key];\n\t\t\t\tif (typeof value === 'string') messages.push(value);\n\t\t\t\tif (Array.isArray(value) && value.every((item): item is string => typeof item === 'string'))\n\t\t\t\t\tmessages.push(...value);\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\thasProp(json, 'integration_response') &&\n\t\t\ttypeof json.integration_response === 'object' &&\n\t\t\tjson.integration_response !== null &&\n\t\t\thasProp(json.integration_response, 'error') &&\n\t\t\ttypeof json.integration_response.error === 'object' &&\n\t\t\tjson.integration_response.error !== null &&\n\t\t\thasProp(json.integration_response.error, 'message') &&\n\t\t\ttypeof json.integration_response.error.message === 'string'\n\t\t) {\n\t\t\tmessages.push(json.integration_response.error.message);\n\t\t}\n\t}\n\tif (messages.length === 0) messages.push('Unknown error');\n\treturn [...new Set(messages)].join(', ');\n}\n\n/** Throws branded errors when API returns a known error. */\nexport function handleApiExceptions(json: unknown, status: number) {\n\tif (status >= 300) {\n\t\tconst message = getErrorMessageFromJson(json);\n\t\tif (status === 404) {\n\t\t\tthrow new NotFoundError(message);\n\t\t}\n\t\tif (message === unauthenticatedMessage) {\n\t\t\tthrow new UnauthorisedError('You are not authenticated.', status);\n\t\t}\n\t\tif (message === unauthorisedMessage) {\n\t\t\tthrow new UnauthorisedError(message, status);\n\t\t}\n\t\tthrow new ApiError(message, status, json);\n\t}\n}\n\nexport const createApiClient = (params: { baseUrl: string; publishableKey: string }): ApiClient => {\n\tconst defaultHeaders: HeadersInit = {\n\t\tAccept: 'application/json',\n\t\t'Content-Type': 'application/json',\n\t\t'x-publishable-key': params.publishableKey,\n\t};\n\n\treturn {\n\t\t/** Fetches from a pathname with a pre-established base path.\n\t\t * Parses received output as JSON, and throw if one of the common error messages is received.\n\t\t */\n\t\tfetch: async (pathname, options = {}) => {\n\t\t\tconst init = { ...options, headers: { ...options.headers, ...defaultHeaders } };\n\t\t\tconst response = await fetch(`${params.baseUrl}${pathname}`, init);\n\t\t\tif (response.status === 404) throw new NotFoundError();\n\n\t\t\tconst json = await parseJsonResponse(response);\n\n\t\t\thandleApiExceptions(json, response.status);\n\n\t\t\t// We’re assuming no other exceptions have happened.\n\t\t\treturn json;\n\t\t},\n\t};\n};\n\nexport const SdkError = {\n\tNotFound: NotFoundError,\n\tUnauthorised: UnauthorisedError,\n\tSchemaValidation: SchemaValidationError,\n\tApi: ApiError,\n\tJsonParsing: JsonParsingError,\n};\n\nexport function isSdkError(error: unknown): error is (typeof SdkError)[keyof typeof SdkError] {\n\treturn Object.values(SdkError).some(ErrorClass => error instanceof ErrorClass);\n}\n","{\n\t\"name\": \"@inploi/sdk\",\n\t\"version\": \"2.10.0\",\n\t\"main\": \"dist/index.js\",\n\t\"types\": \"dist/index.d.ts\",\n\t\"license\": \"MIT\",\n\t\"files\": [\n\t\t\"/dist\",\n\t\t\"/cdn\"\n\t],\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"require\": \"./dist/index.js\",\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"types\": \"./dist/index.d.ts\"\n\t\t}\n\t},\n\t\"scripts\": {\n\t\t\"build:npm\": \"tsup --dts --dts-resolve && node scripts/check-npm-bundle.mjs\",\n\t\t\"build:cdn\": \"tsup --config tsup.cdn.config.ts\",\n\t\t\"build\": \"concurrently 'pnpm run build:npm' 'pnpm run build:cdn'\",\n\t\t\"dev\": \"tsup --watch --config tsup.cdn.config.ts\",\n\t\t\"check\": \"eslint src --fix --max-warnings 0 && tsc\",\n\t\t\"typecheck\": \"tsc\",\n\t\t\"test\": \"vitest run\",\n\t\t\"test:coverage\": \"vitest run --coverage\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@happy-dom/global-registrator\": \"^13.6.2\",\n\t\t\"@inploi/core\": \"workspace:*\",\n\t\t\"@inploi/talent-bank\": \"github:inploi/platform#cec72e0ff2953beb6ca1faf59332ed3b466b7809&path:apps/talent-bank\",\n\t\t\"@total-typescript/ts-reset\": \"^0.5.1\",\n\t\t\"@types/node\": \"catalog:\",\n\t\t\"@types/react\": \"^18.2.33\",\n\t\t\"@types/react-dom\": \"^18.2.14\",\n\t\t\"@vitest/coverage-v8\": \"catalog:\",\n\t\t\"autoprefixer\": \"^10.4.16\",\n\t\t\"concurrently\": \"9.1.2\",\n\t\t\"eslint\": \"^7.32.0\",\n\t\t\"eslint-config-custom\": \"workspace:*\",\n\t\t\"happy-dom\": \"^12.6.0\",\n\t\t\"ts-toolbelt\": \"^9.6.0\",\n\t\t\"tsconfig\": \"workspace:*\",\n\t\t\"tsup\": \"^7.2.0\",\n\t\t\"vite\": \"catalog:\",\n\t\t\"vitest\": \"catalog:\"\n\t},\n\t\"dependencies\": {\n\t\t\"@standard-schema/spec\": \"^1.0.0\",\n\t\t\"neoqs\": \"^6.13.0\",\n\t\t\"valibot\": \"^1.4.2\"\n\t}\n}\n","import { version } from '../package.json';\n\n/**\n * The environment the SDK should run in.\n * - `production`: data will be stored and displayed on dashboards\n * - `sandbox`: data will be stored temporarily and purged periodically\n */\nexport type InploiSdkEnvironment = 'production' | 'sandbox';\n\nexport const ENV_TO_API_URL: Record<InploiSdkEnvironment, string> = {\n\tsandbox: 'https://api.staging.inploi.com',\n\tproduction: 'https://api.inploi.com',\n\t// @ts-expect-error - local test environment\n\t_internal_local: 'http://api.test',\n};\n\nexport const ENV_TO_TALENT_BANK_URL: Record<InploiSdkEnvironment, string> = {\n\tsandbox: 'https://talent-bank.staging.inploi.com',\n\tproduction: 'https://talent-bank.inploi.com',\n\t// @ts-expect-error - local test environment\n\t_internal_local: 'http://localhost:8787',\n};\n\nexport const ANALYTICS_VERSION = version;\n\nexport const LOG_PATHNAME = '/log';\n\nexport const ANALYTICS_COOKIE_NAME = 'isdk_session';\n\n/**\n * Local-storage key used to persist the Talent Bank `candidateId` once the\n * user has identified via the SDK. The SDK forwards this id on every\n * subsequent analytics log request so Laravel can stamp it onto the session.\n */\nexport const ANALYTICS_CANDIDATE_ID_STORAGE_KEY = `${ANALYTICS_COOKIE_NAME}-candidate_id`;\n\n/**\n * Local-storage key prefix for the candidate's consent / approval state\n * (PROD-5763). The final key is composed of:\n *\n * `${CONSENT_STORAGE_KEY_PREFIX}:<publishableKey>:<configHash>`\n *\n * The `configHash` is a deterministic hash of the consent message +\n * labels. Any material wording change produces a new hash → new\n * storage key → candidate is automatically re-prompted, without the\n * customer having to manage a `version` field manually.\n *\n * Per-tenant scoping (the `publishableKey` segment) matters because\n * the consent UI runs inside the Kin iframe at `sdk.inploi.com`, so\n * one origin's localStorage is shared across every tenant a candidate\n * has visited from this browser.\n */\nexport const CONSENT_STORAGE_KEY_PREFIX = `${ANALYTICS_COOKIE_NAME}-consent`;\n","/**\n * Generates a RFC 4122 v4 UUID.\n *\n * `crypto.randomUUID()` is only available in secure contexts (HTTPS). This\n * utility falls back to `crypto.getRandomValues`, which is available in all\n * browsing contexts including HTTP, so the SDK works on non-HTTPS staging\n * environments.\n */\nexport const generateUUID = (): `${string}-${string}-${string}-${string}-${string}` => {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n\t\treturn crypto.randomUUID();\n\t}\n\n\treturn '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c =>\n\t\t(+c ^ (crypto.getRandomValues(new Uint8Array(1))[0]! & (15 >> (+c / 4)))).toString(16),\n\t) as `${string}-${string}-${string}-${string}-${string}`;\n};\n","import type { AddressShadowComparison, ResponseObj } from '@inploi/core/common';\nimport { invariant } from '@inploi/core/common';\n\nimport { InploiRpcClient, Logger, endpoint, typed } from '.';\nimport {\n\tANALYTICS_CANDIDATE_ID_STORAGE_KEY,\n\tANALYTICS_COOKIE_NAME,\n\tANALYTICS_VERSION,\n} from './sdk.constants';\nimport type { TalentBankClient } from './sdk.talent-bank';\nimport { generateUUID } from './sdk.uuid';\n\nconst ANONYMOUS_ID_TTL_MS = 7 * 24 * 60 * 60 * 1000;\n\nconst formatCookie = (value: string) => {\n\tconst now = new Date();\n\tnow.setTime(now.getTime() + ANONYMOUS_ID_TTL_MS);\n\n\treturn `${ANALYTICS_COOKIE_NAME}=${value};expires=${now.toUTCString()};path=/`;\n};\n\ntype FlowProperties = { flow_id: string; flow_version: number; flow_session_id: string; flow_build: number };\n\nexport type FlowType = 'CHATBOT_DRAWER' | 'FORM_DRAWER' | 'FORM_EMBED';\n\ntype FunnelFlowProperties = FlowProperties & { flow_type?: FlowType };\n\ntype JobProperties = {\n\tid: string;\n\tid_type: 'internal' | 'external';\n};\n\nexport type PageEngagementProperties = {\n\t/** Random per page view, minted by the page; not a visitor identifier. */\n\tview_id: string;\n\t/**\n\t * The viewed page's pathname, without query or hash. A summary sent as an in-app navigation ends a view carries the\n\t * next page in its `context.page`, so reports read the page from here.\n\t */\n\tpath: string;\n\t/** Milliseconds the page was visible and in use (input or scroll within the last 30 s). */\n\tengaged_ms: number;\n\t/** The deepest quarter of the page reached. */\n\tscroll_max: 0 | 25 | 50 | 75 | 100;\n\t/**\n\t * Top-level CMS blocks that were in view, with milliseconds in view while engaged. `slug` and `label` are the\n\t * block's authored CMS type and editor label.\n\t */\n\tsections: { id: string; slug: string; label?: string; ms: number }[];\n\tjob: JobProperties | undefined;\n};\n\n/**\n * One question on a candidate's path through an application, in a `FLOW_NODE` summary. Keys, positions, input types,\n * timings and counts only: never an answer, a file or any text the candidate typed.\n */\nexport type FlowPathStep = {\n\t/** The question's key in the flow (its submission key). */\n\tk?: string;\n\t/** 1-based position on this session's path. */\n\ti: number;\n\t/** The question's input type, e.g. `text`, `enum`, `file`. */\n\tt: string;\n\t/** Milliseconds from the question being shown to it being answered or skipped. */\n\tms?: number;\n\t/** `a` answered, `s` skipped; absent while it waits. */\n\to?: 'a' | 's';\n\t/** How many times a refusal (validation) appeared on it; repeated refusals behind one visible message count once. */\n\te?: number;\n\t/** How many times it was changed at review. */\n\tr?: number;\n};\n\n/** Why a path summary was sent: the moments a session can end or pause. */\nexport type FlowPathTrigger = 'submit' | 'redirect' | 'minimise' | 'hidden' | 'pagehide' | 'restart';\n\n/**\n * `FLOW_NODE`, the Candidate Agent's application path summary: sent when a session pauses or ends and its path has\n * changed since the last summary, never per step, so a session costs a few rows. The latest by `sent_at` per `flow_session_id` is the whole path so far.\n */\nexport type FlowPathProperties = FunnelFlowProperties & {\n\tjob: JobProperties | undefined;\n\ttrigger: FlowPathTrigger;\n\tsteps: FlowPathStep[];\n\t/** The earliest steps left out to keep the summary within the api's size limit; the latest are always kept. */\n\tsteps_omitted?: number;\n\t/** The node the candidate was on when it was sent. */\n\tto_node_id?: string;\n\t/** Milliseconds since the candidate's own last action (answer, skip, refusal, edit, typing, a CV, the redirect click). */\n\tidle_ms: number;\n\tsubmit_attempts: number;\n\t/** The last attempt's outcome: `success`, `redirect`, `pending`, `failed` or the failure's outcome. */\n\tsubmit_result?: string;\n\t/** The widget's CV invitation before the first question; a CV question is a step whose `t` is `file`. */\n\tcv?: 'offered' | 'attached';\n\t/** The device class, never a user agent: a coarse (touch) or fine pointer, and the screen width's bucket. */\n\tdevice: { pointer: 'coarse' | 'fine'; width: 'xs' | 's' | 'm' | 'l' };\n\t/** The candidate opened the employer's link after submitting (a redirect such as TribePad's). */\n\tredirect_clicked?: true;\n\t/** Milliseconds from the redirect's submit result to the click; absent on a revisit, whose submit was earlier. */\n\tredirect_ms?: number;\n\t/** The click came on a later visit, from the link restored with the conversation. */\n\tredirect_revisit?: true;\n\tagent_conversation_key?: string;\n};\n\nexport type AnalyticsLogParams =\n\t| {\n\t\t\tevent: 'ADDRESS_SHADOW_COMPARED';\n\t\t\tproperties: AddressShadowComparison;\n\t }\n\t| {\n\t\t\tevent: 'VIEW_JOB';\n\t\t\tproperties: { job: JobProperties };\n\t }\n\t| {\n\t\t\tevent: 'FLOW_REDIRECT';\n\t\t\tproperties: { href: string; job: JobProperties | undefined } & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_START' | 'FLOW_INTERACT';\n\t\t\tproperties: { job: JobProperties | undefined } & FunnelFlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_END';\n\t\t\tproperties: { job: JobProperties | undefined } & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_NODE';\n\t\t\tproperties: FlowPathProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_SUBMIT';\n\t\t\tproperties: {\n\t\t\t\tservice: string;\n\t\t\t\t/** Confirmed first-apply capture, even when downstream delivery failed. */\n\t\t\t\tcaptured?: boolean;\n\t\t\t\tresponse: {\n\t\t\t\t\tstatus: number;\n\t\t\t\t\tpayload: unknown;\n\t\t\t\t};\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t\t/**\n\t\t\t\t * Set when the provider confirmed a duplicate (distinguishing one within an hour of the candidate's own\n\t\t\t\t * failed attempt on that application), or when the API accepted the application for later delivery (`pending`).\n\t\t\t\t */\n\t\t\t\toutcome?: 'duplicate' | 'duplicate_after_own_attempt' | 'pending';\n\t\t\t} & FunnelFlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'SUBMIT_FORM' | 'VIEW_PAGE';\n\t\t\tproperties?: {\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t};\n\t }\n\t/**\n\t * `PAGE_ENGAGEMENT`, one careers-site page view's attention summary: sent when the view is hidden or left, never\n\t * per scroll or tick. Summaries are cumulative, so per `view_id` the maximum of `engaged_ms`, of `scroll_max` and of\n\t * each section's `ms` is the whole view. Counts plus authored CMS block metadata only: never page text, a URL or\n\t * anything the visitor typed.\n\t */\n\t| { event: 'PAGE_ENGAGEMENT'; properties: PageEngagementProperties }\n\t| {\n\t\t\tevent: 'IDENTIFY';\n\t\t\tproperties: {\n\t\t\t\tidentifier: string;\n\t\t\t\tfirst_name?: string;\n\t\t\t\tlast_name?: string;\n\t\t\t\tphone_number?: string;\n\t\t\t\temail?: string;\n\t\t\t\tcustom_traits?: Record<string, unknown>;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_PAGINATE';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_SETTLE';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_JOB_CLICK';\n\t\t\tproperties: {\n\t\t\t\tjob_id: number;\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'VIEW_SEARCH';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'FEEDBACK';\n\t\t\tproperties: {\n\t\t\t\tkey: string;\n\t\t\t\tscore?: -1 | 0 | 1;\n\t\t\t\tcomment?: string;\n\t\t\t\t/** Where the rating or comment was given: the widget header's faces, or the ask at an application's end. */\n\t\t\t\tplacement?: 'header' | 'end';\n\t\t\t\t/** The build of the widget that drew it (the Candidate Agent's `0.0.0-pc.N`). */\n\t\t\t\twidget_version?: string;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'LINK_CLICK';\n\t\t\tproperties: {\n\t\t\t\ttarget_href: string;\n\t\t\t\tjob_id: string | undefined;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'INTERACTION';\n\t\t\tproperties: {\n\t\t\t\ttag: string;\n\t\t\t\t/** `feedback_shown` only: the frame was under 400px wide (a phone) when the faces were first on screen. */\n\t\t\t\tnarrow?: boolean;\n\t\t\t\t/** `feedback_shown` only: the ask after a sent application, rather than the header's faces. */\n\t\t\t\tplacement?: 'end';\n\t\t\t};\n\t };\n\nexport type AnalyticsLogEvent = AnalyticsLogParams['event'];\n\ntype EventPropertyMap = {\n\t[Param in AnalyticsLogParams as Param['event']]: Omit<Param, 'event'>;\n};\n\ntype AnalyticsContext = {\n\tlibrary: {\n\t\tname: 'inploi-sdk';\n\t\tversion: string;\n\t};\n\tpage: {\n\t\thref: string;\n\t\treferrer: string;\n\t\ttitle: string;\n\t};\n};\n\ntype TrackPayload<P = EventPropertyMap[keyof EventPropertyMap]['properties']> = {\n\tanonymous_id: string | null;\n\tsession_id: string | null;\n\t/**\n\t * Talent Bank candidate id — set once the SDK has identified the user\n\t * (via `TalentBankClient.identify`). Laravel's session middleware reads\n\t * this and stamps it onto `session.context.candidate_id` for attribution.\n\t * `null` for anonymous / unidentified users.\n\t */\n\tcandidate_id: string | null;\n\tevent: AnalyticsLogEvent;\n\tsent_at: string;\n\tcontext: AnalyticsContext;\n\tproperties: P;\n\tcustom_properties?: Record<string, unknown>;\n};\n\ntype LogFnParams<T extends keyof EventPropertyMap> = {\n\tevent: T;\n\tcustomProperties?: Record<string, unknown>;\n\t/** Passing a request will make logging possible on a server environment. */\n\trequest?: Request;\n\t/** Sent so it survives the page being left (`fetch` keepalive): for a summary sent on pagehide. */\n\tkeepalive?: boolean;\n} & EventPropertyMap[T];\n\ntype LogFn = <TEvent extends keyof EventPropertyMap>(\n\tparams: LogFnParams<TEvent>,\n) => Promise<ResponseObj<TrackPayload<EventPropertyMap[TEvent]['properties']>>>;\n\nexport type AnalyticsService = {\n\tlog: LogFn;\n\t/** From a log payload data, generate headers to use in server environments to update the anonymous_id */\n\tgetHeaders: (payload?: TrackPayload) => Headers;\n\tgetSessionInfo: typeof getSessionInfo;\n\t/**\n\t * The visitor id for agent conversations. With device persistence it is `getOrCreateAnonymousId`'s stored id; with\n\t * none it lives in this instance only, so a visitor who refused storage keeps one id for the page and nothing is stored.\n\t * Optional: plugins run beside the host's own SDK, and a host before 2.10 hands analytics without it. Plugins call\n\t * `analytics.getOrCreateAnonymousId?.() ?? getOrCreateAnonymousId()`, so such a host keeps the stored id until it updates.\n\t */\n\tgetOrCreateAnonymousId?: () => string;\n};\n\nconst getSessionId = (searchParams: URLSearchParams, isServer: boolean) => {\n\tconst fromSearchParams = searchParams.get('session_id');\n\tif (isServer) return fromSearchParams;\n\tif (fromSearchParams) return fromSearchParams;\n\tconst fromSessionStorage = sessionStorage.getItem(`${ANALYTICS_COOKIE_NAME}-session_id`);\n\tif (typeof fromSessionStorage === 'string') return fromSessionStorage;\n\treturn null;\n};\n\n/**\n * Read the cached Talent Bank candidate id from localStorage.\n *\n * Returns `null` in non-browser / no-localStorage environments so server-side\n * logging and tests don't explode.\n */\nconst getStoredCandidateId = (): string | null => {\n\tif (typeof window === 'undefined') return null;\n\ttry {\n\t\tconst stored = window.localStorage.getItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY);\n\t\treturn typeof stored === 'string' && stored !== '' ? stored : null;\n\t} catch {\n\t\treturn null;\n\t}\n};\n\nconst setStoredCandidateId = (candidateId: string | null): void => {\n\tif (typeof window === 'undefined') return;\n\ttry {\n\t\tif (candidateId) {\n\t\t\twindow.localStorage.setItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY, candidateId);\n\t\t} else {\n\t\t\twindow.localStorage.removeItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY);\n\t\t}\n\t} catch {\n\t\t// localStorage may be unavailable (Safari private mode, sandboxed\n\t\t// iframes, etc). Identification still works for the current page — we\n\t\t// just won't remember it across reloads.\n\t}\n};\n\nconst cookieRegex = new RegExp(`(?:^|;\\\\s*)${ANALYTICS_COOKIE_NAME}=([^;]+)`);\nconst getCookieId = (request?: Request) => {\n\tconst cookie = request ? request.headers.get('cookie') : document.cookie;\n\treturn cookie ? cookieRegex.exec(cookie)?.[1] ?? null : null;\n};\n\n/**\n * Browsers drop a cookie written inside a cross-site iframe (a careers site that frames our pages), so without a\n * fallback every page load there minted a new visitor id and the Candidate Agent lost its conversation. The cookie\n * stays the primary store; localStorage holds the id, with the cookie's expiry, only when the cookie write did not stick.\n */\nconst getStoredFallbackId = (): string | null => {\n\ttry {\n\t\tconst stored: unknown = JSON.parse(window.localStorage.getItem(ANALYTICS_COOKIE_NAME) ?? 'null');\n\t\tif (\n\t\t\ttypeof stored !== 'object' ||\n\t\t\tstored === null ||\n\t\t\t!('id' in stored) ||\n\t\t\t!('expires' in stored) ||\n\t\t\ttypeof stored.id !== 'string' ||\n\t\t\ttypeof stored.expires !== 'number'\n\t\t)\n\t\t\treturn null;\n\t\treturn stored.id !== '' && stored.expires > Date.now() ? stored.id : null;\n\t} catch {\n\t\treturn null;\n\t}\n};\n\n/** The id a response must not replace: a URL handoff outranks the fallback, as in `getSessionInfo`. */\nconst getBrowserStoredId = () =>\n\tgetCookieId() ?? (new URL(location.href).searchParams.get('anonymous_id') ? null : getStoredFallbackId());\n\n/** In a frame on HTTPS the cookie needs SameSite=None to be stored at all; Partitioned keeps it to this embed. */\nconst framedCookieAttributes = () =>\n\tlocation.protocol === 'https:' && window.self !== window.top ? ';SameSite=None;Secure;Partitioned' : '';\n\nconst persistAnonymousId = (id: string) => {\n\tdocument.cookie = formatCookie(id) + framedCookieAttributes();\n\tif (getCookieId() === id) return;\n\ttry {\n\t\twindow.localStorage.setItem(\n\t\t\tANALYTICS_COOKIE_NAME,\n\t\t\tJSON.stringify({ id, expires: Date.now() + ANONYMOUS_ID_TTL_MS }),\n\t\t);\n\t} catch {\n\t\t// No storage at all: the id lasts for this page only.\n\t}\n};\n\nconst getSessionInfo = (request?: Request) => {\n\tconst href = request ? request.url : location.href;\n\tconst { searchParams } = new URL(href);\n\n\treturn {\n\t\tanonymous_id:\n\t\t\trequest ?\n\t\t\t\t(getCookieId(request) ?? searchParams.get('anonymous_id'))\n\t\t\t:\t(getCookieId() ?? searchParams.get('anonymous_id') ?? getStoredFallbackId()),\n\t\tsession_id: getSessionId(searchParams, typeof window === 'undefined'),\n\t};\n};\n\n/**\n * Get or create a persistent anonymous ID.\n *\n * This is the universal identifier that bridges:\n * - SDK analytics (Laravel tracking)\n * - Agent conversations (Durable Object routing)\n * - Identity resolution\n *\n * The ID is:\n * - Generated client-side if none exists\n * - Persisted in a cookie for 7 days, or in localStorage where the cookie is not stored (a cross-site frame)\n * - The same across all SDK plugins\n *\n * @returns The anonymous ID (existing or newly generated)\n */\nexport const getOrCreateAnonymousId = (): string => {\n\t// Server-side: cannot generate, return empty (should not happen in normal flow)\n\tif (typeof window === 'undefined') {\n\t\tthrow new Error('getOrCreateAnonymousId() can only be called in browser environment');\n\t}\n\n\t// Check existing sources first\n\tconst existing = getSessionInfo().anonymous_id;\n\tif (existing) return existing;\n\n\tconst newId = generateUUID();\n\t// Another tab may have created the shared id during generation.\n\tconst beforeWrite = getSessionInfo().anonymous_id;\n\tif (beforeWrite) return beforeWrite;\n\tpersistAnonymousId(newId);\n\treturn newId;\n};\n\nconst getSessionInfoFromResponse = (response: unknown) => {\n\tif (typeof response !== 'object' || response === null) return null;\n\treturn {\n\t\tanonymous_id:\n\t\t\t'anonymous_id' in response && typeof response.anonymous_id === 'string' ? response.anonymous_id : null,\n\t\tsession_id: 'session_id' in response && typeof response.session_id === 'string' ? response.session_id : null,\n\t};\n};\n\nconst serverReferrer = (referrer: typeof Request.prototype.referrer) => {\n\tif (referrer === 'about:client') return '';\n\treturn referrer;\n};\n\nconst analyticsLogEndpoint = endpoint({\n\tpathname: '/log',\n\tmethod: 'POST',\n\tschema: {\n\t\tresponse: typed<unknown>(),\n\t\tbody: typed<TrackPayload>(),\n\t},\n});\n\nexport type AnalyticsOnEventCallback = (event: AnalyticsLogParams) => void;\n\nexport const createAnalyticsService = ({\n\trpcClient,\n\tlogger,\n\tonEvent,\n\ttalentBank,\n\tpersistence = 'device',\n}: {\n\tlogger: Logger;\n\trpcClient: InploiRpcClient;\n\tonEvent?: AnalyticsOnEventCallback;\n\tpersistence?: 'device' | 'none';\n\t/**\n\t * Optional Talent Bank client. When provided, `IDENTIFY` events are sent\n\t * directly to Talent Bank's `POST /identify` (in addition to Laravel's\n\t * `/log`). With device persistence, the returned `candidateId` is cached\n\t * locally and forwarded on subsequent log calls.\n\t */\n\ttalentBank?: TalentBankClient;\n}): AnalyticsService => {\n\tlet memorySessionId: string | null = null;\n\tlet memoryAnonymousId: string | null = null;\n\tlet sessionRequestSequence = 0;\n\tlet latestSessionResponse = 0;\n\tconst sessionInfo = (request?: Request) =>\n\t\tpersistence === 'none' ?\n\t\t\t{ anonymous_id: null, session_id: request ? null : memorySessionId }\n\t\t:\tgetSessionInfo(request);\n\n\tconst logFn: <TEvent extends keyof EventPropertyMap>(\n\t\tparams: LogFnParams<TEvent>,\n\t\tpage: AnalyticsContext['page'],\n\t) => Promise<ResponseObj<TrackPayload<EventPropertyMap[TEvent]['properties']>>> = async (params, page) => {\n\t\ttry {\n\t\t\tconst context: AnalyticsContext = {\n\t\t\t\tlibrary: {\n\t\t\t\t\tname: 'inploi-sdk',\n\t\t\t\t\tversion: ANALYTICS_VERSION,\n\t\t\t\t},\n\t\t\t\tpage,\n\t\t\t};\n\n\t\t\tlet currentSession = sessionInfo(params.request);\n\t\t\tif (\n\t\t\t\tpersistence === 'device' &&\n\t\t\t\tparams.event === 'IDENTIFY' &&\n\t\t\t\t!currentSession.anonymous_id &&\n\t\t\t\t!params.request &&\n\t\t\t\ttypeof window !== 'undefined'\n\t\t\t) {\n\t\t\t\tcurrentSession = { ...currentSession, anonymous_id: getOrCreateAnonymousId() };\n\t\t\t}\n\n\t\t\t// For IDENTIFY events, resolve the Talent Bank candidate directly\n\t\t\t// from the SDK before firing the /log call. The returned candidateId\n\t\t\t// is cached only with device persistence. Memory mode supplies a one-call\n\t\t\t// anonymous id for the identify contract, never for analytics or storage.\n\t\t\tlet resolvedCandidateId = persistence === 'none' ? null : getStoredCandidateId();\n\t\t\tif (params.event === 'IDENTIFY' && talentBank && (currentSession.anonymous_id || persistence === 'none')) {\n\t\t\t\tconst identifyProperties = params.properties as EventPropertyMap['IDENTIFY']['properties'];\n\t\t\t\tconst result = await talentBank.identify({\n\t\t\t\t\temail: identifyProperties.email ?? identifyProperties.identifier,\n\t\t\t\t\tfirstName: identifyProperties.first_name,\n\t\t\t\t\tlastName: identifyProperties.last_name,\n\t\t\t\t\tphone: identifyProperties.phone_number,\n\t\t\t\t\tanonymousId: currentSession.anonymous_id ?? generateUUID(),\n\t\t\t\t\tsource: 'sdk',\n\t\t\t\t});\n\t\t\t\tif (result?.candidateId && persistence === 'device') {\n\t\t\t\t\tresolvedCandidateId = result.candidateId;\n\t\t\t\t\tsetStoredCandidateId(result.candidateId);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst payload: TrackPayload = {\n\t\t\t\tanonymous_id: currentSession.anonymous_id,\n\t\t\t\tsession_id: currentSession.session_id,\n\t\t\t\tcandidate_id: resolvedCandidateId,\n\t\t\t\tevent: params.event,\n\t\t\t\tsent_at: new Date().toISOString(),\n\t\t\t\tcontext,\n\t\t\t\tproperties: params.properties,\n\t\t\t\tcustom_properties: params.customProperties,\n\t\t\t};\n\n\t\t\tconst cookieIdBeforeRequest =\n\t\t\t\tpersistence === 'none' ? null\n\t\t\t\t: params.request ? getCookieId(params.request)\n\t\t\t\t: getBrowserStoredId();\n\t\t\tconst requestSequence = ++sessionRequestSequence;\n\t\t\tconst responseJson = await rpcClient.request(analyticsLogEndpoint, {\n\t\t\t\tbody: payload,\n\t\t\t\t...(params.keepalive && { keepalive: true }),\n\t\t\t});\n\n\t\t\tconst newSession = getSessionInfoFromResponse(responseJson);\n\t\t\tif (persistence === 'none') {\n\t\t\t\tif (!params.request && newSession?.session_id && requestSequence > latestSessionResponse) {\n\t\t\t\t\tlatestSessionResponse = requestSequence;\n\t\t\t\t\t// An echo of the sent id must not undo a replacement received while this request was in flight.\n\t\t\t\t\tif (newSession.session_id !== payload.session_id) memorySessionId = newSession.session_id;\n\t\t\t\t}\n\t\t\t\tpayload.session_id = params.request ? newSession?.session_id || null : memorySessionId;\n\t\t\t\tonEvent?.(payload as AnalyticsLogParams);\n\t\t\t\treturn { success: true, data: payload };\n\t\t\t}\n\t\t\t// Keep an existing visitor id, including one set by Kin in flight. A mismatched session\n\t\t\t// would resolve back to the response's id, so keep the session that was sent as well.\n\t\t\tconst cookieIdNow = params.request ? cookieIdBeforeRequest : getBrowserStoredId();\n\t\t\tconst writtenDuringRequest = cookieIdNow !== null && cookieIdNow !== cookieIdBeforeRequest;\n\t\t\tconst cookieIdToKeep = cookieIdNow ?? cookieIdBeforeRequest;\n\t\t\tconst canAdoptResponse =\n\t\t\t\t!writtenDuringRequest &&\n\t\t\t\t(!cookieIdToKeep || !newSession?.anonymous_id || cookieIdToKeep === newSession.anonymous_id);\n\t\t\tif (canAdoptResponse) {\n\t\t\t\tif (newSession?.anonymous_id) payload.anonymous_id = newSession.anonymous_id;\n\t\t\t\tif (newSession?.session_id) payload.session_id = newSession.session_id;\n\t\t\t} else {\n\t\t\t\tpayload.anonymous_id = cookieIdToKeep;\n\t\t\t}\n\n\t\t\tif (!params.request && typeof window !== 'undefined' && payload.anonymous_id) {\n\t\t\t\tif (canAdoptResponse && payload.session_id) {\n\t\t\t\t\tsessionStorage.setItem(`${ANALYTICS_COOKIE_NAME}-session_id`, payload.session_id.toString());\n\t\t\t\t}\n\t\t\t\tpersistAnonymousId(payload.anonymous_id);\n\t\t\t}\n\n\t\t\tonEvent?.(payload as AnalyticsLogParams);\n\t\t\treturn { success: true, data: payload };\n\t\t} catch (e) {\n\t\t\t/** We dont’t log any PII on the console */\n\t\t\tlogger.error('Failed to send log to API. Inspect error response of `log` for more information.');\n\t\t\treturn { success: false, error: e };\n\t\t}\n\t};\n\n\t// Bootstrap one API session before dispatching other first events. Once known,\n\t// events can run concurrently without minting separate sessions for this document.\n\tlet pendingSessionLog: Promise<unknown> = Promise.resolve();\n\tconst log: LogFn = async params => {\n\t\tinvariant(\n\t\t\tparams.request || typeof window !== 'undefined',\n\t\t\t'Cannot log on the server without a request. Please pass a request to `log`.',\n\t\t);\n\n\t\t// if there’s a request, use it instead of browser APIs\n\t\tconst page =\n\t\t\t'request' in params && params.request ?\n\t\t\t\t{\n\t\t\t\t\thref: params.request.url,\n\t\t\t\t\treferrer: serverReferrer(params.request.referrer),\n\t\t\t\t\ttitle: '',\n\t\t\t\t}\n\t\t\t:\t{\n\t\t\t\t\thref: location.href,\n\t\t\t\t\treferrer: document.referrer,\n\t\t\t\t\ttitle: document.title,\n\t\t\t\t};\n\n\t\tif (\n\t\t\tpersistence === 'none' &&\n\t\t\tparams.event === 'FLOW_NODE' &&\n\t\t\tparams.properties &&\n\t\t\t'trigger' in params.properties &&\n\t\t\t(params.properties.trigger === 'pagehide' || params.properties.trigger === 'hidden')\n\t\t) {\n\t\t\tparams = { ...params, keepalive: true };\n\t\t}\n\t\t// An unloading page cannot wait for the bootstrap response. The API can mint a separate session.\n\t\tif (persistence === 'device' || params.request || memorySessionId || params.keepalive) return logFn(params, page);\n\t\tconst send = () => logFn(params, page);\n\t\tconst response = pendingSessionLog.then(send, send);\n\t\tpendingSessionLog = response;\n\t\treturn response;\n\t};\n\n\treturn {\n\t\tlog,\n\t\tgetHeaders: payload => {\n\t\t\tconst headers = new Headers();\n\t\t\tif (persistence === 'none' || !payload?.anonymous_id) return headers;\n\n\t\t\theaders.append('Set-Cookie', formatCookie(payload.anonymous_id));\n\t\t\treturn headers;\n\t\t},\n\t\tgetSessionInfo: sessionInfo,\n\t\tgetOrCreateAnonymousId: () =>\n\t\t\tpersistence === 'none' ? (memoryAnonymousId ??= generateUUID()) : getOrCreateAnonymousId(),\n\t};\n};\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { stringify } from 'neoqs';\n\nimport { SchemaValidationError, handleApiExceptions, parseJsonResponse } from './sdk.api';\nimport { ENV_TO_API_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger } from './sdk.logger';\n\ntype RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\n/** Extract parameter names from a pathname string */\ntype ExtractParamNames<T extends string> =\n\tT extends `${infer _Before}:${infer Param}/${infer After}` ? Param | ExtractParamNames<`/${After}`>\n\t: T extends `${infer _Before}:${infer Param}` ? Param\n\t: never;\n\n/** Create params object from parameter names */\ntype ExtractPathParams<T extends string> =\n\tstring extends T ? Record<string, string | number>\n\t: ExtractParamNames<T> extends never ? Record<string, never>\n\t: { [K in ExtractParamNames<T>]: string | number };\n\n/** Parses a StandardSchemaV1 schema and input into an output. */\nexport function parse<T extends StandardSchemaV1>(\n\tschema: T,\n\tinput: StandardSchemaV1.InferInput<T>,\n\tsource?: 'body' | 'searchParams' | 'response',\n): StandardSchemaV1.InferOutput<T> {\n\tconst result = schema['~standard'].validate(input);\n\tif (result instanceof Promise) {\n\t\tthrow new TypeError('Async schema');\n\t}\n\n\tif (result.issues) {\n\t\tthrow new SchemaValidationError(result.issues, source);\n\t}\n\n\treturn result.value;\n}\n\n/** Parses a StandardSchemaV1 schema and input into an output, returning a success flag and issues if the parse fails. */\nexport function safeParse<T extends StandardSchemaV1>(\n\tschema: T,\n\tinput: StandardSchemaV1.InferInput<T>,\n\tsource?: 'body' | 'searchParams' | 'response',\n):\n\t| {\n\t\t\tsuccess: true;\n\t\t\toutput: StandardSchemaV1.InferOutput<T>;\n\t }\n\t| {\n\t\t\tsuccess: false;\n\t\t\tissues: readonly StandardSchemaV1.Issue[];\n\t\t\tsource?: 'body' | 'searchParams' | 'response';\n\t } {\n\ttry {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\toutput: parse(schema, input, source),\n\t\t};\n\t} catch (e) {\n\t\tif (e instanceof SchemaValidationError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tissues: e.issues,\n\t\t\t\tsource: e.source,\n\t\t\t};\n\t\t}\n\t\tthrow e;\n\t}\n}\n\nexport interface InploiRpcClientParams {\n\tenvironment: InploiSdkEnvironment;\n\tlogger: Logger;\n\tapiKey:\n\t\t| {\n\t\t\t\t/** Makes the API call with an x-secret-key header\n\t\t\t\t * This will error if used in a browser environment.\n\t\t\t\t */\n\t\t\t\ttype: 'secret';\n\t\t\t\tkey: string;\n\t\t }\n\t\t| {\n\t\t\t\t/** Makes the API call with an x-publishable-key header\n\t\t\t\t * This can be called in a browser or server environment.\n\t\t\t\t */\n\t\t\t\ttype: 'publishable';\n\t\t\t\tkey: string;\n\t\t };\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype NonReducibleUnknown = {} | null | undefined;\ntype LooseAutocomplete<T extends BaseType, BaseType> = T | BaseType;\n\n/** RPC client for making API calls to the Inploi API. */\nexport class InploiRpcClient {\n\tprivate baseUrl: string;\n\tprivate headers: Headers;\n\tprivate logger: Logger;\n\tprivate _environment: InploiSdkEnvironment;\n\n\tconstructor(params: InploiRpcClientParams) {\n\t\tthis.baseUrl = ENV_TO_API_URL[params.environment];\n\t\tthis.headers = new Headers({\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAccept: 'application/json',\n\t\t});\n\t\tif (params.apiKey.type === 'secret') {\n\t\t\tif (typeof window !== 'undefined') {\n\t\t\t\tthrow new Error('Secret key cannot be used in a browser environment');\n\t\t\t}\n\t\t\tthis.headers.set('x-secret-key', params.apiKey.key);\n\t\t} else {\n\t\t\tthis.headers.set('x-publishable-key', params.apiKey.key);\n\t\t}\n\t\tthis.logger = params.logger;\n\t\tthis._environment = params.environment;\n\t}\n\n\tget environment() {\n\t\treturn this._environment;\n\t}\n\n\t/** Gets params for a fetch request to the given endpoint */\n\tgetFetchParams<T extends RpcEndpoint>(\n\t\tendpoint: T,\n\t\toptions: T extends RpcEndpoint<infer _, infer _TPathname, infer TPathParams, infer TSearch, infer TBody> ?\n\t\t\tGetSchemaValues<{\n\t\t\t\tbody: TBody;\n\t\t\t\tsearchParams: TSearch;\n\t\t\t\tparams: TPathParams;\n\t\t\t}> & {\n\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t/** Lets the request outlive the page (`fetch` keepalive), for a last analytics event on pagehide. */\n\t\t\t\tkeepalive?: boolean;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the inputs against the schema.\n\t\t\t\t * If you want to skip validation (e.g.: already validated yourself or with `validateEndpontInputs`), set this to false.\n\t\t\t\t */\n\t\t\t\tvalidateIn?: boolean;\n\t\t\t}\n\t\t:\tnever,\n\t): [url: string, options: RequestInit] {\n\t\tconst validateIn = options.validateIn ?? true;\n\t\tconst { searchParams, body } = validateIn ? validateEndpointInputs(endpoint, options) : options;\n\n\t\tconst url = new URL(this.baseUrl);\n\n\t\t// Replace path parameters in pathname\n\t\tlet pathname = endpoint.pathname;\n\t\tif ('params' in options && options.params) {\n\t\t\tfor (const [key, value] of Object.entries(options.params)) {\n\t\t\t\tpathname = pathname.replace(`:${key}`, String(value));\n\t\t\t}\n\t\t}\n\t\turl.pathname = pathname;\n\n\t\tif (endpoint.schema.searchParams) {\n\t\t\turl.search = stringify(searchParams);\n\t\t}\n\n\t\treturn [\n\t\t\turl.toString(),\n\t\t\t{\n\t\t\t\tmethod: endpoint.method,\n\t\t\t\tbody: body ? JSON.stringify(body) : undefined,\n\t\t\t\theaders: this.headers,\n\t\t\t\tsignal: options.signal,\n\t\t\t\t...(options.keepalive && { keepalive: true }),\n\t\t\t},\n\t\t];\n\t}\n\n\t/** Parses a response against an endpoint’s response schema, considering common errors thrown from the API.\n\t * @throws {JsonParsingError} - If the response is not valid JSON.\n\t * @throws {SchemaValidationError} - If the response does not match the schema.\n\t * @throws {ApiError} - If the API responded with an error message.\n\t */\n\tasync parseResponse<T extends RpcEndpoint>(\n\t\tendpoint: T,\n\t\toptions: {\n\t\t\tresponse: Response;\n\t\t\t/**\n\t\t\t * Whether to validate the response against the schema.\n\t\t\t * This is meant more as an escape hatch for when the response is not as expected and you want to handle it separately yourself.\n\t\t\t * ⚠️ This will lead to potential type/runtime mismatch as it does not verify the response against the schema.\n\t\t\t */\n\t\t\tvalidateOut?: boolean;\n\t\t},\n\t): Promise<StandardSchemaV1.InferOutput<T['schema']['response']>> {\n\t\tconst json = await parseJsonResponse(options.response);\n\t\thandleApiExceptions(json, options.response.status);\n\n\t\tconst validateOut = options.validateOut ?? true;\n\t\tif (!validateOut) return json as StandardSchemaV1.InferOutput<T['schema']['response']>;\n\n\t\tconst result = safeParse(endpoint.schema.response, json, 'response');\n\t\tif (!result.success) {\n\t\t\tthrow new SchemaValidationError(result.issues, result.source);\n\t\t}\n\n\t\treturn result.output as StandardSchemaV1.InferOutput<T['schema']['response']>;\n\t}\n\n\t/** Fetches, parses and validates an API endpoint.\n\t * Logs errors and throws them again so that the caller can handle them.\n\t *\n\t * @throws {JsonParsingError} - If the response is not valid JSON.\n\t * @throws {SchemaValidationError} - If the searchParams, body or response does not match the schema.\n\t * @throws {ApiError} - If the API responded with an error message.\n\t * @throws {UnauthorisedError} - If the request is unauthorised either by missing key or unmet permissions.\n\t * @throws {NotFoundError} - If the endpoint is not found.\n\t * @throws {Error} - Another unhandled error.\n\t */\n\tasync request<T extends RpcEndpoint>(\n\t\tendpoint: T,\n\t\toptions: T extends RpcEndpoint<infer _, infer _TPathname, infer TPathParams, infer TSearch, infer TBody> ?\n\t\t\tGetSchemaValues<{\n\t\t\t\tbody: TBody;\n\t\t\t\tsearchParams: TSearch;\n\t\t\t\tparams: TPathParams;\n\t\t\t}> & {\n\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t/** Lets the request outlive the page (`fetch` keepalive), for a last analytics event on pagehide. */\n\t\t\t\tkeepalive?: boolean;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the inputs against the schema.\n\t\t\t\t * If you want to skip validation (e.g.: already validated yourself or with `validateEndpontInputs`), set this to false.\n\t\t\t\t */\n\t\t\t\tvalidateIn?: boolean;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the response against the schema.\n\t\t\t\t * This is meant more as an escape hatch for when the response is not as expected and you want to handle it separately yourself.\n\t\t\t\t * ⚠️ This will lead to potential type/runtime mismatch as it does not verify the response against the schema.\n\t\t\t\t */\n\t\t\t\tvalidateOut?: boolean;\n\t\t\t}\n\t\t:\tnever,\n\t): Promise<StandardSchemaV1.InferOutput<T['schema']['response']>> {\n\t\ttry {\n\t\t\tconst fetchParams = this.getFetchParams(endpoint, options);\n\t\t\tconst response = await fetch(...fetchParams);\n\t\t\treturn await this.parseResponse(endpoint, { response, validateOut: options.validateOut });\n\t\t} catch (e) {\n\t\t\tif (e instanceof SchemaValidationError) {\n\t\t\t\tthis.logger.error(e.message, e.issues);\n\t\t\t} else {\n\t\t\t\tthis.logger.error(e);\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n}\n\ntype GetSchemaValues<T extends { searchParams: any; body: any; params?: any }> = {\n\t[K in keyof T as T[K] extends never ? never\n\t: T[K] extends Record<string, never> ? never\n\t: K]: T[K] extends never ? never : LooseAutocomplete<T[K], NonReducibleUnknown>;\n};\n\n/**\n * Typed but *not runtime validated* schema\n * useful for type-checking the schema without bundling validation schemas\n */\nexport function typed<T>(): StandardSchemaV1<T, T> {\n\treturn {\n\t\t'~standard': {\n\t\t\tvendor: 'inploi',\n\t\t\tversion: 1,\n\t\t\tvalidate: input => {\n\t\t\t\treturn {\n\t\t\t\t\tvalue: input as T,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t};\n}\n\nexport interface RpcEndpoint<\n\tTMethod extends RequestMethod = RequestMethod,\n\tTPathname extends string = string,\n\tTPathParams = any,\n\tTSearch = any,\n\tTBody = any,\n\tTResponse = any,\n> {\n\tpathname: TPathname;\n\tmethod: TMethod;\n\theaders?: Headers;\n\tschema: {\n\t\tsearchParams?: StandardSchemaV1<TSearch, TSearch>;\n\t\tbody?: StandardSchemaV1<TBody, TBody>;\n\t\tresponse: StandardSchemaV1<TResponse, TResponse>;\n\t};\n\t/** Type-only property to store path parameter types */\n\treadonly __pathParams?: TPathParams;\n}\n\nexport function endpoint<\n\tTMethod extends RequestMethod,\n\tTPathname extends string,\n\tTSearch extends StandardSchemaV1 | never = never,\n\tTBody extends StandardSchemaV1 | never = never,\n\tTResponse extends StandardSchemaV1 | never = never,\n>(endpoint: {\n\tpathname: TPathname;\n\tmethod: TMethod;\n\theaders?: Headers;\n\tschema: {\n\t\tsearchParams?: TSearch;\n\t\tbody?: TBody;\n\t\tresponse: TResponse;\n\t};\n}) {\n\ttype PathParams = ExtractPathParams<TPathname>;\n\treturn endpoint as RpcEndpoint<\n\t\tTMethod,\n\t\tTPathname,\n\t\tPathParams,\n\t\tStandardSchemaV1.InferInput<TSearch>,\n\t\tStandardSchemaV1.InferInput<TBody>,\n\t\tStandardSchemaV1.InferOutput<TResponse>\n\t>;\n}\n\n/** Validates the inputs for an endpoint ahead of time\n * Useful when you need to validate and throw earlier, or use the inputs for something other than the API call.\n */\nexport function validateEndpointInputs<T extends RpcEndpoint>(\n\tendpoint: T,\n\toptions: GetSchemaValues<{ body: unknown; searchParams: unknown }>,\n) {\n\tconst validatedInputs = {\n\t\tsearchParams: undefined,\n\t\tbody: undefined,\n\t\tvalidateIn: false,\n\t} as T extends RpcEndpoint<infer _, infer __, infer ___, infer TSearch, infer TBody> ?\n\t\tGetSchemaValues<{\n\t\t\tbody: TBody;\n\t\t\tsearchParams: TSearch;\n\t\t}> & {\n\t\t\tvalidateIn: false;\n\t\t}\n\t:\tnever;\n\n\tif (endpoint.schema.searchParams) {\n\t\tvalidatedInputs.searchParams = parse(\n\t\t\tendpoint.schema.searchParams,\n\t\t\t'searchParams' in options ? options.searchParams : {},\n\t\t);\n\t}\n\n\tif (endpoint.schema.body) {\n\t\tvalidatedInputs.body = parse(endpoint.schema.body, 'body' in options ? options.body : {});\n\t}\n\n\treturn validatedInputs;\n}\n","import * as v from \"valibot\";\nexport const CANDIDATE_SOURCES = [\n \"agent\",\n \"sdk\",\n \"form\",\n \"integration\",\n \"migration\",\n];\n/**\n * Canonical funnel-milestone groups. Stable enum baked into the contract —\n * lifecycle decisions key off this, never off `stage` (which is free-text).\n */\nexport const STAGE_GROUPS = [\n \"APPLIED\",\n \"SHORTLISTED\",\n \"INTERVIEWED\",\n \"OFFERED\",\n \"HIRED\",\n \"REJECTED\",\n \"WITHDRAWN\",\n];\n/**\n * Historical 1:1 stage slugs per group. Stages are now free-text at the\n * contract boundary — studio owns the per-company list — so this constant\n * exists only as the default-per-group fallback for callers (and tests)\n * that don't supply an explicit stage. See {@link DEFAULT_STAGE_FOR_GROUP}.\n */\nexport const STAGES = [\n \"applied\",\n \"shortlisted\",\n \"interviewed\",\n \"offered\",\n \"hired\",\n \"rejected\",\n \"withdrawn\",\n];\nexport const SCORE_TYPES = [\n \"screening\",\n \"cv_match\",\n \"interview\",\n \"overall\",\n];\nexport const INTERVIEW_STATUSES = [\n \"PENDING\",\n \"SCHEDULED\",\n \"IN_PROGRESS\",\n \"COMPLETED\",\n \"CANCELLED\",\n];\nexport const DUPLICATE_CHECK_SCOPES = [\"job\", \"company\"];\nexport const APPLICATION_SORT_FIELDS = [\"created_at\", \"updated_at\"];\nexport const SORT_ORDERS = [\"asc\", \"desc\"];\n/** Per-application source label. Set once on submit; never mutated thereafter. */\nexport const APPLICATION_SOURCES = [\n \"careers_site\",\n \"chatbot\",\n \"plugin_job_search\",\n \"ats_import\",\n \"referral\",\n \"agency\",\n \"other\",\n \"unknown\",\n];\n/**\n * The closed set of state-mutating actions that can be recorded in the\n * `application_logs` audit table.\n *\n * The named group transitions (`shortlist`, `move_to_interview`,\n * `make_offer`, `hire`, `withdraw`) exist *alongside* the generic\n * `move_to_stage` because the action key is what flows into audit +\n * analytics: a `shortlist` row and a `move_to_stage` row that happen to\n * both land in `SHORTLISTED` carry different intent and the dashboards\n * pivot on that. The legacy `stage_transition` is kept as an alias for\n * `move_to_stage` so existing consumers don't break.\n *\n * `submit` and `score_written` are server-emitted only — never accepted\n * via the generic apply-action surface.\n */\nexport const APPLICATION_ACTIONS = [\n \"submit\",\n \"stage_transition\",\n \"move_to_stage\",\n \"shortlist\",\n \"move_to_interview\",\n \"make_offer\",\n \"hire\",\n \"withdraw\",\n \"disqualify\",\n \"reinstate\",\n \"rate\",\n \"score_written\",\n];\n/** Who initiated the audited action. Verbatim from the request body. */\nexport const ACTOR_TYPES = [\n \"user\",\n \"system\",\n \"automation\",\n \"integration\",\n \"candidate\",\n];\nexport const CandidateSourceSchema = v.picklist(CANDIDATE_SOURCES);\nexport const StageGroupSchema = v.picklist(STAGE_GROUPS);\n/**\n * Stage slug — free-text from talent-bank's POV. Studio owns the per-company\n * stage configuration; talent-bank just stores and reflects whatever slug the\n * caller sends. The trimmed length cap mirrors the column intent (TEXT, but\n * we don't want kilobyte-sized slugs leaking through accidents).\n */\nexport const StageSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100));\nexport const ScoreTypeSchema = v.picklist(SCORE_TYPES);\nexport const InterviewStatusSchema = v.picklist(INTERVIEW_STATUSES);\nexport const DuplicateCheckScopeSchema = v.picklist(DUPLICATE_CHECK_SCOPES);\nexport const ApplicationSortFieldSchema = v.picklist(APPLICATION_SORT_FIELDS);\nexport const SortOrderSchema = v.picklist(SORT_ORDERS);\n/**\n * Disqualification reason slug — free-text from talent-bank's POV. Studio owns\n * the per-company reason configuration (label, ordering, whether a note is\n * required); talent-bank just stores and reflects whatever slug the caller\n * sends, exactly like {@link StageSchema}. The length cap mirrors the column\n * intent (TEXT, but we don't want kilobyte-sized slugs leaking through).\n */\nexport const DisqualificationReasonSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100));\nexport const ApplicationSourceSchema = v.picklist(APPLICATION_SOURCES);\nexport const ApplicationActionSchema = v.picklist(APPLICATION_ACTIONS);\nexport const ActorTypeSchema = v.picklist(ACTOR_TYPES);\n/**\n * The actor type that marks a shortlist as initiated by one of our own\n * automations (e.g. the Studio \"Sync shortlist to Talent Bank\" workflow node).\n *\n * This value is load-bearing across repos: the `/metrics` soft-cap query\n * (`buildShortlistCountQuery`) counts only `application.shortlisted` rows whose\n * `actorType` equals this constant, and the API workflow node must send exactly\n * this `actor.type` for its shortlists to be counted. Keeping it as a single\n * `satisfies ActorType` constant means a typo or a removal from {@link ACTOR_TYPES}\n * is a compile error rather than a silently-zero metric.\n */\nexport const AUTOMATION_ACTOR_TYPE = \"automation\";\n/**\n * Historical default-slug → group map. **Not a runtime validator** — stages\n * are now free-text and studio owns the per-company stage list. Only useful\n * for resolving the v1 default slugs in tests and back-compat paths.\n */\nexport const STAGE_TO_GROUP = {\n applied: \"APPLIED\",\n shortlisted: \"SHORTLISTED\",\n interviewed: \"INTERVIEWED\",\n offered: \"OFFERED\",\n hired: \"HIRED\",\n rejected: \"REJECTED\",\n withdrawn: \"WITHDRAWN\",\n};\n/**\n * Default stage slug per stage group. Used by named group-transition actions\n * when the caller does not supply an explicit `stage`, and by `submit` when\n * the request body omits both `stage` and `stageGroup`.\n */\nexport const DEFAULT_STAGE_FOR_GROUP = {\n APPLIED: \"applied\",\n SHORTLISTED: \"shortlisted\",\n INTERVIEWED: \"interviewed\",\n OFFERED: \"offered\",\n HIRED: \"hired\",\n REJECTED: \"rejected\",\n WITHDRAWN: \"withdrawn\",\n};\n/** Convention default applied on submit when the caller does not supply a stage. */\nexport const DEFAULT_STAGE = \"applied\";\nexport const DEFAULT_STAGE_GROUP = \"APPLIED\";\n/** Terminal stage groups — disqualified or self-withdrawn. */\nexport const TERMINAL_STAGE_GROUPS = new Set([\n \"REJECTED\",\n \"WITHDRAWN\",\n \"HIRED\",\n]);\n/**\n * Source stage groups that `reinstate` is permitted to move an application\n * *out of*. The set is engine-internal — it answers \"given a target row,\n * may the reinstate action proceed?\" — not a synonym for \"is this row\n * disqualified\" (the row's `disqualifiedAt` column answers that).\n *\n * HIRED is included so fat-finger hires can be corrected on the kanban\n * without resorting to a back-channel DB edit. `reinstate.apply` always\n * clears `disqualifiedAt` and `disqualificationReason`, which is a no-op\n * on HIRED rows (already null) — so adding HIRED has no semantic effect\n * on genuine disqualified reinstates.\n *\n * The complementary \"cannot reinstate INTO terminal\" guard\n * ({@link TERMINAL_STAGE_GROUPS}) is unchanged: this action moves\n * applications back into the active funnel, never sideways between\n * terminal states (use `disqualify` for HIRED → REJECTED).\n */\nexport const REINSTATABLE_STAGE_GROUPS = new Set([\n \"REJECTED\",\n \"WITHDRAWN\",\n \"HIRED\",\n]);\n/**\n * Discriminated actor block. Sent on every mutating route's body and\n * written verbatim into the matching `application_logs` row.\n */\nexport const ActorInputSchema = v.variant(\"type\", [\n v.object({\n type: v.literal(\"user\"),\n id: v.pipe(v.string(), v.minLength(1)),\n email: v.pipe(v.string(), v.minLength(1)),\n name: v.pipe(v.string(), v.minLength(1)),\n }),\n v.object({\n type: v.literal(\"system\"),\n id: v.pipe(v.string(), v.minLength(1)),\n name: v.optional(v.string()),\n }),\n v.object({\n type: v.literal(\"automation\"),\n id: v.pipe(v.string(), v.minLength(1)),\n name: v.optional(v.string()),\n }),\n v.object({\n type: v.literal(\"integration\"),\n id: v.pipe(v.string(), v.minLength(1)),\n name: v.optional(v.string()),\n }),\n v.object({\n type: v.literal(\"candidate\"),\n id: v.pipe(v.string(), v.minLength(1)),\n email: v.optional(v.string()),\n }),\n]);\n","import * as v from \"valibot\";\nexport const PaginationSchema = v.object({\n total: v.number(),\n page: v.number(),\n perPage: v.number(),\n lastPage: v.number(),\n});\nexport function paginatedResultSchema(itemSchema) {\n return v.object({\n data: v.array(itemSchema),\n pagination: PaginationSchema,\n });\n}\n","import * as v from \"valibot\";\nimport { CandidateSourceSchema } from \"./enums.js\";\nexport const CandidateSchema = v.object({\n id: v.string(),\n email: v.nullable(v.string()),\n firstName: v.nullable(v.string()),\n lastName: v.nullable(v.string()),\n phone: v.nullable(v.string()),\n source: v.nullable(CandidateSourceSchema),\n identifiedAt: v.nullable(v.string()),\n createdAt: v.string(),\n updatedAt: v.string(),\n});\n","import * as v from \"valibot\";\nimport { UnknownRecordSchema } from \"./_shared.js\";\nimport { CandidateSchema } from \"./candidate.js\";\nimport { ActorTypeSchema, ApplicationActionSchema, ApplicationSourceSchema, DisqualificationReasonSchema, ScoreTypeSchema, StageGroupSchema, StageSchema, } from \"./enums.js\";\nimport { InterviewSchema } from \"./interview.js\";\nexport const ScoreCategorySchema = v.object({\n score: v.number(),\n reason: v.string(),\n confidence: v.number(),\n});\nexport const ApplicationSchema = v.object({\n id: v.string(),\n candidateId: v.string(),\n jobId: v.number(),\n stage: StageSchema,\n stageGroup: StageGroupSchema,\n stageEnteredAt: v.string(),\n rating: v.nullable(v.number()),\n disqualifiedAt: v.nullable(v.string()),\n disqualificationReason: v.nullable(DisqualificationReasonSchema),\n disqualificationNote: v.nullable(v.string()),\n source: ApplicationSourceSchema,\n sourceDetail: v.nullable(v.string()),\n sessionId: v.nullable(v.number()),\n externalApplicationId: v.nullable(v.string()),\n meta: v.nullable(UnknownRecordSchema),\n context: v.nullable(UnknownRecordSchema),\n scoredAt: v.nullable(v.string()),\n createdAt: v.string(),\n updatedAt: v.string(),\n});\nexport const ApplicationScoreSchema = v.object({\n id: v.string(),\n applicationId: v.string(),\n scoreType: ScoreTypeSchema,\n score: v.nullable(v.number()),\n reason: v.nullable(v.string()),\n categories: v.nullable(v.record(v.string(), ScoreCategorySchema)),\n scoredBy: v.nullable(v.string()),\n createdAt: v.string(),\n});\nexport const ApplicationDetailSchema = v.object({\n ...ApplicationSchema.entries,\n candidate: v.nullable(CandidateSchema),\n score: v.nullable(ApplicationScoreSchema),\n interview: v.nullable(InterviewSchema),\n});\nexport const CandidateDetailSchema = v.object({\n ...CandidateSchema.entries,\n applications: v.array(ApplicationSchema),\n});\n/**\n * Audit-log row recording a single state-mutating action against an\n * application. Structured stage columns carry every transition-relevant\n * field in typed form; `meta` carries opaque action-specific extras.\n */\nexport const ApplicationLogSchema = v.object({\n id: v.string(),\n applicationId: v.string(),\n action: ApplicationActionSchema,\n fromStage: v.nullable(StageSchema),\n fromStageGroup: v.nullable(StageGroupSchema),\n toStage: v.nullable(StageSchema),\n toStageGroup: v.nullable(StageGroupSchema),\n disqualificationReason: v.nullable(DisqualificationReasonSchema),\n disqualificationNote: v.nullable(v.string()),\n actorId: v.nullable(v.string()),\n actorType: ActorTypeSchema,\n actorEmail: v.nullable(v.string()),\n actorName: v.nullable(v.string()),\n meta: v.nullable(UnknownRecordSchema),\n schemaVersion: v.number(),\n createdAt: v.string(),\n});\n","import * as v from \"valibot\";\n// Shared building blocks used by HTTP DTO schemas. Not re-exported from the\n// public barrel — these stay private to the contract folder so consumers don't\n// depend on incidental helpers.\nexport const RequiredStringSchema = v.pipe(v.string(), v.minLength(1));\nexport const PositiveIntegerSchema = v.pipe(v.number(), v.integer(), v.minValue(1));\nexport const UnknownRecordSchema = v.record(v.string(), v.unknown());\n","import * as v from \"valibot\";\nimport { UnknownRecordSchema } from \"./_shared.js\";\nimport { InterviewStatusSchema } from \"./enums.js\";\nexport const InterviewSchema = v.object({\n id: v.string(),\n applicationId: v.string(),\n status: InterviewStatusSchema,\n scheduledAt: v.nullable(v.string()),\n completedAt: v.nullable(v.string()),\n meta: v.nullable(UnknownRecordSchema),\n createdAt: v.string(),\n updatedAt: v.string(),\n});\n","import * as v from \"valibot\";\nimport { RequiredStringSchema } from \"../_shared.js\";\nimport { CandidateSourceSchema } from \"../enums.js\";\nexport const IdentifyInputSchema = v.object({\n anonymousId: RequiredStringSchema,\n email: RequiredStringSchema,\n firstName: v.nullish(v.string()),\n lastName: v.nullish(v.string()),\n phone: v.nullish(v.string()),\n source: v.nullish(CandidateSourceSchema),\n});\nexport const IdentifyResultSchema = v.object({\n candidateId: v.string(),\n isNew: v.boolean(),\n});\n","import * as v from \"valibot\";\nimport { PositiveIntegerSchema, RequiredStringSchema, UnknownRecordSchema, } from \"../_shared.js\";\nimport { ApplicationDetailSchema, ApplicationLogSchema, ScoreCategorySchema, } from \"../application.js\";\nimport { ActorInputSchema, ApplicationSortFieldSchema, ApplicationSourceSchema, DisqualificationReasonSchema, ScoreTypeSchema, SortOrderSchema, StageGroupSchema, StageSchema, } from \"../enums.js\";\nimport { paginatedResultSchema } from \"../pagination.js\";\n/**\n * Action keys exposed to consumers via the generic `applyAction` endpoint.\n * Excludes server-driven entries from {@link APPLICATION_ACTIONS} (`submit`,\n * `score_written`) because those are write-only audit-log labels emitted by\n * the store's dedicated paths, not user-dispatchable actions.\n */\nexport const APPLY_ACTION_KEYS = [\n \"stage_transition\",\n \"move_to_stage\",\n \"shortlist\",\n \"move_to_interview\",\n \"make_offer\",\n \"hire\",\n \"withdraw\",\n \"disqualify\",\n \"reinstate\",\n \"rate\",\n];\nexport const ApplyActionKeySchema = v.picklist(APPLY_ACTION_KEYS);\n/**\n * Comma-separated string in query parameters; transformed into a string[]\n * for downstream use. e.g. `?stages=applied,shortlisted`.\n */\nconst CommaSeparatedStringSchema = v.pipe(v.string(), v.transform((s) => s\n .split(\",\")\n .map((t) => t.trim())\n .filter((t) => t.length > 0)));\n// Stages are free-text post-v6 — the query filter accepts whatever the\n// caller passes. Stage groups remain picklist-validated below.\nconst StagesQuerySchema = v.pipe(CommaSeparatedStringSchema, v.array(StageSchema));\nconst StageGroupsQuerySchema = v.pipe(CommaSeparatedStringSchema, v.array(StageGroupSchema));\nconst JobIdsQuerySchema = v.pipe(v.string(), v.transform((s) => s\n .split(\",\")\n .map((t) => Number(t.trim()))\n .filter((n) => Number.isInteger(n) && n > 0)));\nexport const ListApplicationsQuerySchema = v.object({\n stages: v.optional(StagesQuerySchema),\n stage_groups: v.optional(StageGroupsQuerySchema),\n job_id: v.optional(v.string()),\n job_ids: v.optional(JobIdsQuerySchema),\n candidate_id: v.optional(v.string()),\n is_disqualified: v.optional(v.picklist([\"true\", \"false\"])),\n created_from: v.optional(v.string()),\n created_to: v.optional(v.string()),\n updated_from: v.optional(v.string()),\n updated_to: v.optional(v.string()),\n entered_stage_from: v.optional(v.string()),\n entered_stage_to: v.optional(v.string()),\n from: v.optional(v.string()),\n to: v.optional(v.string()),\n q: v.optional(v.string()),\n scored: v.optional(v.picklist([\"true\", \"false\"])),\n sort: v.optional(ApplicationSortFieldSchema),\n order: v.optional(SortOrderSchema),\n page: v.optional(v.string()),\n per_page: v.optional(v.string()),\n});\n/**\n * `stage` and `stageGroup` must be supplied together, or both omitted. Only\n * studio knows which stage slug belongs in which group (the slug is free-text\n * and the platform deliberately does not carry the per-tenant mapping), so a\n * `stage` arriving without an explicit `stageGroup` cannot be classified\n * without guessing. Omitting both still works and falls back to the\n * `applied` / `APPLIED` defaults inside the store.\n */\nexport const SubmitApplicationInputSchema = v.pipe(v.object({\n candidateId: RequiredStringSchema,\n jobId: PositiveIntegerSchema,\n meta: v.nullish(UnknownRecordSchema),\n sessionId: v.nullish(v.number()),\n externalApplicationId: v.nullish(v.string()),\n context: v.nullish(UnknownRecordSchema),\n source: v.nullish(ApplicationSourceSchema),\n sourceDetail: v.nullish(v.string()),\n stage: v.nullish(StageSchema),\n stageGroup: v.nullish(StageGroupSchema),\n actor: v.nullish(ActorInputSchema),\n}), v.check((input) => (input.stage == null) === (input.stageGroup == null), \"stage and stageGroup must be supplied together\"));\nconst DuplicateApplicationSchema = v.object({\n id: v.string(),\n stageGroup: v.string(),\n createdAt: v.string(),\n});\nexport const SubmitApplicationResultSchema = v.union([\n v.object({\n ok: v.literal(true),\n duplicate: v.literal(false),\n applicationId: v.string(),\n candidateId: v.string(),\n }),\n v.object({\n ok: v.literal(true),\n duplicate: v.literal(true),\n existingApplication: DuplicateApplicationSchema,\n }),\n]);\nexport const DuplicateCheckResultSchema = v.object({\n isDuplicate: v.boolean(),\n existingApplication: v.optional(DuplicateApplicationSchema),\n});\nexport const WriteScoreInputSchema = v.object({\n applicationId: RequiredStringSchema,\n scoreType: ScoreTypeSchema,\n score: v.number(),\n reason: v.nullish(v.string()),\n categories: v.nullish(v.record(v.string(), ScoreCategorySchema)),\n scoredBy: v.nullish(v.string()),\n actor: v.nullish(ActorInputSchema),\n});\nexport const WriteScoreResponseSchema = v.object({ scoreId: v.string() });\nexport const ListApplicationsResponseSchema = paginatedResultSchema(ApplicationDetailSchema);\nexport const GetApplicationResponseSchema = ApplicationDetailSchema;\n/**\n * Single-row stage transition. The server does **not** validate the\n * `(toStage, toStageGroup)` pair against any closed map — `toStage` is\n * free-text and studio is the only system that knows whether a given slug\n * belongs to its configured group.\n */\n/**\n * Skip reasons surfaced by the dispatcher when a stage-changing action is a\n * no-op. Kept as a top-level schema because it's a primitive reused both in\n * `ApplyActionSkipReasonSchema` (which adds `already_disqualified`) and by\n * internal store types via the inferred `TransitionSkipReason` type.\n */\nconst TransitionSkipReasonSchema = v.picklist([\n \"already_in_target_stage\",\n \"not_in_source_stage\",\n \"disqualified\",\n]);\nexport const ListApplicationLogsResponseSchema = v.array(ApplicationLogSchema);\n/* ─────────────────────────────────────────────────────────────\n * Generic applyAction surface\n * ──────────────────────────────────────────────────────────── */\n/**\n * Meta schemas per action key. The generic `applyAction` HTTP body wraps one\n * of these in a discriminated union so each action's payload is validated\n * before reaching the store.\n *\n * `note` fields are optional everywhere except where the rule itself\n * requires them (e.g. `disqualify` with `reason='other'`, enforced inside\n * the registry — not duplicated here).\n */\nconst NoteMeta = v.object({\n stage: v.nullish(StageSchema),\n note: v.nullish(v.string()),\n});\nconst HireMeta = v.object({\n stage: v.nullish(StageSchema),\n startDate: v.nullish(v.string()),\n note: v.nullish(v.string()),\n});\nexport const ApplyActionInputSchema = v.variant(\"action\", [\n v.object({\n action: v.literal(\"shortlist\"),\n actor: ActorInputSchema,\n meta: v.nullish(NoteMeta),\n }),\n v.object({\n action: v.literal(\"move_to_interview\"),\n actor: ActorInputSchema,\n meta: v.nullish(NoteMeta),\n }),\n v.object({\n action: v.literal(\"make_offer\"),\n actor: ActorInputSchema,\n meta: v.nullish(NoteMeta),\n }),\n v.object({\n action: v.literal(\"hire\"),\n actor: ActorInputSchema,\n meta: v.nullish(HireMeta),\n }),\n v.object({\n action: v.literal(\"withdraw\"),\n actor: ActorInputSchema,\n meta: v.nullish(NoteMeta),\n }),\n v.object({\n action: v.literal(\"move_to_stage\"),\n actor: ActorInputSchema,\n meta: v.object({\n stage: StageSchema,\n stageGroup: StageGroupSchema,\n note: v.nullish(v.string()),\n }),\n }),\n v.object({\n action: v.literal(\"stage_transition\"),\n actor: ActorInputSchema,\n meta: v.object({\n toStage: StageSchema,\n toStageGroup: StageGroupSchema,\n note: v.nullish(v.string()),\n }),\n }),\n v.object({\n action: v.literal(\"disqualify\"),\n actor: ActorInputSchema,\n meta: v.object({\n reason: DisqualificationReasonSchema,\n note: v.nullish(v.string()),\n }),\n }),\n v.object({\n action: v.literal(\"reinstate\"),\n actor: ActorInputSchema,\n meta: v.object({\n toStage: StageSchema,\n toStageGroup: StageGroupSchema,\n note: v.nullish(v.string()),\n }),\n }),\n v.object({\n action: v.literal(\"rate\"),\n actor: ActorInputSchema,\n meta: v.object({\n rating: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(5))),\n }),\n }),\n]);\nexport const BulkApplyActionInputSchema = v.object({\n applicationIds: v.pipe(v.array(v.string()), v.minLength(1)),\n body: ApplyActionInputSchema,\n});\nconst ApplyActionSkipReasonSchema = v.picklist([\n \"already_in_target_stage\",\n \"not_in_source_stage\",\n \"disqualified\",\n \"already_disqualified\",\n]);\n/**\n * Result envelope for the generic apply-action endpoint. `updated` returns\n * the new application detail; `skipped` returns the no-op reason; `failed`\n * is reserved for bulk responses (single-row failures surface as HTTP 4xx).\n */\nexport const ApplyActionResultSchema = v.variant(\"kind\", [\n v.object({\n kind: v.literal(\"updated\"),\n action: ApplyActionKeySchema,\n application: ApplicationDetailSchema,\n }),\n v.object({\n kind: v.literal(\"skipped\"),\n action: ApplyActionKeySchema,\n applicationId: v.string(),\n reason: ApplyActionSkipReasonSchema,\n }),\n]);\nexport const BulkApplyActionResultSchema = v.object({\n updated: v.array(v.object({\n kind: v.literal(\"updated\"),\n action: ApplyActionKeySchema,\n application: ApplicationDetailSchema,\n })),\n skipped: v.array(v.object({\n kind: v.literal(\"skipped\"),\n action: ApplyActionKeySchema,\n applicationId: v.string(),\n reason: ApplyActionSkipReasonSchema,\n })),\n failed: v.array(v.object({ applicationId: v.string(), error: v.string() })),\n});\n/* ─────────────────────────────────────────────────────────────\n * Per-job application counts (jobs list page badge / column)\n * ──────────────────────────────────────────────────────────── */\nconst NonNegativeIntegerSchema = v.pipe(v.number(), v.integer(), v.minValue(0));\n/**\n * Zero-filled count for every stage group. Talent-bank always returns the\n * full shape so studio (and other consumers) never need to defensive-merge\n * against missing keys when a job has no applications in a particular group.\n */\nexport const JobApplicationCountsSchema = v.object({\n APPLIED: NonNegativeIntegerSchema,\n SHORTLISTED: NonNegativeIntegerSchema,\n INTERVIEWED: NonNegativeIntegerSchema,\n OFFERED: NonNegativeIntegerSchema,\n HIRED: NonNegativeIntegerSchema,\n REJECTED: NonNegativeIntegerSchema,\n WITHDRAWN: NonNegativeIntegerSchema,\n});\nexport const ListJobApplicationCountsQuerySchema = v.object({\n job_ids: JobIdsQuerySchema,\n});\n/**\n * Response is keyed by job-ID string. Every requested job appears in the\n * map, even when it has zero applications, so callers can safely iterate\n * over their input job list without nullable-handling.\n */\nexport const ListJobApplicationCountsResponseSchema = v.object({\n counts: v.record(v.string(), JobApplicationCountsSchema),\n});\n","import { CandidateDetailSchema } from \"../application.js\";\nimport { CandidateSchema } from \"../candidate.js\";\nimport { paginatedResultSchema } from \"../pagination.js\";\nexport const ListCandidatesResponseSchema = paginatedResultSchema(CandidateSchema);\nexport const GetCandidateResponseSchema = CandidateDetailSchema;\n","import * as v from \"valibot\";\nexport const JobMetricsResponseSchema = v.object({\n avg_score: v.nullable(v.number()),\n p90_score: v.nullable(v.number()),\n p85_score: v.nullable(v.number()),\n p80_score: v.nullable(v.number()),\n total_scores: v.number(),\n /**\n * Cumulative count of distinct applications shortlisted by our own\n * automations for this job (\"ever shortlisted by us\"), sourced from\n * `application.shortlisted` analytics events whose actor type is\n * `automation`. Append-only; does not decrease when a candidate moves out\n * of a shortlisted column. Excludes recruiter-initiated shortlists made\n * directly in the ATS (which never reach the action engine) and human\n * shortlists made in studio (actor type `user`).\n */\n total_shortlists: v.number(),\n});\n","import { DuplicateCheckResultSchema, IdentifyInputSchema, IdentifyResultSchema } from '@inploi/talent-bank/contract';\nimport * as v from 'valibot';\n\nimport { ENV_TO_TALENT_BANK_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger } from './sdk.logger';\n\n// `@inploi/talent-bank` is a private package: tsup bundles its schemas into the\n// npm build, but cannot inline its types into `dist/index.d.ts`, so the shapes\n// this client exposes are declared here. The call sites below (`parsed.output`\n// return values and the schema-typed `identify` body) keep them assignable to\n// the bundled contract.\ntype DuplicateCheckScope = 'job' | 'company';\n\ntype CandidateSource = 'agent' | 'sdk' | 'form' | 'integration' | 'migration';\n\nexport type TalentBankCheckDuplicateResult = {\n\tisDuplicate: boolean;\n\texistingApplication?: { id: string; stageGroup: string; createdAt: string };\n};\n\nexport type TalentBankIdentifyParams = {\n\tanonymousId: string;\n\temail: string;\n\tfirstName?: string | null;\n\tlastName?: string | null;\n\tphone?: string | null;\n\t/** Caller tag — defaults to `'sdk'`. */\n\tsource?: CandidateSource;\n};\n\nexport type TalentBankIdentifyResult = { candidateId: string; isNew: boolean };\n\nexport interface TalentBankClient {\n\tcheckDuplicate(params: {\n\t\temail: string;\n\t\tjobId?: string | number;\n\t\tscope: DuplicateCheckScope;\n\t}): Promise<TalentBankCheckDuplicateResult>;\n\n\t/**\n\t * Resolve or create a Talent Bank candidate for the supplied identifier.\n\t *\n\t * This is the direct-to-Talent-Bank replacement for the old Laravel-proxied\n\t * `/log` IDENTIFY flow. The SDK calls this and then forwards the returned\n\t * `candidateId` on every subsequent analytics log so Laravel can stamp it\n\t * onto the session for attribution.\n\t *\n\t * Returns `null` if the call fails — identification is best-effort and must\n\t * never break the host page.\n\t */\n\tidentify(params: TalentBankIdentifyParams): Promise<TalentBankIdentifyResult | null>;\n}\n\nexport const createTalentBankClient = ({\n\tenvironment,\n\tpublishableKey,\n\tlogger,\n}: {\n\tenvironment: InploiSdkEnvironment;\n\tpublishableKey: string;\n\tlogger: Logger;\n}): TalentBankClient => {\n\tconst baseUrl = ENV_TO_TALENT_BANK_URL[environment];\n\n\treturn {\n\t\tasync checkDuplicate(params) {\n\t\t\ttry {\n\t\t\t\tconst searchParams = new URLSearchParams({ email: params.email, scope: params.scope });\n\t\t\t\tif (params.scope === 'job' && params.jobId != null) {\n\t\t\t\t\tsearchParams.set('job_id', String(params.jobId));\n\t\t\t\t}\n\n\t\t\t\tconst response = await fetch(`${baseUrl}/applications/check-duplicate?${searchParams}`, {\n\t\t\t\t\tmethod: 'GET',\n\t\t\t\t\theaders: { Accept: 'application/json', 'x-publishable-key': publishableKey },\n\t\t\t\t});\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.error(`[TalentBankClient] checkDuplicate failed with status ${response.status}`);\n\t\t\t\t\treturn { isDuplicate: false };\n\t\t\t\t}\n\n\t\t\t\tconst json = await response.json();\n\t\t\t\tconst parsed = v.safeParse(DuplicateCheckResultSchema, json);\n\t\t\t\tif (parsed.success) {\n\t\t\t\t\treturn parsed.output;\n\t\t\t\t}\n\n\t\t\t\t// `isDuplicate` is the only field callers gate on; `existingApplication`\n\t\t\t\t// is supplementary. A schema drift in that nested payload must never\n\t\t\t\t// silently downgrade a real duplicate to a non-duplicate, so fall back\n\t\t\t\t// to the flag directly rather than failing closed.\n\t\t\t\tlogger.error('[TalentBankClient] checkDuplicate response failed strict validation; falling back to isDuplicate flag');\n\t\t\t\tif (\n\t\t\t\t\ttypeof json === 'object' &&\n\t\t\t\t\tjson != null &&\n\t\t\t\t\ttypeof (json as { isDuplicate?: unknown }).isDuplicate === 'boolean'\n\t\t\t\t) {\n\t\t\t\t\treturn { isDuplicate: (json as { isDuplicate: boolean }).isDuplicate };\n\t\t\t\t}\n\n\t\t\t\treturn { isDuplicate: false };\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error('[TalentBankClient] checkDuplicate failed:', e);\n\t\t\t\treturn { isDuplicate: false };\n\t\t\t}\n\t\t},\n\n\t\tasync identify(params) {\n\t\t\ttry {\n\t\t\t\tif (!params.anonymousId) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify skipped because anonymousId is missing');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst body: v.InferInput<typeof IdentifyInputSchema> = {\n\t\t\t\t\temail: params.email,\n\t\t\t\t\tfirstName: params.firstName,\n\t\t\t\t\tlastName: params.lastName,\n\t\t\t\t\tphone: params.phone,\n\t\t\t\t\tanonymousId: params.anonymousId,\n\t\t\t\t\tsource: params.source ?? 'sdk',\n\t\t\t\t};\n\t\t\t\tconst parsedBody = v.safeParse(IdentifyInputSchema, body);\n\t\t\t\tif (!parsedBody.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify received invalid input');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst response = await fetch(`${baseUrl}/identify`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t\tAccept: 'application/json',\n\t\t\t\t\t\t'x-publishable-key': publishableKey,\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(parsedBody.output),\n\t\t\t\t});\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.error(`[TalentBankClient] identify failed with status ${response.status}`);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst parsed = v.safeParse(IdentifyResultSchema, await response.json());\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify returned an invalid response');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\treturn parsed.output;\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error('[TalentBankClient] identify failed:', e);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\t};\n};\n","import { AnalyticsOnEventCallback, createAnalyticsService } from './sdk.analytics';\nimport { createApiClient } from './sdk.api';\nimport { ENV_TO_API_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger, inploiBrandedLogger, noLogging } from './sdk.logger';\nimport { InploiSdkPlugin } from './sdk.plugins';\nimport { InploiRpcClient } from './sdk.rpc';\nimport { createTalentBankClient } from './sdk.talent-bank';\n\nexport type InitialiseInploiSdkParams = {\n\t/** Your public API key for the inploi SDK. */\n\tpublishableKey: string;\n\t/** Which app environment to run. This ultimately affects which inploi endpoints to gather data are going to be used.\n\t * Anything other than `production` should be considered a development environment and the data periodicaly purged. */\n\tenv: InploiSdkEnvironment;\n\t/** Logger object that handles logging of different levels.\n\t * You can override this to use your own logger, or to disable logging altogether by passing`false`.\n\t * @default inploiBrandedLogger\n\t * */\n\tlogger?: Logger | false;\n\n\t/** When provided, this callback will be called with every event that is logged to the analytics service. */\n\tonEvent?: AnalyticsOnEventCallback;\n\t/** Analytics identity storage. `none` keeps only an API session in memory; defaults to `device`. */\n\tpersistence?: 'device' | 'none';\n};\n\nexport function initialiseSdk({\n\tpublishableKey,\n\tenv,\n\tlogger = inploiBrandedLogger,\n\tonEvent,\n\tpersistence,\n}: InitialiseInploiSdkParams) {\n\t/** @deprecated - use `rpcClient` instead */\n\tconst apiClient = createApiClient({ baseUrl: ENV_TO_API_URL[env], publishableKey });\n\tconst loggerService = logger === false ? noLogging : logger;\n\tconst rpcClient = new InploiRpcClient({\n\t\tenvironment: env,\n\t\tapiKey: { type: 'publishable', key: publishableKey },\n\t\tlogger: loggerService,\n\t});\n\tconst talentBank = createTalentBankClient({ environment: env, publishableKey, logger: loggerService });\n\tconst analytics = createAnalyticsService({\n\t\trpcClient,\n\t\tlogger: loggerService,\n\t\tonEvent,\n\t\ttalentBank,\n\t\tpersistence,\n\t});\n\n\tconst register = <P extends InploiSdkPlugin>(plugin: P): ReturnType<P> => {\n\t\treturn plugin({ logger: loggerService, apiClient, analytics, rpcClient, publishableKey, env });\n\t};\n\n\treturn { register, analytics, apiClient };\n}\n\nexport type InploiSdk = ReturnType<typeof initialiseSdk>;\n","import { CONSENT_STORAGE_KEY_PREFIX } from './sdk.constants';\n\n/**\n * Tenant-published consent / approval config (PROD-5763).\n *\n * Mirror of `ConsentConfig` in inploi/agents — the agent worker sends\n * this in the `authenticated` WS event for the SDK to render before\n * the chat is usable.\n *\n * enabled — render the consent screen on first session if true.\n * message — body copy; markdown is rendered, so customers can\n * embed links inline (e.g. \"By continuing you agree\n * to our [Privacy Policy](https://...)\").\n * acceptLabel — text on the \"agree\" button. SDK defaults to\n * \"I agree\" if omitted.\n * declineLabel — text on the \"decline\" button. SDK defaults to\n * \"Decline\".\n */\nexport interface ConsentConfig {\n\tenabled: boolean;\n\tmessage: string;\n\tacceptLabel?: string;\n\tdeclineLabel?: string;\n}\n\n/**\n * Deterministic, fast, non-cryptographic hash of the consent config.\n * Used purely as a cache-busting suffix on the localStorage key — so\n * any material wording / label change produces a new key and the\n * candidate is re-prompted. Not a security primitive.\n *\n * djb2 + base36 = ~7 chars, plenty of entropy for a per-tenant key\n * suffix and easy to eyeball / grep in devtools storage.\n *\n * Exported for unit testing.\n */\nexport function hashConsentConfig(config: ConsentConfig): string {\n\tconst canonical = JSON.stringify({\n\t\tmessage: config.message,\n\t\tacceptLabel: config.acceptLabel ?? '',\n\t\tdeclineLabel: config.declineLabel ?? '',\n\t});\n\tlet hash = 5381;\n\tfor (let i = 0; i < canonical.length; i++) {\n\t\t// djb2: hash * 33 + char\n\t\thash = (hash * 33) ^ canonical.charCodeAt(i);\n\t}\n\t// Force unsigned 32-bit, then base36 for compactness.\n\treturn (hash >>> 0).toString(36);\n}\n\n/**\n * Build the localStorage key for a (tenant × consent config) pair.\n *\n * Exported for unit testing.\n */\nexport function consentStorageKey(publishableKey: string, configHash: string): string {\n\treturn `${CONSENT_STORAGE_KEY_PREFIX}:${publishableKey}:${configHash}`;\n}\n\n/**\n * Has the candidate already accepted this exact consent config?\n *\n * Returns `false` in non-browser environments and when localStorage\n * throws (Safari private mode, sandboxed iframes without storage\n * access). Same conservative posture as `getStoredCandidateId` — if\n * we cannot prove acceptance, re-prompt.\n */\nexport function getConsentAcceptance(publishableKey: string, config: ConsentConfig): boolean {\n\tif (typeof window === 'undefined') return false;\n\ttry {\n\t\tconst key = consentStorageKey(publishableKey, hashConsentConfig(config));\n\t\treturn window.localStorage.getItem(key) === 'accepted';\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Persist the candidate's acceptance of this exact consent config.\n *\n * Silently no-ops on storage failures — the consent flow still works\n * for the current page even if we cannot remember it across reloads.\n * That matches the existing identity / candidate-id pattern.\n */\nexport function setConsentAcceptance(publishableKey: string, config: ConsentConfig): void {\n\tif (typeof window === 'undefined') return;\n\ttry {\n\t\tconst key = consentStorageKey(publishableKey, hashConsentConfig(config));\n\t\twindow.localStorage.setItem(key, 'accepted');\n\t} catch {\n\t\t// localStorage unavailable — see comment above.\n\t}\n}\n","export function ready(callback: () => void): void {\n\tif (typeof document === 'undefined') return;\n\n\tif (document.readyState === 'loading') {\n\t\tdocument.addEventListener('DOMContentLoaded', callback, { once: true });\n\t\treturn;\n\t}\n\n\tPromise.resolve().then(callback);\n}\n","import * as v from 'valibot';\n\nimport { InploiRpcClient, endpoint, typed } from './sdk.rpc';\n\nexport const JOB_ALERT_FREQUENCIES = ['DAILY', 'WEEKLY', 'MONTHLY'] as const;\n\n/** A saved search: each filter's values and, for a search around a place, the place and radius in metres\n * (the API's alert engine matches jobs within it), with the unit and place name the candidate saw. */\nconst alertFiltersSchema = v.record(\n\tv.string(),\n\tv.union([\n\t\tv.string(),\n\t\tv.array(v.string()),\n\t\tv.object({\n\t\t\ttype: v.literal('provided'),\n\t\t\tlat: v.number(),\n\t\t\tlng: v.number(),\n\t\t\tradius: v.number(),\n\t\t\tunit: v.optional(v.picklist(['miles', 'km'])),\n\t\t\tlabel: v.optional(v.string()),\n\t\t}),\n\t]),\n);\n\nexport type JobAlertsFilters = v.InferInput<typeof alertFiltersSchema>;\n\nconst closedJobEndpoint = endpoint({\n\tpathname: '/job/:id',\n\tmethod: 'GET',\n\tschema: {\n\t\tresponse: v.object({\n\t\t\tid: v.number(),\n\t\t\texternal_id: v.nullish(v.string()),\n\t\t\tcity: v.nullish(v.string()),\n\t\t\ttown: v.nullish(v.string()),\n\t\t\tcategory: v.nullish(v.string()),\n\t\t}),\n\t},\n});\n\n/** Save alerts only after the candidate opts in; a failed lookup must never widen the search. */\nexport async function saveClosedRoleJobAlerts(\n\trpcClient: InploiRpcClient,\n\t{\n\t\tcontact,\n\t\tjob,\n\t}: {\n\t\tcontact: { email: string; first_name?: string; last_name?: string };\n\t\tjob?: { id: string; id_type: 'internal' | 'external' };\n\t},\n): Promise<void> {\n\tconst filters: JobAlertsFilters = {};\n\tif (job) {\n\t\tconst found = await rpcClient.request(closedJobEndpoint, {\n\t\t\tparams: { id: job.id },\n\t\t});\n\t\t// API JobController::show treats numeric ids as internal even for ATS callers; verify the returned identity.\n\t\tconst identity = job.id_type === 'internal' ? String(found.id) : found.external_id;\n\t\tif (identity !== job.id) throw new Error('Job lookup returned a different role');\n\t\tfor (const field of ['city', 'town', 'category'] as const) {\n\t\t\tconst value = found[field]?.trim();\n\t\t\tif (value) filters[field] = [value];\n\t\t}\n\t}\n\tawait rpcClient.request(saveSearchEndpoint, { body: { contact, alerts: 'WEEKLY', filters } });\n}\n\nexport const saveSearchEndpoint = endpoint({\n\tpathname: '/search/save',\n\tmethod: 'POST',\n\tschema: {\n\t\tresponse: typed<void>(),\n\t\tbody: v.object({\n\t\t\tcontact: v.object({\n\t\t\t\temail: v.pipe(v.optional(v.string()), v.string(), v.email()),\n\t\t\t\tfirst_name: v.optional(v.string()),\n\t\t\t\tlast_name: v.optional(v.string()),\n\t\t\t}),\n\t\t\talerts: v.pipe(v.optional(v.string()), v.string(), v.picklist(JOB_ALERT_FREQUENCIES)),\n\t\t\tfilters: alertFiltersSchema,\n\t\t}),\n\t},\n});\n","import * as v from 'valibot';\n\nimport { InploiRpcClient, endpoint, typed } from './sdk.rpc';\n\n/** The countries the company's live jobs give, as their feeds spell them. */\nexport const getJobCountries = async (rpcClient: InploiRpcClient) => {\n\tconst jobCountriesEndpoint = endpoint({\n\t\tmethod: 'GET',\n\t\tpathname: '/search/filters',\n\t\tschema: {\n\t\t\tresponse: v.pipe(\n\t\t\t\tv.object({ country: v.optional(v.array(v.object({ value: v.string() })), []) }),\n\t\t\t\tv.transform(({ country }) => country.map(({ value }) => value)),\n\t\t\t),\n\t\t\tsearchParams: typed<{ filters: { country: null } }>(),\n\t\t},\n\t});\n\treturn rpcClient.request(jobCountriesEndpoint, { searchParams: { filters: { country: null } } });\n};\n\n/** Per widget/SDK client, including pending and failed reads. Never shared across tenants or environments. */\nconst addressCountries = new WeakMap<InploiRpcClient, string | undefined>();\n\n/**\n * Starts one background read and returns only countries already available. A slow, empty or failed read must\n * never delay or fail an address lookup: it keeps today's unfiltered suggestions, including on immediate Enter.\n */\nexport const addressSearchCountry = (rpcClient: InploiRpcClient): string | undefined => {\n\tif (!addressCountries.has(rpcClient)) {\n\t\taddressCountries.set(rpcClient, undefined);\n\t\tvoid getJobCountries(rpcClient)\n\t\t\t.then(async countries => {\n\t\t\t\tconst { jobCountryCodes } = await import('./sdk.country-codes');\n\t\t\t\t// Every hiring country is kept: Search Box documents a comma-separated ISO2 list with no count limit,\n\t\t\t\t// and dropping one would hide its addresses whenever the others return any suggestion.\n\t\t\t\t// https://docs.mapbox.com/api/search/search-box/#get-suggested-results\n\t\t\t\taddressCountries.set(rpcClient, jobCountryCodes(countries).join(',') || undefined);\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\t// Failed country metadata is optional; keep unfiltered lookup and do not retry on every keystroke.\n\t\t\t});\n\t}\n\treturn addressCountries.get(rpcClient);\n};\n\ntype AddressSuggestion = {\n\tmapbox_id?: string;\n\tfull_address?: string;\n\tname?: string;\n\tplace_formatted?: string;\n};\n\n/** Alternate hiring-country and worldwide picks, skipping duplicates, within the existing five-result list. */\nexport const blendAddressSuggestions = <T extends AddressSuggestion>(filtered: T[], unfiltered: T[]): T[] => {\n\tconst seen = new Set<string>();\n\tconst suggestions: T[] = [];\n\tfor (let i = 0; i < Math.max(filtered.length, unfiltered.length); i++) {\n\t\tfor (const item of [filtered[i], unfiltered[i]]) {\n\t\t\tif (!item) continue;\n\t\t\tconst key = item.mapbox_id || item.full_address || [item.name, item.place_formatted].filter(Boolean).join(', ');\n\t\t\tif (seen.has(key)) continue;\n\t\t\tseen.add(key);\n\t\t\tsuggestions.push(item);\n\t\t\tif (suggestions.length === 5) return suggestions;\n\t\t}\n\t}\n\treturn suggestions;\n};\n\nconst ADDRESS_SUGGESTION_GRACE_MS = 600;\n\n/** Both lookups share the caller's session token and signal; a non-empty list waits briefly for its partner. */\nexport const searchAddressSuggestions = async <T extends AddressSuggestion>(\n\tlookup: (country?: string) => Promise<T[]>,\n\tcountry: string | undefined,\n\tsignal?: AbortSignal,\n): Promise<T[]> => {\n\tsignal?.throwIfAborted();\n\tif (!country) {\n\t\tconst items = await lookup();\n\t\tsignal?.throwIfAborted();\n\t\treturn items;\n\t}\n\treturn new Promise<T[]>((resolve, reject) => {\n\t\tlet filtered: PromiseSettledResult<T[]> | undefined;\n\t\tlet unfiltered: PromiseSettledResult<T[]> | undefined;\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tlet finished = false;\n\t\tconst cleanup = () => {\n\t\t\tfinished = true;\n\t\t\tclearTimeout(timer);\n\t\t\tsignal?.removeEventListener('abort', abort);\n\t\t};\n\t\tconst abort = () => {\n\t\t\tcleanup();\n\t\t\treject(signal?.reason);\n\t\t};\n\t\tconst finish = () => {\n\t\t\tcleanup();\n\t\t\tif (filtered?.status === 'fulfilled' && unfiltered?.status === 'fulfilled') {\n\t\t\t\tresolve(blendAddressSuggestions(filtered.value, unfiltered.value));\n\t\t\t} else if (filtered?.status === 'fulfilled') resolve(filtered.value);\n\t\t\telse if (unfiltered?.status === 'fulfilled') resolve(unfiltered.value);\n\t\t\telse if (filtered?.status === 'rejected') reject(filtered.reason);\n\t\t};\n\t\tconst arrived = (isFiltered: boolean, result: PromiseSettledResult<T[]>) => {\n\t\t\tif (finished) return;\n\t\t\tif (isFiltered) filtered = result;\n\t\t\telse unfiltered = result;\n\t\t\tif (filtered && unfiltered) finish();\n\t\t\telse if (result.status === 'fulfilled' && result.value.length > 0)\n\t\t\t\ttimer = setTimeout(finish, ADDRESS_SUGGESTION_GRACE_MS);\n\t\t};\n\t\tsignal?.addEventListener('abort', abort, { once: true });\n\t\tfor (const isFiltered of [true, false]) {\n\t\t\tlookup(isFiltered ? country : undefined).then(\n\t\t\t\tvalue => arrived(isFiltered, { status: 'fulfilled', value }),\n\t\t\t\t(reason: unknown) => arrived(isFiltered, { status: 'rejected', reason }),\n\t\t\t);\n\t\t}\n\t});\n};\n"],"mappings":"0CAAO,IAAMA,EAAiB,iBACjBC,EAAgB,qCAUhBC,GAA8B,CAC1C,KAAM,IAAIC,IAAS,QAAQ,KAAKH,EAAgBC,EAAe,GAAGE,CAAI,EACtE,MAAO,IAAIA,IAAS,QAAQ,MAAMH,EAAgBC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D,EACAG,GAAQ,iBAAiB,QAASO,EAAO,CAAE,KAAM,EAAK,CAAC,EACvD,QAAWG,IAAc,CAAC,GAAM,EAAK,EACpCX,EAAOW,EAAa5B,EAAU,MAAS,EAAE,KACxCC,GAAS0B,GAAQC,EAAY,CAAE,OAAQ,YAAa,MAAA3B,CAAM,CAAC,EAC1D6B,GAAoBH,GAAQC,EAAY,CAAE,OAAQ,WAAY,OAAAE,CAAO,CAAC,CACxE,CAEF,CAAC,CACF","names":["CONSOLE_PREFIX","CONSOLE_STYLE","inploiBrandedLogger","args","noLogging","createPlugin","pluginFn","invariant","condition","message","hasProp","data","prop","DEFAULT_FORMATTER","unauthenticatedMessage","unauthorisedMessage","ErrorWithStatus","message","status","NotFoundError","UnauthorisedError","SchemaValidationError","issues","source","sourceText","ApiError","data","isApiErrorWithData","error","JsonParsingError","response","parseJsonResponse","response","mediaType","JsonParsingError","ERROR_MESSAGE_KEYS","getErrorMessageFromJson","json","messages","key","hasProp","value","item","handleApiExceptions","status","message","NotFoundError","unauthenticatedMessage","UnauthorisedError","unauthorisedMessage","ApiError","createApiClient","params","defaultHeaders","pathname","options","init","SdkError","SchemaValidationError","isSdkError","error","ErrorClass","version","ENV_TO_API_URL","ENV_TO_TALENT_BANK_URL","ANALYTICS_VERSION","version","ANALYTICS_COOKIE_NAME","ANALYTICS_CANDIDATE_ID_STORAGE_KEY","CONSENT_STORAGE_KEY_PREFIX","generateUUID","c","ANONYMOUS_ID_TTL_MS","formatCookie","value","now","ANALYTICS_COOKIE_NAME","getSessionId","searchParams","isServer","fromSearchParams","fromSessionStorage","getStoredCandidateId","stored","ANALYTICS_CANDIDATE_ID_STORAGE_KEY","setStoredCandidateId","candidateId","cookieRegex","getCookieId","request","cookie","getStoredFallbackId","getBrowserStoredId","framedCookieAttributes","persistAnonymousId","id","getSessionInfo","href","getOrCreateAnonymousId","existing","newId","generateUUID","beforeWrite","getSessionInfoFromResponse","response","serverReferrer","referrer","analyticsLogEndpoint","typed","createAnalyticsService","rpcClient","logger","onEvent","talentBank","persistence","memorySessionId","memoryAnonymousId","sessionRequestSequence","latestSessionResponse","sessionInfo","logFn","params","page","context","ANALYTICS_VERSION","currentSession","resolvedCandidateId","identifyProperties","result","payload","cookieIdBeforeRequest","requestSequence","responseJson","newSession","cookieIdNow","writtenDuringRequest","cookieIdToKeep","canAdoptResponse","e","pendingSessionLog","invariant","send","headers","stringify","parse","schema","input","source","result","SchemaValidationError","safeParse","e","InploiRpcClient","params","ENV_TO_API_URL","endpoint","options","validateIn","searchParams","body","validateEndpointInputs","url","pathname","key","value","stringify","json","parseJsonResponse","handleApiExceptions","fetchParams","response","typed","validatedInputs","v","CANDIDATE_SOURCES","STAGE_GROUPS","SCORE_TYPES","INTERVIEW_STATUSES","DUPLICATE_CHECK_SCOPES","APPLICATION_SORT_FIELDS","SORT_ORDERS","APPLICATION_SOURCES","APPLICATION_ACTIONS","ACTOR_TYPES","CandidateSourceSchema","CANDIDATE_SOURCES","StageGroupSchema","STAGE_GROUPS","StageSchema","ScoreTypeSchema","InterviewStatusSchema","DuplicateCheckScopeSchema","ApplicationSortFieldSchema","SortOrderSchema","DisqualificationReasonSchema","ApplicationSourceSchema","ApplicationActionSchema","ActorTypeSchema","ActorInputSchema","v","PaginationSchema","paginatedResultSchema","itemSchema","v","CandidateSchema","CandidateSourceSchema","v","v","RequiredStringSchema","PositiveIntegerSchema","UnknownRecordSchema","v","InterviewSchema","InterviewStatusSchema","UnknownRecordSchema","ScoreCategorySchema","ApplicationSchema","StageSchema","StageGroupSchema","DisqualificationReasonSchema","ApplicationSourceSchema","UnknownRecordSchema","ApplicationScoreSchema","ScoreTypeSchema","ApplicationDetailSchema","CandidateSchema","InterviewSchema","CandidateDetailSchema","ApplicationLogSchema","ApplicationActionSchema","ActorTypeSchema","v","IdentifyInputSchema","RequiredStringSchema","CandidateSourceSchema","IdentifyResultSchema","v","APPLY_ACTION_KEYS","ApplyActionKeySchema","CommaSeparatedStringSchema","s","t","StagesQuerySchema","StageSchema","StageGroupsQuerySchema","StageGroupSchema","JobIdsQuerySchema","ListApplicationsQuerySchema","ApplicationSortFieldSchema","SortOrderSchema","SubmitApplicationInputSchema","RequiredStringSchema","PositiveIntegerSchema","UnknownRecordSchema","ApplicationSourceSchema","ActorInputSchema","input","DuplicateApplicationSchema","SubmitApplicationResultSchema","DuplicateCheckResultSchema","WriteScoreInputSchema","ScoreTypeSchema","ScoreCategorySchema","WriteScoreResponseSchema","ListApplicationsResponseSchema","paginatedResultSchema","ApplicationDetailSchema","TransitionSkipReasonSchema","ListApplicationLogsResponseSchema","ApplicationLogSchema","NoteMeta","StageSchema","HireMeta","ApplyActionInputSchema","ActorInputSchema","StageGroupSchema","DisqualificationReasonSchema","BulkApplyActionInputSchema","ApplyActionSkipReasonSchema","ApplyActionResultSchema","ApplyActionKeySchema","ApplicationDetailSchema","BulkApplyActionResultSchema","NonNegativeIntegerSchema","JobApplicationCountsSchema","ListJobApplicationCountsQuerySchema","JobIdsQuerySchema","ListJobApplicationCountsResponseSchema","ListCandidatesResponseSchema","paginatedResultSchema","CandidateSchema","v","JobMetricsResponseSchema","v","createTalentBankClient","environment","publishableKey","logger","baseUrl","ENV_TO_TALENT_BANK_URL","params","searchParams","response","json","parsed","DuplicateCheckResultSchema","e","body","parsedBody","IdentifyInputSchema","IdentifyResultSchema","initialiseSdk","publishableKey","env","logger","inploiBrandedLogger","onEvent","persistence","apiClient","createApiClient","ENV_TO_API_URL","loggerService","noLogging","rpcClient","InploiRpcClient","talentBank","createTalentBankClient","analytics","createAnalyticsService","plugin","hashConsentConfig","config","canonical","hash","consentStorageKey","publishableKey","configHash","CONSENT_STORAGE_KEY_PREFIX","getConsentAcceptance","key","setConsentAcceptance","ready","callback","v","JOB_ALERT_FREQUENCIES","alertFiltersSchema","closedJobEndpoint","saveClosedRoleJobAlerts","rpcClient","contact","job","filters","found","field","value","saveSearchEndpoint","typed","v","getJobCountries","rpcClient","jobCountriesEndpoint","country","value","typed","addressCountries","addressSearchCountry","countries","jobCountryCodes","blendAddressSuggestions","filtered","unfiltered","seen","suggestions","i","item","key","ADDRESS_SUGGESTION_GRACE_MS","searchAddressSuggestions","lookup","signal","items","resolve","reject","timer","finished","cleanup","abort","finish","arrived","isFiltered","result","reason"]}
|
|
1
|
+
{"version":3,"sources":["../src/sdk.logger.ts","../src/sdk.plugins.ts","../../core/src/common/common.utils.ts","../../core/src/common/common.currency.ts","../../core/src/common/common.datetime.ts","../../core/src/common/common.address-region.ts","../../core/src/common/common.address-shadow.ts","../../core/src/common/common.geo.ts","../src/sdk.api.ts","../package.json","../src/sdk.constants.ts","../src/sdk.storage.ts","../src/sdk.uuid.ts","../src/sdk.analytics.ts","../src/sdk.rpc.ts","../src/sdk.ts","../src/sdk.events.ts","../src/sdk.consent.ts","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/enums.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/pagination.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/candidate.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/application.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/_shared.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/interview.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/http/identify.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/http/applications.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/http/candidates.js","../../../node_modules/.pnpm/@inploi+talent-bank@git+https+++github.com+inploi+platform.git+cec72e0ff2953beb6ca1faf5_22caa48505527cafb4d817f5df9cd664/node_modules/@inploi/talent-bank/dist/contract/http/metrics.js","../src/sdk.talent-bank.ts","../src/ready.ts","../src/sdk.job-alerts.ts","../src/sdk.countries.ts"],"sourcesContent":["export const CONSOLE_PREFIX = '%c[inploi SDK]';\nexport const CONSOLE_STYLE = 'color: #65BC67; font-weight: bold;';\n\ntype LogMessage = (...data: any[]) => void;\nexport type Logger = {\n\twarn: LogMessage;\n\terror: LogMessage;\n\tinfo: LogMessage;\n\tlog: LogMessage;\n};\n\nexport const inploiBrandedLogger: Logger = {\n\twarn: (...args) => console.warn(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\terror: (...args) => console.error(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\tinfo: (...args) => console.info(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n\tlog: (...args) => console.log(CONSOLE_PREFIX, CONSOLE_STYLE, ...args),\n};\n\nexport const noLogging: Logger = { info: () => void 0, error: () => void 0, log: () => void 0, warn: () => void 0 };\n","import { AnalyticsService } from './sdk.analytics';\nimport { ApiClient } from './sdk.api';\nimport { InploiSdkEnvironment } from './sdk.constants';\nimport { Logger } from './sdk.logger';\nimport { InploiRpcClient } from './sdk.rpc';\n\nexport type PluginParams = {\n\tapiClient: ApiClient;\n\tlogger: Logger;\n};\n\nexport type Plugin<T extends string, P extends Record<string, unknown>> = {\n\tpluginName: T;\n\tpure_createActions: (params: PluginParams) => P;\n};\n\ntype PluginDependencies = {\n\tapiClient: ApiClient;\n\trpcClient: InploiRpcClient;\n\tlogger: Logger;\n\tanalytics: AnalyticsService;\n\t/** The publishable key used to initialise the SDK (available when registered via initialiseSdk) */\n\tpublishableKey?: string;\n\t/** The environment the SDK was initialised with — plugins can use this to select the correct service URL */\n\tenv?: InploiSdkEnvironment;\n};\n\nexport type InploiSdkPlugin = (dependencies: PluginDependencies) => any;\n\nexport const createPlugin = <T extends InploiSdkPlugin>(pluginFn: T) => pluginFn;\n","export const exhaustive = (value: never) => {\n\tthrow new Error(`Unhandled discriminated union member: ${JSON.stringify(value)}`);\n};\n\nexport function invariant(condition: any, message?: string): asserts condition {\n\tif (condition) {\n\t\treturn;\n\t}\n\n\tthrow new Error(message);\n}\n\nexport const uniqueOrThrow = <T>(array: T[]) => {\n\tconst uniqueValues = new Set(array);\n\n\tif (array.length !== uniqueValues.size) {\n\t\tthrow new Error('Duplicate values found');\n\t}\n\treturn true;\n};\n\nexport const uniqueByPropertyOrThrow =\n\t<T extends PropertyKey>(propertyKey: T) =>\n\t(array: { [K in T]: any }[]) => {\n\t\tconst values = array.map(item => item[propertyKey]);\n\t\tconst uniqueValues = new Set(values);\n\n\t\tif (values.length !== uniqueValues.size) {\n\t\t\tthrow new Error(`Duplicate values found for property: ${propertyKey.toString()}`);\n\t\t}\n\t\treturn true;\n\t};\n\n/**\n * A destructive way to ensure an object has a property.\n * This is useful when working with unknowns.\n */\nexport function hasProp<K extends PropertyKey>(data: object, prop: K): data is Record<K, unknown> {\n\treturn prop in data;\n}\n\n/**\n * A sort of type-safe way to check whether a key exists in an object.\n */\nexport function isKeyInObj<O extends Record<string, unknown>>(key: PropertyKey, obj: O): key is keyof O {\n\treturn key in obj;\n}\n","type TFunction = (key: 'competitive' | 'invalid_salary' | 'from' | 'up_to') => string;\n\ninterface SalaryParams {\n\tpay: string | null;\n\tpay_min: string | null;\n\tpay_mask: boolean;\n\tpay_max: string | null;\n\tpay_type: 'ANNUALLY' | 'HOURLY' | 'MONTHLY' | 'WEEKLY' | 'DAILY' | null;\n\tpay_currency: string;\n\tpay_display: boolean;\n}\n\nconst payPeriods: Record<NonNullable<SalaryParams['pay_type']>, string> = {\n\tANNUALLY: 'per year',\n\tDAILY: 'per day',\n\tHOURLY: 'per hour',\n\tMONTHLY: 'per month',\n\tWEEKLY: 'per week',\n};\n\nexport const getSalaryAsText = (params: {\n\tsalary: SalaryParams;\n\tconfig: { locales: string | string[] | undefined };\n\tt?: TFunction;\n}) => {\n\tconst { salary, config, t = s => s } = params;\n\tconst numberFormatter = new Intl.NumberFormat(config.locales, {\n\t\tstyle: 'currency',\n\t\tcurrency: salary.pay_currency,\n\t\ttrailingZeroDisplay: 'stripIfInteger',\n\t});\n\tif (salary.pay_display === false) return undefined;\n\tif (salary.pay === null && salary.pay_min === null && salary.pay_max === null) return undefined;\n\tif (salary.pay_mask) return t('competitive');\n\n\tif (salary.pay_max && Number.isNaN(+salary.pay_max)) return t('invalid_salary');\n\tif (salary.pay_min && Number.isNaN(+salary.pay_min)) return t('invalid_salary');\n\tif (salary.pay && Number.isNaN(+salary.pay)) return t('invalid_salary');\n\n\tconst period = salary.pay_type && salary.pay_type in payPeriods ? payPeriods[salary.pay_type] : undefined;\n\n\tif (salary.pay) return [numberFormatter.format(+salary.pay), period].filter(Boolean).join(' ');\n\n\tif (salary.pay_max && salary.pay_min)\n\t\treturn [numberFormatter.formatRange(+salary.pay_min, +salary.pay_max), period].filter(Boolean).join(' ') || '';\n\n\tif (salary.pay_max)\n\t\treturn `${t('up_to')} ${[numberFormatter.format(+salary.pay_max), period].filter(Boolean).join(' ')}`;\n\tif (salary.pay_min)\n\t\treturn `${t('from')} ${[numberFormatter.format(+salary.pay_min), period].filter(Boolean).join(' ')}`;\n\treturn t('invalid_salary');\n};\n","type TFunction = (key: 'today' | 'over_30_days_ago' | 'in_over_30_days') => string;\n\ntype Params = {\n\tfrom?: Date;\n\tto: string | number | Date;\n\tformatter?: Intl.RelativeTimeFormat;\n\tt?: TFunction;\n};\n\nconst DEFAULT_FORMATTER = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });\n/** From a date, calculates the relative time difference from now */\nexport const getRelativeTimeDifference = ({\n\tfrom = new Date(),\n\tto,\n\tformatter = DEFAULT_FORMATTER,\n\tt = s => s,\n}: Params) => {\n\tconst then = to instanceof Date ? to : new Date(to);\n\tconst diff = then.getTime() - from.getTime();\n\n\tconst diffIn = {\n\t\tdays: Math.round(diff / 1000 / 60 / 60 / 24),\n\t\tmonths: Math.round(diff / 1000 / 60 / 60 / 24 / 30),\n\t};\n\n\tif (diffIn.days === 0) return t('today');\n\tif (Math.abs(diffIn.days) < 30) return formatter.format(diffIn.days, 'days');\n\tif (Math.abs(diffIn.days) < 3) return formatter.format(diffIn.months, 'months');\n\treturn diffIn.months < 0 ? t('over_30_days_ago') : t('in_over_30_days');\n};\n","export const POSTCODE_PATTERN =\n\t/\\b(?:GIR\\s*0AA|[a-z]{1,2}\\d[\\da-z]?\\s*\\d[a-z]{2}|[a-z](?:\\d{2}|\\d[a-z])\\s*[\\da-z]{4})\\b/i;\nexport const UK_POSTCODE_PATTERN = /^(?:GIR0AA|[A-Z]{1,2}\\d[\\dA-Z]?\\d[A-Z]{2})$/;\nexport const EIRCODE_PATTERN = /^[A-Z](?:\\d{2}|\\d[A-Z])[\\dA-Z]{4}$/;\n\n/** Classify only the answered address; a company's country filter never determines its region. */\nexport const addressRegion = ({\n\tpostcode,\n\tlabel = '',\n\tstate,\n\tcountry,\n}: {\n\tpostcode?: string;\n\tlabel?: string;\n\tstate?: string;\n\tcountry?: string;\n}): 'gb' | 'ni' | 'ie' | null => {\n\tconst code = (postcode?.trim() || label.match(POSTCODE_PATTERN)?.[0] || '').replace(/\\s/g, '').toUpperCase();\n\tif (UK_POSTCODE_PATTERN.test(code)) return code.startsWith('BT') ? 'ni' : 'gb';\n\tif (EIRCODE_PATTERN.test(code)) return 'ie';\n\tconst normalise = (value: string) =>\n\t\tvalue\n\t\t\t.normalize('NFD')\n\t\t\t.replace(/[\\u0300-\\u036f]/g, '')\n\t\t\t.toLowerCase()\n\t\t\t.replace(/\\s+/g, ' ')\n\t\t\t.trim();\n\tif (\n\t\tnormalise(state ?? '') === 'northern ireland' ||\n\t\tlabel.split(',').some(part => normalise(part) === 'northern ireland')\n\t)\n\t\treturn 'ni';\n\tconst name = (country?.trim() || label.split(',').at(-1)?.trim())?.toLowerCase();\n\tif (name === 'united kingdom' || name === 'gb') return 'gb';\n\tif (name === 'ireland' || name === 'ie') return 'ie';\n\treturn null;\n};\n","import { EIRCODE_PATTERN, POSTCODE_PATTERN, UK_POSTCODE_PATTERN, addressRegion } from './common.address-region';\n\nconst ADDRESS_SHADOW_URL = 'https://maps.inploi.com/address';\n\nexport type AddressShadowComparison = {\n\thit: boolean;\n\trank: number | null;\n\tresults: number;\n\tsource: 'photon' | 'mapbox';\n\tfallback: string | null;\n\tms: number | null;\n\tregion: 'gb' | 'ni' | 'ie' | null;\n};\n\nconst normaliseAddress = (value: string) =>\n\tvalue\n\t\t.normalize('NFD')\n\t\t.replace(/[\\u0300-\\u036f]/g, '')\n\t\t.toLowerCase()\n\t\t.replace(/\\s+/g, ' ')\n\t\t.trim();\n\nconst addressComponents = (label: string) =>\n\tlabel.split(',').map(part =>\n\t\tnormaliseAddress(part)\n\t\t\t.replace(/^\\d+[a-z]?(?:\\s*[-/]\\s*\\d+[a-z]?)?(?:\\s+|$)/, '')\n\t\t\t.trim(),\n\t);\n\nconst postcodeArea = (postcode: string) =>\n\tUK_POSTCODE_PATTERN.test(postcode) ? `gb:${postcode.slice(0, -3)}`\n\t: EIRCODE_PATTERN.test(postcode) ? `ie:${postcode.slice(0, 3)}`\n\t: null;\n\n/** Approximate street coverage: exact components plus a postcode area or town, never a street alone. */\nconst shadowAddressRank = (pickedLabel: string, pickedPostcode: string, labels: string[]): number | null => {\n\tconst [street = '', townPart = ''] = addressComponents(pickedLabel);\n\tconst area = postcodeArea(pickedPostcode);\n\tconst town = townPart.replace(POSTCODE_PATTERN, '').trim();\n\tconst hasTown =\n\t\ttown && !['united kingdom', 'ireland', 'england', 'scotland', 'wales', 'northern ireland'].includes(town);\n\tif (!street || (!area && !hasTown)) return null;\n\tconst index = labels.slice(0, 3).findIndex(label => {\n\t\tconst components = addressComponents(label);\n\t\tif (!components.includes(street)) return false;\n\t\tconst shadowPostcode = label.match(POSTCODE_PATTERN)?.[0].replace(/\\s/g, '').toUpperCase() ?? '';\n\t\tconst shadowArea = postcodeArea(shadowPostcode);\n\t\tif (area && shadowArea) return area === shadowArea;\n\t\treturn Boolean(hasTown && components.some(part => part.replace(POSTCODE_PATTERN, '').trim() === town));\n\t});\n\treturn index === -1 ? null : index + 1;\n};\n\n/** Best-effort shadow telemetry. Call without awaiting it; no result or failure changes the candidate's pick. */\nexport const shadowAddressPick = async ({\n\tquery,\n\tcountry,\n\tpickedLabel,\n\tpickedPostcode,\n\tpickedCountry,\n\tpickedState,\n\tlog,\n}: {\n\tquery: string;\n\tcountry: string | undefined;\n\tpickedLabel: string;\n\tpickedPostcode?: string;\n\tpickedCountry?: string;\n\tpickedState?: string;\n\tlog: (properties: AddressShadowComparison) => unknown;\n}): Promise<void> => {\n\tif (!country || !country.split(',').every(code => /^(gb|ie)$/i.test(code.trim()))) return;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\ttry {\n\t\tconst controller = new AbortController();\n\t\ttimer = setTimeout(() => controller.abort(), 1500);\n\t\tconst url = new URL(ADDRESS_SHADOW_URL);\n\t\turl.search = new URLSearchParams({ q: query, country, limit: '5' }).toString();\n\t\tconst response = await fetch(url.href, { signal: controller.signal });\n\t\tif (!response.ok) return;\n\t\tconst data: unknown = await response.json();\n\t\tif (\n\t\t\ttypeof data !== 'object' ||\n\t\t\tdata === null ||\n\t\t\t!('results' in data) ||\n\t\t\t!Array.isArray(data.results) ||\n\t\t\t!('source' in data) ||\n\t\t\t(data.source !== 'photon' && data.source !== 'mapbox')\n\t\t)\n\t\t\treturn;\n\t\tconst results: unknown[] = data.results;\n\t\tconst labels: string[] = [];\n\t\tfor (const result of results) {\n\t\t\tif (typeof result !== 'object' || result === null || !('label' in result) || typeof result.label !== 'string')\n\t\t\t\treturn;\n\t\t\tlabels.push(result.label);\n\t\t}\n\t\tconst postcode = (pickedPostcode?.trim() || pickedLabel.match(POSTCODE_PATTERN)?.[0] || '')\n\t\t\t.replace(/\\s/g, '')\n\t\t\t.toUpperCase();\n\t\tconst rank = shadowAddressRank(pickedLabel, postcode, labels);\n\t\tconst duration = response.headers.get('Server-Timing')?.match(/(?:^|,)\\s*lookup\\s*;\\s*dur=([\\d.]+)/)?.[1];\n\t\tconst ms = duration === undefined ? null : Number(duration);\n\t\tconst fallback = response.headers.get('X-Geo-Fallback');\n\t\tconst region = addressRegion({\n\t\t\tpostcode: pickedPostcode,\n\t\t\tlabel: pickedLabel,\n\t\t\tstate: pickedState,\n\t\t\tcountry: pickedCountry,\n\t\t});\n\t\tawait log({\n\t\t\thit: rank !== null,\n\t\t\trank,\n\t\t\tresults: labels.length,\n\t\t\tsource: data.source,\n\t\t\t// Only machine codes are telemetry: never forward arbitrary response text.\n\t\t\tfallback: fallback && /^[a-z0-9_-]{1,64}$/i.test(fallback) ? fallback : null,\n\t\t\tms: ms !== null && Number.isFinite(ms) ? ms : null,\n\t\t\tregion,\n\t\t});\n\t} catch {\n\t\t// Optional telemetry must stay silent on timeout, bad responses, network or analytics failure.\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n};\n","import type { AddressOptions, SearchOptions } from './common.geo-transport';\n\nexport type GeoArm = 'inploi' | 'mapbox' | 'direct';\nexport type GeoSource = 'photon' | 'mapbox' | 'places' | 'direct';\nexport type GeoSurface = 'candidate' | 'chatbot' | 'forms' | 'job-search';\nexport type GeoLookup = { arm: GeoArm; source: GeoSource };\nexport type GeoSearchResult<T> = GeoLookup & { results: T[] };\nexport type GeoAddressSuggestion = {\n\tid: string;\n\tlabel: string;\n\tcountry: string | undefined;\n\taddress: Partial<Record<'line1' | 'line2' | 'line3' | 'city' | 'state' | 'postcode' | 'country', string>>;\n};\nexport type GeoPlace = {\n\tkind: 'place' | 'postcode';\n\tname: string;\n\tlabel: string;\n\tcountry: string;\n\tlat: number;\n\tlng: number;\n};\n\nconst GEO_ORIGIN = 'https://maps.inploi.com';\n\n/** Chunk loading and the Worker response share one deadline; only caller cancellation skips direct fallback. */\nconst geoLookup = async <T>(\n\tlookup: (signal: AbortSignal) => Promise<GeoSearchResult<T> | undefined>,\n\tsignal?: AbortSignal,\n\tdeadline = Date.now() + 2500,\n): Promise<GeoSearchResult<T> | undefined> => {\n\tsignal?.throwIfAborted();\n\tconst controller = new AbortController();\n\tconst abort = () => controller.abort(signal?.reason);\n\tsignal?.addEventListener('abort', abort, { once: true });\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\ttry {\n\t\tconst expired = new Promise<never>((_, reject) => {\n\t\t\tcontroller.signal.addEventListener('abort', () => reject(controller.signal.reason), { once: true });\n\t\t\ttimer = setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));\n\t\t});\n\t\tconst result = await Promise.race([lookup(controller.signal), expired]);\n\t\tsignal?.throwIfAborted();\n\t\treturn result;\n\t} catch {\n\t\tsignal?.throwIfAborted();\n\t\treturn;\n\t} finally {\n\t\tclearTimeout(timer);\n\t\tsignal?.removeEventListener('abort', abort);\n\t}\n};\n\nexport const geoAddressSearch = async (\n\toptions: AddressOptions,\n\tfallback: () => Promise<GeoAddressSuggestion[]>,\n\tdeadline?: number,\n): Promise<GeoSearchResult<GeoAddressSuggestion>> => {\n\tconst result = await geoLookup(\n\t\tasync signal => {\n\t\t\tconst { lookupAddress } = await import('./common.geo-transport');\n\t\t\tsignal.throwIfAborted();\n\t\t\treturn lookupAddress({ ...options, signal });\n\t\t},\n\t\toptions.signal,\n\t\tdeadline,\n\t);\n\treturn result ?? { results: await fallback(), arm: 'direct', source: 'direct' };\n};\n\nexport const geoPlacesSearch = async <T>(\n\toptions: SearchOptions & { surface: 'job-search' },\n\tmap: (place: GeoPlace) => T,\n\tfallback: () => Promise<T[]>,\n): Promise<GeoSearchResult<T>> => {\n\tconst result = await geoLookup(async signal => {\n\t\tconst { lookupPlaces } = await import('./common.geo-transport');\n\t\tsignal.throwIfAborted();\n\t\treturn lookupPlaces({ ...options, signal });\n\t}, options.signal);\n\treturn result ?\n\t\t\t{ ...result, results: result.results.map(map) }\n\t\t:\t{ results: await fallback(), arm: 'direct', source: 'direct' };\n};\n\n/** Codes only: explicitly list fields so neither query nor address text can enter the outcome URL. */\nexport const geoOutcome = (\n\toutcome: GeoLookup & {\n\t\tkind: 'address' | 'places';\n\t\tsurface: GeoSurface;\n\t\tpicked: boolean;\n\t\tedited?: boolean;\n\t\tregion?: 'gb' | 'ni' | 'ie' | 'other' | null;\n\t},\n): void => {\n\ttry {\n\t\tconst url = new URL('/outcome', GEO_ORIGIN);\n\t\turl.search = new URLSearchParams({\n\t\t\tkind: outcome.kind,\n\t\t\tsurface: outcome.surface,\n\t\t\tarm: outcome.arm,\n\t\t\tpicked: outcome.picked ? '1' : '0',\n\t\t}).toString();\n\t\turl.searchParams.set('source', outcome.source);\n\t\tif (outcome.picked && outcome.edited !== undefined) url.searchParams.set('edited', outcome.edited ? '1' : '0');\n\t\tif (outcome.region) url.searchParams.set('region', outcome.region);\n\t\tvoid fetch(url.href, { keepalive: true }).catch(() => {});\n\t} catch {\n\t\t// Optional telemetry never delays or prevents an answer, including synchronous fetch failures.\n\t}\n};\n","import { hasProp } from '@inploi/core/common';\nimport { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport const unauthenticatedMessage = 'Unauthenticated';\nexport const unauthorisedMessage = 'This action is unauthorized.';\n\nexport class ErrorWithStatus extends Error {\n\tpublic status?: number;\n\tconstructor(message?: string, status?: number) {\n\t\tsuper(message);\n\t\tthis.status = status;\n\t\tthis.name = 'ErrorWithStatus';\n\t}\n}\n\nexport class NotFoundError extends ErrorWithStatus {\n\tconstructor(message?: string) {\n\t\tsuper(message ?? 'Not found');\n\t\tthis.name = 'NotFoundError';\n\t\tthis.status = 404;\n\t}\n}\n\nexport class UnauthorisedError extends ErrorWithStatus {\n\tconstructor(message?: string, status?: number) {\n\t\tsuper(message ?? 'You are not authorised to perform this action.');\n\t\tthis.name = 'UnauthorisedError';\n\t\tthis.status = status ?? 401;\n\t}\n}\n\nexport class SchemaValidationError extends ErrorWithStatus {\n\tconstructor(\n\t\tpublic issues: readonly StandardSchemaV1.Issue[],\n\t\tpublic source?: 'body' | 'searchParams' | 'response',\n\t) {\n\t\tconst sourceText = source ? ` in ${source}` : '';\n\t\tsuper(`Schema validation failed${sourceText}`);\n\t\tthis.name = 'SchemaValidationError';\n\t\tthis.status = 400;\n\t}\n}\n\nexport class ApiError extends ErrorWithStatus {\n\tconstructor(\n\t\tmessage: string,\n\t\tstatus?: number,\n\t\tpublic data?: unknown,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'ApiError';\n\t\tthis.status = status ?? 500;\n\t}\n}\n\nexport const isApiErrorWithData = (error: unknown): error is ApiError & { data: unknown } =>\n\terror instanceof ApiError && error.data !== undefined;\n\nexport class JsonParsingError extends ErrorWithStatus {\n\tpublic contentType?: string;\n\n\tconstructor(public response?: Response) {\n\t\tsuper('Error parsing response into JSON.');\n\t\tthis.name = 'ParsingError';\n\t\tthis.status = response && response.status >= 300 ? response.status : 500;\n\t\tthis.contentType = new Headers(response?.headers).get('content-type') ?? undefined;\n\t}\n}\n\n/** @deprecated - use `JsonParsingError` instead */\nexport class ParsingError extends JsonParsingError {}\n\nexport type ApiClient = {\n\tfetch: (pathname: string, options?: RequestInit) => Promise<unknown>;\n};\n\nexport async function parseJsonResponse(response: Response): Promise<unknown> {\n\tconst contentType = new Headers(response.headers).get('content-type');\n\tconst mediaType = contentType?.replace(/;.*/, '').trim().toLowerCase();\n\tif (mediaType && mediaType !== 'application/json' && !mediaType.endsWith('+json')) {\n\t\tthrow new JsonParsingError(response);\n\t}\n\n\treturn response.json().catch(() => {\n\t\tthrow new JsonParsingError(response);\n\t});\n}\n\nconst ERROR_MESSAGE_KEYS = ['message', 'error', 'errors', 'exception', 'exceptions'] as const;\nfunction getErrorMessageFromJson(json: unknown): string {\n\tconst messages: string[] = [];\n\tif (typeof json === 'object' && json !== null) {\n\t\tfor (const key of ERROR_MESSAGE_KEYS) {\n\t\t\tif (hasProp(json, key)) {\n\t\t\t\tconst value = json[key];\n\t\t\t\tif (typeof value === 'string') messages.push(value);\n\t\t\t\tif (Array.isArray(value) && value.every((item): item is string => typeof item === 'string'))\n\t\t\t\t\tmessages.push(...value);\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\thasProp(json, 'integration_response') &&\n\t\t\ttypeof json.integration_response === 'object' &&\n\t\t\tjson.integration_response !== null &&\n\t\t\thasProp(json.integration_response, 'error') &&\n\t\t\ttypeof json.integration_response.error === 'object' &&\n\t\t\tjson.integration_response.error !== null &&\n\t\t\thasProp(json.integration_response.error, 'message') &&\n\t\t\ttypeof json.integration_response.error.message === 'string'\n\t\t) {\n\t\t\tmessages.push(json.integration_response.error.message);\n\t\t}\n\t}\n\tif (messages.length === 0) messages.push('Unknown error');\n\treturn [...new Set(messages)].join(', ');\n}\n\n/** Throws branded errors when API returns a known error. */\nexport function handleApiExceptions(json: unknown, status: number) {\n\tif (status >= 300) {\n\t\tconst message = getErrorMessageFromJson(json);\n\t\tif (status === 404) {\n\t\t\tthrow new NotFoundError(message);\n\t\t}\n\t\tif (message === unauthenticatedMessage) {\n\t\t\tthrow new UnauthorisedError('You are not authenticated.', status);\n\t\t}\n\t\tif (message === unauthorisedMessage) {\n\t\t\tthrow new UnauthorisedError(message, status);\n\t\t}\n\t\tthrow new ApiError(message, status, json);\n\t}\n}\n\nexport const createApiClient = (params: { baseUrl: string; publishableKey: string }): ApiClient => {\n\tconst defaultHeaders: HeadersInit = {\n\t\tAccept: 'application/json',\n\t\t'Content-Type': 'application/json',\n\t\t'x-publishable-key': params.publishableKey,\n\t};\n\n\treturn {\n\t\t/** Fetches from a pathname with a pre-established base path.\n\t\t * Parses received output as JSON, and throw if one of the common error messages is received.\n\t\t */\n\t\tfetch: async (pathname, options = {}) => {\n\t\t\tconst init = { ...options, headers: { ...options.headers, ...defaultHeaders } };\n\t\t\tconst response = await fetch(`${params.baseUrl}${pathname}`, init);\n\t\t\tif (response.status === 404) throw new NotFoundError();\n\n\t\t\tconst json = await parseJsonResponse(response);\n\n\t\t\thandleApiExceptions(json, response.status);\n\n\t\t\t// We’re assuming no other exceptions have happened.\n\t\t\treturn json;\n\t\t},\n\t};\n};\n\nexport const SdkError = {\n\tNotFound: NotFoundError,\n\tUnauthorised: UnauthorisedError,\n\tSchemaValidation: SchemaValidationError,\n\tApi: ApiError,\n\tJsonParsing: JsonParsingError,\n};\n\nexport function isSdkError(error: unknown): error is (typeof SdkError)[keyof typeof SdkError] {\n\treturn Object.values(SdkError).some(ErrorClass => error instanceof ErrorClass);\n}\n","{\n\t\"name\": \"@inploi/sdk\",\n\t\"version\": \"3.0.1\",\n\t\"main\": \"dist/index.js\",\n\t\"types\": \"dist/index.d.ts\",\n\t\"license\": \"MIT\",\n\t\"files\": [\n\t\t\"/dist\",\n\t\t\"/cdn\"\n\t],\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"require\": \"./dist/index.js\",\n\t\t\t\"import\": \"./dist/index.mjs\",\n\t\t\t\"types\": \"./dist/index.d.ts\"\n\t\t}\n\t},\n\t\"scripts\": {\n\t\t\"build:npm\": \"tsup --dts --dts-resolve && node scripts/check-npm-bundle.mjs\",\n\t\t\"build:cdn\": \"tsup --config tsup.cdn.config.ts\",\n\t\t\"build\": \"concurrently 'pnpm run build:npm' 'pnpm run build:cdn'\",\n\t\t\"dev\": \"tsup --watch --config tsup.cdn.config.ts\",\n\t\t\"check\": \"eslint src --fix --max-warnings 0 && tsc\",\n\t\t\"typecheck\": \"tsc\",\n\t\t\"test\": \"vitest run\",\n\t\t\"test:coverage\": \"vitest run --coverage\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@happy-dom/global-registrator\": \"^13.6.2\",\n\t\t\"@inploi/core\": \"workspace:*\",\n\t\t\"@inploi/talent-bank\": \"github:inploi/platform#cec72e0ff2953beb6ca1faf59332ed3b466b7809&path:apps/talent-bank\",\n\t\t\"@total-typescript/ts-reset\": \"^0.5.1\",\n\t\t\"@types/node\": \"catalog:\",\n\t\t\"@types/react\": \"^18.2.33\",\n\t\t\"@types/react-dom\": \"^18.2.14\",\n\t\t\"@vitest/coverage-v8\": \"catalog:\",\n\t\t\"autoprefixer\": \"^10.4.16\",\n\t\t\"concurrently\": \"9.1.2\",\n\t\t\"eslint\": \"^7.32.0\",\n\t\t\"eslint-config-custom\": \"workspace:*\",\n\t\t\"happy-dom\": \"^12.6.0\",\n\t\t\"ts-toolbelt\": \"^9.6.0\",\n\t\t\"tsconfig\": \"workspace:*\",\n\t\t\"tsup\": \"^7.2.0\",\n\t\t\"vite\": \"catalog:\",\n\t\t\"vitest\": \"catalog:\"\n\t},\n\t\"dependencies\": {\n\t\t\"@standard-schema/spec\": \"^1.0.0\",\n\t\t\"neoqs\": \"^6.13.0\",\n\t\t\"valibot\": \"^1.4.2\"\n\t}\n}\n","import { version } from '../package.json';\n\n/**\n * The environment the SDK should run in.\n * - `production`: data will be stored and displayed on dashboards\n * - `sandbox`: data will be stored temporarily and purged periodically\n */\nexport type InploiSdkEnvironment = 'production' | 'sandbox';\n\nexport const ENV_TO_API_URL: Record<InploiSdkEnvironment, string> = {\n\tsandbox: 'https://api.staging.inploi.com',\n\tproduction: 'https://api.inploi.com',\n\t// @ts-expect-error - local test environment\n\t_internal_local: 'http://api.test',\n};\n\nexport const ENV_TO_TALENT_BANK_URL: Record<InploiSdkEnvironment, string> = {\n\tsandbox: 'https://talent-bank.staging.inploi.com',\n\tproduction: 'https://talent-bank.inploi.com',\n\t// @ts-expect-error - local test environment\n\t_internal_local: 'http://localhost:8787',\n};\n\nexport const ANALYTICS_VERSION = version;\n\nexport const LOG_PATHNAME = '/log';\n\nexport const ANALYTICS_COOKIE_NAME = 'isdk_session';\n\n/**\n * Legacy local-storage key for the Talent Bank `candidateId`. The SDK still\n * forwards stored values on analytics logs for session attribution.\n */\nexport const ANALYTICS_CANDIDATE_ID_STORAGE_KEY = `${ANALYTICS_COOKIE_NAME}-candidate_id`;\n\n/**\n * Local-storage key prefix for the candidate's consent / approval state\n * (PROD-5763). The final key is composed of:\n *\n * `${CONSENT_STORAGE_KEY_PREFIX}:<publishableKey>:<configHash>`\n *\n * The `configHash` is a deterministic hash of the consent message +\n * labels. Any material wording change produces a new hash → new\n * storage key → candidate is automatically re-prompted, without the\n * customer having to manage a `version` field manually.\n *\n * Per-tenant scoping (the `publishableKey` segment) matters because\n * the consent UI runs inside the Kin iframe at `sdk.inploi.com`, so\n * one origin's localStorage is shared across every tenant a candidate\n * has visited from this browser.\n */\nexport const CONSENT_STORAGE_KEY_PREFIX = `${ANALYTICS_COOKIE_NAME}-consent`;\n","const memory = new Map<string, string>();\n\n/**\n * sessionStorage that never throws. Browsers that block third-party storage (Chrome Incognito, Brave, strict settings)\n * throw `SecurityError` on reading `window.sessionStorage` at all inside a cross-site frame, so the property read\n * happens per call inside try/catch. A value whose write threw lives in memory for the page and wins over storage.\n */\nexport const safeSessionStorage = {\n\tget: (key: string): string | null => {\n\t\tif (memory.has(key)) return memory.get(key) ?? null;\n\t\ttry {\n\t\t\treturn window.sessionStorage.getItem(key);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t},\n\tset: (key: string, value: string) => {\n\t\ttry {\n\t\t\twindow.sessionStorage.setItem(key, value);\n\t\t\tmemory.delete(key);\n\t\t} catch {\n\t\t\tmemory.set(key, value);\n\t\t}\n\t},\n};\n","/**\n * Generates a RFC 4122 v4 UUID.\n *\n * `crypto.randomUUID()` is only available in secure contexts (HTTPS). This\n * utility falls back to `crypto.getRandomValues`, which is available in all\n * browsing contexts including HTTP, so the SDK works on non-HTTPS staging\n * environments.\n */\nexport const generateUUID = (): `${string}-${string}-${string}-${string}-${string}` => {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n\t\treturn crypto.randomUUID();\n\t}\n\n\treturn '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c =>\n\t\t(+c ^ (crypto.getRandomValues(new Uint8Array(1))[0]! & (15 >> (+c / 4)))).toString(16),\n\t) as `${string}-${string}-${string}-${string}-${string}`;\n};\n","import type { ResponseObj } from '@inploi/core/common';\nimport { invariant } from '@inploi/core/common';\n\nimport { InploiRpcClient, Logger, endpoint, typed } from '.';\nimport {\n\tANALYTICS_CANDIDATE_ID_STORAGE_KEY,\n\tANALYTICS_COOKIE_NAME,\n\tANALYTICS_VERSION,\n} from './sdk.constants';\nimport type { AnalyticsEnvelope, AnalyticsLogEvent, AnalyticsLogParams, SiteKind } from './sdk.events';\nimport { safeSessionStorage } from './sdk.storage';\nimport { generateUUID } from './sdk.uuid';\n\nconst ANONYMOUS_ID_TTL_MS = 7 * 24 * 60 * 60 * 1000;\n\nconst formatCookie = (value: string) => {\n\tconst now = new Date();\n\tnow.setTime(now.getTime() + ANONYMOUS_ID_TTL_MS);\n\n\treturn `${ANALYTICS_COOKIE_NAME}=${value};expires=${now.toUTCString()};path=/`;\n};\n\ntype EventPropertyMap = {\n\t[Param in AnalyticsLogParams as Param['event']]: Omit<Param, 'event'>;\n};\n\ntype AnalyticsContext = {\n\tlibrary: {\n\t\tname: 'inploi-sdk';\n\t\tversion: string;\n\t};\n\tpage: {\n\t\thref: string;\n\t\treferrer: string;\n\t\ttitle: string;\n\t};\n};\n\ntype TrackPayload<P = EventPropertyMap[keyof EventPropertyMap]['properties']> = {\n\tanonymous_id: string | null;\n\tsession_id: string | null;\n\t/**\n\t * Legacy Talent Bank candidate id read from device storage, or `null`.\n\t * Laravel's session middleware stamps it onto `session.context.candidate_id` for attribution.\n\t */\n\tcandidate_id: string | null;\n\tevent: AnalyticsLogEvent;\n\tsent_at: string;\n\tcontext: AnalyticsContext;\n\tproperties: P;\n\t/** Always sent with the `AnalyticsEnvelope`; typed optional because hosts and tests implement `log` themselves. */\n\tcustom_properties?: Record<string, unknown>;\n};\n\ntype LogFnParams<T extends keyof EventPropertyMap> = {\n\tevent: T;\n\tcustomProperties?: Record<string, unknown>;\n\t/** Passing a request will make logging possible on a server environment. */\n\trequest?: Request;\n\t/** Sent so it survives the page being left (`fetch` keepalive): for a summary sent on pagehide. */\n\tkeepalive?: boolean;\n} & EventPropertyMap[T];\n\ntype LogFn = <TEvent extends keyof EventPropertyMap>(\n\tparams: LogFnParams<TEvent>,\n) => Promise<ResponseObj<TrackPayload<EventPropertyMap[TEvent]['properties']>>>;\n\nexport type AnalyticsService = {\n\tlog: LogFn;\n\t/** From a log payload data, generate headers to use in server environments to update the anonymous_id */\n\tgetHeaders: (payload?: TrackPayload) => Headers;\n\tgetSessionInfo: typeof getSessionInfo;\n\t/**\n\t * The visitor id for agent conversations. With device persistence it is `getOrCreateAnonymousId`'s stored id; with\n\t * none it lives in this instance only, so a visitor who refused storage keeps one id for the page and nothing is stored.\n\t * Optional: plugins run beside the host's own SDK, and a host before 2.10 hands analytics without it. Plugins call\n\t * `analytics.getOrCreateAnonymousId?.() ?? getOrCreateAnonymousId()`, so such a host keeps the stored id until it updates.\n\t */\n\tgetOrCreateAnonymousId?: () => string;\n};\n\nconst getSessionId = (searchParams: URLSearchParams, isServer: boolean) => {\n\tconst fromSearchParams = searchParams.get('session_id');\n\tif (isServer) return fromSearchParams;\n\tif (fromSearchParams) return fromSearchParams;\n\tconst fromSessionStorage = safeSessionStorage.get(`${ANALYTICS_COOKIE_NAME}-session_id`);\n\tif (typeof fromSessionStorage === 'string') return fromSessionStorage;\n\treturn null;\n};\n\n/**\n * Read the cached Talent Bank candidate id from localStorage.\n *\n * Returns `null` in non-browser / no-localStorage environments so server-side\n * logging and tests don't explode.\n */\nconst getStoredCandidateId = (): string | null => {\n\tif (typeof window === 'undefined') return null;\n\ttry {\n\t\tconst stored = window.localStorage.getItem(ANALYTICS_CANDIDATE_ID_STORAGE_KEY);\n\t\treturn typeof stored === 'string' && stored !== '' ? stored : null;\n\t} catch {\n\t\treturn null;\n\t}\n};\n\nconst cookieRegex = new RegExp(`(?:^|;\\\\s*)${ANALYTICS_COOKIE_NAME}=([^;]+)`);\nconst getCookieId = (request?: Request) => {\n\tconst cookie = request ? request.headers.get('cookie') : document.cookie;\n\treturn cookie ? cookieRegex.exec(cookie)?.[1] ?? null : null;\n};\n\n/**\n * Browsers drop a cookie written inside a cross-site iframe (a careers site that frames our pages), so without a\n * fallback every page load there minted a new visitor id and the Candidate Agent lost its conversation. The cookie\n * stays the primary store; localStorage holds the id, with the cookie's expiry, only when the cookie write did not stick.\n */\nconst getStoredFallbackId = (): string | null => {\n\ttry {\n\t\tconst stored: unknown = JSON.parse(window.localStorage.getItem(ANALYTICS_COOKIE_NAME) ?? 'null');\n\t\tif (\n\t\t\ttypeof stored !== 'object' ||\n\t\t\tstored === null ||\n\t\t\t!('id' in stored) ||\n\t\t\t!('expires' in stored) ||\n\t\t\ttypeof stored.id !== 'string' ||\n\t\t\ttypeof stored.expires !== 'number'\n\t\t)\n\t\t\treturn null;\n\t\treturn stored.id !== '' && stored.expires > Date.now() ? stored.id : null;\n\t} catch {\n\t\treturn null;\n\t}\n};\n\n/** The id a response must not replace: a URL handoff outranks the fallback, as in `getSessionInfo`. */\nconst getBrowserStoredId = () =>\n\tgetCookieId() ?? (new URL(location.href).searchParams.get('anonymous_id') ? null : getStoredFallbackId());\n\n/** In a frame on HTTPS the cookie needs SameSite=None to be stored at all; Partitioned keeps it to this embed. */\nconst framedCookieAttributes = () =>\n\tlocation.protocol === 'https:' && window.self !== window.top ? ';SameSite=None;Secure;Partitioned' : '';\n\nconst persistAnonymousId = (id: string) => {\n\tdocument.cookie = formatCookie(id) + framedCookieAttributes();\n\tif (getCookieId() === id) return;\n\ttry {\n\t\twindow.localStorage.setItem(\n\t\t\tANALYTICS_COOKIE_NAME,\n\t\t\tJSON.stringify({ id, expires: Date.now() + ANONYMOUS_ID_TTL_MS }),\n\t\t);\n\t} catch {\n\t\t// No storage at all: the id lasts for this page only.\n\t}\n};\n\nconst getSessionInfo = (request?: Request) => {\n\tconst href = request ? request.url : location.href;\n\tconst { searchParams } = new URL(href);\n\n\treturn {\n\t\tanonymous_id:\n\t\t\trequest ?\n\t\t\t\t(getCookieId(request) ?? searchParams.get('anonymous_id'))\n\t\t\t:\t(getCookieId() ?? searchParams.get('anonymous_id') ?? getStoredFallbackId()),\n\t\tsession_id: getSessionId(searchParams, typeof window === 'undefined'),\n\t};\n};\n\n/**\n * Get or create a persistent anonymous ID.\n *\n * This is the universal identifier that bridges:\n * - SDK analytics (Laravel tracking)\n * - Agent conversations (Durable Object routing)\n * - Identity resolution\n *\n * The ID is:\n * - Generated client-side if none exists\n * - Persisted in a cookie for 7 days, or in localStorage where the cookie is not stored (a cross-site frame)\n * - The same across all SDK plugins\n *\n * @returns The anonymous ID (existing or newly generated)\n */\nexport const getOrCreateAnonymousId = (): string => {\n\t// Server-side: cannot generate, return empty (should not happen in normal flow)\n\tif (typeof window === 'undefined') {\n\t\tthrow new Error('getOrCreateAnonymousId() can only be called in browser environment');\n\t}\n\n\t// Check existing sources first\n\tconst existing = getSessionInfo().anonymous_id;\n\tif (existing) return existing;\n\n\tconst newId = generateUUID();\n\t// Another tab may have created the shared id during generation.\n\tconst beforeWrite = getSessionInfo().anonymous_id;\n\tif (beforeWrite) return beforeWrite;\n\tpersistAnonymousId(newId);\n\treturn newId;\n};\n\nconst getSessionInfoFromResponse = (response: unknown) => {\n\tif (typeof response !== 'object' || response === null) return null;\n\treturn {\n\t\tanonymous_id:\n\t\t\t'anonymous_id' in response && typeof response.anonymous_id === 'string' ? response.anonymous_id : null,\n\t\tsession_id: 'session_id' in response && typeof response.session_id === 'string' ? response.session_id : null,\n\t};\n};\n\nconst serverReferrer = (referrer: typeof Request.prototype.referrer) => {\n\tif (referrer === 'about:client') return '';\n\treturn referrer;\n};\n\nconst analyticsLogEndpoint = endpoint({\n\tpathname: '/log',\n\tmethod: 'POST',\n\tschema: {\n\t\tresponse: typed<unknown>(),\n\t\tbody: typed<TrackPayload>(),\n\t},\n});\n\nexport type AnalyticsOnEventCallback = (event: AnalyticsLogParams) => void;\n\nexport const createAnalyticsService = ({\n\trpcClient,\n\tlogger,\n\tonEvent,\n\tpersistence = 'device',\n\tsiteKind,\n}: {\n\tlogger: Logger;\n\trpcClient: InploiRpcClient;\n\tonEvent?: AnalyticsOnEventCallback;\n\tpersistence?: 'device' | 'none';\n\tsiteKind?: SiteKind;\n}): AnalyticsService => {\n\tlet memorySessionId: string | null = null;\n\tlet memoryAnonymousId: string | null = null;\n\tlet sessionRequestSequence = 0;\n\tlet latestSessionResponse = 0;\n\tconst sessionInfo = (request?: Request) =>\n\t\tpersistence === 'none' ?\n\t\t\t{ anonymous_id: null, session_id: request ? null : memorySessionId }\n\t\t:\tgetSessionInfo(request);\n\n\tconst logFn: <TEvent extends keyof EventPropertyMap>(\n\t\tparams: LogFnParams<TEvent>,\n\t\tpage: AnalyticsContext['page'],\n\t\tenvelope: AnalyticsEnvelope,\n\t) => Promise<ResponseObj<TrackPayload<EventPropertyMap[TEvent]['properties']>>> = async (params, page, envelope) => {\n\t\ttry {\n\t\t\tconst context: AnalyticsContext = {\n\t\t\t\tlibrary: {\n\t\t\t\t\tname: 'inploi-sdk',\n\t\t\t\t\tversion: ANALYTICS_VERSION,\n\t\t\t\t},\n\t\t\t\tpage,\n\t\t\t};\n\n\t\t\tconst currentSession = sessionInfo(params.request);\n\t\t\tconst resolvedCandidateId = persistence === 'none' ? null : getStoredCandidateId();\n\n\t\t\tconst payload: TrackPayload = {\n\t\t\t\tanonymous_id: currentSession.anonymous_id,\n\t\t\t\tsession_id: currentSession.session_id,\n\t\t\t\tcandidate_id: resolvedCandidateId,\n\t\t\t\tevent: params.event,\n\t\t\t\tsent_at: new Date().toISOString(),\n\t\t\t\tcontext,\n\t\t\t\tproperties: params.properties,\n\t\t\t\t// The envelope is spread last so a caller's custom property cannot replace it.\n\t\t\t\tcustom_properties: { ...params.customProperties, ...envelope },\n\t\t\t};\n\n\t\t\tconst cookieIdBeforeRequest =\n\t\t\t\tpersistence === 'none' ? null\n\t\t\t\t: params.request ? getCookieId(params.request)\n\t\t\t\t: getBrowserStoredId();\n\t\t\tconst requestSequence = ++sessionRequestSequence;\n\t\t\tconst responseJson = await rpcClient.request(analyticsLogEndpoint, {\n\t\t\t\tbody: payload,\n\t\t\t\t...(params.keepalive && { keepalive: true }),\n\t\t\t});\n\n\t\t\tconst newSession = getSessionInfoFromResponse(responseJson);\n\t\t\tif (persistence === 'none') {\n\t\t\t\tif (!params.request && newSession?.session_id && requestSequence > latestSessionResponse) {\n\t\t\t\t\tlatestSessionResponse = requestSequence;\n\t\t\t\t\t// An echo of the sent id must not undo a replacement received while this request was in flight.\n\t\t\t\t\tif (newSession.session_id !== payload.session_id) memorySessionId = newSession.session_id;\n\t\t\t\t}\n\t\t\t\tpayload.session_id = params.request ? newSession?.session_id || null : memorySessionId;\n\t\t\t\tonEvent?.(payload as AnalyticsLogParams);\n\t\t\t\treturn { success: true, data: payload };\n\t\t\t}\n\t\t\t// Keep an existing visitor id, including one set by Kin in flight. A mismatched session\n\t\t\t// would resolve back to the response's id, so keep the session that was sent as well.\n\t\t\tconst cookieIdNow = params.request ? cookieIdBeforeRequest : getBrowserStoredId();\n\t\t\tconst writtenDuringRequest = cookieIdNow !== null && cookieIdNow !== cookieIdBeforeRequest;\n\t\t\tconst cookieIdToKeep = cookieIdNow ?? cookieIdBeforeRequest;\n\t\t\tconst canAdoptResponse =\n\t\t\t\t!writtenDuringRequest &&\n\t\t\t\t(!cookieIdToKeep || !newSession?.anonymous_id || cookieIdToKeep === newSession.anonymous_id);\n\t\t\tif (canAdoptResponse) {\n\t\t\t\tif (newSession?.anonymous_id) payload.anonymous_id = newSession.anonymous_id;\n\t\t\t\tif (newSession?.session_id) payload.session_id = newSession.session_id;\n\t\t\t} else {\n\t\t\t\tpayload.anonymous_id = cookieIdToKeep;\n\t\t\t}\n\n\t\t\tif (!params.request && typeof window !== 'undefined' && payload.anonymous_id) {\n\t\t\t\tif (canAdoptResponse && payload.session_id) {\n\t\t\t\t\tsafeSessionStorage.set(`${ANALYTICS_COOKIE_NAME}-session_id`, payload.session_id.toString());\n\t\t\t\t}\n\t\t\t\tpersistAnonymousId(payload.anonymous_id);\n\t\t\t}\n\n\t\t\tonEvent?.(payload as AnalyticsLogParams);\n\t\t\treturn { success: true, data: payload };\n\t\t} catch (e) {\n\t\t\t/** We dont’t log any PII on the console */\n\t\t\tlogger.error('Failed to send log to API. Inspect error response of `log` for more information.');\n\t\t\treturn { success: false, error: e };\n\t\t}\n\t};\n\n\t// Bootstrap one API session before dispatching other first events. Once known,\n\t// events can run concurrently without minting separate sessions for this document.\n\tlet pendingSessionLog: Promise<unknown> = Promise.resolve();\n\tconst log: LogFn = async params => {\n\t\tinvariant(\n\t\t\tparams.request || typeof window !== 'undefined',\n\t\t\t'Cannot log on the server without a request. Please pass a request to `log`.',\n\t\t);\n\n\t\t// if there’s a request, use it instead of browser APIs\n\t\tconst page =\n\t\t\t'request' in params && params.request ?\n\t\t\t\t{\n\t\t\t\t\thref: params.request.url,\n\t\t\t\t\treferrer: serverReferrer(params.request.referrer),\n\t\t\t\t\ttitle: '',\n\t\t\t\t}\n\t\t\t:\t{\n\t\t\t\t\thref: location.href,\n\t\t\t\t\treferrer: document.referrer,\n\t\t\t\t\ttitle: document.title,\n\t\t\t\t};\n\n\t\tif (\n\t\t\tpersistence === 'none' &&\n\t\t\tparams.event === 'FLOW_NODE' &&\n\t\t\tparams.properties &&\n\t\t\t'trigger' in params.properties &&\n\t\t\t(params.properties.trigger === 'pagehide' || params.properties.trigger === 'hidden')\n\t\t) {\n\t\t\tparams = { ...params, keepalive: true };\n\t\t}\n\t\t// Made here, before any queueing, so the event keeps one id however it is sent.\n\t\tconst envelope: AnalyticsEnvelope = {\n\t\t\tevent_id: generateUUID(),\n\t\t\tconsent_lane: persistence,\n\t\t\t// Set even when unknown, so a caller's custom property cannot supply it; JSON then leaves it out.\n\t\t\tsite_kind: siteKind,\n\t\t};\n\t\t// An unloading page cannot wait for the bootstrap response. The API can mint a separate session.\n\t\tif (persistence === 'device' || params.request || memorySessionId || params.keepalive)\n\t\t\treturn logFn(params, page, envelope);\n\t\tconst send = () => logFn(params, page, envelope);\n\t\tconst response = pendingSessionLog.then(send, send);\n\t\tpendingSessionLog = response;\n\t\treturn response;\n\t};\n\n\treturn {\n\t\tlog,\n\t\tgetHeaders: payload => {\n\t\t\tconst headers = new Headers();\n\t\t\tif (persistence === 'none' || !payload?.anonymous_id) return headers;\n\n\t\t\theaders.append('Set-Cookie', formatCookie(payload.anonymous_id));\n\t\t\treturn headers;\n\t\t},\n\t\tgetSessionInfo: sessionInfo,\n\t\tgetOrCreateAnonymousId: () =>\n\t\t\tpersistence === 'none' ? (memoryAnonymousId ??= generateUUID()) : getOrCreateAnonymousId(),\n\t};\n};\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { stringify } from 'neoqs';\n\nimport { SchemaValidationError, handleApiExceptions, parseJsonResponse } from './sdk.api';\nimport { ENV_TO_API_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger } from './sdk.logger';\n\ntype RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\n/** Extract parameter names from a pathname string */\ntype ExtractParamNames<T extends string> =\n\tT extends `${infer _Before}:${infer Param}/${infer After}` ? Param | ExtractParamNames<`/${After}`>\n\t: T extends `${infer _Before}:${infer Param}` ? Param\n\t: never;\n\n/** Create params object from parameter names */\ntype ExtractPathParams<T extends string> =\n\tstring extends T ? Record<string, string | number>\n\t: ExtractParamNames<T> extends never ? Record<string, never>\n\t: { [K in ExtractParamNames<T>]: string | number };\n\n/** Parses a StandardSchemaV1 schema and input into an output. */\nexport function parse<T extends StandardSchemaV1>(\n\tschema: T,\n\tinput: StandardSchemaV1.InferInput<T>,\n\tsource?: 'body' | 'searchParams' | 'response',\n): StandardSchemaV1.InferOutput<T> {\n\tconst result = schema['~standard'].validate(input);\n\tif (result instanceof Promise) {\n\t\tthrow new TypeError('Async schema');\n\t}\n\n\tif (result.issues) {\n\t\tthrow new SchemaValidationError(result.issues, source);\n\t}\n\n\treturn result.value;\n}\n\n/** Parses a StandardSchemaV1 schema and input into an output, returning a success flag and issues if the parse fails. */\nexport function safeParse<T extends StandardSchemaV1>(\n\tschema: T,\n\tinput: StandardSchemaV1.InferInput<T>,\n\tsource?: 'body' | 'searchParams' | 'response',\n):\n\t| {\n\t\t\tsuccess: true;\n\t\t\toutput: StandardSchemaV1.InferOutput<T>;\n\t }\n\t| {\n\t\t\tsuccess: false;\n\t\t\tissues: readonly StandardSchemaV1.Issue[];\n\t\t\tsource?: 'body' | 'searchParams' | 'response';\n\t } {\n\ttry {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\toutput: parse(schema, input, source),\n\t\t};\n\t} catch (e) {\n\t\tif (e instanceof SchemaValidationError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tissues: e.issues,\n\t\t\t\tsource: e.source,\n\t\t\t};\n\t\t}\n\t\tthrow e;\n\t}\n}\n\nexport interface InploiRpcClientParams {\n\tenvironment: InploiSdkEnvironment;\n\tlogger: Logger;\n\tapiKey:\n\t\t| {\n\t\t\t\t/** Makes the API call with an x-secret-key header\n\t\t\t\t * This will error if used in a browser environment.\n\t\t\t\t */\n\t\t\t\ttype: 'secret';\n\t\t\t\tkey: string;\n\t\t }\n\t\t| {\n\t\t\t\t/** Makes the API call with an x-publishable-key header\n\t\t\t\t * This can be called in a browser or server environment.\n\t\t\t\t */\n\t\t\t\ttype: 'publishable';\n\t\t\t\tkey: string;\n\t\t };\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype NonReducibleUnknown = {} | null | undefined;\ntype LooseAutocomplete<T extends BaseType, BaseType> = T | BaseType;\n\n/** RPC client for making API calls to the Inploi API. */\nexport class InploiRpcClient {\n\tprivate baseUrl: string;\n\tprivate headers: Headers;\n\tprivate logger: Logger;\n\tprivate _environment: InploiSdkEnvironment;\n\n\tconstructor(params: InploiRpcClientParams) {\n\t\tthis.baseUrl = ENV_TO_API_URL[params.environment];\n\t\tthis.headers = new Headers({\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAccept: 'application/json',\n\t\t});\n\t\tif (params.apiKey.type === 'secret') {\n\t\t\tif (typeof window !== 'undefined') {\n\t\t\t\tthrow new Error('Secret key cannot be used in a browser environment');\n\t\t\t}\n\t\t\tthis.headers.set('x-secret-key', params.apiKey.key);\n\t\t} else {\n\t\t\tthis.headers.set('x-publishable-key', params.apiKey.key);\n\t\t}\n\t\tthis.logger = params.logger;\n\t\tthis._environment = params.environment;\n\t}\n\n\tget environment() {\n\t\treturn this._environment;\n\t}\n\n\t/** Gets params for a fetch request to the given endpoint */\n\tgetFetchParams<T extends RpcEndpoint>(\n\t\tendpoint: T,\n\t\toptions: T extends RpcEndpoint<infer _, infer _TPathname, infer TPathParams, infer TSearch, infer TBody> ?\n\t\t\tGetSchemaValues<{\n\t\t\t\tbody: TBody;\n\t\t\t\tsearchParams: TSearch;\n\t\t\t\tparams: TPathParams;\n\t\t\t}> & {\n\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t/** Lets the request outlive the page (`fetch` keepalive), for a last analytics event on pagehide. */\n\t\t\t\tkeepalive?: boolean;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the inputs against the schema.\n\t\t\t\t * If you want to skip validation (e.g.: already validated yourself or with `validateEndpontInputs`), set this to false.\n\t\t\t\t */\n\t\t\t\tvalidateIn?: boolean;\n\t\t\t}\n\t\t:\tnever,\n\t): [url: string, options: RequestInit] {\n\t\tconst validateIn = options.validateIn ?? true;\n\t\tconst { searchParams, body } = validateIn ? validateEndpointInputs(endpoint, options) : options;\n\n\t\tconst url = new URL(this.baseUrl);\n\n\t\t// Replace path parameters in pathname\n\t\tlet pathname = endpoint.pathname;\n\t\tif ('params' in options && options.params) {\n\t\t\tfor (const [key, value] of Object.entries(options.params)) {\n\t\t\t\tpathname = pathname.replace(`:${key}`, String(value));\n\t\t\t}\n\t\t}\n\t\turl.pathname = pathname;\n\n\t\tif (endpoint.schema.searchParams) {\n\t\t\turl.search = stringify(searchParams);\n\t\t}\n\n\t\treturn [\n\t\t\turl.toString(),\n\t\t\t{\n\t\t\t\tmethod: endpoint.method,\n\t\t\t\tbody: body ? JSON.stringify(body) : undefined,\n\t\t\t\theaders: this.headers,\n\t\t\t\tsignal: options.signal,\n\t\t\t\t...(options.keepalive && { keepalive: true }),\n\t\t\t},\n\t\t];\n\t}\n\n\t/** Parses a response against an endpoint’s response schema, considering common errors thrown from the API.\n\t * @throws {JsonParsingError} - If the response is not valid JSON.\n\t * @throws {SchemaValidationError} - If the response does not match the schema.\n\t * @throws {ApiError} - If the API responded with an error message.\n\t */\n\tasync parseResponse<T extends RpcEndpoint>(\n\t\tendpoint: T,\n\t\toptions: {\n\t\t\tresponse: Response;\n\t\t\t/**\n\t\t\t * Whether to validate the response against the schema.\n\t\t\t * This is meant more as an escape hatch for when the response is not as expected and you want to handle it separately yourself.\n\t\t\t * ⚠️ This will lead to potential type/runtime mismatch as it does not verify the response against the schema.\n\t\t\t */\n\t\t\tvalidateOut?: boolean;\n\t\t},\n\t): Promise<StandardSchemaV1.InferOutput<T['schema']['response']>> {\n\t\tconst json = await parseJsonResponse(options.response);\n\t\thandleApiExceptions(json, options.response.status);\n\n\t\tconst validateOut = options.validateOut ?? true;\n\t\tif (!validateOut) return json as StandardSchemaV1.InferOutput<T['schema']['response']>;\n\n\t\tconst result = safeParse(endpoint.schema.response, json, 'response');\n\t\tif (!result.success) {\n\t\t\tthrow new SchemaValidationError(result.issues, result.source);\n\t\t}\n\n\t\treturn result.output as StandardSchemaV1.InferOutput<T['schema']['response']>;\n\t}\n\n\t/** Fetches, parses and validates an API endpoint.\n\t * Logs errors and throws them again so that the caller can handle them.\n\t *\n\t * @throws {JsonParsingError} - If the response is not valid JSON.\n\t * @throws {SchemaValidationError} - If the searchParams, body or response does not match the schema.\n\t * @throws {ApiError} - If the API responded with an error message.\n\t * @throws {UnauthorisedError} - If the request is unauthorised either by missing key or unmet permissions.\n\t * @throws {NotFoundError} - If the endpoint is not found.\n\t * @throws {Error} - Another unhandled error.\n\t */\n\tasync request<T extends RpcEndpoint>(\n\t\tendpoint: T,\n\t\toptions: T extends RpcEndpoint<infer _, infer _TPathname, infer TPathParams, infer TSearch, infer TBody> ?\n\t\t\tGetSchemaValues<{\n\t\t\t\tbody: TBody;\n\t\t\t\tsearchParams: TSearch;\n\t\t\t\tparams: TPathParams;\n\t\t\t}> & {\n\t\t\t\tsignal?: AbortSignal;\n\t\t\t\t/** Lets the request outlive the page (`fetch` keepalive), for a last analytics event on pagehide. */\n\t\t\t\tkeepalive?: boolean;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the inputs against the schema.\n\t\t\t\t * If you want to skip validation (e.g.: already validated yourself or with `validateEndpontInputs`), set this to false.\n\t\t\t\t */\n\t\t\t\tvalidateIn?: boolean;\n\t\t\t\t/**\n\t\t\t\t * Whether to validate the response against the schema.\n\t\t\t\t * This is meant more as an escape hatch for when the response is not as expected and you want to handle it separately yourself.\n\t\t\t\t * ⚠️ This will lead to potential type/runtime mismatch as it does not verify the response against the schema.\n\t\t\t\t */\n\t\t\t\tvalidateOut?: boolean;\n\t\t\t}\n\t\t:\tnever,\n\t): Promise<StandardSchemaV1.InferOutput<T['schema']['response']>> {\n\t\ttry {\n\t\t\tconst fetchParams = this.getFetchParams(endpoint, options);\n\t\t\tconst response = await fetch(...fetchParams);\n\t\t\treturn await this.parseResponse(endpoint, { response, validateOut: options.validateOut });\n\t\t} catch (e) {\n\t\t\tif (e instanceof SchemaValidationError) {\n\t\t\t\tthis.logger.error(e.message, e.issues);\n\t\t\t} else {\n\t\t\t\tthis.logger.error(e);\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n}\n\ntype GetSchemaValues<T extends { searchParams: any; body: any; params?: any }> = {\n\t[K in keyof T as T[K] extends never ? never\n\t: T[K] extends Record<string, never> ? never\n\t: K]: T[K] extends never ? never : LooseAutocomplete<T[K], NonReducibleUnknown>;\n};\n\n/**\n * Typed but *not runtime validated* schema\n * useful for type-checking the schema without bundling validation schemas\n */\nexport function typed<T>(): StandardSchemaV1<T, T> {\n\treturn {\n\t\t'~standard': {\n\t\t\tvendor: 'inploi',\n\t\t\tversion: 1,\n\t\t\tvalidate: input => {\n\t\t\t\treturn {\n\t\t\t\t\tvalue: input as T,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t};\n}\n\nexport interface RpcEndpoint<\n\tTMethod extends RequestMethod = RequestMethod,\n\tTPathname extends string = string,\n\tTPathParams = any,\n\tTSearch = any,\n\tTBody = any,\n\tTResponse = any,\n> {\n\tpathname: TPathname;\n\tmethod: TMethod;\n\theaders?: Headers;\n\tschema: {\n\t\tsearchParams?: StandardSchemaV1<TSearch, TSearch>;\n\t\tbody?: StandardSchemaV1<TBody, TBody>;\n\t\tresponse: StandardSchemaV1<TResponse, TResponse>;\n\t};\n\t/** Type-only property to store path parameter types */\n\treadonly __pathParams?: TPathParams;\n}\n\nexport function endpoint<\n\tTMethod extends RequestMethod,\n\tTPathname extends string,\n\tTSearch extends StandardSchemaV1 | never = never,\n\tTBody extends StandardSchemaV1 | never = never,\n\tTResponse extends StandardSchemaV1 | never = never,\n>(endpoint: {\n\tpathname: TPathname;\n\tmethod: TMethod;\n\theaders?: Headers;\n\tschema: {\n\t\tsearchParams?: TSearch;\n\t\tbody?: TBody;\n\t\tresponse: TResponse;\n\t};\n}) {\n\ttype PathParams = ExtractPathParams<TPathname>;\n\treturn endpoint as RpcEndpoint<\n\t\tTMethod,\n\t\tTPathname,\n\t\tPathParams,\n\t\tStandardSchemaV1.InferInput<TSearch>,\n\t\tStandardSchemaV1.InferInput<TBody>,\n\t\tStandardSchemaV1.InferOutput<TResponse>\n\t>;\n}\n\n/** Validates the inputs for an endpoint ahead of time\n * Useful when you need to validate and throw earlier, or use the inputs for something other than the API call.\n */\nexport function validateEndpointInputs<T extends RpcEndpoint>(\n\tendpoint: T,\n\toptions: GetSchemaValues<{ body: unknown; searchParams: unknown }>,\n) {\n\tconst validatedInputs = {\n\t\tsearchParams: undefined,\n\t\tbody: undefined,\n\t\tvalidateIn: false,\n\t} as T extends RpcEndpoint<infer _, infer __, infer ___, infer TSearch, infer TBody> ?\n\t\tGetSchemaValues<{\n\t\t\tbody: TBody;\n\t\t\tsearchParams: TSearch;\n\t\t}> & {\n\t\t\tvalidateIn: false;\n\t\t}\n\t:\tnever;\n\n\tif (endpoint.schema.searchParams) {\n\t\tvalidatedInputs.searchParams = parse(\n\t\t\tendpoint.schema.searchParams,\n\t\t\t'searchParams' in options ? options.searchParams : {},\n\t\t);\n\t}\n\n\tif (endpoint.schema.body) {\n\t\tvalidatedInputs.body = parse(endpoint.schema.body, 'body' in options ? options.body : {});\n\t}\n\n\treturn validatedInputs;\n}\n","import { AnalyticsOnEventCallback, createAnalyticsService } from './sdk.analytics';\nimport { createApiClient } from './sdk.api';\nimport { ENV_TO_API_URL, InploiSdkEnvironment } from './sdk.constants';\nimport type { SiteKind } from './sdk.events';\nimport { Logger, inploiBrandedLogger, noLogging } from './sdk.logger';\nimport { InploiSdkPlugin } from './sdk.plugins';\nimport { InploiRpcClient } from './sdk.rpc';\n\nexport type InitialiseInploiSdkParams = {\n\t/** Your public API key for the inploi SDK. */\n\tpublishableKey: string;\n\t/** Which app environment to run. This ultimately affects which inploi endpoints to gather data are going to be used.\n\t * Anything other than `production` should be considered a development environment and the data periodicaly purged. */\n\tenv: InploiSdkEnvironment;\n\t/** Logger object that handles logging of different levels.\n\t * You can override this to use your own logger, or to disable logging altogether by passing`false`.\n\t * @default inploiBrandedLogger\n\t * */\n\tlogger?: Logger | false;\n\n\t/** When provided, this callback will be called with every event that is logged to the analytics service. */\n\tonEvent?: AnalyticsOnEventCallback;\n\t/** Analytics identity storage. `none` keeps only an API session in memory; defaults to `device`. */\n\tpersistence?: 'device' | 'none';\n\t/** What kind of site this is, sent with every event as `site_kind`: a Studio careers site (`hub`) or a client's own page (`embedded`). */\n\tsiteKind?: SiteKind;\n};\n\nexport function initialiseSdk({\n\tpublishableKey,\n\tenv,\n\tlogger = inploiBrandedLogger,\n\tonEvent,\n\tpersistence,\n\tsiteKind,\n}: InitialiseInploiSdkParams) {\n\t/** @deprecated - use `rpcClient` instead */\n\tconst apiClient = createApiClient({ baseUrl: ENV_TO_API_URL[env], publishableKey });\n\tconst loggerService = logger === false ? noLogging : logger;\n\tconst rpcClient = new InploiRpcClient({\n\t\tenvironment: env,\n\t\tapiKey: { type: 'publishable', key: publishableKey },\n\t\tlogger: loggerService,\n\t});\n\tconst analytics = createAnalyticsService({\n\t\trpcClient,\n\t\tlogger: loggerService,\n\t\tonEvent,\n\t\tpersistence,\n\t\tsiteKind,\n\t});\n\n\tconst register = <P extends InploiSdkPlugin>(plugin: P): ReturnType<P> => {\n\t\treturn plugin({ logger: loggerService, apiClient, analytics, rpcClient, publishableKey, env });\n\t};\n\n\treturn { register, analytics, apiClient };\n}\n\nexport type InploiSdk = ReturnType<typeof initialiseSdk>;\n","import type { AddressShadowComparison } from '@inploi/core/common';\n\ntype FlowProperties = { flow_id: string; flow_version: number; flow_session_id: string; flow_build: number };\n\nexport type FlowType = 'CHATBOT_DRAWER' | 'FORM_DRAWER' | 'FORM_EMBED';\n\ntype FunnelFlowProperties = FlowProperties & { flow_type?: FlowType };\n\ntype JobProperties = {\n\tid: string;\n\tid_type: 'internal' | 'external';\n};\n\n/**\n * One id per navigation (a document load, an in-app route change, a restore from the back/forward cache), shared by\n * that navigation's `VIEW_PAGE` or `VIEW_JOB` events, so a view counts once per navigation and a retry is recognised.\n * Minted by the page (`generateUUID`).\n */\ntype NavigationProperties = { navigation_id?: string };\n\nexport type PageEngagementProperties = {\n\t/** Random per page view, minted by the page; not a visitor identifier. */\n\tview_id: string;\n\t/**\n\t * The viewed page's pathname, without query or hash. A summary sent as an in-app navigation ends a view carries the\n\t * next page in its `context.page`, so reports read the page from here.\n\t */\n\tpath: string;\n\t/** Milliseconds the page was visible and in use (input or scroll within the last 30 s). */\n\tengaged_ms: number;\n\t/** The deepest quarter of the page reached. */\n\tscroll_max: 0 | 25 | 50 | 75 | 100;\n\t/**\n\t * Top-level CMS blocks that were in view, with milliseconds in view while engaged. `slug` and `label` are the\n\t * block's authored CMS type and editor label.\n\t */\n\tsections: { id: string; slug: string; label?: string; ms: number }[];\n\tjob: JobProperties | undefined;\n};\n\n/**\n * One question on a candidate's path through an application, in a `FLOW_NODE` summary. Keys, positions, input types,\n * timings and counts only: never an answer, a file or any text the candidate typed.\n */\nexport type FlowPathStep = {\n\t/** The question's key in the flow (its submission key). */\n\tk?: string;\n\t/** 1-based position on this session's path. */\n\ti: number;\n\t/** The question's input type, e.g. `text`, `enum`, `file`. */\n\tt: string;\n\t/** Milliseconds from the question being shown to it being answered or skipped. */\n\tms?: number;\n\t/** `a` answered, `s` skipped; absent while it waits. */\n\to?: 'a' | 's';\n\t/** How many times a refusal (validation) appeared on it; repeated refusals behind one visible message count once. */\n\te?: number;\n\t/** How many times it was changed at review. */\n\tr?: number;\n};\n\n/** Why a path summary was sent: the moments a session can end or pause. */\nexport type FlowPathTrigger = 'submit' | 'redirect' | 'minimise' | 'hidden' | 'pagehide' | 'restart';\n\n/**\n * `FLOW_NODE`, the Candidate Agent's application path summary: sent when a session pauses or ends and its path has\n * changed since the last summary, never per step, so a session costs a few rows. The latest by `sent_at` per `flow_session_id` is the whole path so far.\n */\nexport type FlowPathProperties = FunnelFlowProperties & {\n\tjob: JobProperties | undefined;\n\ttrigger: FlowPathTrigger;\n\tsteps: FlowPathStep[];\n\t/** The earliest steps left out to keep the summary within the api's size limit; the latest are always kept. */\n\tsteps_omitted?: number;\n\t/** The node the candidate was on when it was sent. */\n\tto_node_id?: string;\n\t/** Milliseconds since the candidate's own last action (answer, skip, refusal, edit, typing, a CV, the redirect click). */\n\tidle_ms: number;\n\tsubmit_attempts: number;\n\t/** The last attempt's outcome: `success`, `redirect`, `pending`, `failed` or the failure's outcome. */\n\tsubmit_result?: string;\n\t/** The widget's CV invitation before the first question; a CV question is a step whose `t` is `file`. */\n\tcv?: 'offered' | 'attached';\n\t/** The device class, never a user agent: a coarse (touch) or fine pointer, and the screen width's bucket. */\n\tdevice: { pointer: 'coarse' | 'fine'; width: 'xs' | 's' | 'm' | 'l' };\n\t/** The candidate opened the employer's link after submitting (a redirect such as TribePad's). */\n\tredirect_clicked?: true;\n\t/** Milliseconds from the redirect's submit result to the click; absent on a revisit, whose submit was earlier. */\n\tredirect_ms?: number;\n\t/** The click came on a later visit, from the link restored with the conversation. */\n\tredirect_revisit?: true;\n\tagent_conversation_key?: string;\n};\n\nexport type AnalyticsLogParams =\n\t| {\n\t\t\tevent: 'ADDRESS_SHADOW_COMPARED';\n\t\t\tproperties: AddressShadowComparison;\n\t }\n\t| {\n\t\t\tevent: 'VIEW_JOB';\n\t\t\tproperties: { job: JobProperties } & NavigationProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_REDIRECT';\n\t\t\tproperties: { href: string; job: JobProperties | undefined } & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_START' | 'FLOW_INTERACT';\n\t\t\tproperties: { job: JobProperties | undefined } & FunnelFlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_END';\n\t\t\tproperties: { job: JobProperties | undefined } & FlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_NODE';\n\t\t\tproperties: FlowPathProperties;\n\t }\n\t| {\n\t\t\tevent: 'FLOW_SUBMIT';\n\t\t\tproperties: {\n\t\t\t\tservice: string;\n\t\t\t\t/** Confirmed first-apply capture, even when downstream delivery failed. */\n\t\t\t\tcaptured?: boolean;\n\t\t\t\tresponse: {\n\t\t\t\t\tstatus: number;\n\t\t\t\t\tpayload: unknown;\n\t\t\t\t};\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t\t/**\n\t\t\t\t * Set when the provider confirmed a duplicate (distinguishing one within an hour of the candidate's own\n\t\t\t\t * failed attempt on that application), or when the API accepted the application for later delivery (`pending`).\n\t\t\t\t */\n\t\t\t\toutcome?: 'duplicate' | 'duplicate_after_own_attempt' | 'pending';\n\t\t\t} & FunnelFlowProperties;\n\t }\n\t| {\n\t\t\tevent: 'SUBMIT_FORM';\n\t\t\tproperties?: {\n\t\t\t\tjob: JobProperties | undefined;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'VIEW_PAGE';\n\t\t\tproperties?: { job: JobProperties | undefined } & NavigationProperties;\n\t }\n\t/**\n\t * `PAGE_ENGAGEMENT`, one careers-site page view's attention summary: sent when the view is hidden or left, never\n\t * per scroll or tick. Summaries are cumulative, so per `view_id` the maximum of `engaged_ms`, of `scroll_max` and of\n\t * each section's `ms` is the whole view. Counts plus authored CMS block metadata only: never page text, a URL or\n\t * anything the visitor typed.\n\t */\n\t| { event: 'PAGE_ENGAGEMENT'; properties: PageEngagementProperties }\n\t| {\n\t\t\tevent: 'SEARCH_PAGINATE';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'SEARCH_SETTLE';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| { event: 'SAVE_JOB'; properties: { job_id: number; saved: boolean } }\n\t| {\n\t\t\tevent: 'SEARCH_JOB_CLICK';\n\t\t\tproperties: {\n\t\t\t\tjob_id: number;\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'VIEW_SEARCH';\n\t\t\tproperties: {\n\t\t\t\tquery?: string;\n\t\t\t\tfilters?: Record<string, string[]>;\n\t\t\t\tdefault_filters?: Record<string, string[]>;\n\t\t\t\ttotal_count: number;\n\t\t\t\tpage_size: number;\n\t\t\t\tpage: number;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'FEEDBACK';\n\t\t\tproperties: {\n\t\t\t\tkey: string;\n\t\t\t\tscore?: -1 | 0 | 1;\n\t\t\t\tcomment?: string;\n\t\t\t\t/** Where the rating or comment was given: the widget header's faces, or the ask at an application's end. */\n\t\t\t\tplacement?: 'header' | 'end';\n\t\t\t\t/** The build of the widget that drew it (the Candidate Agent's `0.0.0-pc.N`). */\n\t\t\t\twidget_version?: string;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'LINK_CLICK';\n\t\t\tproperties: {\n\t\t\t\ttarget_href: string;\n\t\t\t\tjob_id: string | undefined;\n\t\t\t};\n\t }\n\t| {\n\t\t\tevent: 'INTERACTION';\n\t\t\tproperties: {\n\t\t\t\ttag: string;\n\t\t\t\t/** `feedback_shown` only: the frame was under 400px wide (a phone) when the faces were first on screen. */\n\t\t\t\tnarrow?: boolean;\n\t\t\t\t/** `feedback_shown` only: the ask after a sent application, rather than the header's faces. */\n\t\t\t\tplacement?: 'end';\n\t\t\t};\n\t };\n\nexport type AnalyticsLogEvent = AnalyticsLogParams['event'];\n\n/**\n * The catalogue: every event the SDK and its plugins send to `/log`, with what it records. Each event's fields are its\n * `AnalyticsLogParams` member above; every event also carries the envelope in `AnalyticsEnvelope`. Typed against\n * `AnalyticsLogEvent`, so an event cannot be added, renamed or removed without changing this list.\n */\nexport const ANALYTICS_EVENTS: Record<AnalyticsLogEvent, string> = {\n\tVIEW_PAGE: 'A careers-site page shown (not a job page).',\n\tVIEW_JOB: \"A job's own page shown; one per job id the page names.\",\n\tPAGE_ENGAGEMENT: \"A page view's attention summary, sent when the view is hidden or left.\",\n\tVIEW_SEARCH: 'A job search seen for two seconds.',\n\tSEARCH_SETTLE: 'A searched query or filter with results, unchanged for five seconds.',\n\tSEARCH_PAGINATE: 'A move to another page of search results.',\n\tSEARCH_JOB_CLICK: 'A job opened from search results.',\n\tSAVE_JOB: 'A job saved or unsaved by the candidate.',\n\tLINK_CLICK: 'A tracked link clicked.',\n\tINTERACTION: 'A tagged interaction (`tag` names it).',\n\tFLOW_START: 'An application flow started.',\n\tFLOW_INTERACT: \"The candidate's first answer in a flow.\",\n\tFLOW_END: 'An application flow ended.',\n\tFLOW_NODE: \"The candidate's path through an application, summarised when it pauses or ends.\",\n\tFLOW_SUBMIT: 'An application submitted, with the outcome.',\n\tFLOW_REDIRECT: 'A flow sent the candidate to an external apply page.',\n\tFEEDBACK: 'A rating or comment.',\n\tADDRESS_SHADOW_COMPARED: \"Engineering telemetry: the address lookup's shadow comparison.\",\n\tSUBMIT_FORM: 'Declared but sent by nothing.',\n};\n\n/**\n * Sent in `custom_properties` with every event, beside any custom properties the caller passes. Today's api stores\n * `custom_properties` as given (`session_logs.custom_properties`, capped at 1 KB), so these land there.\n */\nexport type AnalyticsEnvelope = {\n\t/** Made once per event where it is logged, so a repeat of the same event can be recognised and counted once. */\n\tevent_id: string;\n\t/** The analytics service's lane: `device` stores the visitor id, `none` stores nothing. */\n\tconsent_lane: 'device' | 'none';\n\t/** What kind of site sent it: a Studio careers site (`hub`) or a client's own page (`embedded`). Absent when the host did not say. */\n\tsite_kind?: SiteKind;\n};\n\nexport type SiteKind = 'hub' | 'embedded';\n","import { CONSENT_STORAGE_KEY_PREFIX } from './sdk.constants';\n\n/**\n * Tenant-published consent / approval config (PROD-5763).\n *\n * Mirror of `ConsentConfig` in inploi/agents — the agent worker sends\n * this in the `authenticated` WS event for the SDK to render before\n * the chat is usable.\n *\n * enabled — render the consent screen on first session if true.\n * message — body copy; markdown is rendered, so customers can\n * embed links inline (e.g. \"By continuing you agree\n * to our [Privacy Policy](https://...)\").\n * acceptLabel — text on the \"agree\" button. SDK defaults to\n * \"I agree\" if omitted.\n * declineLabel — text on the \"decline\" button. SDK defaults to\n * \"Decline\".\n */\nexport interface ConsentConfig {\n\tenabled: boolean;\n\tmessage: string;\n\tacceptLabel?: string;\n\tdeclineLabel?: string;\n}\n\n/**\n * Deterministic, fast, non-cryptographic hash of the consent config.\n * Used purely as a cache-busting suffix on the localStorage key — so\n * any material wording / label change produces a new key and the\n * candidate is re-prompted. Not a security primitive.\n *\n * djb2 + base36 = ~7 chars, plenty of entropy for a per-tenant key\n * suffix and easy to eyeball / grep in devtools storage.\n *\n * Exported for unit testing.\n */\nexport function hashConsentConfig(config: ConsentConfig): string {\n\tconst canonical = JSON.stringify({\n\t\tmessage: config.message,\n\t\tacceptLabel: config.acceptLabel ?? '',\n\t\tdeclineLabel: config.declineLabel ?? '',\n\t});\n\tlet hash = 5381;\n\tfor (let i = 0; i < canonical.length; i++) {\n\t\t// djb2: hash * 33 + char\n\t\thash = (hash * 33) ^ canonical.charCodeAt(i);\n\t}\n\t// Force unsigned 32-bit, then base36 for compactness.\n\treturn (hash >>> 0).toString(36);\n}\n\n/**\n * Build the localStorage key for a (tenant × consent config) pair.\n *\n * Exported for unit testing.\n */\nexport function consentStorageKey(publishableKey: string, configHash: string): string {\n\treturn `${CONSENT_STORAGE_KEY_PREFIX}:${publishableKey}:${configHash}`;\n}\n\n/**\n * Has the candidate already accepted this exact consent config?\n *\n * Returns `false` in non-browser environments and when localStorage\n * throws (Safari private mode, sandboxed iframes without storage\n * access). Same conservative posture as `getStoredCandidateId` — if\n * we cannot prove acceptance, re-prompt.\n */\nexport function getConsentAcceptance(publishableKey: string, config: ConsentConfig): boolean {\n\tif (typeof window === 'undefined') return false;\n\ttry {\n\t\tconst key = consentStorageKey(publishableKey, hashConsentConfig(config));\n\t\treturn window.localStorage.getItem(key) === 'accepted';\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Persist the candidate's acceptance of this exact consent config.\n *\n * Silently no-ops on storage failures — the consent flow still works\n * for the current page even if we cannot remember it across reloads.\n * That matches the existing identity / candidate-id pattern.\n */\nexport function setConsentAcceptance(publishableKey: string, config: ConsentConfig): void {\n\tif (typeof window === 'undefined') return;\n\ttry {\n\t\tconst key = consentStorageKey(publishableKey, hashConsentConfig(config));\n\t\twindow.localStorage.setItem(key, 'accepted');\n\t} catch {\n\t\t// localStorage unavailable — see comment above.\n\t}\n}\n","import * as v from \"valibot\";\nexport const CANDIDATE_SOURCES = [\n \"agent\",\n \"sdk\",\n \"form\",\n \"integration\",\n \"migration\",\n];\n/**\n * Canonical funnel-milestone groups. Stable enum baked into the contract —\n * lifecycle decisions key off this, never off `stage` (which is free-text).\n */\nexport const STAGE_GROUPS = [\n \"APPLIED\",\n \"SHORTLISTED\",\n \"INTERVIEWED\",\n \"OFFERED\",\n \"HIRED\",\n \"REJECTED\",\n \"WITHDRAWN\",\n];\n/**\n * Historical 1:1 stage slugs per group. Stages are now free-text at the\n * contract boundary — studio owns the per-company list — so this constant\n * exists only as the default-per-group fallback for callers (and tests)\n * that don't supply an explicit stage. See {@link DEFAULT_STAGE_FOR_GROUP}.\n */\nexport const STAGES = [\n \"applied\",\n \"shortlisted\",\n \"interviewed\",\n \"offered\",\n \"hired\",\n \"rejected\",\n \"withdrawn\",\n];\nexport const SCORE_TYPES = [\n \"screening\",\n \"cv_match\",\n \"interview\",\n \"overall\",\n];\nexport const INTERVIEW_STATUSES = [\n \"PENDING\",\n \"SCHEDULED\",\n \"IN_PROGRESS\",\n \"COMPLETED\",\n \"CANCELLED\",\n];\nexport const DUPLICATE_CHECK_SCOPES = [\"job\", \"company\"];\nexport const APPLICATION_SORT_FIELDS = [\"created_at\", \"updated_at\"];\nexport const SORT_ORDERS = [\"asc\", \"desc\"];\n/** Per-application source label. Set once on submit; never mutated thereafter. */\nexport const APPLICATION_SOURCES = [\n \"careers_site\",\n \"chatbot\",\n \"plugin_job_search\",\n \"ats_import\",\n \"referral\",\n \"agency\",\n \"other\",\n \"unknown\",\n];\n/**\n * The closed set of state-mutating actions that can be recorded in the\n * `application_logs` audit table.\n *\n * The named group transitions (`shortlist`, `move_to_interview`,\n * `make_offer`, `hire`, `withdraw`) exist *alongside* the generic\n * `move_to_stage` because the action key is what flows into audit +\n * analytics: a `shortlist` row and a `move_to_stage` row that happen to\n * both land in `SHORTLISTED` carry different intent and the dashboards\n * pivot on that. The legacy `stage_transition` is kept as an alias for\n * `move_to_stage` so existing consumers don't break.\n *\n * `submit` and `score_written` are server-emitted only — never accepted\n * via the generic apply-action surface.\n */\nexport const APPLICATION_ACTIONS = [\n \"submit\",\n \"stage_transition\",\n \"move_to_stage\",\n \"shortlist\",\n \"move_to_interview\",\n \"make_offer\",\n \"hire\",\n \"withdraw\",\n \"disqualify\",\n \"reinstate\",\n \"rate\",\n \"score_written\",\n];\n/** Who initiated the audited action. Verbatim from the request body. */\nexport const ACTOR_TYPES = [\n \"user\",\n \"system\",\n \"automation\",\n \"integration\",\n \"candidate\",\n];\nexport const CandidateSourceSchema = v.picklist(CANDIDATE_SOURCES);\nexport const StageGroupSchema = v.picklist(STAGE_GROUPS);\n/**\n * Stage slug — free-text from talent-bank's POV. Studio owns the per-company\n * stage configuration; talent-bank just stores and reflects whatever slug the\n * caller sends. The trimmed length cap mirrors the column intent (TEXT, but\n * we don't want kilobyte-sized slugs leaking through accidents).\n */\nexport const StageSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100));\nexport const ScoreTypeSchema = v.picklist(SCORE_TYPES);\nexport const InterviewStatusSchema = v.picklist(INTERVIEW_STATUSES);\nexport const DuplicateCheckScopeSchema = v.picklist(DUPLICATE_CHECK_SCOPES);\nexport const ApplicationSortFieldSchema = v.picklist(APPLICATION_SORT_FIELDS);\nexport const SortOrderSchema = v.picklist(SORT_ORDERS);\n/**\n * Disqualification reason slug — free-text from talent-bank's POV. Studio owns\n * the per-company reason configuration (label, ordering, whether a note is\n * required); talent-bank just stores and reflects whatever slug the caller\n * sends, exactly like {@link StageSchema}. The length cap mirrors the column\n * intent (TEXT, but we don't want kilobyte-sized slugs leaking through).\n */\nexport const DisqualificationReasonSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100));\nexport const ApplicationSourceSchema = v.picklist(APPLICATION_SOURCES);\nexport const ApplicationActionSchema = v.picklist(APPLICATION_ACTIONS);\nexport const ActorTypeSchema = v.picklist(ACTOR_TYPES);\n/**\n * The actor type that marks a shortlist as initiated by one of our own\n * automations (e.g. the Studio \"Sync shortlist to Talent Bank\" workflow node).\n *\n * This value is load-bearing across repos: the `/metrics` soft-cap query\n * (`buildShortlistCountQuery`) counts only `application.shortlisted` rows whose\n * `actorType` equals this constant, and the API workflow node must send exactly\n * this `actor.type` for its shortlists to be counted. Keeping it as a single\n * `satisfies ActorType` constant means a typo or a removal from {@link ACTOR_TYPES}\n * is a compile error rather than a silently-zero metric.\n */\nexport const AUTOMATION_ACTOR_TYPE = \"automation\";\n/**\n * Historical default-slug → group map. **Not a runtime validator** — stages\n * are now free-text and studio owns the per-company stage list. Only useful\n * for resolving the v1 default slugs in tests and back-compat paths.\n */\nexport const STAGE_TO_GROUP = {\n applied: \"APPLIED\",\n shortlisted: \"SHORTLISTED\",\n interviewed: \"INTERVIEWED\",\n offered: \"OFFERED\",\n hired: \"HIRED\",\n rejected: \"REJECTED\",\n withdrawn: \"WITHDRAWN\",\n};\n/**\n * Default stage slug per stage group. Used by named group-transition actions\n * when the caller does not supply an explicit `stage`, and by `submit` when\n * the request body omits both `stage` and `stageGroup`.\n */\nexport const DEFAULT_STAGE_FOR_GROUP = {\n APPLIED: \"applied\",\n SHORTLISTED: \"shortlisted\",\n INTERVIEWED: \"interviewed\",\n OFFERED: \"offered\",\n HIRED: \"hired\",\n REJECTED: \"rejected\",\n WITHDRAWN: \"withdrawn\",\n};\n/** Convention default applied on submit when the caller does not supply a stage. */\nexport const DEFAULT_STAGE = \"applied\";\nexport const DEFAULT_STAGE_GROUP = \"APPLIED\";\n/** Terminal stage groups — disqualified or self-withdrawn. */\nexport const TERMINAL_STAGE_GROUPS = new Set([\n \"REJECTED\",\n \"WITHDRAWN\",\n \"HIRED\",\n]);\n/**\n * Source stage groups that `reinstate` is permitted to move an application\n * *out of*. The set is engine-internal — it answers \"given a target row,\n * may the reinstate action proceed?\" — not a synonym for \"is this row\n * disqualified\" (the row's `disqualifiedAt` column answers that).\n *\n * HIRED is included so fat-finger hires can be corrected on the kanban\n * without resorting to a back-channel DB edit. `reinstate.apply` always\n * clears `disqualifiedAt` and `disqualificationReason`, which is a no-op\n * on HIRED rows (already null) — so adding HIRED has no semantic effect\n * on genuine disqualified reinstates.\n *\n * The complementary \"cannot reinstate INTO terminal\" guard\n * ({@link TERMINAL_STAGE_GROUPS}) is unchanged: this action moves\n * applications back into the active funnel, never sideways between\n * terminal states (use `disqualify` for HIRED → REJECTED).\n */\nexport const REINSTATABLE_STAGE_GROUPS = new Set([\n \"REJECTED\",\n \"WITHDRAWN\",\n \"HIRED\",\n]);\n/**\n * Discriminated actor block. Sent on every mutating route's body and\n * written verbatim into the matching `application_logs` row.\n */\nexport const ActorInputSchema = v.variant(\"type\", [\n v.object({\n type: v.literal(\"user\"),\n id: v.pipe(v.string(), v.minLength(1)),\n email: v.pipe(v.string(), v.minLength(1)),\n name: v.pipe(v.string(), v.minLength(1)),\n }),\n v.object({\n type: v.literal(\"system\"),\n id: v.pipe(v.string(), v.minLength(1)),\n name: v.optional(v.string()),\n }),\n v.object({\n type: v.literal(\"automation\"),\n id: v.pipe(v.string(), v.minLength(1)),\n name: v.optional(v.string()),\n }),\n v.object({\n type: v.literal(\"integration\"),\n id: v.pipe(v.string(), v.minLength(1)),\n name: v.optional(v.string()),\n }),\n v.object({\n type: v.literal(\"candidate\"),\n id: v.pipe(v.string(), v.minLength(1)),\n email: v.optional(v.string()),\n }),\n]);\n","import * as v from \"valibot\";\nexport const PaginationSchema = v.object({\n total: v.number(),\n page: v.number(),\n perPage: v.number(),\n lastPage: v.number(),\n});\nexport function paginatedResultSchema(itemSchema) {\n return v.object({\n data: v.array(itemSchema),\n pagination: PaginationSchema,\n });\n}\n","import * as v from \"valibot\";\nimport { CandidateSourceSchema } from \"./enums.js\";\nexport const CandidateSchema = v.object({\n id: v.string(),\n email: v.nullable(v.string()),\n firstName: v.nullable(v.string()),\n lastName: v.nullable(v.string()),\n phone: v.nullable(v.string()),\n source: v.nullable(CandidateSourceSchema),\n identifiedAt: v.nullable(v.string()),\n createdAt: v.string(),\n updatedAt: v.string(),\n});\n","import * as v from \"valibot\";\nimport { UnknownRecordSchema } from \"./_shared.js\";\nimport { CandidateSchema } from \"./candidate.js\";\nimport { ActorTypeSchema, ApplicationActionSchema, ApplicationSourceSchema, DisqualificationReasonSchema, ScoreTypeSchema, StageGroupSchema, StageSchema, } from \"./enums.js\";\nimport { InterviewSchema } from \"./interview.js\";\nexport const ScoreCategorySchema = v.object({\n score: v.number(),\n reason: v.string(),\n confidence: v.number(),\n});\nexport const ApplicationSchema = v.object({\n id: v.string(),\n candidateId: v.string(),\n jobId: v.number(),\n stage: StageSchema,\n stageGroup: StageGroupSchema,\n stageEnteredAt: v.string(),\n rating: v.nullable(v.number()),\n disqualifiedAt: v.nullable(v.string()),\n disqualificationReason: v.nullable(DisqualificationReasonSchema),\n disqualificationNote: v.nullable(v.string()),\n source: ApplicationSourceSchema,\n sourceDetail: v.nullable(v.string()),\n sessionId: v.nullable(v.number()),\n externalApplicationId: v.nullable(v.string()),\n meta: v.nullable(UnknownRecordSchema),\n context: v.nullable(UnknownRecordSchema),\n scoredAt: v.nullable(v.string()),\n createdAt: v.string(),\n updatedAt: v.string(),\n});\nexport const ApplicationScoreSchema = v.object({\n id: v.string(),\n applicationId: v.string(),\n scoreType: ScoreTypeSchema,\n score: v.nullable(v.number()),\n reason: v.nullable(v.string()),\n categories: v.nullable(v.record(v.string(), ScoreCategorySchema)),\n scoredBy: v.nullable(v.string()),\n createdAt: v.string(),\n});\nexport const ApplicationDetailSchema = v.object({\n ...ApplicationSchema.entries,\n candidate: v.nullable(CandidateSchema),\n score: v.nullable(ApplicationScoreSchema),\n interview: v.nullable(InterviewSchema),\n});\nexport const CandidateDetailSchema = v.object({\n ...CandidateSchema.entries,\n applications: v.array(ApplicationSchema),\n});\n/**\n * Audit-log row recording a single state-mutating action against an\n * application. Structured stage columns carry every transition-relevant\n * field in typed form; `meta` carries opaque action-specific extras.\n */\nexport const ApplicationLogSchema = v.object({\n id: v.string(),\n applicationId: v.string(),\n action: ApplicationActionSchema,\n fromStage: v.nullable(StageSchema),\n fromStageGroup: v.nullable(StageGroupSchema),\n toStage: v.nullable(StageSchema),\n toStageGroup: v.nullable(StageGroupSchema),\n disqualificationReason: v.nullable(DisqualificationReasonSchema),\n disqualificationNote: v.nullable(v.string()),\n actorId: v.nullable(v.string()),\n actorType: ActorTypeSchema,\n actorEmail: v.nullable(v.string()),\n actorName: v.nullable(v.string()),\n meta: v.nullable(UnknownRecordSchema),\n schemaVersion: v.number(),\n createdAt: v.string(),\n});\n","import * as v from \"valibot\";\n// Shared building blocks used by HTTP DTO schemas. Not re-exported from the\n// public barrel — these stay private to the contract folder so consumers don't\n// depend on incidental helpers.\nexport const RequiredStringSchema = v.pipe(v.string(), v.minLength(1));\nexport const PositiveIntegerSchema = v.pipe(v.number(), v.integer(), v.minValue(1));\nexport const UnknownRecordSchema = v.record(v.string(), v.unknown());\n","import * as v from \"valibot\";\nimport { UnknownRecordSchema } from \"./_shared.js\";\nimport { InterviewStatusSchema } from \"./enums.js\";\nexport const InterviewSchema = v.object({\n id: v.string(),\n applicationId: v.string(),\n status: InterviewStatusSchema,\n scheduledAt: v.nullable(v.string()),\n completedAt: v.nullable(v.string()),\n meta: v.nullable(UnknownRecordSchema),\n createdAt: v.string(),\n updatedAt: v.string(),\n});\n","import * as v from \"valibot\";\nimport { RequiredStringSchema } from \"../_shared.js\";\nimport { CandidateSourceSchema } from \"../enums.js\";\nexport const IdentifyInputSchema = v.object({\n anonymousId: RequiredStringSchema,\n email: RequiredStringSchema,\n firstName: v.nullish(v.string()),\n lastName: v.nullish(v.string()),\n phone: v.nullish(v.string()),\n source: v.nullish(CandidateSourceSchema),\n});\nexport const IdentifyResultSchema = v.object({\n candidateId: v.string(),\n isNew: v.boolean(),\n});\n","import * as v from \"valibot\";\nimport { PositiveIntegerSchema, RequiredStringSchema, UnknownRecordSchema, } from \"../_shared.js\";\nimport { ApplicationDetailSchema, ApplicationLogSchema, ScoreCategorySchema, } from \"../application.js\";\nimport { ActorInputSchema, ApplicationSortFieldSchema, ApplicationSourceSchema, DisqualificationReasonSchema, ScoreTypeSchema, SortOrderSchema, StageGroupSchema, StageSchema, } from \"../enums.js\";\nimport { paginatedResultSchema } from \"../pagination.js\";\n/**\n * Action keys exposed to consumers via the generic `applyAction` endpoint.\n * Excludes server-driven entries from {@link APPLICATION_ACTIONS} (`submit`,\n * `score_written`) because those are write-only audit-log labels emitted by\n * the store's dedicated paths, not user-dispatchable actions.\n */\nexport const APPLY_ACTION_KEYS = [\n \"stage_transition\",\n \"move_to_stage\",\n \"shortlist\",\n \"move_to_interview\",\n \"make_offer\",\n \"hire\",\n \"withdraw\",\n \"disqualify\",\n \"reinstate\",\n \"rate\",\n];\nexport const ApplyActionKeySchema = v.picklist(APPLY_ACTION_KEYS);\n/**\n * Comma-separated string in query parameters; transformed into a string[]\n * for downstream use. e.g. `?stages=applied,shortlisted`.\n */\nconst CommaSeparatedStringSchema = v.pipe(v.string(), v.transform((s) => s\n .split(\",\")\n .map((t) => t.trim())\n .filter((t) => t.length > 0)));\n// Stages are free-text post-v6 — the query filter accepts whatever the\n// caller passes. Stage groups remain picklist-validated below.\nconst StagesQuerySchema = v.pipe(CommaSeparatedStringSchema, v.array(StageSchema));\nconst StageGroupsQuerySchema = v.pipe(CommaSeparatedStringSchema, v.array(StageGroupSchema));\nconst JobIdsQuerySchema = v.pipe(v.string(), v.transform((s) => s\n .split(\",\")\n .map((t) => Number(t.trim()))\n .filter((n) => Number.isInteger(n) && n > 0)));\nexport const ListApplicationsQuerySchema = v.object({\n stages: v.optional(StagesQuerySchema),\n stage_groups: v.optional(StageGroupsQuerySchema),\n job_id: v.optional(v.string()),\n job_ids: v.optional(JobIdsQuerySchema),\n candidate_id: v.optional(v.string()),\n is_disqualified: v.optional(v.picklist([\"true\", \"false\"])),\n created_from: v.optional(v.string()),\n created_to: v.optional(v.string()),\n updated_from: v.optional(v.string()),\n updated_to: v.optional(v.string()),\n entered_stage_from: v.optional(v.string()),\n entered_stage_to: v.optional(v.string()),\n from: v.optional(v.string()),\n to: v.optional(v.string()),\n q: v.optional(v.string()),\n scored: v.optional(v.picklist([\"true\", \"false\"])),\n sort: v.optional(ApplicationSortFieldSchema),\n order: v.optional(SortOrderSchema),\n page: v.optional(v.string()),\n per_page: v.optional(v.string()),\n});\n/**\n * `stage` and `stageGroup` must be supplied together, or both omitted. Only\n * studio knows which stage slug belongs in which group (the slug is free-text\n * and the platform deliberately does not carry the per-tenant mapping), so a\n * `stage` arriving without an explicit `stageGroup` cannot be classified\n * without guessing. Omitting both still works and falls back to the\n * `applied` / `APPLIED` defaults inside the store.\n */\nexport const SubmitApplicationInputSchema = v.pipe(v.object({\n candidateId: RequiredStringSchema,\n jobId: PositiveIntegerSchema,\n meta: v.nullish(UnknownRecordSchema),\n sessionId: v.nullish(v.number()),\n externalApplicationId: v.nullish(v.string()),\n context: v.nullish(UnknownRecordSchema),\n source: v.nullish(ApplicationSourceSchema),\n sourceDetail: v.nullish(v.string()),\n stage: v.nullish(StageSchema),\n stageGroup: v.nullish(StageGroupSchema),\n actor: v.nullish(ActorInputSchema),\n}), v.check((input) => (input.stage == null) === (input.stageGroup == null), \"stage and stageGroup must be supplied together\"));\nconst DuplicateApplicationSchema = v.object({\n id: v.string(),\n stageGroup: v.string(),\n createdAt: v.string(),\n});\nexport const SubmitApplicationResultSchema = v.union([\n v.object({\n ok: v.literal(true),\n duplicate: v.literal(false),\n applicationId: v.string(),\n candidateId: v.string(),\n }),\n v.object({\n ok: v.literal(true),\n duplicate: v.literal(true),\n existingApplication: DuplicateApplicationSchema,\n }),\n]);\nexport const DuplicateCheckResultSchema = v.object({\n isDuplicate: v.boolean(),\n existingApplication: v.optional(DuplicateApplicationSchema),\n});\nexport const WriteScoreInputSchema = v.object({\n applicationId: RequiredStringSchema,\n scoreType: ScoreTypeSchema,\n score: v.number(),\n reason: v.nullish(v.string()),\n categories: v.nullish(v.record(v.string(), ScoreCategorySchema)),\n scoredBy: v.nullish(v.string()),\n actor: v.nullish(ActorInputSchema),\n});\nexport const WriteScoreResponseSchema = v.object({ scoreId: v.string() });\nexport const ListApplicationsResponseSchema = paginatedResultSchema(ApplicationDetailSchema);\nexport const GetApplicationResponseSchema = ApplicationDetailSchema;\n/**\n * Single-row stage transition. The server does **not** validate the\n * `(toStage, toStageGroup)` pair against any closed map — `toStage` is\n * free-text and studio is the only system that knows whether a given slug\n * belongs to its configured group.\n */\n/**\n * Skip reasons surfaced by the dispatcher when a stage-changing action is a\n * no-op. Kept as a top-level schema because it's a primitive reused both in\n * `ApplyActionSkipReasonSchema` (which adds `already_disqualified`) and by\n * internal store types via the inferred `TransitionSkipReason` type.\n */\nconst TransitionSkipReasonSchema = v.picklist([\n \"already_in_target_stage\",\n \"not_in_source_stage\",\n \"disqualified\",\n]);\nexport const ListApplicationLogsResponseSchema = v.array(ApplicationLogSchema);\n/* ─────────────────────────────────────────────────────────────\n * Generic applyAction surface\n * ──────────────────────────────────────────────────────────── */\n/**\n * Meta schemas per action key. The generic `applyAction` HTTP body wraps one\n * of these in a discriminated union so each action's payload is validated\n * before reaching the store.\n *\n * `note` fields are optional everywhere except where the rule itself\n * requires them (e.g. `disqualify` with `reason='other'`, enforced inside\n * the registry — not duplicated here).\n */\nconst NoteMeta = v.object({\n stage: v.nullish(StageSchema),\n note: v.nullish(v.string()),\n});\nconst HireMeta = v.object({\n stage: v.nullish(StageSchema),\n startDate: v.nullish(v.string()),\n note: v.nullish(v.string()),\n});\nexport const ApplyActionInputSchema = v.variant(\"action\", [\n v.object({\n action: v.literal(\"shortlist\"),\n actor: ActorInputSchema,\n meta: v.nullish(NoteMeta),\n }),\n v.object({\n action: v.literal(\"move_to_interview\"),\n actor: ActorInputSchema,\n meta: v.nullish(NoteMeta),\n }),\n v.object({\n action: v.literal(\"make_offer\"),\n actor: ActorInputSchema,\n meta: v.nullish(NoteMeta),\n }),\n v.object({\n action: v.literal(\"hire\"),\n actor: ActorInputSchema,\n meta: v.nullish(HireMeta),\n }),\n v.object({\n action: v.literal(\"withdraw\"),\n actor: ActorInputSchema,\n meta: v.nullish(NoteMeta),\n }),\n v.object({\n action: v.literal(\"move_to_stage\"),\n actor: ActorInputSchema,\n meta: v.object({\n stage: StageSchema,\n stageGroup: StageGroupSchema,\n note: v.nullish(v.string()),\n }),\n }),\n v.object({\n action: v.literal(\"stage_transition\"),\n actor: ActorInputSchema,\n meta: v.object({\n toStage: StageSchema,\n toStageGroup: StageGroupSchema,\n note: v.nullish(v.string()),\n }),\n }),\n v.object({\n action: v.literal(\"disqualify\"),\n actor: ActorInputSchema,\n meta: v.object({\n reason: DisqualificationReasonSchema,\n note: v.nullish(v.string()),\n }),\n }),\n v.object({\n action: v.literal(\"reinstate\"),\n actor: ActorInputSchema,\n meta: v.object({\n toStage: StageSchema,\n toStageGroup: StageGroupSchema,\n note: v.nullish(v.string()),\n }),\n }),\n v.object({\n action: v.literal(\"rate\"),\n actor: ActorInputSchema,\n meta: v.object({\n rating: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(5))),\n }),\n }),\n]);\nexport const BulkApplyActionInputSchema = v.object({\n applicationIds: v.pipe(v.array(v.string()), v.minLength(1)),\n body: ApplyActionInputSchema,\n});\nconst ApplyActionSkipReasonSchema = v.picklist([\n \"already_in_target_stage\",\n \"not_in_source_stage\",\n \"disqualified\",\n \"already_disqualified\",\n]);\n/**\n * Result envelope for the generic apply-action endpoint. `updated` returns\n * the new application detail; `skipped` returns the no-op reason; `failed`\n * is reserved for bulk responses (single-row failures surface as HTTP 4xx).\n */\nexport const ApplyActionResultSchema = v.variant(\"kind\", [\n v.object({\n kind: v.literal(\"updated\"),\n action: ApplyActionKeySchema,\n application: ApplicationDetailSchema,\n }),\n v.object({\n kind: v.literal(\"skipped\"),\n action: ApplyActionKeySchema,\n applicationId: v.string(),\n reason: ApplyActionSkipReasonSchema,\n }),\n]);\nexport const BulkApplyActionResultSchema = v.object({\n updated: v.array(v.object({\n kind: v.literal(\"updated\"),\n action: ApplyActionKeySchema,\n application: ApplicationDetailSchema,\n })),\n skipped: v.array(v.object({\n kind: v.literal(\"skipped\"),\n action: ApplyActionKeySchema,\n applicationId: v.string(),\n reason: ApplyActionSkipReasonSchema,\n })),\n failed: v.array(v.object({ applicationId: v.string(), error: v.string() })),\n});\n/* ─────────────────────────────────────────────────────────────\n * Per-job application counts (jobs list page badge / column)\n * ──────────────────────────────────────────────────────────── */\nconst NonNegativeIntegerSchema = v.pipe(v.number(), v.integer(), v.minValue(0));\n/**\n * Zero-filled count for every stage group. Talent-bank always returns the\n * full shape so studio (and other consumers) never need to defensive-merge\n * against missing keys when a job has no applications in a particular group.\n */\nexport const JobApplicationCountsSchema = v.object({\n APPLIED: NonNegativeIntegerSchema,\n SHORTLISTED: NonNegativeIntegerSchema,\n INTERVIEWED: NonNegativeIntegerSchema,\n OFFERED: NonNegativeIntegerSchema,\n HIRED: NonNegativeIntegerSchema,\n REJECTED: NonNegativeIntegerSchema,\n WITHDRAWN: NonNegativeIntegerSchema,\n});\nexport const ListJobApplicationCountsQuerySchema = v.object({\n job_ids: JobIdsQuerySchema,\n});\n/**\n * Response is keyed by job-ID string. Every requested job appears in the\n * map, even when it has zero applications, so callers can safely iterate\n * over their input job list without nullable-handling.\n */\nexport const ListJobApplicationCountsResponseSchema = v.object({\n counts: v.record(v.string(), JobApplicationCountsSchema),\n});\n","import { CandidateDetailSchema } from \"../application.js\";\nimport { CandidateSchema } from \"../candidate.js\";\nimport { paginatedResultSchema } from \"../pagination.js\";\nexport const ListCandidatesResponseSchema = paginatedResultSchema(CandidateSchema);\nexport const GetCandidateResponseSchema = CandidateDetailSchema;\n","import * as v from \"valibot\";\nexport const JobMetricsResponseSchema = v.object({\n avg_score: v.nullable(v.number()),\n p90_score: v.nullable(v.number()),\n p85_score: v.nullable(v.number()),\n p80_score: v.nullable(v.number()),\n total_scores: v.number(),\n /**\n * Cumulative count of distinct applications shortlisted by our own\n * automations for this job (\"ever shortlisted by us\"), sourced from\n * `application.shortlisted` analytics events whose actor type is\n * `automation`. Append-only; does not decrease when a candidate moves out\n * of a shortlisted column. Excludes recruiter-initiated shortlists made\n * directly in the ATS (which never reach the action engine) and human\n * shortlists made in studio (actor type `user`).\n */\n total_shortlists: v.number(),\n});\n","import { DuplicateCheckResultSchema, IdentifyInputSchema, IdentifyResultSchema } from '@inploi/talent-bank/contract';\nimport * as v from 'valibot';\n\nimport { ENV_TO_TALENT_BANK_URL, InploiSdkEnvironment } from './sdk.constants';\nimport { Logger } from './sdk.logger';\n\n// `@inploi/talent-bank` is a private package: tsup bundles its schemas into the\n// npm build, but cannot inline its types into `dist/index.d.ts`, so the shapes\n// this client exposes are declared here. The call sites below (`parsed.output`\n// return values and the schema-typed `identify` body) keep them assignable to\n// the bundled contract.\ntype DuplicateCheckScope = 'job' | 'company';\n\ntype CandidateSource = 'agent' | 'sdk' | 'form' | 'integration' | 'migration';\n\nexport type TalentBankCheckDuplicateResult = {\n\tisDuplicate: boolean;\n\texistingApplication?: { id: string; stageGroup: string; createdAt: string };\n};\n\nexport type TalentBankIdentifyParams = {\n\tanonymousId: string;\n\temail: string;\n\tfirstName?: string | null;\n\tlastName?: string | null;\n\tphone?: string | null;\n\t/** Caller tag — defaults to `'sdk'`. */\n\tsource?: CandidateSource;\n};\n\nexport type TalentBankIdentifyResult = { candidateId: string; isNew: boolean };\n\nexport interface TalentBankClient {\n\tcheckDuplicate(params: {\n\t\temail: string;\n\t\tjobId?: string | number;\n\t\tscope: DuplicateCheckScope;\n\t}): Promise<TalentBankCheckDuplicateResult>;\n\n\t/**\n\t * Resolve or create a Talent Bank candidate for the supplied identifier.\n\t *\n\t * Returns `null` if the call fails — identification is best-effort and must\n\t * never break the host page.\n\t */\n\tidentify(params: TalentBankIdentifyParams): Promise<TalentBankIdentifyResult | null>;\n}\n\nexport const createTalentBankClient = ({\n\tenvironment,\n\tpublishableKey,\n\tlogger,\n}: {\n\tenvironment: InploiSdkEnvironment;\n\tpublishableKey: string;\n\tlogger: Logger;\n}): TalentBankClient => {\n\tconst baseUrl = ENV_TO_TALENT_BANK_URL[environment];\n\n\treturn {\n\t\tasync checkDuplicate(params) {\n\t\t\ttry {\n\t\t\t\tconst searchParams = new URLSearchParams({ email: params.email, scope: params.scope });\n\t\t\t\tif (params.scope === 'job' && params.jobId != null) {\n\t\t\t\t\tsearchParams.set('job_id', String(params.jobId));\n\t\t\t\t}\n\n\t\t\t\tconst response = await fetch(`${baseUrl}/applications/check-duplicate?${searchParams}`, {\n\t\t\t\t\tmethod: 'GET',\n\t\t\t\t\theaders: { Accept: 'application/json', 'x-publishable-key': publishableKey },\n\t\t\t\t});\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.error(`[TalentBankClient] checkDuplicate failed with status ${response.status}`);\n\t\t\t\t\treturn { isDuplicate: false };\n\t\t\t\t}\n\n\t\t\t\tconst json = await response.json();\n\t\t\t\tconst parsed = v.safeParse(DuplicateCheckResultSchema, json);\n\t\t\t\tif (parsed.success) {\n\t\t\t\t\treturn parsed.output;\n\t\t\t\t}\n\n\t\t\t\t// `isDuplicate` is the only field callers gate on; `existingApplication`\n\t\t\t\t// is supplementary. A schema drift in that nested payload must never\n\t\t\t\t// silently downgrade a real duplicate to a non-duplicate, so fall back\n\t\t\t\t// to the flag directly rather than failing closed.\n\t\t\t\tlogger.error('[TalentBankClient] checkDuplicate response failed strict validation; falling back to isDuplicate flag');\n\t\t\t\tif (\n\t\t\t\t\ttypeof json === 'object' &&\n\t\t\t\t\tjson != null &&\n\t\t\t\t\ttypeof (json as { isDuplicate?: unknown }).isDuplicate === 'boolean'\n\t\t\t\t) {\n\t\t\t\t\treturn { isDuplicate: (json as { isDuplicate: boolean }).isDuplicate };\n\t\t\t\t}\n\n\t\t\t\treturn { isDuplicate: false };\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error('[TalentBankClient] checkDuplicate failed:', e);\n\t\t\t\treturn { isDuplicate: false };\n\t\t\t}\n\t\t},\n\n\t\tasync identify(params) {\n\t\t\ttry {\n\t\t\t\tif (!params.anonymousId) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify skipped because anonymousId is missing');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst body: v.InferInput<typeof IdentifyInputSchema> = {\n\t\t\t\t\temail: params.email,\n\t\t\t\t\tfirstName: params.firstName,\n\t\t\t\t\tlastName: params.lastName,\n\t\t\t\t\tphone: params.phone,\n\t\t\t\t\tanonymousId: params.anonymousId,\n\t\t\t\t\tsource: params.source ?? 'sdk',\n\t\t\t\t};\n\t\t\t\tconst parsedBody = v.safeParse(IdentifyInputSchema, body);\n\t\t\t\tif (!parsedBody.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify received invalid input');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst response = await fetch(`${baseUrl}/identify`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t\tAccept: 'application/json',\n\t\t\t\t\t\t'x-publishable-key': publishableKey,\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(parsedBody.output),\n\t\t\t\t});\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.error(`[TalentBankClient] identify failed with status ${response.status}`);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\tconst parsed = v.safeParse(IdentifyResultSchema, await response.json());\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tlogger.error('[TalentBankClient] identify returned an invalid response');\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\treturn parsed.output;\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error('[TalentBankClient] identify failed:', e);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\t};\n};\n","export function ready(callback: () => void): void {\n\tif (typeof document === 'undefined') return;\n\n\tif (document.readyState === 'loading') {\n\t\tdocument.addEventListener('DOMContentLoaded', callback, { once: true });\n\t\treturn;\n\t}\n\n\tPromise.resolve().then(callback);\n}\n","import * as v from 'valibot';\n\nimport { InploiRpcClient, endpoint, typed } from './sdk.rpc';\n\nexport const JOB_ALERT_FREQUENCIES = ['DAILY', 'WEEKLY', 'MONTHLY'] as const;\n\n/** A saved search: each filter's values and, for a search around a place, the place and radius in metres\n * (the API's alert engine matches jobs within it), with the unit and place name the candidate saw. */\nconst alertFiltersSchema = v.record(\n\tv.string(),\n\tv.union([\n\t\tv.string(),\n\t\tv.array(v.string()),\n\t\tv.object({\n\t\t\ttype: v.literal('provided'),\n\t\t\tlat: v.number(),\n\t\t\tlng: v.number(),\n\t\t\tradius: v.number(),\n\t\t\tunit: v.optional(v.picklist(['miles', 'km'])),\n\t\t\tlabel: v.optional(v.string()),\n\t\t}),\n\t]),\n);\n\nexport type JobAlertsFilters = v.InferInput<typeof alertFiltersSchema>;\n\nconst closedJobEndpoint = endpoint({\n\tpathname: '/job/:id',\n\tmethod: 'GET',\n\tschema: {\n\t\tresponse: v.object({\n\t\t\tid: v.number(),\n\t\t\texternal_id: v.nullish(v.string()),\n\t\t\tcity: v.nullish(v.string()),\n\t\t\ttown: v.nullish(v.string()),\n\t\t\tcategory: v.nullish(v.string()),\n\t\t}),\n\t},\n});\n\n/** Save alerts only after the candidate opts in; a failed lookup must never widen the search. */\nexport async function saveClosedRoleJobAlerts(\n\trpcClient: InploiRpcClient,\n\t{\n\t\tcontact,\n\t\tjob,\n\t}: {\n\t\tcontact: { email: string; first_name?: string; last_name?: string };\n\t\tjob?: { id: string; id_type: 'internal' | 'external' };\n\t},\n): Promise<void> {\n\tconst filters: JobAlertsFilters = {};\n\tif (job) {\n\t\tconst found = await rpcClient.request(closedJobEndpoint, {\n\t\t\tparams: { id: job.id },\n\t\t});\n\t\t// API JobController::show treats numeric ids as internal even for ATS callers; verify the returned identity.\n\t\tconst identity = job.id_type === 'internal' ? String(found.id) : found.external_id;\n\t\tif (identity !== job.id) throw new Error('Job lookup returned a different role');\n\t\tfor (const field of ['city', 'town', 'category'] as const) {\n\t\t\tconst value = found[field]?.trim();\n\t\t\tif (value) filters[field] = [value];\n\t\t}\n\t}\n\tawait rpcClient.request(saveSearchEndpoint, { body: { contact, alerts: 'WEEKLY', filters } });\n}\n\nexport const saveSearchEndpoint = endpoint({\n\tpathname: '/search/save',\n\tmethod: 'POST',\n\tschema: {\n\t\tresponse: typed<void>(),\n\t\tbody: v.object({\n\t\t\tcontact: v.object({\n\t\t\t\temail: v.pipe(v.optional(v.string()), v.string(), v.email()),\n\t\t\t\tfirst_name: v.optional(v.string()),\n\t\t\t\tlast_name: v.optional(v.string()),\n\t\t\t}),\n\t\t\talerts: v.pipe(v.optional(v.string()), v.string(), v.picklist(JOB_ALERT_FREQUENCIES)),\n\t\t\tfilters: alertFiltersSchema,\n\t\t}),\n\t},\n});\n","import * as v from 'valibot';\n\nimport { InploiRpcClient, endpoint, typed } from './sdk.rpc';\n\n/** The countries the company's live jobs give, as their feeds spell them. */\nexport const getJobCountries = async (rpcClient: InploiRpcClient) => {\n\tconst jobCountriesEndpoint = endpoint({\n\t\tmethod: 'GET',\n\t\tpathname: '/search/filters',\n\t\tschema: {\n\t\t\tresponse: v.pipe(\n\t\t\t\tv.object({ country: v.optional(v.array(v.object({ value: v.string() })), []) }),\n\t\t\t\tv.transform(({ country }) => country.map(({ value }) => value)),\n\t\t\t),\n\t\t\tsearchParams: typed<{ filters: { country: null } }>(),\n\t\t},\n\t});\n\treturn rpcClient.request(jobCountriesEndpoint, { searchParams: { filters: { country: null } } });\n};\n\n/** Per widget/SDK client, including pending and failed reads. Never shared across tenants or environments. */\nconst addressCountries = new WeakMap<InploiRpcClient, string | undefined>();\n\n/**\n * Starts one background read and returns only countries already available. A slow, empty or failed read must\n * never delay or fail an address lookup: it keeps today's unfiltered suggestions, including on immediate Enter.\n */\nexport const addressSearchCountry = (rpcClient: InploiRpcClient): string | undefined => {\n\tif (!addressCountries.has(rpcClient)) {\n\t\taddressCountries.set(rpcClient, undefined);\n\t\tvoid getJobCountries(rpcClient)\n\t\t\t.then(async countries => {\n\t\t\t\tconst { jobCountryCodes } = await import('./sdk.country-codes');\n\t\t\t\t// Every hiring country is kept: Search Box documents a comma-separated ISO2 list with no count limit,\n\t\t\t\t// and dropping one would hide its addresses whenever the others return any suggestion.\n\t\t\t\t// https://docs.mapbox.com/api/search/search-box/#get-suggested-results\n\t\t\t\taddressCountries.set(rpcClient, jobCountryCodes(countries).join(',') || undefined);\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\t// Failed country metadata is optional; keep unfiltered lookup and do not retry on every keystroke.\n\t\t\t});\n\t}\n\treturn addressCountries.get(rpcClient);\n};\n\ntype AddressSuggestion = {\n\tmapbox_id?: string;\n\tfull_address?: string;\n\tname?: string;\n\tplace_formatted?: string;\n};\n\n/** Alternate hiring-country and worldwide picks, skipping duplicates, within the existing five-result list. */\nexport const blendAddressSuggestions = <T extends AddressSuggestion>(filtered: T[], unfiltered: T[]): T[] => {\n\tconst seen = new Set<string>();\n\tconst suggestions: T[] = [];\n\tfor (let i = 0; i < Math.max(filtered.length, unfiltered.length); i++) {\n\t\tfor (const item of [filtered[i], unfiltered[i]]) {\n\t\t\tif (!item) continue;\n\t\t\tconst key = item.mapbox_id || item.full_address || [item.name, item.place_formatted].filter(Boolean).join(', ');\n\t\t\tif (seen.has(key)) continue;\n\t\t\tseen.add(key);\n\t\t\tsuggestions.push(item);\n\t\t\tif (suggestions.length === 5) return suggestions;\n\t\t}\n\t}\n\treturn suggestions;\n};\n\nconst ADDRESS_SUGGESTION_GRACE_MS = 600;\n\n/** Both lookups share the caller's session token and signal; a non-empty list waits briefly for its partner. */\nexport const searchAddressSuggestions = async <T extends AddressSuggestion>(\n\tlookup: (country?: string) => Promise<T[]>,\n\tcountry: string | undefined,\n\tsignal?: AbortSignal,\n): Promise<T[]> => {\n\tsignal?.throwIfAborted();\n\tif (!country) {\n\t\tconst items = await lookup();\n\t\tsignal?.throwIfAborted();\n\t\treturn items;\n\t}\n\treturn new Promise<T[]>((resolve, reject) => {\n\t\tlet filtered: PromiseSettledResult<T[]> | undefined;\n\t\tlet unfiltered: PromiseSettledResult<T[]> | undefined;\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tlet finished = false;\n\t\tconst cleanup = () => {\n\t\t\tfinished = true;\n\t\t\tclearTimeout(timer);\n\t\t\tsignal?.removeEventListener('abort', abort);\n\t\t};\n\t\tconst abort = () => {\n\t\t\tcleanup();\n\t\t\treject(signal?.reason);\n\t\t};\n\t\tconst finish = () => {\n\t\t\tcleanup();\n\t\t\tif (filtered?.status === 'fulfilled' && unfiltered?.status === 'fulfilled') {\n\t\t\t\tresolve(blendAddressSuggestions(filtered.value, unfiltered.value));\n\t\t\t} else if (filtered?.status === 'fulfilled') resolve(filtered.value);\n\t\t\telse if (unfiltered?.status === 'fulfilled') resolve(unfiltered.value);\n\t\t\telse if (filtered?.status === 'rejected') reject(filtered.reason);\n\t\t};\n\t\tconst arrived = (isFiltered: boolean, result: PromiseSettledResult<T[]>) => {\n\t\t\tif (finished) return;\n\t\t\tif (isFiltered) filtered = result;\n\t\t\telse unfiltered = result;\n\t\t\tif (filtered && unfiltered) finish();\n\t\t\telse if (result.status === 'fulfilled' && result.value.length > 0)\n\t\t\t\ttimer = setTimeout(finish, ADDRESS_SUGGESTION_GRACE_MS);\n\t\t};\n\t\tsignal?.addEventListener('abort', abort, { once: true });\n\t\tfor (const isFiltered of [true, false]) {\n\t\t\tlookup(isFiltered ? country : undefined).then(\n\t\t\t\tvalue => arrived(isFiltered, { status: 'fulfilled', value }),\n\t\t\t\t(reason: unknown) => arrived(isFiltered, { status: 'rejected', reason }),\n\t\t\t);\n\t\t}\n\t});\n};\n"],"mappings":"0CAAO,IAAMA,EAAiB,iBACjBC,EAAgB,qCAUhBC,GAA8B,CAC1C,KAAM,IAAIC,IAAS,QAAQ,KAAKH,EAAgBC,EAAe,GAAGE,CAAI,EACtE,MAAO,IAAIA,IAAS,QAAQ,MAAMH,EAAgBC,EAAe,GAAGE,CAAI,EACxE,KAAM,IAAIA,IAAS,QAAQ,KAAKH,EAAgBC,EAAe,GAAGE,CAAI,EACtE,IAAK,IAAIA,IAAS,QAAQ,IAAIH,EAAgBC,EAAe,GAAGE,CAAI,CACrE,EAEaC,GAAoB,CAAE,KAAM,IAAG,GAAW,MAAO,IAAG,GAAW,IAAK,IAAG,GAAW,KAAM,IAAG,EAAU,ECW3G,IAAMC,GAA2CC,GAAgBA,ECzBjE,SAASC,GAAUC,EAAgBC,EAAqC,CAC9E,GAAI,CAAAD,EAIJ,MAAM,IAAI,MAAMC,CAAO,CACxB,CA2BO,SAASC,EAA+BC,EAAcC,EAAqC,CACjG,OAAOA,KAAQD,CAChB,CE9BA,IAAME,GAAoB,IAAI,KAAK,mBAAmB,OAAW,CAAE,QAAS,MAAO,CAAC,EIN7E,IAAMC,GAAyB,kBACzBC,GAAsB,+BAEtBC,EAAN,cAA8B,KAAM,CAE1C,YAAYC,EAAkBC,EAAiB,CAC9C,MAAMD,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GACTC,EAAU,IAAM,CACrBD,EAAW,GACX,aAAaD,CAAK,EAClBJ,GAAQ,oBAAoB,QAASO,CAAK,CAC3C,EACMA,EAAQ,IAAM,CACnBD,EAAQ,EACRH,EAAOH,GAAQ,MAAM,CACtB,EACMQ,EAAS,IAAM,CACpBF,EAAQ,EACJhB,GAAU,SAAW,aAAeC,GAAY,SAAW,YAC9DW,EAAQb,GAAwBC,EAAS,MAAOC,EAAW,KAAK,CAAC,EACvDD,GAAU,SAAW,YAAaY,EAAQZ,EAAS,KAAK,EAC1DC,GAAY,SAAW,YAAaW,EAAQX,EAAW,KAAK,EAC5DD,GAAU,SAAW,YAAYa,EAAOb,EAAS,MAAM,CACjE,EACMmB,GAAU,CAACC,EAAqBC,IAAsC,CACvEN,IACAK,EAAYpB,EAAWqB,EACtBpB,EAAaoB,EACdrB,GAAYC,EAAYiB,EAAO,EAC1BG,EAAO,SAAW,aAAeA,EAAO,MAAM,OAAS,IAC/DP,EAAQ,WAAWI,EAAQX,EAA2B,GACxD,EACAG,GAAQ,iBAAiB,QAASO,EAAO,CAAE,KAAM,EAAK,CAAC,EACvD,QAAWG,IAAc,CAAC,GAAM,EAAK,EACpCX,EAAOW,EAAa5B,EAAU,MAAS,EAAE,KACxCC,GAAS0B,GAAQC,EAAY,CAAE,OAAQ,YAAa,MAAA3B,CAAM,CAAC,EAC1D6B,GAAoBH,GAAQC,EAAY,CAAE,OAAQ,WAAY,OAAAE,CAAO,CAAC,CACxE,CAEF,CAAC,CACF","names":["CONSOLE_PREFIX","CONSOLE_STYLE","inploiBrandedLogger","args","noLogging","createPlugin","pluginFn","invariant","condition","message","hasProp","data","prop","DEFAULT_FORMATTER","unauthenticatedMessage","unauthorisedMessage","ErrorWithStatus","message","status","NotFoundError","UnauthorisedError","SchemaValidationError","issues","source","sourceText","ApiError","data","isApiErrorWithData","error","JsonParsingError","response","parseJsonResponse","response","mediaType","JsonParsingError","ERROR_MESSAGE_KEYS","getErrorMessageFromJson","json","messages","key","hasProp","value","item","handleApiExceptions","status","message","NotFoundError","unauthenticatedMessage","UnauthorisedError","unauthorisedMessage","ApiError","createApiClient","params","defaultHeaders","pathname","options","init","SdkError","SchemaValidationError","isSdkError","error","ErrorClass","version","ENV_TO_API_URL","ENV_TO_TALENT_BANK_URL","ANALYTICS_VERSION","version","ANALYTICS_COOKIE_NAME","ANALYTICS_CANDIDATE_ID_STORAGE_KEY","CONSENT_STORAGE_KEY_PREFIX","memory","safeSessionStorage","key","value","generateUUID","c","ANONYMOUS_ID_TTL_MS","formatCookie","value","now","ANALYTICS_COOKIE_NAME","getSessionId","searchParams","isServer","fromSearchParams","fromSessionStorage","safeSessionStorage","getStoredCandidateId","stored","ANALYTICS_CANDIDATE_ID_STORAGE_KEY","cookieRegex","getCookieId","request","cookie","getStoredFallbackId","getBrowserStoredId","framedCookieAttributes","persistAnonymousId","id","getSessionInfo","href","getOrCreateAnonymousId","existing","newId","generateUUID","beforeWrite","getSessionInfoFromResponse","response","serverReferrer","referrer","analyticsLogEndpoint","typed","createAnalyticsService","rpcClient","logger","onEvent","persistence","siteKind","memorySessionId","memoryAnonymousId","sessionRequestSequence","latestSessionResponse","sessionInfo","logFn","params","page","envelope","context","ANALYTICS_VERSION","currentSession","resolvedCandidateId","payload","cookieIdBeforeRequest","requestSequence","responseJson","newSession","cookieIdNow","writtenDuringRequest","cookieIdToKeep","canAdoptResponse","e","pendingSessionLog","invariant","send","headers","stringify","parse","schema","input","source","result","SchemaValidationError","safeParse","e","InploiRpcClient","params","ENV_TO_API_URL","endpoint","options","validateIn","searchParams","body","validateEndpointInputs","url","pathname","key","value","stringify","json","parseJsonResponse","handleApiExceptions","fetchParams","response","typed","validatedInputs","initialiseSdk","publishableKey","env","logger","inploiBrandedLogger","onEvent","persistence","siteKind","apiClient","createApiClient","ENV_TO_API_URL","loggerService","noLogging","rpcClient","InploiRpcClient","analytics","createAnalyticsService","plugin","ANALYTICS_EVENTS","hashConsentConfig","config","canonical","hash","i","consentStorageKey","publishableKey","configHash","CONSENT_STORAGE_KEY_PREFIX","getConsentAcceptance","key","setConsentAcceptance","v","CANDIDATE_SOURCES","STAGE_GROUPS","SCORE_TYPES","INTERVIEW_STATUSES","DUPLICATE_CHECK_SCOPES","APPLICATION_SORT_FIELDS","SORT_ORDERS","APPLICATION_SOURCES","APPLICATION_ACTIONS","ACTOR_TYPES","CandidateSourceSchema","CANDIDATE_SOURCES","StageGroupSchema","STAGE_GROUPS","StageSchema","ScoreTypeSchema","InterviewStatusSchema","DuplicateCheckScopeSchema","ApplicationSortFieldSchema","SortOrderSchema","DisqualificationReasonSchema","ApplicationSourceSchema","ApplicationActionSchema","ActorTypeSchema","ActorInputSchema","v","PaginationSchema","paginatedResultSchema","itemSchema","v","CandidateSchema","CandidateSourceSchema","v","v","RequiredStringSchema","PositiveIntegerSchema","UnknownRecordSchema","v","InterviewSchema","InterviewStatusSchema","UnknownRecordSchema","ScoreCategorySchema","ApplicationSchema","StageSchema","StageGroupSchema","DisqualificationReasonSchema","ApplicationSourceSchema","UnknownRecordSchema","ApplicationScoreSchema","ScoreTypeSchema","ApplicationDetailSchema","CandidateSchema","InterviewSchema","CandidateDetailSchema","ApplicationLogSchema","ApplicationActionSchema","ActorTypeSchema","v","IdentifyInputSchema","RequiredStringSchema","CandidateSourceSchema","IdentifyResultSchema","v","APPLY_ACTION_KEYS","ApplyActionKeySchema","CommaSeparatedStringSchema","s","t","StagesQuerySchema","StageSchema","StageGroupsQuerySchema","StageGroupSchema","JobIdsQuerySchema","ListApplicationsQuerySchema","ApplicationSortFieldSchema","SortOrderSchema","SubmitApplicationInputSchema","RequiredStringSchema","PositiveIntegerSchema","UnknownRecordSchema","ApplicationSourceSchema","ActorInputSchema","input","DuplicateApplicationSchema","SubmitApplicationResultSchema","DuplicateCheckResultSchema","WriteScoreInputSchema","ScoreTypeSchema","ScoreCategorySchema","WriteScoreResponseSchema","ListApplicationsResponseSchema","paginatedResultSchema","ApplicationDetailSchema","TransitionSkipReasonSchema","ListApplicationLogsResponseSchema","ApplicationLogSchema","NoteMeta","StageSchema","HireMeta","ApplyActionInputSchema","ActorInputSchema","StageGroupSchema","DisqualificationReasonSchema","BulkApplyActionInputSchema","ApplyActionSkipReasonSchema","ApplyActionResultSchema","ApplyActionKeySchema","ApplicationDetailSchema","BulkApplyActionResultSchema","NonNegativeIntegerSchema","JobApplicationCountsSchema","ListJobApplicationCountsQuerySchema","JobIdsQuerySchema","ListJobApplicationCountsResponseSchema","ListCandidatesResponseSchema","paginatedResultSchema","CandidateSchema","v","JobMetricsResponseSchema","v","createTalentBankClient","environment","publishableKey","logger","baseUrl","ENV_TO_TALENT_BANK_URL","params","searchParams","response","json","parsed","DuplicateCheckResultSchema","e","body","parsedBody","IdentifyInputSchema","IdentifyResultSchema","ready","callback","v","JOB_ALERT_FREQUENCIES","alertFiltersSchema","closedJobEndpoint","saveClosedRoleJobAlerts","rpcClient","contact","job","filters","found","field","value","saveSearchEndpoint","typed","v","getJobCountries","rpcClient","jobCountriesEndpoint","country","value","typed","addressCountries","addressSearchCountry","countries","jobCountryCodes","blendAddressSuggestions","filtered","unfiltered","seen","suggestions","i","item","key","ADDRESS_SUGGESTION_GRACE_MS","searchAddressSuggestions","lookup","signal","items","resolve","reject","timer","finished","cleanup","abort","finish","arrived","isFiltered","result","reason"]}
|