@inploi/sdk 2.9.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -12,61 +12,6 @@ type Logger = {
12
12
  declare const inploiBrandedLogger: Logger;
13
13
  declare const noLogging: Logger;
14
14
 
15
- /**
16
- * The environment the SDK should run in.
17
- * - `production`: data will be stored and displayed on dashboards
18
- * - `sandbox`: data will be stored temporarily and purged periodically
19
- */
20
- type InploiSdkEnvironment = 'production' | 'sandbox';
21
-
22
- type DuplicateCheckScope = 'job' | 'company';
23
- type CandidateSource = 'agent' | 'sdk' | 'form' | 'integration' | 'migration';
24
- type TalentBankCheckDuplicateResult = {
25
- isDuplicate: boolean;
26
- existingApplication?: {
27
- id: string;
28
- stageGroup: string;
29
- createdAt: string;
30
- };
31
- };
32
- type TalentBankIdentifyParams = {
33
- anonymousId: string;
34
- email: string;
35
- firstName?: string | null;
36
- lastName?: string | null;
37
- phone?: string | null;
38
- /** Caller tag — defaults to `'sdk'`. */
39
- source?: CandidateSource;
40
- };
41
- type TalentBankIdentifyResult = {
42
- candidateId: string;
43
- isNew: boolean;
44
- };
45
- interface TalentBankClient {
46
- checkDuplicate(params: {
47
- email: string;
48
- jobId?: string | number;
49
- scope: DuplicateCheckScope;
50
- }): Promise<TalentBankCheckDuplicateResult>;
51
- /**
52
- * Resolve or create a Talent Bank candidate for the supplied identifier.
53
- *
54
- * This is the direct-to-Talent-Bank replacement for the old Laravel-proxied
55
- * `/log` IDENTIFY flow. The SDK calls this and then forwards the returned
56
- * `candidateId` on every subsequent analytics log so Laravel can stamp it
57
- * onto the session for attribution.
58
- *
59
- * Returns `null` if the call fails — identification is best-effort and must
60
- * never break the host page.
61
- */
62
- identify(params: TalentBankIdentifyParams): Promise<TalentBankIdentifyResult | null>;
63
- }
64
- declare const createTalentBankClient: ({ environment, publishableKey, logger, }: {
65
- environment: InploiSdkEnvironment;
66
- publishableKey: string;
67
- logger: Logger;
68
- }) => TalentBankClient;
69
-
70
15
  type FlowProperties = {
71
16
  flow_id: string;
72
17
  flow_version: number;
@@ -81,6 +26,14 @@ type JobProperties = {
81
26
  id: string;
82
27
  id_type: 'internal' | 'external';
83
28
  };
29
+ /**
30
+ * One id per navigation (a document load, an in-app route change, a restore from the back/forward cache), shared by
31
+ * that navigation's `VIEW_PAGE` or `VIEW_JOB` events, so a view counts once per navigation and a retry is recognised.
32
+ * Minted by the page (`generateUUID`).
33
+ */
34
+ type NavigationProperties = {
35
+ navigation_id?: string;
36
+ };
84
37
  type PageEngagementProperties = {
85
38
  /** Random per page view, minted by the page; not a visitor identifier. */
86
39
  view_id: string;
@@ -166,7 +119,7 @@ type AnalyticsLogParams = {
166
119
  event: 'VIEW_JOB';
167
120
  properties: {
168
121
  job: JobProperties;
169
- };
122
+ } & NavigationProperties;
170
123
  } | {
171
124
  event: 'FLOW_REDIRECT';
172
125
  properties: {
@@ -204,10 +157,15 @@ type AnalyticsLogParams = {
204
157
  outcome?: 'duplicate' | 'duplicate_after_own_attempt' | 'pending';
205
158
  } & FunnelFlowProperties;
206
159
  } | {
207
- event: 'SUBMIT_FORM' | 'VIEW_PAGE';
160
+ event: 'SUBMIT_FORM';
208
161
  properties?: {
209
162
  job: JobProperties | undefined;
210
163
  };
164
+ } | {
165
+ event: 'VIEW_PAGE';
166
+ properties?: {
167
+ job: JobProperties | undefined;
168
+ } & NavigationProperties;
211
169
  }
212
170
  /**
213
171
  * `PAGE_ENGAGEMENT`, one careers-site page view's attention summary: sent when the view is hidden or left, never
@@ -218,16 +176,6 @@ type AnalyticsLogParams = {
218
176
  | {
219
177
  event: 'PAGE_ENGAGEMENT';
220
178
  properties: PageEngagementProperties;
221
- } | {
222
- event: 'IDENTIFY';
223
- properties: {
224
- identifier: string;
225
- first_name?: string;
226
- last_name?: string;
227
- phone_number?: string;
228
- email?: string;
229
- custom_traits?: Record<string, unknown>;
230
- };
231
179
  } | {
232
180
  event: 'SEARCH_PAGINATE';
233
181
  properties: {
@@ -248,6 +196,12 @@ type AnalyticsLogParams = {
248
196
  page_size: number;
249
197
  page: number;
250
198
  };
199
+ } | {
200
+ event: 'SAVE_JOB';
201
+ properties: {
202
+ job_id: number;
203
+ saved: boolean;
204
+ };
251
205
  } | {
252
206
  event: 'SEARCH_JOB_CLICK';
253
207
  properties: {
@@ -297,6 +251,26 @@ type AnalyticsLogParams = {
297
251
  };
298
252
  };
299
253
  type AnalyticsLogEvent = AnalyticsLogParams['event'];
254
+ /**
255
+ * The catalogue: every event the SDK and its plugins send to `/log`, with what it records. Each event's fields are its
256
+ * `AnalyticsLogParams` member above; every event also carries the envelope in `AnalyticsEnvelope`. Typed against
257
+ * `AnalyticsLogEvent`, so an event cannot be added, renamed or removed without changing this list.
258
+ */
259
+ declare const ANALYTICS_EVENTS: Record<AnalyticsLogEvent, string>;
260
+ /**
261
+ * Sent in `custom_properties` with every event, beside any custom properties the caller passes. Today's api stores
262
+ * `custom_properties` as given (`session_logs.custom_properties`, capped at 1 KB), so these land there.
263
+ */
264
+ type AnalyticsEnvelope = {
265
+ /** Made once per event where it is logged, so a repeat of the same event can be recognised and counted once. */
266
+ event_id: string;
267
+ /** The analytics service's lane: `device` stores the visitor id, `none` stores nothing. */
268
+ consent_lane: 'device' | 'none';
269
+ /** 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. */
270
+ site_kind?: SiteKind;
271
+ };
272
+ type SiteKind = 'hub' | 'embedded';
273
+
300
274
  type EventPropertyMap = {
301
275
  [Param in AnalyticsLogParams as Param['event']]: Omit<Param, 'event'>;
302
276
  };
@@ -315,16 +289,15 @@ type TrackPayload<P = EventPropertyMap[keyof EventPropertyMap]['properties']> =
315
289
  anonymous_id: string | null;
316
290
  session_id: string | null;
317
291
  /**
318
- * Talent Bank candidate id — set once the SDK has identified the user
319
- * (via `TalentBankClient.identify`). Laravel's session middleware reads
320
- * this and stamps it onto `session.context.candidate_id` for attribution.
321
- * `null` for anonymous / unidentified users.
292
+ * Legacy Talent Bank candidate id read from device storage, or `null`.
293
+ * Laravel's session middleware stamps it onto `session.context.candidate_id` for attribution.
322
294
  */
323
295
  candidate_id: string | null;
324
296
  event: AnalyticsLogEvent;
325
297
  sent_at: string;
326
298
  context: AnalyticsContext;
327
299
  properties: P;
300
+ /** Always sent with the `AnalyticsEnvelope`; typed optional because hosts and tests implement `log` themselves. */
328
301
  custom_properties?: Record<string, unknown>;
329
302
  };
330
303
  type LogFnParams<T extends keyof EventPropertyMap> = {
@@ -341,6 +314,13 @@ type AnalyticsService = {
341
314
  /** From a log payload data, generate headers to use in server environments to update the anonymous_id */
342
315
  getHeaders: (payload?: TrackPayload) => Headers;
343
316
  getSessionInfo: typeof getSessionInfo;
317
+ /**
318
+ * The visitor id for agent conversations. With device persistence it is `getOrCreateAnonymousId`'s stored id; with
319
+ * none it lives in this instance only, so a visitor who refused storage keeps one id for the page and nothing is stored.
320
+ * Optional: plugins run beside the host's own SDK, and a host before 2.10 hands analytics without it. Plugins call
321
+ * `analytics.getOrCreateAnonymousId?.() ?? getOrCreateAnonymousId()`, so such a host keeps the stored id until it updates.
322
+ */
323
+ getOrCreateAnonymousId?: () => string;
344
324
  };
345
325
  declare const getSessionInfo: (request?: Request) => {
346
326
  anonymous_id: string | null;
@@ -403,6 +383,13 @@ declare const SdkError: {
403
383
  };
404
384
  declare function isSdkError(error: unknown): error is (typeof SdkError)[keyof typeof SdkError];
405
385
 
386
+ /**
387
+ * The environment the SDK should run in.
388
+ * - `production`: data will be stored and displayed on dashboards
389
+ * - `sandbox`: data will be stored temporarily and purged periodically
390
+ */
391
+ type InploiSdkEnvironment = 'production' | 'sandbox';
392
+
406
393
  type RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
407
394
  /** Extract parameter names from a pathname string */
408
395
  type ExtractParamNames<T extends string> = T extends `${infer _Before}:${infer Param}/${infer After}` ? Param | ExtractParamNames<`/${After}`> : T extends `${infer _Before}:${infer Param}` ? Param : never;
@@ -576,8 +563,10 @@ type InitialiseInploiSdkParams = {
576
563
  onEvent?: AnalyticsOnEventCallback;
577
564
  /** Analytics identity storage. `none` keeps only an API session in memory; defaults to `device`. */
578
565
  persistence?: 'device' | 'none';
566
+ /** 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`). */
567
+ siteKind?: SiteKind;
579
568
  };
580
- declare function initialiseSdk({ publishableKey, env, logger, onEvent, persistence, }: InitialiseInploiSdkParams): {
569
+ declare function initialiseSdk({ publishableKey, env, logger, onEvent, persistence, siteKind, }: InitialiseInploiSdkParams): {
581
570
  register: <P extends InploiSdkPlugin>(plugin: P) => ReturnType<P>;
582
571
  analytics: AnalyticsService;
583
572
  apiClient: ApiClient;
@@ -642,6 +631,49 @@ declare function getConsentAcceptance(publishableKey: string, config: ConsentCon
642
631
  */
643
632
  declare function setConsentAcceptance(publishableKey: string, config: ConsentConfig): void;
644
633
 
634
+ type DuplicateCheckScope = 'job' | 'company';
635
+ type CandidateSource = 'agent' | 'sdk' | 'form' | 'integration' | 'migration';
636
+ type TalentBankCheckDuplicateResult = {
637
+ isDuplicate: boolean;
638
+ existingApplication?: {
639
+ id: string;
640
+ stageGroup: string;
641
+ createdAt: string;
642
+ };
643
+ };
644
+ type TalentBankIdentifyParams = {
645
+ anonymousId: string;
646
+ email: string;
647
+ firstName?: string | null;
648
+ lastName?: string | null;
649
+ phone?: string | null;
650
+ /** Caller tag — defaults to `'sdk'`. */
651
+ source?: CandidateSource;
652
+ };
653
+ type TalentBankIdentifyResult = {
654
+ candidateId: string;
655
+ isNew: boolean;
656
+ };
657
+ interface TalentBankClient {
658
+ checkDuplicate(params: {
659
+ email: string;
660
+ jobId?: string | number;
661
+ scope: DuplicateCheckScope;
662
+ }): Promise<TalentBankCheckDuplicateResult>;
663
+ /**
664
+ * Resolve or create a Talent Bank candidate for the supplied identifier.
665
+ *
666
+ * Returns `null` if the call fails — identification is best-effort and must
667
+ * never break the host page.
668
+ */
669
+ identify(params: TalentBankIdentifyParams): Promise<TalentBankIdentifyResult | null>;
670
+ }
671
+ declare const createTalentBankClient: ({ environment, publishableKey, logger, }: {
672
+ environment: InploiSdkEnvironment;
673
+ publishableKey: string;
674
+ logger: Logger;
675
+ }) => TalentBankClient;
676
+
645
677
  /**
646
678
  * Generates a RFC 4122 v4 UUID.
647
679
  *
@@ -722,4 +754,4 @@ declare const searchAddressSuggestions: <T extends AddressSuggestion>(lookup: (c
722
754
  */
723
755
  declare const jobCountryCodes: (jobCountries: string[]) => string[];
724
756
 
725
- export { AnalyticsLogEvent, AnalyticsLogParams, AnalyticsOnEventCallback, AnalyticsService, ApiClient, ApiError, ConsentConfig, FlowPathProperties, FlowPathStep, FlowPathTrigger, FlowType, InitialiseInploiSdkParams, InploiRpcClient, InploiSdk, InploiSdkEnvironment, InploiSdkPlugin, JOB_ALERT_FREQUENCIES, JobAlertsFilters, Logger, NotFoundError, PageEngagementProperties, JsonParsingError as ParsingError, PluginParams, RpcEndpoint, SchemaValidationError, SdkError, TalentBankCheckDuplicateResult, TalentBankClient, TalentBankIdentifyParams, TalentBankIdentifyResult, UnauthorisedError, addressSearchCountry, blendAddressSuggestions, consentStorageKey, createPlugin, createTalentBankClient, endpoint, generateUUID, getConsentAcceptance, getJobCountries, getOrCreateAnonymousId, hashConsentConfig, initialiseSdk, inploiBrandedLogger, isApiErrorWithData, isSdkError, jobCountryCodes, noLogging, ready, saveClosedRoleJobAlerts, saveSearchEndpoint, searchAddressSuggestions, setConsentAcceptance, typed, validateEndpointInputs };
757
+ export { ANALYTICS_EVENTS, AnalyticsEnvelope, AnalyticsLogEvent, AnalyticsLogParams, AnalyticsOnEventCallback, AnalyticsService, ApiClient, ApiError, ConsentConfig, FlowPathProperties, FlowPathStep, FlowPathTrigger, FlowType, InitialiseInploiSdkParams, InploiRpcClient, InploiSdk, InploiSdkEnvironment, InploiSdkPlugin, JOB_ALERT_FREQUENCIES, JobAlertsFilters, Logger, NotFoundError, PageEngagementProperties, JsonParsingError as ParsingError, PluginParams, RpcEndpoint, SchemaValidationError, SdkError, SiteKind, TalentBankCheckDuplicateResult, TalentBankClient, TalentBankIdentifyParams, TalentBankIdentifyResult, UnauthorisedError, addressSearchCountry, blendAddressSuggestions, consentStorageKey, createPlugin, createTalentBankClient, endpoint, generateUUID, getConsentAcceptance, getJobCountries, getOrCreateAnonymousId, hashConsentConfig, initialiseSdk, inploiBrandedLogger, isApiErrorWithData, isSdkError, jobCountryCodes, noLogging, ready, saveClosedRoleJobAlerts, saveSearchEndpoint, searchAddressSuggestions, setConsentAcceptance, typed, validateEndpointInputs };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Rt=Object.create;var X=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var Lt=Object.getOwnPropertyNames;var Dt=Object.getPrototypeOf,Ot=Object.prototype.hasOwnProperty;var Nt=(t,n)=>()=>(t&&(n=t(t=0)),n);var Ue=(t,n)=>{for(var r in n)X(t,r,{get:n[r],enumerable:!0})},Me=(t,n,r,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let a of Lt(n))!Ot.call(t,a)&&a!==r&&X(t,a,{get:()=>n[a],enumerable:!(o=Ct(n,a))||o.enumerable});return t};var w=(t,n,r)=>(r=t!=null?Rt(Dt(t)):{},Me(n||!t||!t.__esModule?X(r,"default",{value:t,enumerable:!0}):r,t)),jt=t=>Me(X({},"__esModule",{value:!0}),t);var kt={};Ue(kt,{jobCountryCodes:()=>De});var wt,bn,M,Sn,_n,De,Oe=Nt(()=>{"use strict";wt={uk:"gb","great britain":"gb",england:"gb",scotland:"gb",wales:"gb","northern ireland":"gb",lincolnshire:"gb",surrey:"gb","republic of ireland":"ie",eire:"ie","hong kong sar":"hk","united states of america":"us",turkey:"tr","czech republic":"cz",burma:"mm",kosovo:"xk",xk:"xk"},bn=`adand aeare afafg agatg aiaia alalb amarm aoago aqata ararg asasm ataut auaus awabw axala azaze babih bbbrb bdbgd bebel
1
+ "use strict";var Ct=Object.create;var X=Object.defineProperty;var Lt=Object.getOwnPropertyDescriptor;var Ot=Object.getOwnPropertyNames;var Dt=Object.getPrototypeOf,Nt=Object.prototype.hasOwnProperty;var jt=(t,n)=>()=>(t&&(n=t(t=0)),n);var Fe=(t,n)=>{for(var r in n)X(t,r,{get:n[r],enumerable:!0})},Be=(t,n,r,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let c of Ot(n))!Nt.call(t,c)&&c!==r&&X(t,c,{get:()=>n[c],enumerable:!(o=Lt(n,c))||o.enumerable});return t};var A=(t,n,r)=>(r=t!=null?Ct(Dt(t)):{},Be(n||!t||!t.__esModule?X(r,"default",{value:t,enumerable:!0}):r,t)),Ft=t=>Be(X({},"__esModule",{value:!0}),t);var xt={};Fe(xt,{jobCountryCodes:()=>Ce});var Et,bn,q,Sn,_n,Ce,Le=jt(()=>{"use strict";Et={uk:"gb","great britain":"gb",england:"gb",scotland:"gb",wales:"gb","northern ireland":"gb",lincolnshire:"gb",surrey:"gb","republic of ireland":"ie",eire:"ie","hong kong sar":"hk","united states of america":"us",turkey:"tr","czech republic":"cz",burma:"mm",kosovo:"xk",xk:"xk"},bn=`adand aeare afafg agatg aiaia alalb amarm aoago aqata ararg asasm ataut auaus awabw axala azaze babih bbbrb bdbgd bebel
2
2
  bfbfa bgbgr bhbhr bibdi bjben blblm bmbmu bnbrn bobol bqbes brbra bsbhs btbtn bvbvt bwbwa byblr bzblz cacan cccck cdcod
3
3
  cfcaf cgcog chche ciciv ckcok clchl cmcmr cnchn cocol crcri cucub cvcpv cwcuw cxcxr cycyp czcze dedeu djdji dkdnk dmdma
4
4
  dodom dzdza ececu eeest egegy ehesh ereri esesp eteth fifin fjfji fkflk fmfsm fofro frfra gagab gbgbr gdgrd gegeo gfguf
@@ -10,5 +10,5 @@ ncncl nener nfnfk ngnga ninic nlnld nonor npnpl nrnru nuniu nznzl omomn papan pe
10
10
  pnpcn prpri pspse ptprt pwplw pypry qaqat rereu rorou rssrb rurus rwrwa sasau sbslb scsyc sdsdn seswe sgsgp shshn sisvn
11
11
  sjsjm sksvk slsle smsmr snsen sosom srsur ssssd ststp svslv sxsxm sysyr szswz tctca tdtcd tfatf tgtgo ththa tjtjk tktkl
12
12
  tltls tmtkm tntun toton trtur tttto tvtuv twtwn tztza uaukr uguga umumi ususa uyury uzuzb vavat vcvct veven vgvgb vivir
13
- vnvnm vuvut wfwlf wswsm yeyem ytmyt zazaf zmzmb zwzwe`,Sn=()=>{if(M)return M;M=new Map;let t=new Intl.DisplayNames(["en"],{type:"region",fallback:"none"});for(let n of bn.split(/\s+/)){let r=n.slice(0,2),o=t.of(r.toUpperCase());o&&M.set(o.toLowerCase(),r),M.set(r,r),M.set(n.slice(2),r)}return M},_n=t=>{let n=t.trim().toLowerCase();if(Object.prototype.hasOwnProperty.call(wt,n))return wt[n];let r=/^[a-z]{2}-[a-z0-9]{1,3}$/.test(n)?n.slice(0,2):n;return Sn().get(r)},De=t=>[...new Set(t.flatMap(r=>_n(r)??[]))].sort()});var xn={};Ue(xn,{ApiError:()=>B,InploiRpcClient:()=>$,JOB_ALERT_FREQUENCIES:()=>Ce,NotFoundError:()=>j,ParsingError:()=>q,SchemaValidationError:()=>P,SdkError:()=>ke,UnauthorisedError:()=>F,addressSearchCountry:()=>Et,blendAddressSuggestions:()=>je,consentStorageKey:()=>fe,createPlugin:()=>Ge,createTalentBankClient:()=>ge,endpoint:()=>Y,generateUUID:()=>W,getConsentAcceptance:()=>St,getJobCountries:()=>Ne,getOrCreateAnonymousId:()=>Ie,hashConsentConfig:()=>ve,initialiseSdk:()=>bt,inploiBrandedLogger:()=>ne,isApiErrorWithData:()=>Ve,isSdkError:()=>ze,jobCountryCodes:()=>De,noLogging:()=>re,ready:()=>Tt,saveClosedRoleJobAlerts:()=>xt,saveSearchEndpoint:()=>Le,searchAddressSuggestions:()=>It,setConsentAcceptance:()=>_t,typed:()=>D,validateEndpointInputs:()=>Pe});module.exports=jt(xn);var ee="%c[inploi SDK]",te="color: #65BC67; font-weight: bold;",ne={warn:(...t)=>console.warn(ee,te,...t),error:(...t)=>console.error(ee,te,...t),info:(...t)=>console.info(ee,te,...t),log:(...t)=>console.log(ee,te,...t)},re={info:()=>{},error:()=>{},log:()=>{},warn:()=>{}};var Ge=t=>t;function Te(t,n){if(!t)throw new Error(n)}function V(t,n){return n in t}var Dn=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});var Ft="Unauthenticated",Bt="This action is unauthorized.",N=class extends Error{constructor(r,o){super(r);this.status=o,this.name="ErrorWithStatus"}},j=class extends N{constructor(n){super(n??"Not found"),this.name="NotFoundError",this.status=404}},F=class extends N{constructor(n,r){super(n??"You are not authorised to perform this action."),this.name="UnauthorisedError",this.status=r??401}},P=class extends N{constructor(r,o){let a=o?` in ${o}`:"";super(`Schema validation failed${a}`);this.issues=r;this.source=o;this.name="SchemaValidationError",this.status=400}},B=class extends N{constructor(r,o,a){super(r);this.data=a;this.name="ApiError",this.status=o??500}},Ve=t=>t instanceof B&&t.data!==void 0,q=class extends N{constructor(r){super("Error parsing response into JSON.");this.response=r;this.name="ParsingError",this.status=r&&r.status>=300?r.status:500,this.contentType=new Headers(r?.headers).get("content-type")??void 0}};async function xe(t){let r=new Headers(t.headers).get("content-type")?.replace(/;.*/,"").trim().toLowerCase();if(r&&r!=="application/json"&&!r.endsWith("+json"))throw new q(t);return t.json().catch(()=>{throw new q(t)})}var qt=["message","error","errors","exception","exceptions"];function Ut(t){let n=[];if(typeof t=="object"&&t!==null){for(let r of qt)if(V(t,r)){let o=t[r];typeof o=="string"&&n.push(o),Array.isArray(o)&&o.every(a=>typeof a=="string")&&n.push(...o)}V(t,"integration_response")&&typeof t.integration_response=="object"&&t.integration_response!==null&&V(t.integration_response,"error")&&typeof t.integration_response.error=="object"&&t.integration_response.error!==null&&V(t.integration_response.error,"message")&&typeof t.integration_response.error.message=="string"&&n.push(t.integration_response.error.message)}return n.length===0&&n.push("Unknown error"),[...new Set(n)].join(", ")}function we(t,n){if(n>=300){let r=Ut(t);throw n===404?new j(r):r===Ft?new F("You are not authenticated.",n):r===Bt?new F(r,n):new B(r,n,t)}}var $e=t=>{let n={Accept:"application/json","Content-Type":"application/json","x-publishable-key":t.publishableKey};return{fetch:async(r,o={})=>{let a={...o,headers:{...o.headers,...n}},l=await fetch(`${t.baseUrl}${r}`,a);if(l.status===404)throw new j;let d=await xe(l);return we(d,l.status),d}}},ke={NotFound:j,Unauthorised:F,SchemaValidation:P,Api:B,JsonParsing:q};function ze(t){return Object.values(ke).some(n=>t instanceof n)}var Je="2.9.1";var oe={sandbox:"https://api.staging.inploi.com",production:"https://api.inploi.com",_internal_local:"http://api.test"},He={sandbox:"https://talent-bank.staging.inploi.com",production:"https://talent-bank.inploi.com",_internal_local:"http://localhost:8787"},We=Je;var L="isdk_session",ie=`${L}-candidate_id`,Ke=`${L}-consent`;var W=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+t/4).toString(16));var Qe=7*24*60*60*1e3,Ze=t=>{let n=new Date;return n.setTime(n.getTime()+Qe),`${L}=${t};expires=${n.toUTCString()};path=/`},Gt=(t,n)=>{let r=t.get("session_id");if(n||r)return r;let o=sessionStorage.getItem(`${L}-session_id`);return typeof o=="string"?o:null},Vt=()=>{if(typeof window>"u")return null;try{let t=window.localStorage.getItem(ie);return typeof t=="string"&&t!==""?t:null}catch{return null}},$t=t=>{if(!(typeof window>"u"))try{t?window.localStorage.setItem(ie,t):window.localStorage.removeItem(ie)}catch{}},zt=new RegExp(`(?:^|;\\s*)${L}=([^;]+)`),K=t=>{let n=t?t.headers.get("cookie"):document.cookie;return n?zt.exec(n)?.[1]??null:null},Xe=()=>{try{let t=JSON.parse(window.localStorage.getItem(L)??"null");return typeof t!="object"||t===null||!("id"in t)||!("expires"in t)||typeof t.id!="string"||typeof t.expires!="number"?null:t.id!==""&&t.expires>Date.now()?t.id:null}catch{return null}},Ye=()=>K()??(new URL(location.href).searchParams.get("anonymous_id")?null:Xe()),Jt=()=>location.protocol==="https:"&&window.self!==window.top?";SameSite=None;Secure;Partitioned":"",et=t=>{if(document.cookie=Ze(t)+Jt(),K()!==t)try{window.localStorage.setItem(L,JSON.stringify({id:t,expires:Date.now()+Qe}))}catch{}},Ee=t=>{let n=t?t.url:location.href,{searchParams:r}=new URL(n);return{anonymous_id:t?K(t)??r.get("anonymous_id"):K()??r.get("anonymous_id")??Xe(),session_id:Gt(r,typeof window>"u")}},Ie=()=>{if(typeof window>"u")throw new Error("getOrCreateAnonymousId() can only be called in browser environment");let t=Ee().anonymous_id;if(t)return t;let n=W(),r=Ee().anonymous_id;return r||(et(n),n)},Ht=t=>typeof t!="object"||t===null?null:{anonymous_id:"anonymous_id"in t&&typeof t.anonymous_id=="string"?t.anonymous_id:null,session_id:"session_id"in t&&typeof t.session_id=="string"?t.session_id:null},Wt=t=>t==="about:client"?"":t,Kt={pathname:"/log",method:"POST",schema:{response:D(),body:D()}},tt=({rpcClient:t,logger:n,onEvent:r,talentBank:o,persistence:a="device"})=>{let l=null,d=0,u=0,v=p=>a==="none"?{anonymous_id:null,session_id:p?null:l}:Ee(p),E=async(p,y)=>{try{let f={library:{name:"inploi-sdk",version:We},page:y},I=v(p.request);a==="device"&&p.event==="IDENTIFY"&&!I.anonymous_id&&!p.request&&typeof window<"u"&&(I={...I,anonymous_id:Ie()});let Fe=a==="none"?null:Vt();if(p.event==="IDENTIFY"&&o&&(I.anonymous_id||a==="none")){let H=p.properties,_e=await o.identify({email:H.email??H.identifier,firstName:H.first_name,lastName:H.last_name,phone:H.phone_number,anonymousId:I.anonymous_id??W(),source:"sdk"});_e?.candidateId&&a==="device"&&(Fe=_e.candidateId,$t(_e.candidateId))}let b={anonymous_id:I.anonymous_id,session_id:I.session_id,candidate_id:Fe,event:p.event,sent_at:new Date().toISOString(),context:f,properties:p.properties,custom_properties:p.customProperties},ye=a==="none"?null:p.request?K(p.request):Ye(),Be=++d,At=await t.request(Kt,{body:b,...p.keepalive&&{keepalive:!0}}),A=Ht(At);if(a==="none")return!p.request&&A?.session_id&&Be>u&&(u=Be,A.session_id!==b.session_id&&(l=A.session_id)),b.session_id=p.request?A?.session_id||null:l,r?.(b),{success:!0,data:b};let be=p.request?ye:Ye(),Pt=be!==null&&be!==ye,Se=be??ye,qe=!Pt&&(!Se||!A?.anonymous_id||Se===A.anonymous_id);return qe?(A?.anonymous_id&&(b.anonymous_id=A.anonymous_id),A?.session_id&&(b.session_id=A.session_id)):b.anonymous_id=Se,!p.request&&typeof window<"u"&&b.anonymous_id&&(qe&&b.session_id&&sessionStorage.setItem(`${L}-session_id`,b.session_id.toString()),et(b.anonymous_id)),r?.(b),{success:!0,data:b}}catch(f){return n.error("Failed to send log to API. Inspect error response of `log` for more information."),{success:!1,error:f}}},G=Promise.resolve();return{log:async p=>{Te(p.request||typeof window<"u","Cannot log on the server without a request. Please pass a request to `log`.");let y="request"in p&&p.request?{href:p.request.url,referrer:Wt(p.request.referrer),title:""}:{href:location.href,referrer:document.referrer,title:document.title};if(a==="none"&&p.event==="FLOW_NODE"&&p.properties&&"trigger"in p.properties&&(p.properties.trigger==="pagehide"||p.properties.trigger==="hidden")&&(p={...p,keepalive:!0}),a==="device"||p.request||l||p.keepalive)return E(p,y);let f=()=>E(p,y),I=G.then(f,f);return G=I,I},getHeaders:p=>{let y=new Headers;return a==="none"||!p?.anonymous_id||y.append("Set-Cookie",Ze(p.anonymous_id)),y},getSessionInfo:v}};var nt=require("neoqs");function Ae(t,n,r){let o=t["~standard"].validate(n);if(o instanceof Promise)throw new TypeError("Async schema");if(o.issues)throw new P(o.issues,r);return o.value}function Yt(t,n,r){try{return{success:!0,output:Ae(t,n,r)}}catch(o){if(o instanceof P)return{success:!1,issues:o.issues,source:o.source};throw o}}var $=class{constructor(n){if(this.baseUrl=oe[n.environment],this.headers=new Headers({"Content-Type":"application/json",Accept:"application/json"}),n.apiKey.type==="secret"){if(typeof window<"u")throw new Error("Secret key cannot be used in a browser environment");this.headers.set("x-secret-key",n.apiKey.key)}else this.headers.set("x-publishable-key",n.apiKey.key);this.logger=n.logger,this._environment=n.environment}get environment(){return this._environment}getFetchParams(n,r){let o=r.validateIn??!0,{searchParams:a,body:l}=o?Pe(n,r):r,d=new URL(this.baseUrl),u=n.pathname;if("params"in r&&r.params)for(let[v,E]of Object.entries(r.params))u=u.replace(`:${v}`,String(E));return d.pathname=u,n.schema.searchParams&&(d.search=(0,nt.stringify)(a)),[d.toString(),{method:n.method,body:l?JSON.stringify(l):void 0,headers:this.headers,signal:r.signal,...r.keepalive&&{keepalive:!0}}]}async parseResponse(n,r){let o=await xe(r.response);if(we(o,r.response.status),!(r.validateOut??!0))return o;let l=Yt(n.schema.response,o,"response");if(!l.success)throw new P(l.issues,l.source);return l.output}async request(n,r){try{let o=this.getFetchParams(n,r),a=await fetch(...o);return await this.parseResponse(n,{response:a,validateOut:r.validateOut})}catch(o){throw o instanceof P?this.logger.error(o.message,o.issues):this.logger.error(o),o}}};function D(){return{"~standard":{vendor:"inploi",version:1,validate:t=>({value:t})}}}function Y(t){return t}function Pe(t,n){let r={searchParams:void 0,body:void 0,validateIn:!1};return t.schema.searchParams&&(r.searchParams=Ae(t.schema.searchParams,"searchParams"in n?n.searchParams:{})),t.schema.body&&(r.body=Ae(t.schema.body,"body"in n?n.body:{})),r}var s=w(require("valibot"),1),Qt=["agent","sdk","form","integration","migration"],Zt=["APPLIED","SHORTLISTED","INTERVIEWED","OFFERED","HIRED","REJECTED","WITHDRAWN"];var Xt=["screening","cv_match","interview","overall"],en=["PENDING","SCHEDULED","IN_PROGRESS","COMPLETED","CANCELLED"],tn=["job","company"],nn=["created_at","updated_at"],rn=["asc","desc"],on=["careers_site","chatbot","plugin_job_search","ats_import","referral","agency","other","unknown"],sn=["submit","stage_transition","move_to_stage","shortlist","move_to_interview","make_offer","hire","withdraw","disqualify","reinstate","rate","score_written"],an=["user","system","automation","integration","candidate"],se=s.picklist(Qt),R=s.picklist(Zt),k=s.pipe(s.string(),s.trim(),s.minLength(1),s.maxLength(100)),ae=s.picklist(Xt),rt=s.picklist(en),Zn=s.picklist(tn),ot=s.picklist(nn),it=s.picklist(rn),Q=s.pipe(s.string(),s.trim(),s.minLength(1),s.maxLength(100)),ce=s.picklist(on),st=s.picklist(sn),at=s.picklist(an);var _=s.variant("type",[s.object({type:s.literal("user"),id:s.pipe(s.string(),s.minLength(1)),email:s.pipe(s.string(),s.minLength(1)),name:s.pipe(s.string(),s.minLength(1))}),s.object({type:s.literal("system"),id:s.pipe(s.string(),s.minLength(1)),name:s.optional(s.string())}),s.object({type:s.literal("automation"),id:s.pipe(s.string(),s.minLength(1)),name:s.optional(s.string())}),s.object({type:s.literal("integration"),id:s.pipe(s.string(),s.minLength(1)),name:s.optional(s.string())}),s.object({type:s.literal("candidate"),id:s.pipe(s.string(),s.minLength(1)),email:s.optional(s.string())})]);var C=w(require("valibot"),1),cn=C.object({total:C.number(),page:C.number(),perPage:C.number(),lastPage:C.number()});function le(t){return C.object({data:C.array(t),pagination:cn})}var m=w(require("valibot"),1);var Z=m.object({id:m.string(),email:m.nullable(m.string()),firstName:m.nullable(m.string()),lastName:m.nullable(m.string()),phone:m.nullable(m.string()),source:m.nullable(se),identifiedAt:m.nullable(m.string()),createdAt:m.string(),updatedAt:m.string()});var i=w(require("valibot"),1);var g=w(require("valibot"),1),z=g.pipe(g.string(),g.minLength(1)),ct=g.pipe(g.number(),g.integer(),g.minValue(1)),O=g.record(g.string(),g.unknown());var T=w(require("valibot"),1);var lt=T.object({id:T.string(),applicationId:T.string(),status:rt,scheduledAt:T.nullable(T.string()),completedAt:T.nullable(T.string()),meta:T.nullable(O),createdAt:T.string(),updatedAt:T.string()});var Re=i.object({score:i.number(),reason:i.string(),confidence:i.number()}),pt=i.object({id:i.string(),candidateId:i.string(),jobId:i.number(),stage:k,stageGroup:R,stageEnteredAt:i.string(),rating:i.nullable(i.number()),disqualifiedAt:i.nullable(i.string()),disqualificationReason:i.nullable(Q),disqualificationNote:i.nullable(i.string()),source:ce,sourceDetail:i.nullable(i.string()),sessionId:i.nullable(i.number()),externalApplicationId:i.nullable(i.string()),meta:i.nullable(O),context:i.nullable(O),scoredAt:i.nullable(i.string()),createdAt:i.string(),updatedAt:i.string()}),ln=i.object({id:i.string(),applicationId:i.string(),scoreType:ae,score:i.nullable(i.number()),reason:i.nullable(i.string()),categories:i.nullable(i.record(i.string(),Re)),scoredBy:i.nullable(i.string()),createdAt:i.string()}),pe=i.object({...pt.entries,candidate:i.nullable(Z),score:i.nullable(ln),interview:i.nullable(lt)}),pn=i.object({...Z.entries,applications:i.array(pt)}),dt=i.object({id:i.string(),applicationId:i.string(),action:st,fromStage:i.nullable(k),fromStageGroup:i.nullable(R),toStage:i.nullable(k),toStageGroup:i.nullable(R),disqualificationReason:i.nullable(Q),disqualificationNote:i.nullable(i.string()),actorId:i.nullable(i.string()),actorType:at,actorEmail:i.nullable(i.string()),actorName:i.nullable(i.string()),meta:i.nullable(O),schemaVersion:i.number(),createdAt:i.string()});var h=w(require("valibot"),1);var ut=h.object({anonymousId:z,email:z,firstName:h.nullish(h.string()),lastName:h.nullish(h.string()),phone:h.nullish(h.string()),source:h.nullish(se)}),mt=h.object({candidateId:h.string(),isNew:h.boolean()});var e=w(require("valibot"),1);var dn=["stage_transition","move_to_stage","shortlist","move_to_interview","make_offer","hire","withdraw","disqualify","reinstate","rate"],ue=e.picklist(dn),gt=e.pipe(e.string(),e.transform(t=>t.split(",").map(n=>n.trim()).filter(n=>n.length>0))),un=e.pipe(gt,e.array(k)),mn=e.pipe(gt,e.array(R)),vt=e.pipe(e.string(),e.transform(t=>t.split(",").map(n=>Number(n.trim())).filter(n=>Number.isInteger(n)&&n>0))),br=e.object({stages:e.optional(un),stage_groups:e.optional(mn),job_id:e.optional(e.string()),job_ids:e.optional(vt),candidate_id:e.optional(e.string()),is_disqualified:e.optional(e.picklist(["true","false"])),created_from:e.optional(e.string()),created_to:e.optional(e.string()),updated_from:e.optional(e.string()),updated_to:e.optional(e.string()),entered_stage_from:e.optional(e.string()),entered_stage_to:e.optional(e.string()),from:e.optional(e.string()),to:e.optional(e.string()),q:e.optional(e.string()),scored:e.optional(e.picklist(["true","false"])),sort:e.optional(ot),order:e.optional(it),page:e.optional(e.string()),per_page:e.optional(e.string())}),Sr=e.pipe(e.object({candidateId:z,jobId:ct,meta:e.nullish(O),sessionId:e.nullish(e.number()),externalApplicationId:e.nullish(e.string()),context:e.nullish(O),source:e.nullish(ce),sourceDetail:e.nullish(e.string()),stage:e.nullish(k),stageGroup:e.nullish(R),actor:e.nullish(_)}),e.check(t=>t.stage==null==(t.stageGroup==null),"stage and stageGroup must be supplied together")),ft=e.object({id:e.string(),stageGroup:e.string(),createdAt:e.string()}),_r=e.union([e.object({ok:e.literal(!0),duplicate:e.literal(!1),applicationId:e.string(),candidateId:e.string()}),e.object({ok:e.literal(!0),duplicate:e.literal(!0),existingApplication:ft})]),ht=e.object({isDuplicate:e.boolean(),existingApplication:e.optional(ft)}),Tr=e.object({applicationId:z,scoreType:ae,score:e.number(),reason:e.nullish(e.string()),categories:e.nullish(e.record(e.string(),Re)),scoredBy:e.nullish(e.string()),actor:e.nullish(_)}),xr=e.object({scoreId:e.string()}),wr=le(pe);var kr=e.picklist(["already_in_target_stage","not_in_source_stage","disqualified"]),Er=e.array(dt),de=e.object({stage:e.nullish(k),note:e.nullish(e.string())}),gn=e.object({stage:e.nullish(k),startDate:e.nullish(e.string()),note:e.nullish(e.string())}),vn=e.variant("action",[e.object({action:e.literal("shortlist"),actor:_,meta:e.nullish(de)}),e.object({action:e.literal("move_to_interview"),actor:_,meta:e.nullish(de)}),e.object({action:e.literal("make_offer"),actor:_,meta:e.nullish(de)}),e.object({action:e.literal("hire"),actor:_,meta:e.nullish(gn)}),e.object({action:e.literal("withdraw"),actor:_,meta:e.nullish(de)}),e.object({action:e.literal("move_to_stage"),actor:_,meta:e.object({stage:k,stageGroup:R,note:e.nullish(e.string())})}),e.object({action:e.literal("stage_transition"),actor:_,meta:e.object({toStage:k,toStageGroup:R,note:e.nullish(e.string())})}),e.object({action:e.literal("disqualify"),actor:_,meta:e.object({reason:Q,note:e.nullish(e.string())})}),e.object({action:e.literal("reinstate"),actor:_,meta:e.object({toStage:k,toStageGroup:R,note:e.nullish(e.string())})}),e.object({action:e.literal("rate"),actor:_,meta:e.object({rating:e.nullable(e.pipe(e.number(),e.integer(),e.minValue(1),e.maxValue(5)))})})]),Ir=e.object({applicationIds:e.pipe(e.array(e.string()),e.minLength(1)),body:vn}),yt=e.picklist(["already_in_target_stage","not_in_source_stage","disqualified","already_disqualified"]),Ar=e.variant("kind",[e.object({kind:e.literal("updated"),action:ue,application:pe}),e.object({kind:e.literal("skipped"),action:ue,applicationId:e.string(),reason:yt})]),Pr=e.object({updated:e.array(e.object({kind:e.literal("updated"),action:ue,application:pe})),skipped:e.array(e.object({kind:e.literal("skipped"),action:ue,applicationId:e.string(),reason:yt})),failed:e.array(e.object({applicationId:e.string(),error:e.string()}))}),U=e.pipe(e.number(),e.integer(),e.minValue(0)),fn=e.object({APPLIED:U,SHORTLISTED:U,INTERVIEWED:U,OFFERED:U,HIRED:U,REJECTED:U,WITHDRAWN:U}),Rr=e.object({job_ids:vt}),Cr=e.object({counts:e.record(e.string(),fn)});var jr=le(Z);var S=w(require("valibot"),1),Br=S.object({avg_score:S.nullable(S.number()),p90_score:S.nullable(S.number()),p85_score:S.nullable(S.number()),p80_score:S.nullable(S.number()),total_scores:S.number(),total_shortlists:S.number()});var me=w(require("valibot"));var ge=({environment:t,publishableKey:n,logger:r})=>{let o=He[t];return{async checkDuplicate(a){try{let l=new URLSearchParams({email:a.email,scope:a.scope});a.scope==="job"&&a.jobId!=null&&l.set("job_id",String(a.jobId));let d=await fetch(`${o}/applications/check-duplicate?${l}`,{method:"GET",headers:{Accept:"application/json","x-publishable-key":n}});if(!d.ok)return r.error(`[TalentBankClient] checkDuplicate failed with status ${d.status}`),{isDuplicate:!1};let u=await d.json(),v=me.safeParse(ht,u);return v.success?v.output:(r.error("[TalentBankClient] checkDuplicate response failed strict validation; falling back to isDuplicate flag"),typeof u=="object"&&u!=null&&typeof u.isDuplicate=="boolean"?{isDuplicate:u.isDuplicate}:{isDuplicate:!1})}catch(l){return r.error("[TalentBankClient] checkDuplicate failed:",l),{isDuplicate:!1}}},async identify(a){try{if(!a.anonymousId)return r.error("[TalentBankClient] identify skipped because anonymousId is missing"),null;let l={email:a.email,firstName:a.firstName,lastName:a.lastName,phone:a.phone,anonymousId:a.anonymousId,source:a.source??"sdk"},d=me.safeParse(ut,l);if(!d.success)return r.error("[TalentBankClient] identify received invalid input"),null;let u=await fetch(`${o}/identify`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-publishable-key":n},body:JSON.stringify(d.output)});if(!u.ok)return r.error(`[TalentBankClient] identify failed with status ${u.status}`),null;let v=me.safeParse(mt,await u.json());return v.success?v.output:(r.error("[TalentBankClient] identify returned an invalid response"),null)}catch(l){return r.error("[TalentBankClient] identify failed:",l),null}}}};function bt({publishableKey:t,env:n,logger:r=ne,onEvent:o,persistence:a}){let l=$e({baseUrl:oe[n],publishableKey:t}),d=r===!1?re:r,u=new $({environment:n,apiKey:{type:"publishable",key:t},logger:d}),v=ge({environment:n,publishableKey:t,logger:d}),E=tt({rpcClient:u,logger:d,onEvent:o,talentBank:v,persistence:a});return{register:J=>J({logger:d,apiClient:l,analytics:E,rpcClient:u,publishableKey:t,env:n}),analytics:E,apiClient:l}}function ve(t){let n=JSON.stringify({message:t.message,acceptLabel:t.acceptLabel??"",declineLabel:t.declineLabel??""}),r=5381;for(let o=0;o<n.length;o++)r=r*33^n.charCodeAt(o);return(r>>>0).toString(36)}function fe(t,n){return`${Ke}:${t}:${n}`}function St(t,n){if(typeof window>"u")return!1;try{let r=fe(t,ve(n));return window.localStorage.getItem(r)==="accepted"}catch{return!1}}function _t(t,n){if(!(typeof window>"u"))try{let r=fe(t,ve(n));window.localStorage.setItem(r,"accepted")}catch{}}function Tt(t){if(!(typeof document>"u")){if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",t,{once:!0});return}Promise.resolve().then(t)}}var c=w(require("valibot"));var Ce=["DAILY","WEEKLY","MONTHLY"],hn=c.record(c.string(),c.union([c.string(),c.array(c.string()),c.object({type:c.literal("provided"),lat:c.number(),lng:c.number(),radius:c.number(),unit:c.optional(c.picklist(["miles","km"])),label:c.optional(c.string())})])),yn={pathname:"/job/:id",method:"GET",schema:{response:c.object({id:c.number(),external_id:c.nullish(c.string()),city:c.nullish(c.string()),town:c.nullish(c.string()),category:c.nullish(c.string())})}};async function xt(t,{contact:n,job:r}){let o={};if(r){let a=await t.request(yn,{params:{id:r.id}});if((r.id_type==="internal"?String(a.id):a.external_id)!==r.id)throw new Error("Job lookup returned a different role");for(let d of["city","town","category"]){let u=a[d]?.trim();u&&(o[d]=[u])}}await t.request(Le,{body:{contact:n,alerts:"WEEKLY",filters:o}})}var Le={pathname:"/search/save",method:"POST",schema:{response:D(),body:c.object({contact:c.object({email:c.pipe(c.optional(c.string()),c.string(),c.email()),first_name:c.optional(c.string()),last_name:c.optional(c.string())}),alerts:c.pipe(c.optional(c.string()),c.string(),c.picklist(Ce)),filters:hn})}};var x=w(require("valibot"));var Ne=async t=>{let n={method:"GET",pathname:"/search/filters",schema:{response:x.pipe(x.object({country:x.optional(x.array(x.object({value:x.string()})),[])}),x.transform(({country:r})=>r.map(({value:o})=>o))),searchParams:D()}};return t.request(n,{searchParams:{filters:{country:null}}})},he=new WeakMap,Et=t=>(he.has(t)||(he.set(t,void 0),Ne(t).then(async n=>{let{jobCountryCodes:r}=await Promise.resolve().then(()=>(Oe(),kt));he.set(t,r(n).join(",")||void 0)}).catch(()=>{})),he.get(t)),je=(t,n)=>{let r=new Set,o=[];for(let a=0;a<Math.max(t.length,n.length);a++)for(let l of[t[a],n[a]]){if(!l)continue;let d=l.mapbox_id||l.full_address||[l.name,l.place_formatted].filter(Boolean).join(", ");if(!r.has(d)&&(r.add(d),o.push(l),o.length===5))return o}return o},Tn=600,It=async(t,n,r)=>{if(r?.throwIfAborted(),!n){let o=await t();return r?.throwIfAborted(),o}return new Promise((o,a)=>{let l,d,u,v=!1,E=()=>{v=!0,clearTimeout(u),r?.removeEventListener("abort",G)},G=()=>{E(),a(r?.reason)},J=()=>{E(),l?.status==="fulfilled"&&d?.status==="fulfilled"?o(je(l.value,d.value)):l?.status==="fulfilled"?o(l.value):d?.status==="fulfilled"?o(d.value):l?.status==="rejected"&&a(l.reason)},p=(y,f)=>{v||(y?l=f:d=f,l&&d?J():f.status==="fulfilled"&&f.value.length>0&&(u=setTimeout(J,Tn)))};r?.addEventListener("abort",G,{once:!0});for(let y of[!0,!1])t(y?n:void 0).then(f=>p(y,{status:"fulfilled",value:f}),f=>p(y,{status:"rejected",reason:f}))})};Oe();0&&(module.exports={ApiError,InploiRpcClient,JOB_ALERT_FREQUENCIES,NotFoundError,ParsingError,SchemaValidationError,SdkError,UnauthorisedError,addressSearchCountry,blendAddressSuggestions,consentStorageKey,createPlugin,createTalentBankClient,endpoint,generateUUID,getConsentAcceptance,getJobCountries,getOrCreateAnonymousId,hashConsentConfig,initialiseSdk,inploiBrandedLogger,isApiErrorWithData,isSdkError,jobCountryCodes,noLogging,ready,saveClosedRoleJobAlerts,saveSearchEndpoint,searchAddressSuggestions,setConsentAcceptance,typed,validateEndpointInputs});
13
+ vnvnm vuvut wfwlf wswsm yeyem ytmyt zazaf zmzmb zwzwe`,Sn=()=>{if(q)return q;q=new Map;let t=new Intl.DisplayNames(["en"],{type:"region",fallback:"none"});for(let n of bn.split(/\s+/)){let r=n.slice(0,2),o=t.of(r.toUpperCase());o&&q.set(o.toLowerCase(),r),q.set(r,r),q.set(n.slice(2),r)}return q},_n=t=>{let n=t.trim().toLowerCase();if(Object.prototype.hasOwnProperty.call(Et,n))return Et[n];let r=/^[a-z]{2}-[a-z0-9]{1,3}$/.test(n)?n.slice(0,2):n;return Sn().get(r)},Ce=t=>[...new Set(t.flatMap(r=>_n(r)??[]))].sort()});var An={};Fe(An,{ANALYTICS_EVENTS:()=>nt,ApiError:()=>F,InploiRpcClient:()=>W,JOB_ALERT_FREQUENCIES:()=>Pe,NotFoundError:()=>N,ParsingError:()=>B,SchemaValidationError:()=>k,SdkError:()=>Ae,UnauthorisedError:()=>j,addressSearchCountry:()=>wt,blendAddressSuggestions:()=>De,consentStorageKey:()=>se,createPlugin:()=>Ue,createTalentBankClient:()=>_t,endpoint:()=>H,generateUUID:()=>K,getConsentAcceptance:()=>rt,getJobCountries:()=>Oe,getOrCreateAnonymousId:()=>xe,hashConsentConfig:()=>ie,initialiseSdk:()=>tt,inploiBrandedLogger:()=>ne,isApiErrorWithData:()=>qe,isSdkError:()=>Ge,jobCountryCodes:()=>Ce,noLogging:()=>re,ready:()=>Tt,saveClosedRoleJobAlerts:()=>At,saveSearchEndpoint:()=>Re,searchAddressSuggestions:()=>kt,setConsentAcceptance:()=>ot,typed:()=>C,validateEndpointInputs:()=>ke});module.exports=Ft(An);var ee="%c[inploi SDK]",te="color: #65BC67; font-weight: bold;",ne={warn:(...t)=>console.warn(ee,te,...t),error:(...t)=>console.error(ee,te,...t),info:(...t)=>console.info(ee,te,...t),log:(...t)=>console.log(ee,te,...t)},re={info:()=>{},error:()=>{},log:()=>{},warn:()=>{}};var Ue=t=>t;function Se(t,n){if(!t)throw new Error(n)}function V(t,n){return n in t}var On=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});var Bt="Unauthenticated",Ut="This action is unauthorized.",D=class extends Error{constructor(r,o){super(r);this.status=o,this.name="ErrorWithStatus"}},N=class extends D{constructor(n){super(n??"Not found"),this.name="NotFoundError",this.status=404}},j=class extends D{constructor(n,r){super(n??"You are not authorised to perform this action."),this.name="UnauthorisedError",this.status=r??401}},k=class extends D{constructor(r,o){let c=o?` in ${o}`:"";super(`Schema validation failed${c}`);this.issues=r;this.source=o;this.name="SchemaValidationError",this.status=400}},F=class extends D{constructor(r,o,c){super(r);this.data=c;this.name="ApiError",this.status=o??500}},qe=t=>t instanceof F&&t.data!==void 0,B=class extends D{constructor(r){super("Error parsing response into JSON.");this.response=r;this.name="ParsingError",this.status=r&&r.status>=300?r.status:500,this.contentType=new Headers(r?.headers).get("content-type")??void 0}};async function _e(t){let r=new Headers(t.headers).get("content-type")?.replace(/;.*/,"").trim().toLowerCase();if(r&&r!=="application/json"&&!r.endsWith("+json"))throw new B(t);return t.json().catch(()=>{throw new B(t)})}var qt=["message","error","errors","exception","exceptions"];function Mt(t){let n=[];if(typeof t=="object"&&t!==null){for(let r of qt)if(V(t,r)){let o=t[r];typeof o=="string"&&n.push(o),Array.isArray(o)&&o.every(c=>typeof c=="string")&&n.push(...o)}V(t,"integration_response")&&typeof t.integration_response=="object"&&t.integration_response!==null&&V(t.integration_response,"error")&&typeof t.integration_response.error=="object"&&t.integration_response.error!==null&&V(t.integration_response.error,"message")&&typeof t.integration_response.error.message=="string"&&n.push(t.integration_response.error.message)}return n.length===0&&n.push("Unknown error"),[...new Set(n)].join(", ")}function Te(t,n){if(n>=300){let r=Mt(t);throw n===404?new N(r):r===Bt?new j("You are not authenticated.",n):r===Ut?new j(r,n):new F(r,n,t)}}var Me=t=>{let n={Accept:"application/json","Content-Type":"application/json","x-publishable-key":t.publishableKey};return{fetch:async(r,o={})=>{let c={...o,headers:{...o.headers,...n}},l=await fetch(`${t.baseUrl}${r}`,c);if(l.status===404)throw new N;let d=await _e(l);return Te(d,l.status),d}}},Ae={NotFound:N,Unauthorised:j,SchemaValidation:k,Api:F,JsonParsing:B};function Ge(t){return Object.values(Ae).some(n=>t instanceof n)}var Ve="3.0.0";var oe={sandbox:"https://api.staging.inploi.com",production:"https://api.inploi.com",_internal_local:"http://api.test"},Ke={sandbox:"https://talent-bank.staging.inploi.com",production:"https://talent-bank.inploi.com",_internal_local:"http://localhost:8787"},We=Ve;var R="isdk_session",$e=`${R}-candidate_id`,Je=`${R}-consent`;var K=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+t/4).toString(16));var He=7*24*60*60*1e3,Ye=t=>{let n=new Date;return n.setTime(n.getTime()+He),`${R}=${t};expires=${n.toUTCString()};path=/`},Vt=(t,n)=>{let r=t.get("session_id");if(n||r)return r;let o=sessionStorage.getItem(`${R}-session_id`);return typeof o=="string"?o:null},Kt=()=>{if(typeof window>"u")return null;try{let t=window.localStorage.getItem($e);return typeof t=="string"&&t!==""?t:null}catch{return null}},Wt=new RegExp(`(?:^|;\\s*)${R}=([^;]+)`),z=t=>{let n=t?t.headers.get("cookie"):document.cookie;return n?Wt.exec(n)?.[1]??null:null},Qe=()=>{try{let t=JSON.parse(window.localStorage.getItem(R)??"null");return typeof t!="object"||t===null||!("id"in t)||!("expires"in t)||typeof t.id!="string"||typeof t.expires!="number"?null:t.id!==""&&t.expires>Date.now()?t.id:null}catch{return null}},ze=()=>z()??(new URL(location.href).searchParams.get("anonymous_id")?null:Qe()),$t=()=>location.protocol==="https:"&&window.self!==window.top?";SameSite=None;Secure;Partitioned":"",Ze=t=>{if(document.cookie=Ye(t)+$t(),z()!==t)try{window.localStorage.setItem(R,JSON.stringify({id:t,expires:Date.now()+He}))}catch{}},Ee=t=>{let n=t?t.url:location.href,{searchParams:r}=new URL(n);return{anonymous_id:t?z(t)??r.get("anonymous_id"):z()??r.get("anonymous_id")??Qe(),session_id:Vt(r,typeof window>"u")}},xe=()=>{if(typeof window>"u")throw new Error("getOrCreateAnonymousId() can only be called in browser environment");let t=Ee().anonymous_id;if(t)return t;let n=K(),r=Ee().anonymous_id;return r||(Ze(n),n)},Jt=t=>typeof t!="object"||t===null?null:{anonymous_id:"anonymous_id"in t&&typeof t.anonymous_id=="string"?t.anonymous_id:null,session_id:"session_id"in t&&typeof t.session_id=="string"?t.session_id:null},zt=t=>t==="about:client"?"":t,Ht={pathname:"/log",method:"POST",schema:{response:C(),body:C()}},Xe=({rpcClient:t,logger:n,onEvent:r,persistence:o="device",siteKind:c})=>{let l=null,d=null,u=0,f=0,x=p=>o==="none"?{anonymous_id:null,session_id:p?null:l}:Ee(p),M=async(p,v,Z)=>{try{let G={library:{name:"inploi-sdk",version:We},page:v},J=x(p.request),It=o==="none"?null:Kt(),y={anonymous_id:J.anonymous_id,session_id:J.session_id,candidate_id:It,event:p.event,sent_at:new Date().toISOString(),context:G,properties:p.properties,custom_properties:{...p.customProperties,...Z}},he=o==="none"?null:p.request?z(p.request):ze(),Ne=++u,Pt=await t.request(Ht,{body:y,...p.keepalive&&{keepalive:!0}}),w=Jt(Pt);if(o==="none")return!p.request&&w?.session_id&&Ne>f&&(f=Ne,w.session_id!==y.session_id&&(l=w.session_id)),y.session_id=p.request?w?.session_id||null:l,r?.(y),{success:!0,data:y};let ye=p.request?he:ze(),Rt=ye!==null&&ye!==he,be=ye??he,je=!Rt&&(!be||!w?.anonymous_id||be===w.anonymous_id);return je?(w?.anonymous_id&&(y.anonymous_id=w.anonymous_id),w?.session_id&&(y.session_id=w.session_id)):y.anonymous_id=be,!p.request&&typeof window<"u"&&y.anonymous_id&&(je&&y.session_id&&sessionStorage.setItem(`${R}-session_id`,y.session_id.toString()),Ze(y.anonymous_id)),r?.(y),{success:!0,data:y}}catch(G){return n.error("Failed to send log to API. Inspect error response of `log` for more information."),{success:!1,error:G}}},O=Promise.resolve();return{log:async p=>{Se(p.request||typeof window<"u","Cannot log on the server without a request. Please pass a request to `log`.");let v="request"in p&&p.request?{href:p.request.url,referrer:zt(p.request.referrer),title:""}:{href:location.href,referrer:document.referrer,title:document.title};o==="none"&&p.event==="FLOW_NODE"&&p.properties&&"trigger"in p.properties&&(p.properties.trigger==="pagehide"||p.properties.trigger==="hidden")&&(p={...p,keepalive:!0});let Z={event_id:K(),consent_lane:o,site_kind:c};if(o==="device"||p.request||l||p.keepalive)return M(p,v,Z);let G=()=>M(p,v,Z),J=O.then(G,G);return O=J,J},getHeaders:p=>{let v=new Headers;return o==="none"||!p?.anonymous_id||v.append("Set-Cookie",Ye(p.anonymous_id)),v},getSessionInfo:x,getOrCreateAnonymousId:()=>o==="none"?d??(d=K()):xe()}};var et=require("neoqs");function we(t,n,r){let o=t["~standard"].validate(n);if(o instanceof Promise)throw new TypeError("Async schema");if(o.issues)throw new k(o.issues,r);return o.value}function Yt(t,n,r){try{return{success:!0,output:we(t,n,r)}}catch(o){if(o instanceof k)return{success:!1,issues:o.issues,source:o.source};throw o}}var W=class{constructor(n){if(this.baseUrl=oe[n.environment],this.headers=new Headers({"Content-Type":"application/json",Accept:"application/json"}),n.apiKey.type==="secret"){if(typeof window<"u")throw new Error("Secret key cannot be used in a browser environment");this.headers.set("x-secret-key",n.apiKey.key)}else this.headers.set("x-publishable-key",n.apiKey.key);this.logger=n.logger,this._environment=n.environment}get environment(){return this._environment}getFetchParams(n,r){let o=r.validateIn??!0,{searchParams:c,body:l}=o?ke(n,r):r,d=new URL(this.baseUrl),u=n.pathname;if("params"in r&&r.params)for(let[f,x]of Object.entries(r.params))u=u.replace(`:${f}`,String(x));return d.pathname=u,n.schema.searchParams&&(d.search=(0,et.stringify)(c)),[d.toString(),{method:n.method,body:l?JSON.stringify(l):void 0,headers:this.headers,signal:r.signal,...r.keepalive&&{keepalive:!0}}]}async parseResponse(n,r){let o=await _e(r.response);if(Te(o,r.response.status),!(r.validateOut??!0))return o;let l=Yt(n.schema.response,o,"response");if(!l.success)throw new k(l.issues,l.source);return l.output}async request(n,r){try{let o=this.getFetchParams(n,r),c=await fetch(...o);return await this.parseResponse(n,{response:c,validateOut:r.validateOut})}catch(o){throw o instanceof k?this.logger.error(o.message,o.issues):this.logger.error(o),o}}};function C(){return{"~standard":{vendor:"inploi",version:1,validate:t=>({value:t})}}}function H(t){return t}function ke(t,n){let r={searchParams:void 0,body:void 0,validateIn:!1};return t.schema.searchParams&&(r.searchParams=we(t.schema.searchParams,"searchParams"in n?n.searchParams:{})),t.schema.body&&(r.body=we(t.schema.body,"body"in n?n.body:{})),r}function tt({publishableKey:t,env:n,logger:r=ne,onEvent:o,persistence:c,siteKind:l}){let d=Me({baseUrl:oe[n],publishableKey:t}),u=r===!1?re:r,f=new W({environment:n,apiKey:{type:"publishable",key:t},logger:u}),x=Xe({rpcClient:f,logger:u,onEvent:o,persistence:c,siteKind:l});return{register:O=>O({logger:u,apiClient:d,analytics:x,rpcClient:f,publishableKey:t,env:n}),analytics:x,apiClient:d}}var nt={VIEW_PAGE:"A careers-site page shown (not a job page).",VIEW_JOB:"A job's own page shown; one per job id the page names.",PAGE_ENGAGEMENT:"A page view's attention summary, sent when the view is hidden or left.",VIEW_SEARCH:"A job search seen for two seconds.",SEARCH_SETTLE:"A searched query or filter with results, unchanged for five seconds.",SEARCH_PAGINATE:"A move to another page of search results.",SEARCH_JOB_CLICK:"A job opened from search results.",SAVE_JOB:"A job saved or unsaved by the candidate.",LINK_CLICK:"A tracked link clicked.",INTERACTION:"A tagged interaction (`tag` names it).",FLOW_START:"An application flow started.",FLOW_INTERACT:"The candidate's first answer in a flow.",FLOW_END:"An application flow ended.",FLOW_NODE:"The candidate's path through an application, summarised when it pauses or ends.",FLOW_SUBMIT:"An application submitted, with the outcome.",FLOW_REDIRECT:"A flow sent the candidate to an external apply page.",FEEDBACK:"A rating or comment.",ADDRESS_SHADOW_COMPARED:"Engineering telemetry: the address lookup's shadow comparison.",SUBMIT_FORM:"Declared but sent by nothing."};function ie(t){let n=JSON.stringify({message:t.message,acceptLabel:t.acceptLabel??"",declineLabel:t.declineLabel??""}),r=5381;for(let o=0;o<n.length;o++)r=r*33^n.charCodeAt(o);return(r>>>0).toString(36)}function se(t,n){return`${Je}:${t}:${n}`}function rt(t,n){if(typeof window>"u")return!1;try{let r=se(t,ie(n));return window.localStorage.getItem(r)==="accepted"}catch{return!1}}function ot(t,n){if(!(typeof window>"u"))try{let r=se(t,ie(n));window.localStorage.setItem(r,"accepted")}catch{}}var s=A(require("valibot"),1),Qt=["agent","sdk","form","integration","migration"],Zt=["APPLIED","SHORTLISTED","INTERVIEWED","OFFERED","HIRED","REJECTED","WITHDRAWN"];var Xt=["screening","cv_match","interview","overall"],en=["PENDING","SCHEDULED","IN_PROGRESS","COMPLETED","CANCELLED"],tn=["job","company"],nn=["created_at","updated_at"],rn=["asc","desc"],on=["careers_site","chatbot","plugin_job_search","ats_import","referral","agency","other","unknown"],sn=["submit","stage_transition","move_to_stage","shortlist","move_to_interview","make_offer","hire","withdraw","disqualify","reinstate","rate","score_written"],an=["user","system","automation","integration","candidate"],ae=s.picklist(Qt),I=s.picklist(Zt),E=s.pipe(s.string(),s.trim(),s.minLength(1),s.maxLength(100)),ce=s.picklist(Xt),it=s.picklist(en),pr=s.picklist(tn),st=s.picklist(nn),at=s.picklist(rn),Y=s.pipe(s.string(),s.trim(),s.minLength(1),s.maxLength(100)),le=s.picklist(on),ct=s.picklist(sn),lt=s.picklist(an);var S=s.variant("type",[s.object({type:s.literal("user"),id:s.pipe(s.string(),s.minLength(1)),email:s.pipe(s.string(),s.minLength(1)),name:s.pipe(s.string(),s.minLength(1))}),s.object({type:s.literal("system"),id:s.pipe(s.string(),s.minLength(1)),name:s.optional(s.string())}),s.object({type:s.literal("automation"),id:s.pipe(s.string(),s.minLength(1)),name:s.optional(s.string())}),s.object({type:s.literal("integration"),id:s.pipe(s.string(),s.minLength(1)),name:s.optional(s.string())}),s.object({type:s.literal("candidate"),id:s.pipe(s.string(),s.minLength(1)),email:s.optional(s.string())})]);var P=A(require("valibot"),1),cn=P.object({total:P.number(),page:P.number(),perPage:P.number(),lastPage:P.number()});function pe(t){return P.object({data:P.array(t),pagination:cn})}var m=A(require("valibot"),1);var Q=m.object({id:m.string(),email:m.nullable(m.string()),firstName:m.nullable(m.string()),lastName:m.nullable(m.string()),phone:m.nullable(m.string()),source:m.nullable(ae),identifiedAt:m.nullable(m.string()),createdAt:m.string(),updatedAt:m.string()});var i=A(require("valibot"),1);var g=A(require("valibot"),1),$=g.pipe(g.string(),g.minLength(1)),pt=g.pipe(g.number(),g.integer(),g.minValue(1)),L=g.record(g.string(),g.unknown());var _=A(require("valibot"),1);var dt=_.object({id:_.string(),applicationId:_.string(),status:it,scheduledAt:_.nullable(_.string()),completedAt:_.nullable(_.string()),meta:_.nullable(L),createdAt:_.string(),updatedAt:_.string()});var Ie=i.object({score:i.number(),reason:i.string(),confidence:i.number()}),ut=i.object({id:i.string(),candidateId:i.string(),jobId:i.number(),stage:E,stageGroup:I,stageEnteredAt:i.string(),rating:i.nullable(i.number()),disqualifiedAt:i.nullable(i.string()),disqualificationReason:i.nullable(Y),disqualificationNote:i.nullable(i.string()),source:le,sourceDetail:i.nullable(i.string()),sessionId:i.nullable(i.number()),externalApplicationId:i.nullable(i.string()),meta:i.nullable(L),context:i.nullable(L),scoredAt:i.nullable(i.string()),createdAt:i.string(),updatedAt:i.string()}),ln=i.object({id:i.string(),applicationId:i.string(),scoreType:ce,score:i.nullable(i.number()),reason:i.nullable(i.string()),categories:i.nullable(i.record(i.string(),Ie)),scoredBy:i.nullable(i.string()),createdAt:i.string()}),de=i.object({...ut.entries,candidate:i.nullable(Q),score:i.nullable(ln),interview:i.nullable(dt)}),pn=i.object({...Q.entries,applications:i.array(ut)}),mt=i.object({id:i.string(),applicationId:i.string(),action:ct,fromStage:i.nullable(E),fromStageGroup:i.nullable(I),toStage:i.nullable(E),toStageGroup:i.nullable(I),disqualificationReason:i.nullable(Y),disqualificationNote:i.nullable(i.string()),actorId:i.nullable(i.string()),actorType:lt,actorEmail:i.nullable(i.string()),actorName:i.nullable(i.string()),meta:i.nullable(L),schemaVersion:i.number(),createdAt:i.string()});var h=A(require("valibot"),1);var gt=h.object({anonymousId:$,email:$,firstName:h.nullish(h.string()),lastName:h.nullish(h.string()),phone:h.nullish(h.string()),source:h.nullish(ae)}),vt=h.object({candidateId:h.string(),isNew:h.boolean()});var e=A(require("valibot"),1);var dn=["stage_transition","move_to_stage","shortlist","move_to_interview","make_offer","hire","withdraw","disqualify","reinstate","rate"],me=e.picklist(dn),ft=e.pipe(e.string(),e.transform(t=>t.split(",").map(n=>n.trim()).filter(n=>n.length>0))),un=e.pipe(ft,e.array(E)),mn=e.pipe(ft,e.array(I)),ht=e.pipe(e.string(),e.transform(t=>t.split(",").map(n=>Number(n.trim())).filter(n=>Number.isInteger(n)&&n>0))),Cr=e.object({stages:e.optional(un),stage_groups:e.optional(mn),job_id:e.optional(e.string()),job_ids:e.optional(ht),candidate_id:e.optional(e.string()),is_disqualified:e.optional(e.picklist(["true","false"])),created_from:e.optional(e.string()),created_to:e.optional(e.string()),updated_from:e.optional(e.string()),updated_to:e.optional(e.string()),entered_stage_from:e.optional(e.string()),entered_stage_to:e.optional(e.string()),from:e.optional(e.string()),to:e.optional(e.string()),q:e.optional(e.string()),scored:e.optional(e.picklist(["true","false"])),sort:e.optional(st),order:e.optional(at),page:e.optional(e.string()),per_page:e.optional(e.string())}),Lr=e.pipe(e.object({candidateId:$,jobId:pt,meta:e.nullish(L),sessionId:e.nullish(e.number()),externalApplicationId:e.nullish(e.string()),context:e.nullish(L),source:e.nullish(le),sourceDetail:e.nullish(e.string()),stage:e.nullish(E),stageGroup:e.nullish(I),actor:e.nullish(S)}),e.check(t=>t.stage==null==(t.stageGroup==null),"stage and stageGroup must be supplied together")),yt=e.object({id:e.string(),stageGroup:e.string(),createdAt:e.string()}),Or=e.union([e.object({ok:e.literal(!0),duplicate:e.literal(!1),applicationId:e.string(),candidateId:e.string()}),e.object({ok:e.literal(!0),duplicate:e.literal(!0),existingApplication:yt})]),bt=e.object({isDuplicate:e.boolean(),existingApplication:e.optional(yt)}),Dr=e.object({applicationId:$,scoreType:ce,score:e.number(),reason:e.nullish(e.string()),categories:e.nullish(e.record(e.string(),Ie)),scoredBy:e.nullish(e.string()),actor:e.nullish(S)}),Nr=e.object({scoreId:e.string()}),jr=pe(de);var Fr=e.picklist(["already_in_target_stage","not_in_source_stage","disqualified"]),Br=e.array(mt),ue=e.object({stage:e.nullish(E),note:e.nullish(e.string())}),gn=e.object({stage:e.nullish(E),startDate:e.nullish(e.string()),note:e.nullish(e.string())}),vn=e.variant("action",[e.object({action:e.literal("shortlist"),actor:S,meta:e.nullish(ue)}),e.object({action:e.literal("move_to_interview"),actor:S,meta:e.nullish(ue)}),e.object({action:e.literal("make_offer"),actor:S,meta:e.nullish(ue)}),e.object({action:e.literal("hire"),actor:S,meta:e.nullish(gn)}),e.object({action:e.literal("withdraw"),actor:S,meta:e.nullish(ue)}),e.object({action:e.literal("move_to_stage"),actor:S,meta:e.object({stage:E,stageGroup:I,note:e.nullish(e.string())})}),e.object({action:e.literal("stage_transition"),actor:S,meta:e.object({toStage:E,toStageGroup:I,note:e.nullish(e.string())})}),e.object({action:e.literal("disqualify"),actor:S,meta:e.object({reason:Y,note:e.nullish(e.string())})}),e.object({action:e.literal("reinstate"),actor:S,meta:e.object({toStage:E,toStageGroup:I,note:e.nullish(e.string())})}),e.object({action:e.literal("rate"),actor:S,meta:e.object({rating:e.nullable(e.pipe(e.number(),e.integer(),e.minValue(1),e.maxValue(5)))})})]),Ur=e.object({applicationIds:e.pipe(e.array(e.string()),e.minLength(1)),body:vn}),St=e.picklist(["already_in_target_stage","not_in_source_stage","disqualified","already_disqualified"]),qr=e.variant("kind",[e.object({kind:e.literal("updated"),action:me,application:de}),e.object({kind:e.literal("skipped"),action:me,applicationId:e.string(),reason:St})]),Mr=e.object({updated:e.array(e.object({kind:e.literal("updated"),action:me,application:de})),skipped:e.array(e.object({kind:e.literal("skipped"),action:me,applicationId:e.string(),reason:St})),failed:e.array(e.object({applicationId:e.string(),error:e.string()}))}),U=e.pipe(e.number(),e.integer(),e.minValue(0)),fn=e.object({APPLIED:U,SHORTLISTED:U,INTERVIEWED:U,OFFERED:U,HIRED:U,REJECTED:U,WITHDRAWN:U}),Gr=e.object({job_ids:ht}),Vr=e.object({counts:e.record(e.string(),fn)});var zr=pe(Q);var b=A(require("valibot"),1),Yr=b.object({avg_score:b.nullable(b.number()),p90_score:b.nullable(b.number()),p85_score:b.nullable(b.number()),p80_score:b.nullable(b.number()),total_scores:b.number(),total_shortlists:b.number()});var ge=A(require("valibot"));var _t=({environment:t,publishableKey:n,logger:r})=>{let o=Ke[t];return{async checkDuplicate(c){try{let l=new URLSearchParams({email:c.email,scope:c.scope});c.scope==="job"&&c.jobId!=null&&l.set("job_id",String(c.jobId));let d=await fetch(`${o}/applications/check-duplicate?${l}`,{method:"GET",headers:{Accept:"application/json","x-publishable-key":n}});if(!d.ok)return r.error(`[TalentBankClient] checkDuplicate failed with status ${d.status}`),{isDuplicate:!1};let u=await d.json(),f=ge.safeParse(bt,u);return f.success?f.output:(r.error("[TalentBankClient] checkDuplicate response failed strict validation; falling back to isDuplicate flag"),typeof u=="object"&&u!=null&&typeof u.isDuplicate=="boolean"?{isDuplicate:u.isDuplicate}:{isDuplicate:!1})}catch(l){return r.error("[TalentBankClient] checkDuplicate failed:",l),{isDuplicate:!1}}},async identify(c){try{if(!c.anonymousId)return r.error("[TalentBankClient] identify skipped because anonymousId is missing"),null;let l={email:c.email,firstName:c.firstName,lastName:c.lastName,phone:c.phone,anonymousId:c.anonymousId,source:c.source??"sdk"},d=ge.safeParse(gt,l);if(!d.success)return r.error("[TalentBankClient] identify received invalid input"),null;let u=await fetch(`${o}/identify`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-publishable-key":n},body:JSON.stringify(d.output)});if(!u.ok)return r.error(`[TalentBankClient] identify failed with status ${u.status}`),null;let f=ge.safeParse(vt,await u.json());return f.success?f.output:(r.error("[TalentBankClient] identify returned an invalid response"),null)}catch(l){return r.error("[TalentBankClient] identify failed:",l),null}}}};function Tt(t){if(!(typeof document>"u")){if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",t,{once:!0});return}Promise.resolve().then(t)}}var a=A(require("valibot"));var Pe=["DAILY","WEEKLY","MONTHLY"],hn=a.record(a.string(),a.union([a.string(),a.array(a.string()),a.object({type:a.literal("provided"),lat:a.number(),lng:a.number(),radius:a.number(),unit:a.optional(a.picklist(["miles","km"])),label:a.optional(a.string())})])),yn={pathname:"/job/:id",method:"GET",schema:{response:a.object({id:a.number(),external_id:a.nullish(a.string()),city:a.nullish(a.string()),town:a.nullish(a.string()),category:a.nullish(a.string())})}};async function At(t,{contact:n,job:r}){let o={};if(r){let c=await t.request(yn,{params:{id:r.id}});if((r.id_type==="internal"?String(c.id):c.external_id)!==r.id)throw new Error("Job lookup returned a different role");for(let d of["city","town","category"]){let u=c[d]?.trim();u&&(o[d]=[u])}}await t.request(Re,{body:{contact:n,alerts:"WEEKLY",filters:o}})}var Re={pathname:"/search/save",method:"POST",schema:{response:C(),body:a.object({contact:a.object({email:a.pipe(a.optional(a.string()),a.string(),a.email()),first_name:a.optional(a.string()),last_name:a.optional(a.string())}),alerts:a.pipe(a.optional(a.string()),a.string(),a.picklist(Pe)),filters:hn})}};var T=A(require("valibot"));var Oe=async t=>{let n={method:"GET",pathname:"/search/filters",schema:{response:T.pipe(T.object({country:T.optional(T.array(T.object({value:T.string()})),[])}),T.transform(({country:r})=>r.map(({value:o})=>o))),searchParams:C()}};return t.request(n,{searchParams:{filters:{country:null}}})},ve=new WeakMap,wt=t=>(ve.has(t)||(ve.set(t,void 0),Oe(t).then(async n=>{let{jobCountryCodes:r}=await Promise.resolve().then(()=>(Le(),xt));ve.set(t,r(n).join(",")||void 0)}).catch(()=>{})),ve.get(t)),De=(t,n)=>{let r=new Set,o=[];for(let c=0;c<Math.max(t.length,n.length);c++)for(let l of[t[c],n[c]]){if(!l)continue;let d=l.mapbox_id||l.full_address||[l.name,l.place_formatted].filter(Boolean).join(", ");if(!r.has(d)&&(r.add(d),o.push(l),o.length===5))return o}return o},Tn=600,kt=async(t,n,r)=>{if(r?.throwIfAborted(),!n){let o=await t();return r?.throwIfAborted(),o}return new Promise((o,c)=>{let l,d,u,f=!1,x=()=>{f=!0,clearTimeout(u),r?.removeEventListener("abort",M)},M=()=>{x(),c(r?.reason)},O=()=>{x(),l?.status==="fulfilled"&&d?.status==="fulfilled"?o(De(l.value,d.value)):l?.status==="fulfilled"?o(l.value):d?.status==="fulfilled"?o(d.value):l?.status==="rejected"&&c(l.reason)},fe=(p,v)=>{f||(p?l=v:d=v,l&&d?O():v.status==="fulfilled"&&v.value.length>0&&(u=setTimeout(O,Tn)))};r?.addEventListener("abort",M,{once:!0});for(let p of[!0,!1])t(p?n:void 0).then(v=>fe(p,{status:"fulfilled",value:v}),v=>fe(p,{status:"rejected",reason:v}))})};Le();0&&(module.exports={ANALYTICS_EVENTS,ApiError,InploiRpcClient,JOB_ALERT_FREQUENCIES,NotFoundError,ParsingError,SchemaValidationError,SdkError,UnauthorisedError,addressSearchCountry,blendAddressSuggestions,consentStorageKey,createPlugin,createTalentBankClient,endpoint,generateUUID,getConsentAcceptance,getJobCountries,getOrCreateAnonymousId,hashConsentConfig,initialiseSdk,inploiBrandedLogger,isApiErrorWithData,isSdkError,jobCountryCodes,noLogging,ready,saveClosedRoleJobAlerts,saveSearchEndpoint,searchAddressSuggestions,setConsentAcceptance,typed,validateEndpointInputs});
14
14
  //# sourceMappingURL=index.js.map