@sprig-technologies/sprig-browser 2.29.0 → 2.30.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/dist/core.js ADDED
@@ -0,0 +1 @@
1
+ import{D as s,S as a}from"./metricsReporter-D4_mNhAn.js";import{S as r,c as i,s as o}from"./core-kjUN1Tk4.js";export{s as DismissReason,r as SprigAPI,a as SprigEvent,i as default,o as sprig};
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./index-Dl-jpk4y.cjs");exports.DismissReason=e.DismissReason;exports.SprigAPI=e.SprigAPI;exports.SprigEvent=e.SprigEvent;exports.default=e.index;exports.sprig=e.sprig;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./core-CQmniVXc.cjs");require("./replay.cjs");const r=require("./metricsReporter-FY7QqLGR.cjs");exports.SprigAPI=e.SprigAPI;exports.default=e.core;exports.sprig=e.sprig;exports.DismissReason=r.DismissReason;exports.SprigEvent=r.SprigEvent;
package/dist/index.d.ts CHANGED
@@ -27,6 +27,7 @@ type elementNode = {
27
27
  childNodes: serializedNodeWithId[];
28
28
  isSVG?: true;
29
29
  needBlock?: boolean;
30
+ isCustom?: true;
30
31
  };
31
32
  type textNode = {
32
33
  type: NodeType.Text;
@@ -98,7 +99,7 @@ type DataURLOptions = Partial<{
98
99
  type: string;
99
100
  quality: number;
100
101
  }>;
101
- type MaskTextFn = (text: string) => string;
102
+ type MaskTextFn = (text: string, element: HTMLElement | null) => string;
102
103
  type MaskInputFn = (text: string, element: HTMLElement) => string;
103
104
 
104
105
  declare class Mirror$1 implements IMirror<Node> {
@@ -185,7 +186,8 @@ declare enum IncrementalSource {
185
186
  Drag = 12,
186
187
  StyleDeclaration = 13,
187
188
  Selection = 14,
188
- AdoptedStyleSheet = 15
189
+ AdoptedStyleSheet = 15,
190
+ CustomElement = 16
189
191
  }
190
192
  type mutationData = {
191
193
  source: IncrementalSource.Mutation;
@@ -228,7 +230,10 @@ type selectionData = {
228
230
  type adoptedStyleSheetData = {
229
231
  source: IncrementalSource.AdoptedStyleSheet;
230
232
  } & adoptedStyleSheetParam;
231
- type incrementalData = mutationData | mousemoveData | mouseInteractionData | scrollData | viewportResizeData | inputData | mediaInteractionData | styleSheetRuleData | canvasMutationData | fontData | selectionData | styleDeclarationData | adoptedStyleSheetData;
233
+ type customElementData = {
234
+ source: IncrementalSource.CustomElement;
235
+ } & customElementParam;
236
+ type incrementalData = mutationData | mousemoveData | mouseInteractionData | scrollData | viewportResizeData | inputData | mediaInteractionData | styleSheetRuleData | canvasMutationData | fontData | selectionData | styleDeclarationData | adoptedStyleSheetData | customElementData;
232
237
  type event = domContentLoadedEvent | loadedEvent | fullSnapshotEvent | incrementalSnapshotEvent | metaEvent | customEvent | pluginEvent;
233
238
  type eventWithTime = event & {
234
239
  timestamp: number;
@@ -280,6 +285,7 @@ type hooksParam = {
280
285
  canvasMutation?: canvasMutationCallback;
281
286
  font?: fontCallback;
282
287
  selection?: selectionCallback;
288
+ customElement?: customElementCallback;
283
289
  };
284
290
  type textMutation = {
285
291
  id: number;
@@ -347,8 +353,8 @@ declare enum CanvasContext {
347
353
  type mouseInteractionParam = {
348
354
  type: MouseInteractions;
349
355
  id: number;
350
- x: number;
351
- y: number;
356
+ x?: number;
357
+ y?: number;
352
358
  pointerType?: PointerTypes;
353
359
  };
354
360
  type mouseInteractionCallBack = (d: mouseInteractionParam) => void;
@@ -443,6 +449,7 @@ type mediaInteractionParam = {
443
449
  currentTime?: number;
444
450
  volume?: number;
445
451
  muted?: boolean;
452
+ loop?: boolean;
446
453
  playbackRate?: number;
447
454
  };
448
455
  type mediaInteractionCallback = (p: mediaInteractionParam) => void;
@@ -462,6 +469,12 @@ type selectionParam = {
462
469
  ranges: Array<SelectionRange>;
463
470
  };
464
471
  type selectionCallback = (p: selectionParam) => void;
472
+ type customElementParam = {
473
+ define?: {
474
+ name: string;
475
+ };
476
+ };
477
+ type customElementCallback = (c: customElementParam) => void;
465
478
  type DeprecatedMirror = {
466
479
  map: {
467
480
  [key: number]: INode;
@@ -822,6 +835,7 @@ declare const RRMediaElement_base: {
822
835
  paused?: boolean | undefined;
823
836
  muted?: boolean | undefined;
824
837
  playbackRate?: number | undefined;
838
+ loop?: boolean | undefined;
825
839
  attachShadow(_init: ShadowRootInit): IRRElement;
826
840
  play(): void;
827
841
  pause(): void;
@@ -1442,14 +1456,6 @@ interface XhrHeaders {
1442
1456
  [key: string]: string;
1443
1457
  }
1444
1458
 
1445
- declare const isValidChunkSize: (chunkSize: any, { minChunkSize, maxChunkSize, }?: {
1446
- minChunkSize?: number | undefined;
1447
- maxChunkSize?: number | undefined;
1448
- }) => chunkSize is number | null | undefined;
1449
- declare const getChunkSizeError: (chunkSize: any, { minChunkSize, maxChunkSize, }?: {
1450
- minChunkSize?: number | undefined;
1451
- maxChunkSize?: number | undefined;
1452
- }) => TypeError;
1453
1459
  declare type ChunkedStreamIterableOptions = {
1454
1460
  defaultChunkSize?: number;
1455
1461
  minChunkSize?: number;
@@ -1467,11 +1473,6 @@ declare class ChunkedStreamIterable implements AsyncIterable<Blob> {
1467
1473
  get chunkByteSize(): number;
1468
1474
  [Symbol.asyncIterator](): AsyncIterator<Blob>;
1469
1475
  }
1470
- /**
1471
- * Checks if an upload chunk was partially received (HTTP 308) and needs a retry.
1472
- * Validates against the 'Range' header to ensure the full chunk was processed.
1473
- */
1474
- declare const isIncompleteChunkUploadNeedingRetry: (res: XhrResponse | undefined, _options?: any) => res is XhrResponse;
1475
1476
  declare type EventName = 'attempt' | 'attemptFailure' | 'chunkSuccess' | 'error' | 'offline' | 'online' | 'progress' | 'success';
1476
1477
  declare type AllowedMethods = 'PUT' | 'POST' | 'PATCH';
1477
1478
  interface UpChunkOptions {
@@ -1560,20 +1561,7 @@ declare class UpChunk {
1560
1561
  */
1561
1562
  private sendChunks;
1562
1563
  }
1563
- declare function createUpload$1(options: UpChunkOptions): UpChunk;
1564
-
1565
- type _mux_upchunk_ChunkedStreamIterable = ChunkedStreamIterable;
1566
- declare const _mux_upchunk_ChunkedStreamIterable: typeof ChunkedStreamIterable;
1567
- type _mux_upchunk_ChunkedStreamIterableOptions = ChunkedStreamIterableOptions;
1568
- type _mux_upchunk_UpChunk = UpChunk;
1569
- declare const _mux_upchunk_UpChunk: typeof UpChunk;
1570
- type _mux_upchunk_UpChunkOptions = UpChunkOptions;
1571
- declare const _mux_upchunk_getChunkSizeError: typeof getChunkSizeError;
1572
- declare const _mux_upchunk_isIncompleteChunkUploadNeedingRetry: typeof isIncompleteChunkUploadNeedingRetry;
1573
- declare const _mux_upchunk_isValidChunkSize: typeof isValidChunkSize;
1574
- declare namespace _mux_upchunk {
1575
- export { _mux_upchunk_ChunkedStreamIterable as ChunkedStreamIterable, type _mux_upchunk_ChunkedStreamIterableOptions as ChunkedStreamIterableOptions, _mux_upchunk_UpChunk as UpChunk, type _mux_upchunk_UpChunkOptions as UpChunkOptions, createUpload$1 as createUpload, _mux_upchunk_getChunkSizeError as getChunkSizeError, _mux_upchunk_isIncompleteChunkUploadNeedingRetry as isIncompleteChunkUploadNeedingRetry, _mux_upchunk_isValidChunkSize as isValidChunkSize };
1576
- }
1564
+ declare const createUpload: typeof UpChunk.createUpload;
1577
1565
 
1578
1566
  declare enum NOTIFICATION_TYPES {
1579
1567
  ACTIVATE = "ACTIVATE:experiment, user_id,attributes, variation, event",
@@ -2151,11 +2139,11 @@ interface PageUrlEvent {
2151
2139
  }
2152
2140
 
2153
2141
  declare enum DismissReason {
2154
- Closed = "close.click",
2155
- Complete = "survey.completed",
2156
- FeedbackClosed = "feedback.closed",
2157
- PageChange = "page.change",
2158
- API = "api",
2142
+ Closed = "close.click",// user clicked the close button
2143
+ Complete = "survey.completed",// user answered all questions
2144
+ FeedbackClosed = "feedback.closed",// user either clicked on feedback button or close button
2145
+ PageChange = "page.change",// productConfig.dismissOnPageChange == true and we detected a page change (excludes hash/query param changes)
2146
+ API = "api",// JS called Sprig('dismissActiveSurvey')
2159
2147
  Override = "override"
2160
2148
  }
2161
2149
  type StudyType = "feedbackButton" | "inProductSurvey";
@@ -2214,34 +2202,15 @@ interface MetricThreshold {
2214
2202
  value: number;
2215
2203
  }
2216
2204
 
2217
- type ReplayDurationType = "after" | "before" | "beforeAndAfter";
2218
- type EventDigest = {
2219
- timestamp: number;
2220
- type: "Sprig_Click";
2221
- } | {
2222
- timestamp: number;
2223
- name: string;
2224
- type: "Sprig_TrackEvent";
2225
- } | {
2226
- timestamp: number;
2227
- type: "Sprig_PageView";
2228
- url: string;
2229
- } | {
2230
- timestamp: number;
2231
- surveyId: string;
2232
- type: "Sprig_ShowSurvey";
2233
- } | {
2234
- timestamp: number;
2235
- surveyId: string;
2236
- type: "Sprig_SubmitSurvey";
2237
- };
2238
-
2239
2205
  interface RecordedTaskResponseType {
2240
2206
  questionId: number;
2241
2207
  type: CardType;
2242
2208
  value: RecordedTaskResponseValueType;
2243
2209
  }
2244
2210
 
2211
+ type SurveyState = "ready" | "no survey";
2212
+ type ReplayDurationType = "after" | "before" | "beforeAndAfter";
2213
+
2245
2214
  interface MobileReplayConfig {
2246
2215
  mobileMetricsReportingEnabled?: boolean;
2247
2216
  metricsReportingInterval?: number;
@@ -2469,6 +2438,7 @@ interface Config extends MobileReplayConfig {
2469
2438
  Authorization?: string;
2470
2439
  "Content-Type"?: string;
2471
2440
  "userleap-platform": Platform | "ios" | "android" | "video_recorder";
2441
+ "sprig-modules"?: string;
2472
2442
  /** @example "SJcVfq-7QQ" */
2473
2443
  "x-ul-environment-id"?: string;
2474
2444
  "x-ul-installation-method": InstallationMethod;
@@ -2508,6 +2478,7 @@ interface Config extends MobileReplayConfig {
2508
2478
  path?: string;
2509
2479
  platform?: Platform;
2510
2480
  previewKey?: string | null;
2481
+ previewMode?: boolean;
2511
2482
  productConfig?: AppProductConfig;
2512
2483
  replayNonce?: string;
2513
2484
  replaySettings?: object;
@@ -2521,8 +2492,10 @@ interface Config extends MobileReplayConfig {
2521
2492
  studyType?: StudyType;
2522
2493
  surveyId: number;
2523
2494
  tabTitle: string;
2495
+ trackPageViewUrl?: string;
2524
2496
  ulEvents: typeof SprigEvent;
2525
2497
  UpChunk: Window["UpChunk"];
2498
+ upchunkLibraryURL?: string;
2526
2499
  useDesktopPrototype?: boolean;
2527
2500
  useMobileStyling: boolean;
2528
2501
  userId: UUID | null;
@@ -2558,7 +2531,32 @@ declare class SprigQueue {
2558
2531
  empty(): void;
2559
2532
  }
2560
2533
 
2561
- type SurveyState = "ready" | "no survey";
2534
+ declare global {
2535
+ interface SymbolConstructor {
2536
+ readonly observable: symbol;
2537
+ }
2538
+ }
2539
+
2540
+ type EventDigest = {
2541
+ timestamp: number;
2542
+ type: "Sprig_Click";
2543
+ } | {
2544
+ timestamp: number;
2545
+ name: string;
2546
+ type: "Sprig_TrackEvent";
2547
+ } | {
2548
+ timestamp: number;
2549
+ type: "Sprig_PageView";
2550
+ url: string;
2551
+ } | {
2552
+ timestamp: number;
2553
+ surveyId: string;
2554
+ type: "Sprig_ShowSurvey";
2555
+ } | {
2556
+ timestamp: number;
2557
+ surveyId: string;
2558
+ type: "Sprig_SubmitSurvey";
2559
+ };
2562
2560
 
2563
2561
  declare namespace optimizely {
2564
2562
  interface Optimizely {
@@ -2704,6 +2702,7 @@ declare namespace sprigConfig {
2704
2702
  url: string,
2705
2703
  properties?: SprigProperties,
2706
2704
  showSurveyCallback?: (surveyId?: number) => Promise<boolean>,
2705
+ calledFromApi?: boolean,
2707
2706
  ) => void;
2708
2707
  unmute: () => void;
2709
2708
  }
@@ -2742,10 +2741,12 @@ declare namespace sprigConfig {
2742
2741
  mobileHeadersJSON?: string;
2743
2742
  nonce?: string;
2744
2743
  partnerAnonymousId: string | null;
2744
+ replayLibraryURL?: string;
2745
2745
  replayNonce?: string;
2746
2746
  reportError: (name: string, err: Error, extraInfo?: object) => void;
2747
2747
  sampleRate?: number;
2748
2748
  token: string | null;
2749
+ upchunkLibraryURL?: string;
2749
2750
  UPDATES: typeof EVENTS;
2750
2751
  viewSDKURL?: string;
2751
2752
  windowDimensions?: {
@@ -2759,7 +2760,6 @@ type ArgumentType<T> = T extends (arg1: infer U, ...args: unknown[]) => unknown
2759
2760
  ? U
2760
2761
  : unknown;
2761
2762
  type PublicOf<T> = { [K in keyof T]: T[K] };
2762
- type createUpload = (typeof _mux_upchunk)["createUpload"];
2763
2763
  type rrwebRecord = (typeof rrweb)["record"];
2764
2764
  type rrwebCustomEvent = (typeof rrweb)["record"]["addCustomEvent"];
2765
2765
  declare global {
@@ -2777,9 +2777,7 @@ declare global {
2777
2777
  optimizelyDatafile?: object;
2778
2778
  previewMode?: unknown;
2779
2779
  UpChunk: {
2780
- createUpload: (
2781
- ...args: ArgumentTypes<createUpload>
2782
- ) => PublicOf<ReturnType<createUpload>>;
2780
+ createUpload: typeof createUpload;
2783
2781
  };
2784
2782
  _Sprig?: sprigConfig.WindowSprig;
2785
2783
  Sprig: sprigConfig.WindowSprig;
@@ -2797,7 +2795,13 @@ declare global {
2797
2795
  type WindowSprig = sprigConfig.WindowSprig;
2798
2796
  type SprigAttributes = Record<string, boolean | number | string>;
2799
2797
  type SprigListener = Listener<unknown[]>;
2800
- type SprigMetadata = Record<string, unknown>;
2798
+ type SprigMetadata = {
2799
+ url?: string;
2800
+ trackPageView?: boolean;
2801
+ optimizelyExperiments?: object;
2802
+ launchDarklyFlags?: object;
2803
+ eventProperties?: SprigProperties;
2804
+ };
2801
2805
  type SprigProperties = Record<string, unknown>;
2802
2806
  type SprigAPIActions = sprigConfig.SprigAPIActions;
2803
2807
  type TrackPayload = sprigConfig.TrackPayload;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{D as s,g as a,S as i,j as r,h as p}from"./index-HZs0t66-.js";export{s as DismissReason,a as SprigAPI,i as SprigEvent,r as default,p as sprig};
1
+ import{S as s,c as a,s as i}from"./core-kjUN1Tk4.js";import"./replay.js";import{D as r,S as o}from"./metricsReporter-D4_mNhAn.js";export{r as DismissReason,s as SprigAPI,o as SprigEvent,a as default,i as sprig};
@@ -0,0 +1,2 @@
1
+ var K=Object.defineProperty,B=(e,t,s)=>t in e?K(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,a=(e,t,s)=>(B(e,typeof t!="symbol"?t+"":t,s),s),A=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(A||{}),D=(e=>(e.ReplayCapture="replay.capture",e.FeedbackButtonLoaded="feedback.button.loaded",e.SDKReady="sdk.ready",e.SurveyAppeared="survey.appeared",e.SurveyClosed="survey.closed",e.SurveyDimensions="survey.dimensions",e.SurveyFadingOut="survey.fadingOut",e.SurveyHeight="survey.height",e.SurveyPresented="survey.presented",e.SurveyLifeCycle="survey.lifeCycle",e.SurveyWidth="survey.width",e.SurveyWillClose="survey.willClose",e.SurveyWillPresent="survey.will.present",e.CloseSurveyOnOverlayClick="close.survey.overlayClick",e.VisitorIDUpdated="visitor.id.updated",e.QuestionAnswered="question.answered",e))(D||{});const G={FEEDBACK_BUTTON_LOADED:"feedback.button.loaded",SDK_READY:"sdk.ready",SURVEY_APPEARED:"survey.appeared",SURVEY_CLOSED:"survey.closed",SURVEY_DIMENSIONS:"survey.dimensions",SURVEY_FADING_OUT:"survey.fadingOut",SURVEY_HEIGHT:"survey.height",SURVEY_WIDTH:"survey.width",SURVEY_PRESENTED:"survey.presented",SURVEY_LIFE_CYCLE:"survey.lifeCycle",SURVEY_WILL_CLOSE:"survey.willClose",SURVEY_WILL_PRESENT:"survey.will.present",QUESTION_ANSWERED:"question.answered",REPLAY_CAPTURE:"replay.capture",CLOSE_SURVEY_ON_OVERLAY_CLICK:"close.survey.overlayClick",VISITOR_ID_UPDATED:"visitor.id.updated",DATA:{DISMISS_REASONS:{API:"api",CLOSED:"close.click",COMPLETE:"survey.completed",PAGE_CHANGE:"page.change",OVERRIDE:"override"},SURVEY_ID:"survey.id"}};let g;const z=new Uint8Array(16);function Q(){if(!g&&(g=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!g))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return g(z)}const n=[];for(let e=0;e<256;++e)n.push((e+256).toString(16).slice(1));function X(e,t=0){return n[e[t+0]]+n[e[t+1]]+n[e[t+2]]+n[e[t+3]]+"-"+n[e[t+4]]+n[e[t+5]]+"-"+n[e[t+6]]+n[e[t+7]]+"-"+n[e[t+8]]+n[e[t+9]]+"-"+n[e[t+10]]+n[e[t+11]]+n[e[t+12]]+n[e[t+13]]+n[e[t+14]]+n[e[t+15]]}const Z=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),U={randomUUID:Z};function ee(e,t,s){if(U.randomUUID&&!t&&!e)return U.randomUUID();e=e||{};const r=e.random||(e.rng||Q)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,X(r)}var te=class extends Error{constructor(e,t,s){super(`Possible EventEmitter memory leak detected. ${s} ${t.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`),this.emitter=e,this.type=t,this.count=s,this.name="MaxListenersExceededWarning"}},k=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=k.defaultMaxListeners,this.hasWarnedAboutPotentialMemoryLeak=!1}_emitInternalEvent(e,t,s){this.emit(e,t,s)}_getListeners(e){return Array.prototype.concat.apply([],this.events.get(e))||[]}_removeListener(e,t){const s=e.indexOf(t);return s>-1&&e.splice(s,1),[]}_wrapOnceListener(e,t){const s=(...r)=>(this.removeListener(e,s),t.apply(this,r));return Object.defineProperty(s,"name",{value:t.name}),s}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const s=this._getListeners(e);return s.forEach(r=>{r.apply(this,t)}),s.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const s=this._getListeners(e).concat(t);if(this.events.set(e,s),this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=!0;const r=new te(this,e,this.listenerCount(e));console.warn(r)}return this}on(e,t){return this.addListener(e,t)}once(e,t){return this.addListener(e,this._wrapOnceListener(e,t))}prependListener(e,t){const s=this._getListeners(e);if(s.length>0){const r=[t].concat(s);this.events.set(e,r)}else this.events.set(e,s.concat(t));return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const s=this._getListeners(e);return s.length>0&&(this._removeListener(s,t),this.events.set(e,s),this._emitInternalEvent("removeListener",e,t)),this}off(e,t){return this.removeListener(e,t)}removeAllListeners(e){return e?this.events.delete(e):this.events.clear(),this}listeners(e){return Array.from(this._getListeners(e))}listenerCount(e){return this._getListeners(e).length}rawListeners(e){return this.listeners(e)}},C=k;C.defaultMaxListeners=10;const se=new C,w=e=>new Promise(t=>{setTimeout(()=>{t()},e)}),re=({"userleap-platform":e})=>e!=="web";class x{constructor(t){a(this,"storage"),a(this,"tempStorage",{}),a(this,"isStorageAvailable"),this.storage=window[t],this.isStorageAvailable=this.checkIfStorageAvailable()}checkIfStorageAvailable(){try{const t="__storage_test__";return this.storage.setItem(t,t),this.storage.removeItem(t),!0}catch{return!1}}setItem(t,s){this.isStorageAvailable?this.storage.setItem(t,s):this.tempStorage[t]=s}getItem(t){return this.isStorageAvailable?this.storage.getItem(t):this.tempStorage[t]}removeItem(t){this.isStorageAvailable?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable?this.storage.clear():this.tempStorage={}}}const ne=new x("sessionStorage"),ie=new x("localStorage");class oe{constructor(t){a(this,"payload"),a(this,"promise"),a(this,"reject",()=>{}),a(this,"resolve",()=>{}),this.payload=t,this.promise=new Promise((s,r)=>{this.reject=r,this.resolve=s})}resolveRequest(t){this.resolve(t)}}const I={replay:null},ae=e=>{I.replay=e},le=()=>{const e=[];return I.replay&&e.push("replay"),e.join(",")},ce={RATELIMIT_RESET_DEFAULT:10};let T=!1,P="",_=!1,M=!1,E=[];const ue=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",N=e=>{var t;(t=e?.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(M=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`),document.removeEventListener("securitypolicyviolation",N))},V=(e="")=>{T=!0,P=e};function de(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.30.1","x-ul-installation-method":ue(e),"sprig-modules":le()};if(e.envId&&(t["x-ul-environment-id"]=e.envId),e.token&&(t.Authorization="Bearer "+e.token),e.userId&&(t["x-ul-user-id"]=e.userId),e.visitorId&&(t["x-ul-visitor-id"]=e.visitorId),e.partnerAnonymousId&&(t["x-ul-anonymous-id"]=e.partnerAnonymousId),e.mobileHeadersJSON){const s=JSON.parse(e.mobileHeadersJSON);Object.assign(t,s)}return e.locale&&(t["accept-language"]=e.locale),window.previewMode&&(t["x-ul-preview-mode"]="1"),t}const W=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const s=new oe(t);return E.push(s),s.promise}},p=async(e,t)=>{const{retries:s=0,shouldDropOnRateLimit:r=!1,shouldRetryRequest:m=!1,...l}=t,c={url:e,options:l,retries:s,shouldDropOnRateLimit:r};if(_&&!m)return W(c);const h={ok:!1,reportError:!1};if(T)return console.info(`UserLeap - ${P}`),h;try{const o=await fetch(e,l);if(o.status===429)if(!_&&!r||m){_=!0;const i=o.headers.has("ratelimit-reset")?Number(o.headers.get("ratelimit-reset")):ce.RATELIMIT_RESET_DEFAULT;return await w(i*1e3),p(e,{...l,shouldDropOnRateLimit:r,shouldRetryRequest:!0})}else return W(c);if(_=!1,E.length&&(E.map(i=>{const y=i.payload;p(y.url,{...y.options,retries:y.retries,shouldDropOnRateLimit:y.shouldDropOnRateLimit}).then(J=>{i.resolveRequest(J)})}),E=[]),o.ok){if(o.status===249)return V(),h;const i=await o.text();try{return i&&i!=="OK"&&(o.json=JSON.parse(i)),o}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${i}`)}}}return o}catch(o){const i=s+1;return i>5||M?{ok:!1,reportError:!1,error:o}:(await w(Math.pow(2,s)*1e3),p(e,{...l,retries:i}))}},u={Error:1,Warn:2,Info:3,Debug:4};let b=1e3,f=u.Debug,d=[];const he=e=>{const t=Object.entries(u).find(s=>s[1]===e);return t?.[0]??""},pe=e=>e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3}),ve=(e,t)=>`${pe(t)}:${e}`,me=()=>{d=d.filter(e=>e.level<=f)},ye=()=>{d.length>b&&d.shift()},S=(e,t)=>{e>f||(d.push({level:e,line:ve(t,new Date)}),ye())},Y=e=>{S(u.Debug,e)},ge=e=>{S(u.Info,e)},j=e=>{S(u.Warn,e)},_e=e=>{S(u.Error,e)},Ee=()=>d.map(e=>e.line),fe=()=>new TextEncoder().encode(Ee().join(`
2
+ `)),Se=async e=>{if(!e)return;const t=fe();return p(e,{body:t,method:"PUT"})},Le=(e,t)=>{e!==void 0&&(b=e),t!==void 0&&(f=t),Y(`Initializing logger with limit of ${b} lines and ${he(f)} level`),me()},$=Object.freeze({contains:(e,t)=>t.includes(e),notContains:(e,t)=>!t.includes(e),exactly:(e,t)=>t===e,notExactly:(e,t)=>t!==e,startsWith:(e,t)=>t.startsWith(e),endsWith:(e,t)=>t.endsWith(e),regex:(e,t)=>new RegExp(e).test(t),legacy:(e,t)=>new RegExp(e,"i").test(t)});function F(e,t){const{matchType:s,pattern:r}=e,m=s?$[s]:$.legacy;let l=!1;try{l=m(r,t)}catch(c){const h=`[Sprig] (ERR-445) Failed to check url match with pattern ${r}`;c instanceof Error&&(console.warn(h,c),c.stack=JSON.stringify(e),window.UserLeap.reportError(h,c))}return l}const we=e=>{const{pageUrlEvents:t}=window.UserLeap._config,s=t?.find(r=>r.id===e);return s?F(s,window.location.href):!1};let q=!0,R=!1;const Ie=()=>q=!1,be=()=>R=!0,Re=["sdk_event_queue_latency_seconds","sdk_replay_add_event_batch_seconds","sdk_replay_cleanup_seconds","sdk_replay_compression_seconds","sdk_replay_get_events_between_seconds","sdk_replay_snapshot_seconds"];let v={},O;class Oe{constructor(t){a(this,"_values",[]),a(this,"_isWebMetric"),this.name=t,this._isWebMetric=Re.includes(this.name)}report(t){if(q&&this._values.push({time:Date.now(),value:t}),R||!this._isWebMetric)return;const s=this.findExceededThreshold(t);s&&O&&O(t,s)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const s=v[this.name];if(s)return s.find(r=>this.valueExceedsThreshold(t,r))}valueExceedsThreshold(t,s){return s.type==="max"?t>s.value:s.type==="min"?t<s.value:!1}}const Ae=(e,t)=>{v={},R=!1,e?.forEach(s=>{var r;s.metric in v||(v[s.metric]=[]),(r=v[s.metric])==null||r.push(s)}),O=t},L={},H=e=>{const t=new Oe(e);return L[e]=t,t},De=(e,t)=>{let s=L[e];return s||(s=H(e)),s.report(t)},Ue=async e=>{const t=Object.values(L).map(s=>({name:s.name,values:s.collect()}));if(t.some(s=>s.values.length))try{await e(JSON.stringify(t))}catch(s){j(`Error posting metrics: ${s}`)}},ke=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{Ue(t)},e*1e3):Ie()};export{A as D,G as E,L as P,D as S,ne as a,De as b,we as c,Y as d,_e as e,se as f,ae as g,de as h,ge as i,re as j,Ae as k,ie as l,I as m,ke as n,be as o,Le as p,N as q,H as r,p as s,V as t,Se as u,ee as v,j as w,F as x,w as y};
@@ -0,0 +1,2 @@
1
+ "use strict";var J=Object.defineProperty;var K=(e,t,r)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var a=(e,t,r)=>(K(e,typeof t!="symbol"?t+"":t,r),r);var O=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(O||{}),U=(e=>(e.ReplayCapture="replay.capture",e.FeedbackButtonLoaded="feedback.button.loaded",e.SDKReady="sdk.ready",e.SurveyAppeared="survey.appeared",e.SurveyClosed="survey.closed",e.SurveyDimensions="survey.dimensions",e.SurveyFadingOut="survey.fadingOut",e.SurveyHeight="survey.height",e.SurveyPresented="survey.presented",e.SurveyLifeCycle="survey.lifeCycle",e.SurveyWidth="survey.width",e.SurveyWillClose="survey.willClose",e.SurveyWillPresent="survey.will.present",e.CloseSurveyOnOverlayClick="close.survey.overlayClick",e.VisitorIDUpdated="visitor.id.updated",e.QuestionAnswered="question.answered",e))(U||{});const G={FEEDBACK_BUTTON_LOADED:"feedback.button.loaded",SDK_READY:"sdk.ready",SURVEY_APPEARED:"survey.appeared",SURVEY_CLOSED:"survey.closed",SURVEY_DIMENSIONS:"survey.dimensions",SURVEY_FADING_OUT:"survey.fadingOut",SURVEY_HEIGHT:"survey.height",SURVEY_WIDTH:"survey.width",SURVEY_PRESENTED:"survey.presented",SURVEY_LIFE_CYCLE:"survey.lifeCycle",SURVEY_WILL_CLOSE:"survey.willClose",SURVEY_WILL_PRESENT:"survey.will.present",QUESTION_ANSWERED:"question.answered",REPLAY_CAPTURE:"replay.capture",CLOSE_SURVEY_ON_OVERLAY_CLICK:"close.survey.overlayClick",VISITOR_ID_UPDATED:"visitor.id.updated",DATA:{DISMISS_REASONS:{API:"api",CLOSED:"close.click",COMPLETE:"survey.completed",PAGE_CHANGE:"page.change",OVERRIDE:"override"},SURVEY_ID:"survey.id"}};let g;const Q=new Uint8Array(16);function z(){if(!g&&(g=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!g))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return g(Q)}const n=[];for(let e=0;e<256;++e)n.push((e+256).toString(16).slice(1));function X(e,t=0){return n[e[t+0]]+n[e[t+1]]+n[e[t+2]]+n[e[t+3]]+"-"+n[e[t+4]]+n[e[t+5]]+"-"+n[e[t+6]]+n[e[t+7]]+"-"+n[e[t+8]]+n[e[t+9]]+"-"+n[e[t+10]]+n[e[t+11]]+n[e[t+12]]+n[e[t+13]]+n[e[t+14]]+n[e[t+15]]}const Z=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),A={randomUUID:Z};function ee(e,t,r){if(A.randomUUID&&!t&&!e)return A.randomUUID();e=e||{};const s=e.random||(e.rng||z)();return s[6]=s[6]&15|64,s[8]=s[8]&63|128,X(s)}var te=class extends Error{constructor(e,t,r){super(`Possible EventEmitter memory leak detected. ${r} ${t.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`),this.emitter=e,this.type=t,this.count=r,this.name="MaxListenersExceededWarning"}},x=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=x.defaultMaxListeners,this.hasWarnedAboutPotentialMemoryLeak=!1}_emitInternalEvent(e,t,r){this.emit(e,t,r)}_getListeners(e){return Array.prototype.concat.apply([],this.events.get(e))||[]}_removeListener(e,t){const r=e.indexOf(t);return r>-1&&e.splice(r,1),[]}_wrapOnceListener(e,t){const r=(...s)=>(this.removeListener(e,r),t.apply(this,s));return Object.defineProperty(r,"name",{value:t.name}),r}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const r=this._getListeners(e);return r.forEach(s=>{s.apply(this,t)}),r.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const r=this._getListeners(e).concat(t);if(this.events.set(e,r),this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=!0;const s=new te(this,e,this.listenerCount(e));console.warn(s)}return this}on(e,t){return this.addListener(e,t)}once(e,t){return this.addListener(e,this._wrapOnceListener(e,t))}prependListener(e,t){const r=this._getListeners(e);if(r.length>0){const s=[t].concat(r);this.events.set(e,s)}else this.events.set(e,r.concat(t));return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const r=this._getListeners(e);return r.length>0&&(this._removeListener(r,t),this.events.set(e,r),this._emitInternalEvent("removeListener",e,t)),this}off(e,t){return this.removeListener(e,t)}removeAllListeners(e){return e?this.events.delete(e):this.events.clear(),this}listeners(e){return Array.from(this._getListeners(e))}listenerCount(e){return this._getListeners(e).length}rawListeners(e){return this.listeners(e)}},D=x;D.defaultMaxListeners=10;const re=new D,R=e=>new Promise(t=>{setTimeout(()=>{t()},e)}),se=({"userleap-platform":e})=>e!=="web";class M{constructor(t){a(this,"storage");a(this,"tempStorage",{});a(this,"isStorageAvailable");this.storage=window[t],this.isStorageAvailable=this.checkIfStorageAvailable()}checkIfStorageAvailable(){try{const t="__storage_test__";return this.storage.setItem(t,t),this.storage.removeItem(t),!0}catch{return!1}}setItem(t,r){this.isStorageAvailable?this.storage.setItem(t,r):this.tempStorage[t]=r}getItem(t){return this.isStorageAvailable?this.storage.getItem(t):this.tempStorage[t]}removeItem(t){this.isStorageAvailable?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable?this.storage.clear():this.tempStorage={}}}const ne=new M("sessionStorage"),ie=new M("localStorage");class oe{constructor(t){a(this,"payload");a(this,"promise");a(this,"reject",()=>{});a(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((r,s)=>{this.reject=s,this.resolve=r})}resolveRequest(t){this.resolve(t)}}const S={replay:null},ae=e=>{S.replay=e},le=()=>{const e=[];return S.replay&&e.push("replay"),e.join(",")},ce={RATELIMIT_RESET_DEFAULT:10};let P=!1,V="",_=!1,H=!1,L=[];const ue=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",W=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(H=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`),document.removeEventListener("securitypolicyviolation",W))},Y=(e="")=>{P=!0,V=e};function de(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.30.1","x-ul-installation-method":ue(e),"sprig-modules":le()};if(e.envId&&(t["x-ul-environment-id"]=e.envId),e.token&&(t.Authorization="Bearer "+e.token),e.userId&&(t["x-ul-user-id"]=e.userId),e.visitorId&&(t["x-ul-visitor-id"]=e.visitorId),e.partnerAnonymousId&&(t["x-ul-anonymous-id"]=e.partnerAnonymousId),e.mobileHeadersJSON){const r=JSON.parse(e.mobileHeadersJSON);Object.assign(t,r)}return e.locale&&(t["accept-language"]=e.locale),window.previewMode&&(t["x-ul-preview-mode"]="1"),t}const T=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const r=new oe(t);return L.push(r),r.promise}},m=async(e,t)=>{const{retries:r=0,shouldDropOnRateLimit:s=!1,shouldRetryRequest:y=!1,...l}=t,c={url:e,options:l,retries:r,shouldDropOnRateLimit:s};if(_&&!y)return T(c);const p={ok:!1,reportError:!1};if(P)return console.info(`UserLeap - ${V}`),p;try{const i=await fetch(e,l);if(i.status===429)if(!_&&!s||y){_=!0;const u=i.headers.has("ratelimit-reset")?Number(i.headers.get("ratelimit-reset")):ce.RATELIMIT_RESET_DEFAULT;return await R(u*1e3),m(e,{...l,shouldDropOnRateLimit:s,shouldRetryRequest:!0})}else return T(c);if(_=!1,L.length&&(L.map(o=>{const u=o.payload;m(u.url,{...u.options,retries:u.retries,shouldDropOnRateLimit:u.shouldDropOnRateLimit}).then(B=>{o.resolveRequest(B)})}),L=[]),i.ok){if(i.status===249)return Y(),p;const o=await i.text();try{return o&&o!=="OK"&&(i.json=JSON.parse(o)),i}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${o}`)}}}return i}catch(i){const o=r+1;return o>5||H?{ok:!1,reportError:!1,error:i}:(await R(Math.pow(2,r)*1e3),m(e,{...l,retries:o}))}},h={Error:1,Warn:2,Info:3,Debug:4};let b=1e3,v=h.Debug,d=[];const he=e=>{const t=Object.entries(h).find(r=>r[1]===e);return(t==null?void 0:t[0])??""},pe=e=>e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3}),fe=(e,t)=>`${pe(t)}:${e}`,me=()=>{d=d.filter(e=>e.level<=v)},ye=()=>{d.length>b&&d.shift()},E=(e,t)=>{e>v||(d.push({level:e,line:fe(t,new Date)}),ye())},q=e=>{E(h.Debug,e)},ge=e=>{E(h.Info,e)},N=e=>{E(h.Warn,e)},_e=e=>{E(h.Error,e)},Le=()=>d.map(e=>e.line),ve=()=>new TextEncoder().encode(Le().join(`
2
+ `)),Ee=async e=>{if(!e)return;const t=ve();return m(e,{body:t,method:"PUT"})},we=(e,t)=>{e!==void 0&&(b=e),t!==void 0&&(v=t),q(`Initializing logger with limit of ${b} lines and ${he(v)} level`),me()},C=Object.freeze({contains:(e,t)=>t.includes(e),notContains:(e,t)=>!t.includes(e),exactly:(e,t)=>t===e,notExactly:(e,t)=>t!==e,startsWith:(e,t)=>t.startsWith(e),endsWith:(e,t)=>t.endsWith(e),regex:(e,t)=>new RegExp(e).test(t),legacy:(e,t)=>new RegExp(e,"i").test(t)});function j(e,t){const{matchType:r,pattern:s}=e,y=r?C[r]:C.legacy;let l=!1;try{l=y(s,t)}catch(c){const p=`[Sprig] (ERR-445) Failed to check url match with pattern ${s}`;c instanceof Error&&(console.warn(p,c),c.stack=JSON.stringify(e),window.UserLeap.reportError(p,c))}return l}const Re=e=>{const{pageUrlEvents:t}=window.UserLeap._config,r=t==null?void 0:t.find(s=>s.id===e);return r?j(r,window.location.href):!1};let F=!0,k=!1;const be=()=>F=!1,Ie=()=>k=!0,Se=["sdk_event_queue_latency_seconds","sdk_replay_add_event_batch_seconds","sdk_replay_cleanup_seconds","sdk_replay_compression_seconds","sdk_replay_get_events_between_seconds","sdk_replay_snapshot_seconds"];let f={},I;class ke{constructor(t){a(this,"_values",[]);a(this,"_isWebMetric");this.name=t,this._isWebMetric=Se.includes(this.name)}report(t){if(F&&this._values.push({time:Date.now(),value:t}),k||!this._isWebMetric)return;const r=this.findExceededThreshold(t);r&&I&&I(t,r)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const r=f[this.name];if(r)return r.find(s=>this.valueExceedsThreshold(t,s))}valueExceedsThreshold(t,r){return r.type==="max"?t>r.value:r.type==="min"?t<r.value:!1}}const Ae=(e,t)=>{f={},k=!1,e==null||e.forEach(r=>{var s;r.metric in f||(f[r.metric]=[]),(s=f[r.metric])==null||s.push(r)}),I=t},w={},$=e=>{const t=new ke(e);return w[e]=t,t},Te=(e,t)=>{let r=w[e];return r||(r=$(e)),r.report(t)},Ce=async e=>{const t=Object.values(w).map(r=>({name:r.name,values:r.collect()}));if(t.some(r=>r.values.length))try{await e(JSON.stringify(t))}catch(r){N(`Error posting metrics: ${r}`)}},Oe=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{Ce(t)},e*1e3):be()};exports.DismissReason=O;exports.EVENTS=G;exports.PerformanceMetrics=w;exports.SprigEvent=U;exports.checkUrlMatch=j;exports.checkUrlStillMatching=Re;exports.configureLogger=we;exports.cspViolationHandler=W;exports.debug=q;exports.delay=R;exports.disableThresholdChecking=Ie;exports.error=_e;exports.eventEmitter=re;exports.getHttpHeaders=de;exports.info=ge;exports.initPerformanceReporting=Oe;exports.killNetworkRequests=Y;exports.localStorageHelper=ie;exports.modules=S;exports.registerMetric=$;exports.registerReplay=ae;exports.registerThresholds=Ae;exports.reportAndRegister=Te;exports.sessionStorageHelper=ne;exports.shouldDirectEmbed=se;exports.sprigFetch=m;exports.uploadLogfile=Ee;exports.v4=ee;exports.warn=N;
@@ -0,0 +1,7 @@
1
+ "use strict";var is=Object.defineProperty;var as=(t,e,n)=>e in t?is(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Pe=(t,e,n)=>(as(t,typeof e!="symbol"?e+"":e,n),n);const b=require("./metricsReporter-FY7QqLGR.cjs");var Lt=(t=>(t[t.DomContentLoaded=0]="DomContentLoaded",t[t.Load=1]="Load",t[t.FullSnapshot=2]="FullSnapshot",t[t.IncrementalSnapshot=3]="IncrementalSnapshot",t[t.Meta=4]="Meta",t[t.Custom=5]="Custom",t[t.Plugin=6]="Plugin",t))(Lt||{});class os{constructor(e){Pe(this,"awaitingResolvers",[]);Pe(this,"activeCount",0);this.capacity=e}async acquire(){if(this.activeCount<this.capacity){this.activeCount++;return}return new Promise(e=>{this.awaitingResolvers.push(e)})}release(){const e=this.awaitingResolvers.shift();e&&this.activeCount<=this.capacity?e():this.activeCount--}async execute(e){try{return await this.acquire(),await e()}finally{this.release()}}setLimit(e){this.capacity=e}}const er=new os(2),ls=t=>er.setLimit(t),cs=async t=>er.execute(async()=>{var r;b.info(`Beginning upload of chunk ${t.chunkIndex} for survey: ${t.surveyId}`);const e=await b.sprigFetch(t.uploadUrl,{body:t.data,method:"PUT"});b.info(`Completed upload of chunk ${t.chunkIndex} for survey: ${t.surveyId}`);const n=(r=e.headers)==null?void 0:r.get("ETag");if(!n)throw new Error(`Upload response did not include etag for upload ${t.uploadId}, part ${t.chunkIndex}`);return n}),tr=async({apiUrl:t,surveyId:e,uploadId:n,etags:r,headers:s,responseGroupUuid:i,replayDuration:a,eventDigest:o},l=!1)=>{var c;if(!l&&!n&&!r){b.info(`Cannot mark upload complete: isMobile: ${l} / uploadId: ${n} / etags: ${r}`);return}b.info(`Marking upload complete for survey: ${e}`);const d=await b.sprigFetch(`${t}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:r,uploadId:n,responseGroupUuid:i,surveyId:e,replayDuration:a,eventDigest:o,userAgent:(c=window==null?void 0:window.navigator)==null?void 0:c.userAgent}),headers:s,shouldRetryRequest:!0});return b.info(`Done marking upload complete for survey: ${e}`),d},R=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,j=Object.keys,F=Array.isArray;function V(t,e){return typeof e!="object"||j(e).forEach(function(n){t[n]=e[n]}),t}typeof Promise>"u"||R.Promise||(R.Promise=Promise);const We=Object.getPrototypeOf,us={}.hasOwnProperty;function W(t,e){return us.call(t,e)}function Ke(t,e){typeof e=="function"&&(e=e(We(t))),(typeof Reflect>"u"?j:Reflect.ownKeys)(e).forEach(n=>{re(t,n,e[n])})}const nr=Object.defineProperty;function re(t,e,n,r){nr(t,e,V(n&&W(n,"get")&&typeof n.get=="function"?{get:n.get,set:n.set,configurable:!0}:{value:n,configurable:!0,writable:!0},r))}function De(t){return{from:function(e){return t.prototype=Object.create(e.prototype),re(t.prototype,"constructor",t),{extend:Ke.bind(null,t.prototype)}}}}const ds=Object.getOwnPropertyDescriptor;function wn(t,e){let n;return ds(t,e)||(n=We(t))&&wn(n,e)}const hs=[].slice;function _t(t,e,n){return hs.call(t,e,n)}function rr(t,e){return e(t)}function Fe(t){if(!t)throw new Error("Assertion Failed")}function sr(t){R.setImmediate?setImmediate(t):setTimeout(t,0)}function ir(t,e){return t.reduce((n,r,s)=>{var i=e(r,s);return i&&(n[i[0]]=i[1]),n},{})}function se(t,e){if(typeof e=="string"&&W(t,e))return t[e];if(!e)return t;if(typeof e!="string"){for(var n=[],r=0,s=e.length;r<s;++r){var i=se(t,e[r]);n.push(i)}return n}var a=e.indexOf(".");if(a!==-1){var o=t[e.substr(0,a)];return o==null?void 0:se(o,e.substr(a+1))}}function Y(t,e,n){if(t&&e!==void 0&&(!("isFrozen"in Object)||!Object.isFrozen(t)))if(typeof e!="string"&&"length"in e){Fe(typeof n!="string"&&"length"in n);for(var r=0,s=e.length;r<s;++r)Y(t,e[r],n[r])}else{var i=e.indexOf(".");if(i!==-1){var a=e.substr(0,i),o=e.substr(i+1);if(o==="")n===void 0?F(t)&&!isNaN(parseInt(a))?t.splice(a,1):delete t[a]:t[a]=n;else{var l=t[a];l&&W(t,a)||(l=t[a]={}),Y(l,o,n)}}else n===void 0?F(t)&&!isNaN(parseInt(e))?t.splice(e,1):delete t[e]:t[e]=n}}function ar(t){var e={};for(var n in t)W(t,n)&&(e[n]=t[n]);return e}const fs=[].concat;function or(t){return fs.apply([],t)}const lr="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(or([8,16,32,64].map(t=>["Int","Uint","Float"].map(e=>e+t+"Array")))).filter(t=>R[t]),ps=lr.map(t=>R[t]);ir(lr,t=>[t,!0]);let le=null;function nt(t){le=typeof WeakMap<"u"&&new WeakMap;const e=qt(t);return le=null,e}function qt(t){if(!t||typeof t!="object")return t;let e=le&&le.get(t);if(e)return e;if(F(t)){e=[],le&&le.set(t,e);for(var n=0,r=t.length;n<r;++n)e.push(qt(t[n]))}else if(ps.indexOf(t.constructor)>=0)e=t;else{const i=We(t);for(var s in e=i===Object.prototype?{}:Object.create(i),le&&le.set(t,e),t)W(t,s)&&(e[s]=qt(t[s]))}return e}const{toString:ms}={};function Ht(t){return ms.call(t).slice(8,-1)}const Vt=typeof Symbol<"u"?Symbol.iterator:"@@iterator",ys=typeof Vt=="symbol"?function(t){var e;return t!=null&&(e=t[Vt])&&e.apply(t)}:function(){return null},Te={};function te(t){var e,n,r,s;if(arguments.length===1){if(F(t))return t.slice();if(this===Te&&typeof t=="string")return[t];if(s=ys(t)){for(n=[];!(r=s.next()).done;)n.push(r.value);return n}if(t==null)return[t];if(typeof(e=t.length)=="number"){for(n=new Array(e);e--;)n[e]=t[e];return n}return[t]}for(e=arguments.length,n=new Array(e);e--;)n[e]=arguments[e];return n}const _n=typeof Symbol<"u"?t=>t[Symbol.toStringTag]==="AsyncFunction":()=>!1;var X=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function cr(t,e){X=t,ur=e}var ur=()=>!0;const gs=!new Error("").stack;function xe(){if(gs)try{throw xe.arguments,new Error}catch(t){return t}return new Error}function zt(t,e){var n=t.stack;return n?(e=e||0,n.indexOf(t.name)===0&&(e+=(t.name+t.message).split(`
2
+ `).length),n.split(`
3
+ `).slice(e).filter(ur).map(r=>`
4
+ `+r).join("")):""}var dr=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],kn=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(dr),vs={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function Oe(t,e){this._e=xe(),this.name=t,this.message=e}function hr(t,e){return t+". Errors: "+Object.keys(e).map(n=>e[n].toString()).filter((n,r,s)=>s.indexOf(n)===r).join(`
5
+ `)}function kt(t,e,n,r){this._e=xe(),this.failures=e,this.failedKeys=r,this.successCount=n,this.message=hr(t,e)}function qe(t,e){this._e=xe(),this.name="BulkError",this.failures=Object.keys(e).map(n=>e[n]),this.failuresByPos=e,this.message=hr(t,e)}De(Oe).from(Error).extend({stack:{get:function(){return this._stack||(this._stack=this.name+": "+this.message+zt(this._e,2))}},toString:function(){return this.name+": "+this.message}}),De(kt).from(Oe),De(qe).from(Oe);var En=kn.reduce((t,e)=>(t[e]=e+"Error",t),{});const bs=Oe;var I=kn.reduce((t,e)=>{var n=e+"Error";function r(s,i){this._e=xe(),this.name=n,s?typeof s=="string"?(this.message=`${s}${i?`
6
+ `+i:""}`,this.inner=i||null):typeof s=="object"&&(this.message=`${s.name} ${s.message}`,this.inner=s):(this.message=vs[e]||n,this.inner=null)}return De(r).from(bs),t[e]=r,t},{});I.Syntax=SyntaxError,I.Type=TypeError,I.Range=RangeError;var Bn=dr.reduce((t,e)=>(t[e+"Error"]=I[e],t),{}),ht=kn.reduce((t,e)=>(["Syntax","Type","Range"].indexOf(e)===-1&&(t[e+"Error"]=I[e]),t),{});function O(){}function Ye(t){return t}function ws(t,e){return t==null||t===Ye?e:function(n){return e(t(n))}}function _e(t,e){return function(){t.apply(this,arguments),e.apply(this,arguments)}}function _s(t,e){return t===O?e:function(){var n=t.apply(this,arguments);n!==void 0&&(arguments[0]=n);var r=this.onsuccess,s=this.onerror;this.onsuccess=null,this.onerror=null;var i=e.apply(this,arguments);return r&&(this.onsuccess=this.onsuccess?_e(r,this.onsuccess):r),s&&(this.onerror=this.onerror?_e(s,this.onerror):s),i!==void 0?i:n}}function ks(t,e){return t===O?e:function(){t.apply(this,arguments);var n=this.onsuccess,r=this.onerror;this.onsuccess=this.onerror=null,e.apply(this,arguments),n&&(this.onsuccess=this.onsuccess?_e(n,this.onsuccess):n),r&&(this.onerror=this.onerror?_e(r,this.onerror):r)}}function Es(t,e){return t===O?e:function(n){var r=t.apply(this,arguments);V(n,r);var s=this.onsuccess,i=this.onerror;this.onsuccess=null,this.onerror=null;var a=e.apply(this,arguments);return s&&(this.onsuccess=this.onsuccess?_e(s,this.onsuccess):s),i&&(this.onerror=this.onerror?_e(i,this.onerror):i),r===void 0?a===void 0?void 0:a:V(r,a)}}function xs(t,e){return t===O?e:function(){return e.apply(this,arguments)!==!1&&t.apply(this,arguments)}}function xn(t,e){return t===O?e:function(){var n=t.apply(this,arguments);if(n&&typeof n.then=="function"){for(var r=this,s=arguments.length,i=new Array(s);s--;)i[s]=arguments[s];return n.then(function(){return e.apply(r,i)})}return e.apply(this,arguments)}}ht.ModifyError=kt,ht.DexieError=Oe,ht.BulkError=qe;var Je={};const fr=100,[Gt,Et,Wt]=typeof Promise>"u"?[]:(()=>{let t=Promise.resolve();if(typeof crypto>"u"||!crypto.subtle)return[t,We(t),t];const e=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[e,We(e),t]})(),pr=Et&&Et.then,ft=Gt&&Gt.constructor,Sn=!!Wt;var Yt=!1,Ss=Wt?()=>{Wt.then(it)}:R.setImmediate?setImmediate.bind(null,it):R.MutationObserver?()=>{var t=document.createElement("div");new MutationObserver(()=>{it(),t=null}).observe(t,{attributes:!0}),t.setAttribute("i","1")}:()=>{setTimeout(it,0)},He=function(t,e){Le.push([t,e]),xt&&(Ss(),xt=!1)},Jt=!0,xt=!0,ve=[],pt=[],Qt=null,Xt=Ye,Re={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Mn,pgp:!1,env:{},finalize:function(){this.unhandleds.forEach(t=>{try{Mn(t[0],t[1])}catch{}})}},P=Re,Le=[],be=0,mt=[];function S(t){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this.onuncatched=O,this._lib=!1;var e=this._PSD=P;if(X&&(this._stackHolder=xe(),this._prev=null,this._numPrev=0),typeof t!="function"){if(t!==Je)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(this._state===!1&&en(this,this._value))}this._state=null,this._value=null,++e.ref,yr(this,t)}const Zt={get:function(){var t=P,e=St;function n(r,s){var i=!t.global&&(t!==P||e!==St);const a=i&&!ie();var o=new S((l,d)=>{Cn(this,new mr(Ct(r,t,i,a),Ct(s,t,i,a),l,d,t))});return X&&br(o,this),o}return n.prototype=Je,n},set:function(t){re(this,"then",t&&t.prototype===Je?Zt:{get:function(){return t},set:Zt.set})}};function mr(t,e,n,r,s){this.onFulfilled=typeof t=="function"?t:null,this.onRejected=typeof e=="function"?e:null,this.resolve=n,this.reject=r,this.psd=s}function yr(t,e){try{e(n=>{if(t._state===null){if(n===t)throw new TypeError("A promise cannot be resolved with itself.");var r=t._lib&&rt();n&&typeof n.then=="function"?yr(t,(s,i)=>{n instanceof S?n._then(s,i):n.then(s,i)}):(t._state=!0,t._value=n,gr(t)),r&&st()}},en.bind(null,t))}catch(n){en(t,n)}}function en(t,e){if(pt.push(e),t._state===null){var n=t._lib&&rt();e=Xt(e),t._state=!1,t._value=e,X&&e!==null&&typeof e=="object"&&!e._promise&&function(r,s,i){try{r.apply(null,i)}catch{}}(()=>{var r=wn(e,"stack");e._promise=t,re(e,"stack",{get:()=>Yt?r&&(r.get?r.get.apply(e):r.value):t.stack})}),function(r){ve.some(s=>s._value===r._value)||ve.push(r)}(t),gr(t),n&&st()}}function gr(t){var e=t._listeners;t._listeners=[];for(var n=0,r=e.length;n<r;++n)Cn(t,e[n]);var s=t._PSD;--s.ref||s.finalize(),be===0&&(++be,He(()=>{--be==0&&Pn()},[]))}function Cn(t,e){if(t._state!==null){var n=t._state?e.onFulfilled:e.onRejected;if(n===null)return(t._state?e.resolve:e.reject)(t._value);++e.psd.ref,++be,He(Cs,[n,t,e])}else t._listeners.push(e)}function Cs(t,e,n){try{Qt=e;var r,s=e._value;e._state?r=t(s):(pt.length&&(pt=[]),r=t(s),pt.indexOf(s)===-1&&function(i){for(var a=ve.length;a;)if(ve[--a]._value===i._value)return void ve.splice(a,1)}(e)),n.resolve(r)}catch(i){n.reject(i)}finally{Qt=null,--be==0&&Pn(),--n.psd.ref||n.psd.finalize()}}function vr(t,e,n){if(e.length===n)return e;var r="";if(t._state===!1){var s,i,a=t._value;a!=null?(s=a.name||"Error",i=a.message||a,r=zt(a,0)):(s=a,i=""),e.push(s+(i?": "+i:"")+r)}return X&&((r=zt(t._stackHolder,2))&&e.indexOf(r)===-1&&e.push(r),t._prev&&vr(t._prev,e,n)),e}function br(t,e){var n=e?e._numPrev+1:0;n<100&&(t._prev=e,t._numPrev=n)}function it(){rt()&&st()}function rt(){var t=Jt;return Jt=!1,xt=!1,t}function st(){var t,e,n;do for(;Le.length>0;)for(t=Le,Le=[],n=t.length,e=0;e<n;++e){var r=t[e];r[0].apply(null,r[1])}while(Le.length>0);Jt=!0,xt=!0}function Pn(){var t=ve;ve=[],t.forEach(r=>{r._PSD.onunhandled.call(null,r._value,r)});for(var e=mt.slice(0),n=e.length;n;)e[--n]()}function at(t){return new S(Je,!1,t)}function K(t,e){var n=P;return function(){var r=rt(),s=P;try{return fe(n,!0),t.apply(this,arguments)}catch(i){e&&e(i)}finally{fe(s,!1),r&&st()}}}Ke(S.prototype,{then:Zt,_then:function(t,e){Cn(this,new mr(null,null,t,e,P))},catch:function(t){if(arguments.length===1)return this.then(null,t);var e=arguments[0],n=arguments[1];return typeof e=="function"?this.then(null,r=>r instanceof e?n(r):at(r)):this.then(null,r=>r&&r.name===e?n(r):at(r))},finally:function(t){return this.then(e=>(t(),e),e=>(t(),at(e)))},stack:{get:function(){if(this._stack)return this._stack;try{Yt=!0;var t=vr(this,[],20).join(`
7
+ From previous: `);return this._state!==null&&(this._stack=t),t}finally{Yt=!1}}},timeout:function(t,e){return t<1/0?new S((n,r)=>{var s=setTimeout(()=>r(new I.Timeout(e)),t);this.then(n,r).finally(clearTimeout.bind(null,s))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&re(S.prototype,Symbol.toStringTag,"Dexie.Promise"),Re.env=wr(),Ke(S,{all:function(){var t=te.apply(null,arguments).map(ot);return new S(function(e,n){t.length===0&&e([]);var r=t.length;t.forEach((s,i)=>S.resolve(s).then(a=>{t[i]=a,--r||e(t)},n))})},resolve:t=>{if(t instanceof S)return t;if(t&&typeof t.then=="function")return new S((n,r)=>{t.then(n,r)});var e=new S(Je,!0,t);return br(e,Qt),e},reject:at,race:function(){var t=te.apply(null,arguments).map(ot);return new S((e,n)=>{t.map(r=>S.resolve(r).then(e,n))})},PSD:{get:()=>P,set:t=>P=t},totalEchoes:{get:()=>St},newPSD:he,usePSD:Ne,scheduler:{get:()=>He,set:t=>{He=t}},rejectionMapper:{get:()=>Xt,set:t=>{Xt=t}},follow:(t,e)=>new S((n,r)=>he((s,i)=>{var a=P;a.unhandleds=[],a.onunhandled=i,a.finalize=_e(function(){(function(o){function l(){o(),mt.splice(mt.indexOf(l),1)}mt.push(l),++be,He(()=>{--be==0&&Pn()},[])})(()=>{this.unhandleds.length===0?s():i(this.unhandleds[0])})},a.finalize),t()},e,n,r))}),ft&&(ft.allSettled&&re(S,"allSettled",function(){const t=te.apply(null,arguments).map(ot);return new S(e=>{t.length===0&&e([]);let n=t.length;const r=new Array(n);t.forEach((s,i)=>S.resolve(s).then(a=>r[i]={status:"fulfilled",value:a},a=>r[i]={status:"rejected",reason:a}).then(()=>--n||e(r)))})}),ft.any&&typeof AggregateError<"u"&&re(S,"any",function(){const t=te.apply(null,arguments).map(ot);return new S((e,n)=>{t.length===0&&n(new AggregateError([]));let r=t.length;const s=new Array(r);t.forEach((i,a)=>S.resolve(i).then(o=>e(o),o=>{s[a]=o,--r||n(new AggregateError(s))}))})}));const U={awaits:0,echoes:0,id:0};var Ps=0,yt=[],Kt=0,St=0,Is=0;function he(t,e,n,r){var s=P,i=Object.create(s);i.parent=s,i.ref=0,i.global=!1,i.id=++Is;var a=Re.env;i.env=Sn?{Promise:S,PromiseProp:{value:S,configurable:!0,writable:!0},all:S.all,race:S.race,allSettled:S.allSettled,any:S.any,resolve:S.resolve,reject:S.reject,nthen:Nn(a.nthen,i),gthen:Nn(a.gthen,i)}:{},e&&V(i,e),++s.ref,i.finalize=function(){--this.parent.ref||this.parent.finalize()};var o=Ne(i,t,n,r);return i.ref===0&&i.finalize(),o}function Be(){return U.id||(U.id=++Ps),++U.awaits,U.echoes+=fr,U.id}function ie(){return!!U.awaits&&(--U.awaits==0&&(U.id=0),U.echoes=U.awaits*fr,!0)}function ot(t){return U.echoes&&t&&t.constructor===ft?(Be(),t.then(e=>(ie(),e),e=>(ie(),M(e)))):t}function As(t){++St,U.echoes&&--U.echoes!=0||(U.echoes=U.id=0),yt.push(P),fe(t,!0)}function Ts(){var t=yt[yt.length-1];yt.pop(),fe(t,!1)}function fe(t,e){var n=P;if((e?!U.echoes||Kt++&&t===P:!Kt||--Kt&&t===P)||_r(e?As.bind(null,t):Ts),t!==P&&(P=t,n===Re&&(Re.env=wr()),Sn)){var r=Re.env.Promise,s=t.env;Et.then=s.nthen,r.prototype.then=s.gthen,(n.global||t.global)&&(Object.defineProperty(R,"Promise",s.PromiseProp),r.all=s.all,r.race=s.race,r.resolve=s.resolve,r.reject=s.reject,s.allSettled&&(r.allSettled=s.allSettled),s.any&&(r.any=s.any))}}function wr(){var t=R.Promise;return Sn?{Promise:t,PromiseProp:Object.getOwnPropertyDescriptor(R,"Promise"),all:t.all,race:t.race,allSettled:t.allSettled,any:t.any,resolve:t.resolve,reject:t.reject,nthen:Et.then,gthen:t.prototype.then}:{}}function Ne(t,e,n,r,s){var i=P;try{return fe(t,!0),e(n,r,s)}finally{fe(i,!1)}}function _r(t){pr.call(Gt,t)}function Ct(t,e,n,r){return typeof t!="function"?t:function(){var s=P;n&&Be(),fe(e,!0);try{return t.apply(this,arguments)}finally{fe(s,!1),r&&_r(ie)}}}function Nn(t,e){return function(n,r){return t.call(this,Ct(n,e),Ct(r,e))}}(""+pr).indexOf("[native code]")===-1&&(Be=ie=O);const jn="unhandledrejection";function Mn(t,e){var n;try{n=e.onuncatched(t)}catch{}if(n!==!1)try{var r,s={promise:e,reason:t};if(R.document&&document.createEvent?((r=document.createEvent("Event")).initEvent(jn,!0,!0),V(r,s)):R.CustomEvent&&V(r=new CustomEvent(jn,{detail:s}),s),r&&R.dispatchEvent&&(dispatchEvent(r),!R.PromiseRejectionEvent&&R.onunhandledrejection))try{R.onunhandledrejection(r)}catch{}X&&r&&!r.defaultPrevented&&console.warn(`Unhandled rejection: ${t.stack||t}`)}catch{}}var M=S.reject;function tn(t,e,n,r){if(t.idbdb&&(t._state.openComplete||P.letThrough||t._vip)){var s=t._createTransaction(e,n,t._dbSchema);try{s.create(),t._state.PR1398_maxLoop=3}catch(i){return i.name===En.InvalidState&&t.isOpen()&&--t._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),t._close(),t.open().then(()=>tn(t,e,n,r))):M(i)}return s._promise(e,(i,a)=>he(()=>(P.trans=s,r(i,a,s)))).then(i=>s._completion.then(()=>i))}if(t._state.openComplete)return M(new I.DatabaseClosed(t._state.dbOpenError));if(!t._state.isBeingOpened){if(!t._options.autoOpen)return M(new I.DatabaseClosed);t.open().catch(O)}return t._state.dbReadyPromise.then(()=>tn(t,e,n,r))}const $n="3.2.7",ge="￿",nn=-1/0,Z="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",kr="String expected.",Ve=[],Dt=typeof navigator<"u"&&/(MSIE|Trident|Edge)/.test(navigator.userAgent),Ds=Dt,Os=Dt,Er=t=>!/(dexie\.js|dexie\.min\.js)/.test(t),Ot="__dbnames",Bt="readonly",Nt="readwrite";function ke(t,e){return t?e?function(){return t.apply(this,arguments)&&e.apply(this,arguments)}:t:e}const xr={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function lt(t){return typeof t!="string"||/\./.test(t)?e=>e:e=>(e[t]===void 0&&t in e&&delete(e=nt(e))[t],e)}class Rs{_trans(e,n,r){const s=this._tx||P.trans,i=this.name;function a(l,d,c){if(!c.schema[i])throw new I.NotFound("Table "+i+" not part of transaction");return n(c.idbtrans,c)}const o=rt();try{return s&&s.db===this.db?s===P.trans?s._promise(e,a,r):he(()=>s._promise(e,a,r),{trans:s,transless:P.transless||P}):tn(this.db,e,[this.name],a)}finally{o&&st()}}get(e,n){return e&&e.constructor===Object?this.where(e).first(n):this._trans("readonly",r=>this.core.get({trans:r,key:e}).then(s=>this.hook.reading.fire(s))).then(n)}where(e){if(typeof e=="string")return new this.db.WhereClause(this,e);if(F(e))return new this.db.WhereClause(this,`[${e.join("+")}]`);const n=j(e);if(n.length===1)return this.where(n[0]).equals(e[n[0]]);const r=this.schema.indexes.concat(this.schema.primKey).filter(d=>{if(d.compound&&n.every(c=>d.keyPath.indexOf(c)>=0)){for(let c=0;c<n.length;++c)if(n.indexOf(d.keyPath[c])===-1)return!1;return!0}return!1}).sort((d,c)=>d.keyPath.length-c.keyPath.length)[0];if(r&&this.db._maxKey!==ge){const d=r.keyPath.slice(0,n.length);return this.where(d).equals(d.map(c=>e[c]))}!r&&X&&console.warn(`The query ${JSON.stringify(e)} on ${this.name} would benefit of a compound index [${n.join("+")}]`);const{idxByName:s}=this.schema,i=this.db._deps.indexedDB;function a(d,c){try{return i.cmp(d,c)===0}catch{return!1}}const[o,l]=n.reduce(([d,c],h)=>{const u=s[h],f=e[h];return[d||u,d||!u?ke(c,u&&u.multi?g=>{const y=se(g,h);return F(y)&&y.some(v=>a(f,v))}:g=>a(f,se(g,h))):c]},[null,null]);return o?this.where(o.name).equals(e[o.keyPath]).filter(l):r?this.filter(l):this.where(n).equals("")}filter(e){return this.toCollection().and(e)}count(e){return this.toCollection().count(e)}offset(e){return this.toCollection().offset(e)}limit(e){return this.toCollection().limit(e)}each(e){return this.toCollection().each(e)}toArray(e){return this.toCollection().toArray(e)}toCollection(){return new this.db.Collection(new this.db.WhereClause(this))}orderBy(e){return new this.db.Collection(new this.db.WhereClause(this,F(e)?`[${e.join("+")}]`:e))}reverse(){return this.toCollection().reverse()}mapToClass(e){this.schema.mappedClass=e;const n=r=>{if(!r)return r;const s=Object.create(e.prototype);for(var i in r)if(W(r,i))try{s[i]=r[i]}catch{}return s};return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=n,this.hook("reading",n),e}defineClass(){return this.mapToClass(function(e){V(this,e)})}add(e,n){const{auto:r,keyPath:s}=this.schema.primKey;let i=e;return s&&r&&(i=lt(s)(e)),this._trans("readwrite",a=>this.core.mutate({trans:a,type:"add",keys:n!=null?[n]:null,values:[i]})).then(a=>a.numFailures?S.reject(a.failures[0]):a.lastResult).then(a=>{if(s)try{Y(e,s,a)}catch{}return a})}update(e,n){if(typeof e!="object"||F(e))return this.where(":id").equals(e).modify(n);{const r=se(e,this.schema.primKey.keyPath);if(r===void 0)return M(new I.InvalidArgument("Given object does not contain its primary key"));try{typeof n!="function"?j(n).forEach(s=>{Y(e,s,n[s])}):n(e,{value:e,primKey:r})}catch{}return this.where(":id").equals(r).modify(n)}}put(e,n){const{auto:r,keyPath:s}=this.schema.primKey;let i=e;return s&&r&&(i=lt(s)(e)),this._trans("readwrite",a=>this.core.mutate({trans:a,type:"put",values:[i],keys:n!=null?[n]:null})).then(a=>a.numFailures?S.reject(a.failures[0]):a.lastResult).then(a=>{if(s)try{Y(e,s,a)}catch{}return a})}delete(e){return this._trans("readwrite",n=>this.core.mutate({trans:n,type:"delete",keys:[e]})).then(n=>n.numFailures?S.reject(n.failures[0]):void 0)}clear(){return this._trans("readwrite",e=>this.core.mutate({trans:e,type:"deleteRange",range:xr})).then(e=>e.numFailures?S.reject(e.failures[0]):void 0)}bulkGet(e){return this._trans("readonly",n=>this.core.getMany({keys:e,trans:n}).then(r=>r.map(s=>this.hook.reading.fire(s))))}bulkAdd(e,n,r){const s=Array.isArray(n)?n:void 0,i=(r=r||(s?void 0:n))?r.allKeys:void 0;return this._trans("readwrite",a=>{const{auto:o,keyPath:l}=this.schema.primKey;if(l&&s)throw new I.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(s&&s.length!==e.length)throw new I.InvalidArgument("Arguments objects and keys must have the same length");const d=e.length;let c=l&&o?e.map(lt(l)):e;return this.core.mutate({trans:a,type:"add",keys:s,values:c,wantResults:i}).then(({numFailures:h,results:u,lastResult:f,failures:g})=>{if(h===0)return i?u:f;throw new qe(`${this.name}.bulkAdd(): ${h} of ${d} operations failed`,g)})})}bulkPut(e,n,r){const s=Array.isArray(n)?n:void 0,i=(r=r||(s?void 0:n))?r.allKeys:void 0;return this._trans("readwrite",a=>{const{auto:o,keyPath:l}=this.schema.primKey;if(l&&s)throw new I.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(s&&s.length!==e.length)throw new I.InvalidArgument("Arguments objects and keys must have the same length");const d=e.length;let c=l&&o?e.map(lt(l)):e;return this.core.mutate({trans:a,type:"put",keys:s,values:c,wantResults:i}).then(({numFailures:h,results:u,lastResult:f,failures:g})=>{if(h===0)return i?u:f;throw new qe(`${this.name}.bulkPut(): ${h} of ${d} operations failed`,g)})})}bulkDelete(e){const n=e.length;return this._trans("readwrite",r=>this.core.mutate({trans:r,type:"delete",keys:e})).then(({numFailures:r,lastResult:s,failures:i})=>{if(r===0)return s;throw new qe(`${this.name}.bulkDelete(): ${r} of ${n} operations failed`,i)})}}function ze(t){var e={},n=function(a,o){if(o){for(var l=arguments.length,d=new Array(l-1);--l;)d[l-1]=arguments[l];return e[a].subscribe.apply(null,d),t}if(typeof a=="string")return e[a]};n.addEventType=i;for(var r=1,s=arguments.length;r<s;++r)i(arguments[r]);return n;function i(a,o,l){if(typeof a!="object"){var d;o||(o=xs),l||(l=O);var c={subscribers:[],fire:l,subscribe:function(h){c.subscribers.indexOf(h)===-1&&(c.subscribers.push(h),c.fire=o(c.fire,h))},unsubscribe:function(h){c.subscribers=c.subscribers.filter(function(u){return u!==h}),c.fire=c.subscribers.reduce(o,l)}};return e[a]=n[a]=c,c}j(d=a).forEach(function(h){var u=d[h];if(F(u))i(h,d[h][0],d[h][1]);else{if(u!=="asap")throw new I.InvalidArgument("Invalid event config");var f=i(h,Ye,function(){for(var g=arguments.length,y=new Array(g);g--;)y[g]=arguments[g];f.subscribers.forEach(function(v){sr(function(){v.apply(null,y)})})})}})}}function $e(t,e){return De(e).from({prototype:t}),e}function Ie(t,e){return!(t.filter||t.algorithm||t.or)&&(e?t.justLimit:!t.replayFilter)}function jt(t,e){t.filter=ke(t.filter,e)}function Mt(t,e,n){var r=t.replayFilter;t.replayFilter=r?()=>ke(r(),e()):e,t.justLimit=n&&!r}function gt(t,e){if(t.isPrimKey)return e.primaryKey;const n=e.getIndexByKeyPath(t.index);if(!n)throw new I.Schema("KeyPath "+t.index+" on object store "+e.name+" is not indexed");return n}function Un(t,e,n){const r=gt(t,e.schema);return e.openCursor({trans:n,values:!t.keysOnly,reverse:t.dir==="prev",unique:!!t.unique,query:{index:r,range:t.range}})}function ct(t,e,n,r){const s=t.replayFilter?ke(t.filter,t.replayFilter()):t.filter;if(t.or){const i={},a=(o,l,d)=>{if(!s||s(l,d,u=>l.stop(u),u=>l.fail(u))){var c=l.primaryKey,h=""+c;h==="[object ArrayBuffer]"&&(h=""+new Uint8Array(c)),W(i,h)||(i[h]=!0,e(o,l,d))}};return Promise.all([t.or._iterate(a,n),Fn(Un(t,r,n),t.algorithm,a,!t.keysOnly&&t.valueMapper)])}return Fn(Un(t,r,n),ke(t.algorithm,s),e,!t.keysOnly&&t.valueMapper)}function Fn(t,e,n,r){var s=K(r?(i,a,o)=>n(r(i),a,o):n);return t.then(i=>{if(i)return i.start(()=>{var a=()=>i.continue();e&&!e(i,o=>a=o,o=>{i.stop(o),a=O},o=>{i.fail(o),a=O})||s(i.value,i,o=>a=o),a()})})}function H(t,e){try{const n=Ln(t),r=Ln(e);if(n!==r)return n==="Array"?1:r==="Array"?-1:n==="binary"?1:r==="binary"?-1:n==="string"?1:r==="string"?-1:n==="Date"?1:r!=="Date"?NaN:-1;switch(n){case"number":case"Date":case"string":return t>e?1:t<e?-1:0;case"binary":return function(s,i){const a=s.length,o=i.length,l=a<o?a:o;for(let d=0;d<l;++d)if(s[d]!==i[d])return s[d]<i[d]?-1:1;return a===o?0:a<o?-1:1}(qn(t),qn(e));case"Array":return function(s,i){const a=s.length,o=i.length,l=a<o?a:o;for(let d=0;d<l;++d){const c=H(s[d],i[d]);if(c!==0)return c}return a===o?0:a<o?-1:1}(t,e)}}catch{}return NaN}function Ln(t){const e=typeof t;if(e!=="object")return e;if(ArrayBuffer.isView(t))return"binary";const n=Ht(t);return n==="ArrayBuffer"?"binary":n}function qn(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t)}class Ks{_read(e,n){var r=this._ctx;return r.error?r.table._trans(null,M.bind(null,r.error)):r.table._trans("readonly",e).then(n)}_write(e){var n=this._ctx;return n.error?n.table._trans(null,M.bind(null,n.error)):n.table._trans("readwrite",e,"locked")}_addAlgorithm(e){var n=this._ctx;n.algorithm=ke(n.algorithm,e)}_iterate(e,n){return ct(this._ctx,e,n,this._ctx.table.core)}clone(e){var n=Object.create(this.constructor.prototype),r=Object.create(this._ctx);return e&&V(r,e),n._ctx=r,n}raw(){return this._ctx.valueMapper=null,this}each(e){var n=this._ctx;return this._read(r=>ct(n,e,r,n.table.core))}count(e){return this._read(n=>{const r=this._ctx,s=r.table.core;if(Ie(r,!0))return s.count({trans:n,query:{index:gt(r,s.schema),range:r.range}}).then(a=>Math.min(a,r.limit));var i=0;return ct(r,()=>(++i,!1),n,s).then(()=>i)}).then(e)}sortBy(e,n){const r=e.split(".").reverse(),s=r[0],i=r.length-1;function a(d,c){return c?a(d[r[c]],c-1):d[s]}var o=this._ctx.dir==="next"?1:-1;function l(d,c){var h=a(d,i),u=a(c,i);return h<u?-o:h>u?o:0}return this.toArray(function(d){return d.sort(l)}).then(n)}toArray(e){return this._read(n=>{var r=this._ctx;if(r.dir==="next"&&Ie(r,!0)&&r.limit>0){const{valueMapper:s}=r,i=gt(r,r.table.core.schema);return r.table.core.query({trans:n,limit:r.limit,values:!0,query:{index:i,range:r.range}}).then(({result:a})=>s?a.map(s):a)}{const s=[];return ct(r,i=>s.push(i),n,r.table.core).then(()=>s)}},e)}offset(e){var n=this._ctx;return e<=0||(n.offset+=e,Ie(n)?Mt(n,()=>{var r=e;return(s,i)=>r===0||(r===1?(--r,!1):(i(()=>{s.advance(r),r=0}),!1))}):Mt(n,()=>{var r=e;return()=>--r<0})),this}limit(e){return this._ctx.limit=Math.min(this._ctx.limit,e),Mt(this._ctx,()=>{var n=e;return function(r,s,i){return--n<=0&&s(i),n>=0}},!0),this}until(e,n){return jt(this._ctx,function(r,s,i){return!e(r.value)||(s(i),n)}),this}first(e){return this.limit(1).toArray(function(n){return n[0]}).then(e)}last(e){return this.reverse().first(e)}filter(e){var n,r;return jt(this._ctx,function(s){return e(s.value)}),n=this._ctx,r=e,n.isMatch=ke(n.isMatch,r),this}and(e){return this.filter(e)}or(e){return new this.db.WhereClause(this._ctx.table,e,this)}reverse(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this}desc(){return this.reverse()}eachKey(e){var n=this._ctx;return n.keysOnly=!n.isMatch,this.each(function(r,s){e(s.key,s)})}eachUniqueKey(e){return this._ctx.unique="unique",this.eachKey(e)}eachPrimaryKey(e){var n=this._ctx;return n.keysOnly=!n.isMatch,this.each(function(r,s){e(s.primaryKey,s)})}keys(e){var n=this._ctx;n.keysOnly=!n.isMatch;var r=[];return this.each(function(s,i){r.push(i.key)}).then(function(){return r}).then(e)}primaryKeys(e){var n=this._ctx;if(n.dir==="next"&&Ie(n,!0)&&n.limit>0)return this._read(s=>{var i=gt(n,n.table.core.schema);return n.table.core.query({trans:s,values:!1,limit:n.limit,query:{index:i,range:n.range}})}).then(({result:s})=>s).then(e);n.keysOnly=!n.isMatch;var r=[];return this.each(function(s,i){r.push(i.primaryKey)}).then(function(){return r}).then(e)}uniqueKeys(e){return this._ctx.unique="unique",this.keys(e)}firstKey(e){return this.limit(1).keys(function(n){return n[0]}).then(e)}lastKey(e){return this.reverse().firstKey(e)}distinct(){var e=this._ctx,n=e.index&&e.table.schema.idxByName[e.index];if(!n||!n.multi)return this;var r={};return jt(this._ctx,function(s){var i=s.primaryKey.toString(),a=W(r,i);return r[i]=!0,!a}),this}modify(e){var n=this._ctx;return this._write(r=>{var s;if(typeof e=="function")s=e;else{var i=j(e),a=i.length;s=function(y){for(var v=!1,m=0;m<a;++m){var p=i[m],_=e[p];se(y,p)!==_&&(Y(y,p,_),v=!0)}return v}}const o=n.table.core,{outbound:l,extractKey:d}=o.schema.primaryKey,c=this.db._options.modifyChunkSize||200,h=[];let u=0;const f=[],g=(y,v)=>{const{failures:m,numFailures:p}=v;u+=y-p;for(let _ of j(m))h.push(m[_])};return this.clone().primaryKeys().then(y=>{const v=m=>{const p=Math.min(c,y.length-m);return o.getMany({trans:r,keys:y.slice(m,m+p),cache:"immutable"}).then(_=>{const x=[],C=[],E=l?[]:null,w=[];for(let k=0;k<p;++k){const B=_[k],D={value:nt(B),primKey:y[m+k]};s.call(D,D.value,D)!==!1&&(D.value==null?w.push(y[m+k]):l||H(d(B),d(D.value))===0?(C.push(D.value),l&&E.push(y[m+k])):(w.push(y[m+k]),x.push(D.value)))}const T=Ie(n)&&n.limit===1/0&&(typeof e!="function"||e===$t)&&{index:n.index,range:n.range};return Promise.resolve(x.length>0&&o.mutate({trans:r,type:"add",values:x}).then(k=>{for(let B in k.failures)w.splice(parseInt(B),1);g(x.length,k)})).then(()=>(C.length>0||T&&typeof e=="object")&&o.mutate({trans:r,type:"put",keys:E,values:C,criteria:T,changeSpec:typeof e!="function"&&e}).then(k=>g(C.length,k))).then(()=>(w.length>0||T&&e===$t)&&o.mutate({trans:r,type:"delete",keys:w,criteria:T}).then(k=>g(w.length,k))).then(()=>y.length>m+p&&v(m+c))})};return v(0).then(()=>{if(h.length>0)throw new kt("Error modifying one or more objects",h,u,f);return y.length})})})}delete(){var e=this._ctx,n=e.range;return Ie(e)&&(e.isPrimKey&&!Os||n.type===3)?this._write(r=>{const{primaryKey:s}=e.table.core.schema,i=n;return e.table.core.count({trans:r,query:{index:s,range:i}}).then(a=>e.table.core.mutate({trans:r,type:"deleteRange",range:i}).then(({failures:o,lastResult:l,results:d,numFailures:c})=>{if(c)throw new kt("Could not delete some values",Object.keys(o).map(h=>o[h]),a-c);return a-c}))}):this.modify($t)}}const $t=(t,e)=>e.value=null;function Bs(t,e){return t<e?-1:t===e?0:1}function Ns(t,e){return t>e?-1:t===e?0:1}function G(t,e,n){var r=t instanceof Cr?new t.Collection(t):t;return r._ctx.error=n?new n(e):new TypeError(e),r}function Ae(t){return new t.Collection(t,()=>Sr("")).limit(0)}function js(t,e,n,r,s,i){for(var a=Math.min(t.length,r.length),o=-1,l=0;l<a;++l){var d=e[l];if(d!==r[l])return s(t[l],n[l])<0?t.substr(0,l)+n[l]+n.substr(l+1):s(t[l],r[l])<0?t.substr(0,l)+r[l]+n.substr(l+1):o>=0?t.substr(0,o)+e[o]+n.substr(o+1):null;s(t[l],d)<0&&(o=l)}return a<r.length&&i==="next"?t+n.substr(t.length):a<t.length&&i==="prev"?t.substr(0,n.length):o<0?null:t.substr(0,o)+r[o]+n.substr(o+1)}function ut(t,e,n,r){var s,i,a,o,l,d,c,h=n.length;if(!n.every(y=>typeof y=="string"))return G(t,kr);function u(y){s=function(m){return m==="next"?p=>p.toUpperCase():p=>p.toLowerCase()}(y),i=function(m){return m==="next"?p=>p.toLowerCase():p=>p.toUpperCase()}(y),a=y==="next"?Bs:Ns;var v=n.map(function(m){return{lower:i(m),upper:s(m)}}).sort(function(m,p){return a(m.lower,p.lower)});o=v.map(function(m){return m.upper}),l=v.map(function(m){return m.lower}),d=y,c=y==="next"?"":r}u("next");var f=new t.Collection(t,()=>oe(o[0],l[h-1]+r));f._ondirectionchange=function(y){u(y)};var g=0;return f._addAlgorithm(function(y,v,m){var p=y.key;if(typeof p!="string")return!1;var _=i(p);if(e(_,l,g))return!0;for(var x=null,C=g;C<h;++C){var E=js(p,_,o[C],l[C],a,d);E===null&&x===null?g=C+1:(x===null||a(x,E)>0)&&(x=E)}return v(x!==null?function(){y.continue(x+c)}:m),!1}),f}function oe(t,e,n,r){return{type:2,lower:t,upper:e,lowerOpen:n,upperOpen:r}}function Sr(t){return{type:1,lower:t,upper:t}}class Cr{get Collection(){return this._ctx.table.db.Collection}between(e,n,r,s){r=r!==!1,s=s===!0;try{return this._cmp(e,n)>0||this._cmp(e,n)===0&&(r||s)&&(!r||!s)?Ae(this):new this.Collection(this,()=>oe(e,n,!r,!s))}catch{return G(this,Z)}}equals(e){return e==null?G(this,Z):new this.Collection(this,()=>Sr(e))}above(e){return e==null?G(this,Z):new this.Collection(this,()=>oe(e,void 0,!0))}aboveOrEqual(e){return e==null?G(this,Z):new this.Collection(this,()=>oe(e,void 0,!1))}below(e){return e==null?G(this,Z):new this.Collection(this,()=>oe(void 0,e,!1,!0))}belowOrEqual(e){return e==null?G(this,Z):new this.Collection(this,()=>oe(void 0,e))}startsWith(e){return typeof e!="string"?G(this,kr):this.between(e,e+ge,!0,!0)}startsWithIgnoreCase(e){return e===""?this.startsWith(e):ut(this,(n,r)=>n.indexOf(r[0])===0,[e],ge)}equalsIgnoreCase(e){return ut(this,(n,r)=>n===r[0],[e],"")}anyOfIgnoreCase(){var e=te.apply(Te,arguments);return e.length===0?Ae(this):ut(this,(n,r)=>r.indexOf(n)!==-1,e,"")}startsWithAnyOfIgnoreCase(){var e=te.apply(Te,arguments);return e.length===0?Ae(this):ut(this,(n,r)=>r.some(s=>n.indexOf(s)===0),e,ge)}anyOf(){const e=te.apply(Te,arguments);let n=this._cmp;try{e.sort(n)}catch{return G(this,Z)}if(e.length===0)return Ae(this);const r=new this.Collection(this,()=>oe(e[0],e[e.length-1]));r._ondirectionchange=i=>{n=i==="next"?this._ascending:this._descending,e.sort(n)};let s=0;return r._addAlgorithm((i,a,o)=>{const l=i.key;for(;n(l,e[s])>0;)if(++s,s===e.length)return a(o),!1;return n(l,e[s])===0||(a(()=>{i.continue(e[s])}),!1)}),r}notEqual(e){return this.inAnyRange([[nn,e],[e,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})}noneOf(){const e=te.apply(Te,arguments);if(e.length===0)return new this.Collection(this);try{e.sort(this._ascending)}catch{return G(this,Z)}const n=e.reduce((r,s)=>r?r.concat([[r[r.length-1][1],s]]):[[nn,s]],null);return n.push([e[e.length-1],this.db._maxKey]),this.inAnyRange(n,{includeLowers:!1,includeUppers:!1})}inAnyRange(e,n){const r=this._cmp,s=this._ascending,i=this._descending,a=this._min,o=this._max;if(e.length===0)return Ae(this);if(!e.every(p=>p[0]!==void 0&&p[1]!==void 0&&s(p[0],p[1])<=0))return G(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",I.InvalidArgument);const l=!n||n.includeLowers!==!1,d=n&&n.includeUppers===!0;let c,h=s;function u(p,_){return h(p[0],_[0])}try{c=e.reduce(function(p,_){let x=0,C=p.length;for(;x<C;++x){const E=p[x];if(r(_[0],E[1])<0&&r(_[1],E[0])>0){E[0]=a(E[0],_[0]),E[1]=o(E[1],_[1]);break}}return x===C&&p.push(_),p},[]),c.sort(u)}catch{return G(this,Z)}let f=0;const g=d?p=>s(p,c[f][1])>0:p=>s(p,c[f][1])>=0,y=l?p=>i(p,c[f][0])>0:p=>i(p,c[f][0])>=0;let v=g;const m=new this.Collection(this,()=>oe(c[0][0],c[c.length-1][1],!l,!d));return m._ondirectionchange=p=>{p==="next"?(v=g,h=s):(v=y,h=i),c.sort(u)},m._addAlgorithm((p,_,x)=>{for(var C=p.key;v(C);)if(++f,f===c.length)return _(x),!1;return!!function(E){return!g(E)&&!y(E)}(C)||(this._cmp(C,c[f][1])===0||this._cmp(C,c[f][0])===0||_(()=>{h===s?p.continue(c[f][0]):p.continue(c[f][1])}),!1)}),m}startsWithAnyOf(){const e=te.apply(Te,arguments);return e.every(n=>typeof n=="string")?e.length===0?Ae(this):this.inAnyRange(e.map(n=>[n,n+ge])):G(this,"startsWithAnyOf() only works with strings")}}function Q(t){return K(function(e){return Qe(e),t(e.target.error),!1})}function Qe(t){t.stopPropagation&&t.stopPropagation(),t.preventDefault&&t.preventDefault()}const Xe="storagemutated",ce="x-storagemutated-1",pe=ze(null,Xe);class Ms{_lock(){return Fe(!P.global),++this._reculock,this._reculock!==1||P.global||(P.lockOwnerFor=this),this}_unlock(){if(Fe(!P.global),--this._reculock==0)for(P.global||(P.lockOwnerFor=null);this._blockedFuncs.length>0&&!this._locked();){var e=this._blockedFuncs.shift();try{Ne(e[1],e[0])}catch{}}return this}_locked(){return this._reculock&&P.lockOwnerFor!==this}create(e){if(!this.mode)return this;const n=this.db.idbdb,r=this.db._state.dbOpenError;if(Fe(!this.idbtrans),!e&&!n)switch(r&&r.name){case"DatabaseClosedError":throw new I.DatabaseClosed(r);case"MissingAPIError":throw new I.MissingAPI(r.message,r);default:throw new I.OpenFailed(r)}if(!this.active)throw new I.TransactionInactive;return Fe(this._completion._state===null),(e=this.idbtrans=e||(this.db.core?this.db.core.transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability}):n.transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability}))).onerror=K(s=>{Qe(s),this._reject(e.error)}),e.onabort=K(s=>{Qe(s),this.active&&this._reject(new I.Abort(e.error)),this.active=!1,this.on("abort").fire(s)}),e.oncomplete=K(()=>{this.active=!1,this._resolve(),"mutatedParts"in e&&pe.storagemutated.fire(e.mutatedParts)}),this}_promise(e,n,r){if(e==="readwrite"&&this.mode!=="readwrite")return M(new I.ReadOnly("Transaction is readonly"));if(!this.active)return M(new I.TransactionInactive);if(this._locked())return new S((i,a)=>{this._blockedFuncs.push([()=>{this._promise(e,n,r).then(i,a)},P])});if(r)return he(()=>{var i=new S((a,o)=>{this._lock();const l=n(a,o,this);l&&l.then&&l.then(a,o)});return i.finally(()=>this._unlock()),i._lib=!0,i});var s=new S((i,a)=>{var o=n(i,a,this);o&&o.then&&o.then(i,a)});return s._lib=!0,s}_root(){return this.parent?this.parent._root():this}waitFor(e){var n=this._root();const r=S.resolve(e);if(n._waitingFor)n._waitingFor=n._waitingFor.then(()=>r);else{n._waitingFor=r,n._waitingQueue=[];var s=n.idbtrans.objectStore(n.storeNames[0]);(function a(){for(++n._spinCount;n._waitingQueue.length;)n._waitingQueue.shift()();n._waitingFor&&(s.get(-1/0).onsuccess=a)})()}var i=n._waitingFor;return new S((a,o)=>{r.then(l=>n._waitingQueue.push(K(a.bind(null,l))),l=>n._waitingQueue.push(K(o.bind(null,l)))).finally(()=>{n._waitingFor===i&&(n._waitingFor=null)})})}abort(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new I.Abort))}table(e){const n=this._memoizedTables||(this._memoizedTables={});if(W(n,e))return n[e];const r=this.schema[e];if(!r)throw new I.NotFound("Table "+e+" not part of transaction");const s=new this.db.Table(e,r,this);return s.core=this.db.core.table(e),n[e]=s,s}}function rn(t,e,n,r,s,i,a){return{name:t,keyPath:e,unique:n,multi:r,auto:s,compound:i,src:(n&&!a?"&":"")+(r?"*":"")+(s?"++":"")+Pr(e)}}function Pr(t){return typeof t=="string"?t:t?"["+[].join.call(t,"+")+"]":""}function Ir(t,e,n){return{name:t,primKey:e,indexes:n,mappedClass:null,idxByName:ir(n,r=>[r.name,r])}}let Ze=t=>{try{return t.only([[]]),Ze=()=>[[]],[[]]}catch{return Ze=()=>ge,ge}};function sn(t){return t==null?()=>{}:typeof t=="string"?function(e){return e.split(".").length===1?r=>r[e]:r=>se(r,e)}(t):e=>se(e,t)}function Hn(t){return[].slice.call(t)}let $s=0;function Ge(t){return t==null?":id":typeof t=="string"?t:`[${t.join("+")}]`}function Us(t,e,n){function r(l){if(l.type===3)return null;if(l.type===4)throw new Error("Cannot convert never type to IDBKeyRange");const{lower:d,upper:c,lowerOpen:h,upperOpen:u}=l;return d===void 0?c===void 0?null:e.upperBound(c,!!u):c===void 0?e.lowerBound(d,!!h):e.bound(d,c,!!h,!!u)}const{schema:s,hasGetAll:i}=function(l,d){const c=Hn(l.objectStoreNames);return{schema:{name:l.name,tables:c.map(h=>d.objectStore(h)).map(h=>{const{keyPath:u,autoIncrement:f}=h,g=F(u),y=u==null,v={},m={name:h.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:y,compound:g,keyPath:u,autoIncrement:f,unique:!0,extractKey:sn(u)},indexes:Hn(h.indexNames).map(p=>h.index(p)).map(p=>{const{name:_,unique:x,multiEntry:C,keyPath:E}=p,w={name:_,compound:F(E),keyPath:E,unique:x,multiEntry:C,extractKey:sn(E)};return v[Ge(E)]=w,w}),getIndexByKeyPath:p=>v[Ge(p)]};return v[":id"]=m.primaryKey,u!=null&&(v[Ge(u)]=m.primaryKey),m})},hasGetAll:c.length>0&&"getAll"in d.objectStore(c[0])&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604)}}(t,n),a=s.tables.map(l=>function(d){const c=d.name;return{name:c,schema:d,mutate:function({trans:h,type:u,keys:f,values:g,range:y}){return new Promise((v,m)=>{v=K(v);const p=h.objectStore(c),_=p.keyPath==null,x=u==="put"||u==="add";if(!x&&u!=="delete"&&u!=="deleteRange")throw new Error("Invalid operation type: "+u);const{length:C}=f||g||{length:1};if(f&&g&&f.length!==g.length)throw new Error("Given keys array must have same length as given values array.");if(C===0)return v({numFailures:0,failures:{},results:[],lastResult:void 0});let E;const w=[],T=[];let k=0;const B=q=>{++k,Qe(q)};if(u==="deleteRange"){if(y.type===4)return v({numFailures:k,failures:T,results:[],lastResult:void 0});y.type===3?w.push(E=p.clear()):w.push(E=p.delete(r(y)))}else{const[q,$]=x?_?[g,f]:[g,null]:[f,null];if(x)for(let N=0;N<C;++N)w.push(E=$&&$[N]!==void 0?p[u](q[N],$[N]):p[u](q[N])),E.onerror=B;else for(let N=0;N<C;++N)w.push(E=p[u](q[N])),E.onerror=B}const D=q=>{const $=q.target.result;w.forEach((N,Se)=>N.error!=null&&(T[Se]=N.error)),v({numFailures:k,failures:T,results:u==="delete"?f:w.map(N=>N.result),lastResult:$})};E.onerror=q=>{B(q),D(q)},E.onsuccess=D})},getMany:({trans:h,keys:u})=>new Promise((f,g)=>{f=K(f);const y=h.objectStore(c),v=u.length,m=new Array(v);let p,_=0,x=0;const C=w=>{const T=w.target;m[T._pos]=T.result,++x===_&&f(m)},E=Q(g);for(let w=0;w<v;++w)u[w]!=null&&(p=y.get(u[w]),p._pos=w,p.onsuccess=C,p.onerror=E,++_);_===0&&f(m)}),get:({trans:h,key:u})=>new Promise((f,g)=>{f=K(f);const y=h.objectStore(c).get(u);y.onsuccess=v=>f(v.target.result),y.onerror=Q(g)}),query:function(h){return u=>new Promise((f,g)=>{f=K(f);const{trans:y,values:v,limit:m,query:p}=u,_=m===1/0?void 0:m,{index:x,range:C}=p,E=y.objectStore(c),w=x.isPrimaryKey?E:E.index(x.name),T=r(C);if(m===0)return f({result:[]});if(h){const k=v?w.getAll(T,_):w.getAllKeys(T,_);k.onsuccess=B=>f({result:B.target.result}),k.onerror=Q(g)}else{let k=0;const B=v||!("openKeyCursor"in w)?w.openCursor(T):w.openKeyCursor(T),D=[];B.onsuccess=q=>{const $=B.result;return $?(D.push(v?$.value:$.primaryKey),++k===m?f({result:D}):void $.continue()):f({result:D})},B.onerror=Q(g)}})}(i),openCursor:function({trans:h,values:u,query:f,reverse:g,unique:y}){return new Promise((v,m)=>{v=K(v);const{index:p,range:_}=f,x=h.objectStore(c),C=p.isPrimaryKey?x:x.index(p.name),E=g?y?"prevunique":"prev":y?"nextunique":"next",w=u||!("openKeyCursor"in C)?C.openCursor(r(_),E):C.openKeyCursor(r(_),E);w.onerror=Q(m),w.onsuccess=K(T=>{const k=w.result;if(!k)return void v(null);k.___id=++$s,k.done=!1;const B=k.continue.bind(k);let D=k.continuePrimaryKey;D&&(D=D.bind(k));const q=k.advance.bind(k),$=()=>{throw new Error("Cursor not stopped")};k.trans=h,k.stop=k.continue=k.continuePrimaryKey=k.advance=()=>{throw new Error("Cursor not started")},k.fail=K(m),k.next=function(){let N=1;return this.start(()=>N--?this.continue():this.stop()).then(()=>this)},k.start=N=>{const Se=new Promise((z,me)=>{z=K(z),w.onerror=Q(me),k.fail=me,k.stop=Me=>{k.stop=k.continue=k.continuePrimaryKey=k.advance=$,z(Me)}}),Ce=()=>{if(w.result)try{N()}catch(z){k.fail(z)}else k.done=!0,k.start=()=>{throw new Error("Cursor behind last entry")},k.stop()};return w.onsuccess=K(z=>{w.onsuccess=Ce,Ce()}),k.continue=B,k.continuePrimaryKey=D,k.advance=q,Ce(),Se},v(k)},m)})},count({query:h,trans:u}){const{index:f,range:g}=h;return new Promise((y,v)=>{const m=u.objectStore(c),p=f.isPrimaryKey?m:m.index(f.name),_=r(g),x=_?p.count(_):p.count();x.onsuccess=K(C=>y(C.target.result)),x.onerror=Q(v)})}}}(l)),o={};return a.forEach(l=>o[l.name]=l),{stack:"dbcore",transaction:t.transaction.bind(t),table(l){if(!o[l])throw new Error(`Table '${l}' not found`);return o[l]},MIN_KEY:-1/0,MAX_KEY:Ze(e),schema:s}}function an({_novip:t},e){const n=e.db,r=function(s,i,{IDBKeyRange:a,indexedDB:o},l){return{dbcore:function(c,h){return h.reduce((u,{create:f})=>({...u,...f(u)}),c)}(Us(i,a,l),s.dbcore)}}(t._middlewares,n,t._deps,e);t.core=r.dbcore,t.tables.forEach(s=>{const i=s.name;t.core.schema.tables.some(a=>a.name===i)&&(s.core=t.core.table(i),t[i]instanceof t.Table&&(t[i].core=s.core))})}function Pt({_novip:t},e,n,r){n.forEach(s=>{const i=r[s];e.forEach(a=>{const o=wn(a,s);(!o||"value"in o&&o.value===void 0)&&(a===t.Transaction.prototype||a instanceof t.Transaction?re(a,s,{get(){return this.table(s)},set(l){nr(this,s,{value:l,writable:!0,configurable:!0,enumerable:!0})}}):a[s]=new t.Table(s,i))})})}function on({_novip:t},e){e.forEach(n=>{for(let r in n)n[r]instanceof t.Table&&delete n[r]})}function Fs(t,e){return t._cfg.version-e._cfg.version}function Ls(t,e,n,r){const s=t._dbSchema,i=t._createTransaction("readwrite",t._storeNames,s);i.create(n),i._completion.catch(r);const a=i._reject.bind(i),o=P.transless||P;he(()=>{P.trans=i,P.transless=o,e===0?(j(s).forEach(l=>{Ut(n,l,s[l].primKey,s[l].indexes)}),an(t,n),S.follow(()=>t.on.populate.fire(i)).catch(a)):function({_novip:l},d,c,h){const u=[],f=l._versions;let g=l._dbSchema=cn(l,l.idbdb,h),y=!1;const v=f.filter(p=>p._cfg.version>=d);function m(){return u.length?S.resolve(u.shift()(c.idbtrans)).then(m):S.resolve()}return v.forEach(p=>{u.push(()=>{const _=g,x=p._cfg.dbschema;un(l,_,h),un(l,x,h),g=l._dbSchema=x;const C=Ar(_,x);C.add.forEach(w=>{Ut(h,w[0],w[1].primKey,w[1].indexes)}),C.change.forEach(w=>{if(w.recreate)throw new I.Upgrade("Not yet support for changing primary key");{const T=h.objectStore(w.name);w.add.forEach(k=>ln(T,k)),w.change.forEach(k=>{T.deleteIndex(k.name),ln(T,k)}),w.del.forEach(k=>T.deleteIndex(k))}});const E=p._cfg.contentUpgrade;if(E&&p._cfg.version>d){an(l,h),c._memoizedTables={},y=!0;let w=ar(x);C.del.forEach(D=>{w[D]=_[D]}),on(l,[l.Transaction.prototype]),Pt(l,[l.Transaction.prototype],j(w),w),c.schema=w;const T=_n(E);let k;T&&Be();const B=S.follow(()=>{if(k=E(c),k&&T){var D=ie.bind(null,null);k.then(D,D)}});return k&&typeof k.then=="function"?S.resolve(k):B.then(()=>k)}}),u.push(_=>{(!y||!Ds)&&function(x,C){[].slice.call(C.db.objectStoreNames).forEach(E=>x[E]==null&&C.db.deleteObjectStore(E))}(p._cfg.dbschema,_),on(l,[l.Transaction.prototype]),Pt(l,[l.Transaction.prototype],l._storeNames,l._dbSchema),c.schema=l._dbSchema})}),m().then(()=>{var p,_;_=h,j(p=g).forEach(x=>{_.db.objectStoreNames.contains(x)||Ut(_,x,p[x].primKey,p[x].indexes)})})}(t,e,i,n).catch(a)})}function Ar(t,e){const n={del:[],add:[],change:[]};let r;for(r in t)e[r]||n.del.push(r);for(r in e){const s=t[r],i=e[r];if(s){const a={name:r,def:i,recreate:!1,del:[],add:[],change:[]};if(""+(s.primKey.keyPath||"")!=""+(i.primKey.keyPath||"")||s.primKey.auto!==i.primKey.auto&&!Dt)a.recreate=!0,n.change.push(a);else{const o=s.idxByName,l=i.idxByName;let d;for(d in o)l[d]||a.del.push(d);for(d in l){const c=o[d],h=l[d];c?c.src!==h.src&&a.change.push(h):a.add.push(h)}(a.del.length>0||a.add.length>0||a.change.length>0)&&n.change.push(a)}}else n.add.push([r,i])}return n}function Ut(t,e,n,r){const s=t.db.createObjectStore(e,n.keyPath?{keyPath:n.keyPath,autoIncrement:n.auto}:{autoIncrement:n.auto});return r.forEach(i=>ln(s,i)),s}function ln(t,e){t.createIndex(e.name,e.keyPath,{unique:e.unique,multiEntry:e.multi})}function cn(t,e,n){const r={};return _t(e.objectStoreNames,0).forEach(s=>{const i=n.objectStore(s);let a=i.keyPath;const o=rn(Pr(a),a||"",!1,!1,!!i.autoIncrement,a&&typeof a!="string",!0),l=[];for(let c=0;c<i.indexNames.length;++c){const h=i.index(i.indexNames[c]);a=h.keyPath;var d=rn(h.name,a,!!h.unique,!!h.multiEntry,!1,a&&typeof a!="string",!1);l.push(d)}r[s]=Ir(s,o,l)}),r}function un({_novip:t},e,n){const r=n.db.objectStoreNames;for(let s=0;s<r.length;++s){const i=r[s],a=n.objectStore(i);t._hasGetAll="getAll"in a;for(let o=0;o<a.indexNames.length;++o){const l=a.indexNames[o],d=a.index(l).keyPath,c=typeof d=="string"?d:"["+_t(d).join("+")+"]";if(e[i]){const h=e[i].idxByName[c];h&&(h.name=l,delete e[i].idxByName[c],e[i].idxByName[l]=h)}}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&R.WorkerGlobalScope&&R instanceof R.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(t._hasGetAll=!1)}class qs{_parseStoresSpec(e,n){j(e).forEach(r=>{if(e[r]!==null){var s=e[r].split(",").map((a,o)=>{const l=(a=a.trim()).replace(/([&*]|\+\+)/g,""),d=/^\[/.test(l)?l.match(/^\[(.*)\]$/)[1].split("+"):l;return rn(l,d||null,/\&/.test(a),/\*/.test(a),/\+\+/.test(a),F(d),o===0)}),i=s.shift();if(i.multi)throw new I.Schema("Primary key cannot be multi-valued");s.forEach(a=>{if(a.auto)throw new I.Schema("Only primary key can be marked as autoIncrement (++)");if(!a.keyPath)throw new I.Schema("Index must have a name and cannot be an empty string")}),n[r]=Ir(r,i,s)}})}stores(e){const n=this.db;this._cfg.storesSource=this._cfg.storesSource?V(this._cfg.storesSource,e):e;const r=n._versions,s={};let i={};return r.forEach(a=>{V(s,a._cfg.storesSource),i=a._cfg.dbschema={},a._parseStoresSpec(s,i)}),n._dbSchema=i,on(n,[n._allTables,n,n.Transaction.prototype]),Pt(n,[n._allTables,n,n.Transaction.prototype,this._cfg.tables],j(i),i),n._storeNames=j(i),this}upgrade(e){return this._cfg.contentUpgrade=xn(this._cfg.contentUpgrade||O,e),this}}function In(t,e){let n=t._dbNamesDB;return n||(n=t._dbNamesDB=new we(Ot,{addons:[],indexedDB:t,IDBKeyRange:e}),n.version(1).stores({dbnames:"name"})),n.table("dbnames")}function An(t){return t&&typeof t.databases=="function"}function dn(t){return he(function(){return P.letThrough=!0,t()})}function Hs(){var t;return!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(e){var n=function(){return indexedDB.databases().finally(e)};t=setInterval(n,100),n()}).finally(function(){return clearInterval(t)}):Promise.resolve()}function Vs(t){const e=t._state,{indexedDB:n}=t._deps;if(e.isBeingOpened||t.idbdb)return e.dbReadyPromise.then(()=>e.dbOpenError?M(e.dbOpenError):t);X&&(e.openCanceller._stackHolder=xe()),e.isBeingOpened=!0,e.dbOpenError=null,e.openComplete=!1;const r=e.openCanceller;function s(){if(e.openCanceller!==r)throw new I.DatabaseClosed("db.open() was cancelled")}let i=e.dbReadyResolve,a=null,o=!1;const l=()=>new S((d,c)=>{if(s(),!n)throw new I.MissingAPI;const h=t.name,u=e.autoSchema?n.open(h):n.open(h,Math.round(10*t.verno));if(!u)throw new I.MissingAPI;u.onerror=Q(c),u.onblocked=K(t._fireOnBlocked),u.onupgradeneeded=K(f=>{if(a=u.transaction,e.autoSchema&&!t._options.allowEmptyDB){u.onerror=Qe,a.abort(),u.result.close();const y=n.deleteDatabase(h);y.onsuccess=y.onerror=K(()=>{c(new I.NoSuchDatabase(`Database ${h} doesnt exist`))})}else{a.onerror=Q(c);var g=f.oldVersion>Math.pow(2,62)?0:f.oldVersion;o=g<1,t._novip.idbdb=u.result,Ls(t,g/10,a,c)}},c),u.onsuccess=K(()=>{a=null;const f=t._novip.idbdb=u.result,g=_t(f.objectStoreNames);if(g.length>0)try{const v=f.transaction((y=g).length===1?y[0]:y,"readonly");e.autoSchema?function({_novip:m},p,_){m.verno=p.version/10;const x=m._dbSchema=cn(0,p,_);m._storeNames=_t(p.objectStoreNames,0),Pt(m,[m._allTables],j(x),x)}(t,f,v):(un(t,t._dbSchema,v),function(m,p){const _=Ar(cn(0,m.idbdb,p),m._dbSchema);return!(_.add.length||_.change.some(x=>x.add.length||x.change.length))}(t,v)||console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.")),an(t,v)}catch{}var y;Ve.push(t),f.onversionchange=K(v=>{e.vcFired=!0,t.on("versionchange").fire(v)}),f.onclose=K(v=>{t.on("close").fire(v)}),o&&function({indexedDB:v,IDBKeyRange:m},p){!An(v)&&p!==Ot&&In(v,m).put({name:p}).catch(O)}(t._deps,h),d()},c)}).catch(d=>d&&d.name==="UnknownError"&&e.PR1398_maxLoop>0?(e.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),l()):S.reject(d));return S.race([r,(typeof navigator>"u"?S.resolve():Hs()).then(l)]).then(()=>(s(),e.onReadyBeingFired=[],S.resolve(dn(()=>t.on.ready.fire(t.vip))).then(function d(){if(e.onReadyBeingFired.length>0){let c=e.onReadyBeingFired.reduce(xn,O);return e.onReadyBeingFired=[],S.resolve(dn(()=>c(t.vip))).then(d)}}))).finally(()=>{e.onReadyBeingFired=null,e.isBeingOpened=!1}).then(()=>t).catch(d=>{e.dbOpenError=d;try{a&&a.abort()}catch{}return r===e.openCanceller&&t._close(),M(d)}).finally(()=>{e.openComplete=!0,i()})}function hn(t){var e=i=>t.next(i),n=s(e),r=s(i=>t.throw(i));function s(i){return a=>{var o=i(a),l=o.value;return o.done?l:l&&typeof l.then=="function"?l.then(n,r):F(l)?Promise.all(l).then(n,r):n(l)}}return s(e)()}function zs(t,e,n){var r=arguments.length;if(r<2)throw new I.InvalidArgument("Too few arguments");for(var s=new Array(r-1);--r;)s[r-1]=arguments[r];return n=s.pop(),[t,or(s),n]}function Tr(t,e,n,r,s){return S.resolve().then(()=>{const i=P.transless||P,a=t._createTransaction(e,n,t._dbSchema,r),o={trans:a,transless:i};if(r)a.idbtrans=r.idbtrans;else try{a.create(),t._state.PR1398_maxLoop=3}catch(h){return h.name===En.InvalidState&&t.isOpen()&&--t._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),t._close(),t.open().then(()=>Tr(t,e,n,null,s))):M(h)}const l=_n(s);let d;l&&Be();const c=S.follow(()=>{if(d=s.call(a,a),d)if(l){var h=ie.bind(null,null);d.then(h,h)}else typeof d.next=="function"&&typeof d.throw=="function"&&(d=hn(d))},o);return(d&&typeof d.then=="function"?S.resolve(d).then(h=>a.active?h:M(new I.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))):c.then(()=>d)).then(h=>(r&&a._resolve(),a._completion.then(()=>h))).catch(h=>(a._reject(h),M(h)))})}function dt(t,e,n){const r=F(t)?t.slice():[t];for(let s=0;s<n;++s)r.push(e);return r}const Gs={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(t){return{...t,table(e){const n=t.table(e),{schema:r}=n,s={},i=[];function a(c,h,u){const f=Ge(c),g=s[f]=s[f]||[],y=c==null?0:typeof c=="string"?1:c.length,v=h>0,m={...u,isVirtual:v,keyTail:h,keyLength:y,extractKey:sn(c),unique:!v&&u.unique};return g.push(m),m.isPrimaryKey||i.push(m),y>1&&a(y===2?c[0]:c.slice(0,y-1),h+1,u),g.sort((p,_)=>p.keyTail-_.keyTail),m}const o=a(r.primaryKey.keyPath,0,r.primaryKey);s[":id"]=[o];for(const c of r.indexes)a(c.keyPath,0,c);function l(c){const h=c.query.index;return h.isVirtual?{...c,query:{index:h,range:(u=c.query.range,f=h.keyTail,{type:u.type===1?2:u.type,lower:dt(u.lower,u.lowerOpen?t.MAX_KEY:t.MIN_KEY,f),lowerOpen:!0,upper:dt(u.upper,u.upperOpen?t.MIN_KEY:t.MAX_KEY,f),upperOpen:!0})}}:c;var u,f}return{...n,schema:{...r,primaryKey:o,indexes:i,getIndexByKeyPath:function(c){const h=s[Ge(c)];return h&&h[0]}},count:c=>n.count(l(c)),query:c=>n.query(l(c)),openCursor(c){const{keyTail:h,isVirtual:u,keyLength:f}=c.query.index;return u?n.openCursor(l(c)).then(g=>g&&function(y){return Object.create(y,{continue:{value:function(m){m!=null?y.continue(dt(m,c.reverse?t.MAX_KEY:t.MIN_KEY,h)):c.unique?y.continue(y.key.slice(0,f).concat(c.reverse?t.MIN_KEY:t.MAX_KEY,h)):y.continue()}},continuePrimaryKey:{value(m,p){y.continuePrimaryKey(dt(m,t.MAX_KEY,h),p)}},primaryKey:{get:()=>y.primaryKey},key:{get(){const m=y.key;return f===1?m[0]:m.slice(0,f)}},value:{get:()=>y.value}})}(g)):n.openCursor(c)}}}}}};function Tn(t,e,n,r){return n=n||{},r=r||"",j(t).forEach(s=>{if(W(e,s)){var i=t[s],a=e[s];if(typeof i=="object"&&typeof a=="object"&&i&&a){const o=Ht(i);o!==Ht(a)?n[r+s]=e[s]:o==="Object"?Tn(i,a,n,r+s+"."):i!==a&&(n[r+s]=e[s])}else i!==a&&(n[r+s]=e[s])}else n[r+s]=void 0}),j(e).forEach(s=>{W(t,s)||(n[r+s]=e[s])}),n}const Ws={stack:"dbcore",name:"HooksMiddleware",level:2,create:t=>({...t,table(e){const n=t.table(e),{primaryKey:r}=n.schema;return{...n,mutate(i){const a=P.trans,{deleting:o,creating:l,updating:d}=a.table(e).hook;switch(i.type){case"add":if(l.fire===O)break;return a._promise("readwrite",()=>c(i),!0);case"put":if(l.fire===O&&d.fire===O)break;return a._promise("readwrite",()=>c(i),!0);case"delete":if(o.fire===O)break;return a._promise("readwrite",()=>c(i),!0);case"deleteRange":if(o.fire===O)break;return a._promise("readwrite",()=>function(u){return h(u.trans,u.range,1e4)}(i),!0)}return n.mutate(i);function c(u){const f=P.trans,g=u.keys||function(y,v){return v.type==="delete"?v.keys:v.keys||v.values.map(y.extractKey)}(r,u);if(!g)throw new Error("Keys missing");return(u=u.type==="add"||u.type==="put"?{...u,keys:g}:{...u}).type!=="delete"&&(u.values=[...u.values]),u.keys&&(u.keys=[...u.keys]),function(y,v,m){return v.type==="add"?Promise.resolve([]):y.getMany({trans:v.trans,keys:m,cache:"immutable"})}(n,u,g).then(y=>{const v=g.map((m,p)=>{const _=y[p],x={onerror:null,onsuccess:null};if(u.type==="delete")o.fire.call(x,m,_,f);else if(u.type==="add"||_===void 0){const C=l.fire.call(x,m,u.values[p],f);m==null&&C!=null&&(m=C,u.keys[p]=m,r.outbound||Y(u.values[p],r.keyPath,m))}else{const C=Tn(_,u.values[p]),E=d.fire.call(x,C,m,_,f);if(E){const w=u.values[p];Object.keys(E).forEach(T=>{W(w,T)?w[T]=E[T]:Y(w,T,E[T])})}}return x});return n.mutate(u).then(({failures:m,results:p,numFailures:_,lastResult:x})=>{for(let C=0;C<g.length;++C){const E=p?p[C]:g[C],w=v[C];E==null?w.onerror&&w.onerror(m[C]):w.onsuccess&&w.onsuccess(u.type==="put"&&y[C]?u.values[C]:E)}return{failures:m,results:p,numFailures:_,lastResult:x}}).catch(m=>(v.forEach(p=>p.onerror&&p.onerror(m)),Promise.reject(m)))})}function h(u,f,g){return n.query({trans:u,values:!1,query:{index:r,range:f},limit:g}).then(({result:y})=>c({type:"delete",keys:y,trans:u}).then(v=>v.numFailures>0?Promise.reject(v.failures[0]):y.length<g?{failures:[],numFailures:0,lastResult:void 0}:h(u,{...f,lower:y[y.length-1],lowerOpen:!0},g)))}}}}})};function Dr(t,e,n){try{if(!e||e.keys.length<t.length)return null;const r=[];for(let s=0,i=0;s<e.keys.length&&i<t.length;++s)H(e.keys[s],t[i])===0&&(r.push(n?nt(e.values[s]):e.values[s]),++i);return r.length===t.length?r:null}catch{return null}}const Ys={stack:"dbcore",level:-1,create:t=>({table:e=>{const n=t.table(e);return{...n,getMany:r=>{if(!r.cache)return n.getMany(r);const s=Dr(r.keys,r.trans._cache,r.cache==="clone");return s?S.resolve(s):n.getMany(r).then(i=>(r.trans._cache={keys:r.keys,values:r.cache==="clone"?nt(i):i},i))},mutate:r=>(r.type!=="add"&&(r.trans._cache=null),n.mutate(r))}}})};function Dn(t){return!("from"in t)}const ee=function(t,e){if(!this){const n=new ee;return t&&"d"in t&&V(n,t),n}V(this,arguments.length?{d:1,from:t,to:arguments.length>1?e:t}:{d:0})};function et(t,e,n){const r=H(e,n);if(isNaN(r))return;if(r>0)throw RangeError();if(Dn(t))return V(t,{from:e,to:n,d:1});const s=t.l,i=t.r;if(H(n,t.from)<0)return s?et(s,e,n):t.l={from:e,to:n,d:1,l:null,r:null},Vn(t);if(H(e,t.to)>0)return i?et(i,e,n):t.r={from:e,to:n,d:1,l:null,r:null},Vn(t);H(e,t.from)<0&&(t.from=e,t.l=null,t.d=i?i.d+1:1),H(n,t.to)>0&&(t.to=n,t.r=null,t.d=t.l?t.l.d+1:1);const a=!t.r;s&&!t.l&&It(t,s),i&&a&&It(t,i)}function It(t,e){Dn(e)||function n(r,{from:s,to:i,l:a,r:o}){et(r,s,i),a&&n(r,a),o&&n(r,o)}(t,e)}function Js(t,e){const n=fn(e);let r=n.next();if(r.done)return!1;let s=r.value;const i=fn(t);let a=i.next(s.from),o=a.value;for(;!r.done&&!a.done;){if(H(o.from,s.to)<=0&&H(o.to,s.from)>=0)return!0;H(s.from,o.from)<0?s=(r=n.next(o.from)).value:o=(a=i.next(s.from)).value}return!1}function fn(t){let e=Dn(t)?null:{s:0,n:t};return{next(n){const r=arguments.length>0;for(;e;)switch(e.s){case 0:if(e.s=1,r)for(;e.n.l&&H(n,e.n.from)<0;)e={up:e,n:e.n.l,s:1};else for(;e.n.l;)e={up:e,n:e.n.l,s:1};case 1:if(e.s=2,!r||H(n,e.n.to)<=0)return{value:e.n,done:!1};case 2:if(e.n.r){e.s=3,e={up:e,n:e.n.r,s:0};continue}case 3:e=e.up}return{done:!0}}}}function Vn(t){var e,n;const r=(((e=t.r)===null||e===void 0?void 0:e.d)||0)-(((n=t.l)===null||n===void 0?void 0:n.d)||0),s=r>1?"r":r<-1?"l":"";if(s){const i=s==="r"?"l":"r",a={...t},o=t[s];t.from=o.from,t.to=o.to,t[s]=o[s],a[s]=o[i],t[i]=a,a.d=zn(a)}t.d=zn(t)}function zn({r:t,l:e}){return(t?e?Math.max(t.d,e.d):t.d:e?e.d:0)+1}Ke(ee.prototype,{add(t){return It(this,t),this},addKey(t){return et(this,t,t),this},addKeys(t){return t.forEach(e=>et(this,e,e)),this},[Vt](){return fn(this)}});const Qs={stack:"dbcore",level:0,create:t=>{const e=t.schema.name,n=new ee(t.MIN_KEY,t.MAX_KEY);return{...t,table:r=>{const s=t.table(r),{schema:i}=s,{primaryKey:a}=i,{extractKey:o,outbound:l}=a,d={...s,mutate:u=>{const f=u.trans,g=f.mutatedParts||(f.mutatedParts={}),y=E=>{const w=`idb://${e}/${r}/${E}`;return g[w]||(g[w]=new ee)},v=y(""),m=y(":dels"),{type:p}=u;let[_,x]=u.type==="deleteRange"?[u.range]:u.type==="delete"?[u.keys]:u.values.length<50?[[],u.values]:[];const C=u.trans._cache;return s.mutate(u).then(E=>{if(F(_)){p!=="delete"&&(_=E.results),v.addKeys(_);const w=Dr(_,C);w||p==="add"||m.addKeys(_),(w||x)&&function(T,k,B,D){function q($){const N=T($.name||"");function Se(z){return z!=null?$.extractKey(z):null}const Ce=z=>$.multiEntry&&F(z)?z.forEach(me=>N.addKey(me)):N.addKey(z);(B||D).forEach((z,me)=>{const Me=B&&Se(B[me]),Rt=D&&Se(D[me]);H(Me,Rt)!==0&&(Me!=null&&Ce(Me),Rt!=null&&Ce(Rt))})}k.indexes.forEach(q)}(y,i,w,x)}else if(_){const w={from:_.lower,to:_.upper};m.add(w),v.add(w)}else v.add(n),m.add(n),i.indexes.forEach(w=>y(w.name).add(n));return E})}},c=({query:{index:u,range:f}})=>{var g,y;return[u,new ee((g=f.lower)!==null&&g!==void 0?g:t.MIN_KEY,(y=f.upper)!==null&&y!==void 0?y:t.MAX_KEY)]},h={get:u=>[a,new ee(u.key)],getMany:u=>[a,new ee().addKeys(u.keys)],count:c,query:c,openCursor:c};return j(h).forEach(u=>{d[u]=function(f){const{subscr:g}=P;if(g){const y=x=>{const C=`idb://${e}/${r}/${x}`;return g[C]||(g[C]=new ee)},v=y(""),m=y(":dels"),[p,_]=h[u](f);if(y(p.name||"").add(_),!p.isPrimaryKey){if(u!=="count"){const x=u==="query"&&l&&f.values&&s.query({...f,values:!1});return s[u].apply(this,arguments).then(C=>{if(u==="query"){if(l&&f.values)return x.then(({result:w})=>(v.addKeys(w),C));const E=f.values?C.result.map(o):C.result;f.values?v.addKeys(E):m.addKeys(E)}else if(u==="openCursor"){const E=C,w=f.values;return E&&Object.create(E,{key:{get:()=>(m.addKey(E.primaryKey),E.key)},primaryKey:{get(){const T=E.primaryKey;return m.addKey(T),T}},value:{get:()=>(w&&v.addKey(E.primaryKey),E.value)}})}return C})}m.add(n)}}return s[u].apply(this,arguments)}}),d}}}};class we{constructor(e,n){this._middlewares={},this.verno=0;const r=we.dependencies;this._options=n={addons:we.addons,autoOpen:!0,indexedDB:r.indexedDB,IDBKeyRange:r.IDBKeyRange,...n},this._deps={indexedDB:n.indexedDB,IDBKeyRange:n.IDBKeyRange};const{addons:s}=n;this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this;const i={dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:O,dbReadyPromise:null,cancelOpen:O,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3};var a;i.dbReadyPromise=new S(o=>{i.dbReadyResolve=o}),i.openCanceller=new S((o,l)=>{i.cancelOpen=l}),this._state=i,this.name=e,this.on=ze(this,"populate","blocked","versionchange","close",{ready:[xn,O]}),this.on.ready.subscribe=rr(this.on.ready.subscribe,o=>(l,d)=>{we.vip(()=>{const c=this._state;if(c.openComplete)c.dbOpenError||S.resolve().then(l),d&&o(l);else if(c.onReadyBeingFired)c.onReadyBeingFired.push(l),d&&o(l);else{o(l);const h=this;d||o(function u(){h.on.ready.unsubscribe(l),h.on.ready.unsubscribe(u)})}})}),this.Collection=(a=this,$e(Ks.prototype,function(o,l){this.db=a;let d=xr,c=null;if(l)try{d=l()}catch(g){c=g}const h=o._ctx,u=h.table,f=u.hook.reading.fire;this._ctx={table:u,index:h.index,isPrimKey:!h.index||u.schema.primKey.keyPath&&h.index===u.schema.primKey.name,range:d,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:c,or:h.or,valueMapper:f!==Ye?f:null}})),this.Table=function(o){return $e(Rs.prototype,function(l,d,c){this.db=o,this._tx=c,this.name=l,this.schema=d,this.hook=o._allTables[l]?o._allTables[l].hook:ze(null,{creating:[_s,O],reading:[ws,Ye],updating:[Es,O],deleting:[ks,O]})})}(this),this.Transaction=function(o){return $e(Ms.prototype,function(l,d,c,h,u){this.db=o,this.mode=l,this.storeNames=d,this.schema=c,this.chromeTransactionDurability=h,this.idbtrans=null,this.on=ze(this,"complete","error","abort"),this.parent=u||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new S((f,g)=>{this._resolve=f,this._reject=g}),this._completion.then(()=>{this.active=!1,this.on.complete.fire()},f=>{var g=this.active;return this.active=!1,this.on.error.fire(f),this.parent?this.parent._reject(f):g&&this.idbtrans&&this.idbtrans.abort(),M(f)})})}(this),this.Version=function(o){return $e(qs.prototype,function(l){this.db=o,this._cfg={version:l,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})}(this),this.WhereClause=function(o){return $e(Cr.prototype,function(l,d,c){this.db=o,this._ctx={table:l,index:d===":id"?null:d,or:c};const h=o._deps.indexedDB;if(!h)throw new I.MissingAPI;this._cmp=this._ascending=h.cmp.bind(h),this._descending=(u,f)=>h.cmp(f,u),this._max=(u,f)=>h.cmp(u,f)>0?u:f,this._min=(u,f)=>h.cmp(u,f)<0?u:f,this._IDBKeyRange=o._deps.IDBKeyRange})}(this),this.on("versionchange",o=>{o.newVersion>0?console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`):console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`),this.close()}),this.on("blocked",o=>{!o.newVersion||o.newVersion<o.oldVersion?console.warn(`Dexie.delete('${this.name}') was blocked`):console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${o.oldVersion/10}`)}),this._maxKey=Ze(n.IDBKeyRange),this._createTransaction=(o,l,d,c)=>new this.Transaction(o,l,d,this._options.chromeTransactionDurability,c),this._fireOnBlocked=o=>{this.on("blocked").fire(o),Ve.filter(l=>l.name===this.name&&l!==this&&!l._state.vcFired).map(l=>l.on("versionchange").fire(o))},this.use(Gs),this.use(Ws),this.use(Qs),this.use(Ys),this.vip=Object.create(this,{_vip:{value:!0}}),s.forEach(o=>o(this))}version(e){if(isNaN(e)||e<.1)throw new I.Type("Given version is not a positive number");if(e=Math.round(10*e)/10,this.idbdb||this._state.isBeingOpened)throw new I.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,e);const n=this._versions;var r=n.filter(s=>s._cfg.version===e)[0];return r||(r=new this.Version(e),n.push(r),n.sort(Fs),r.stores({}),this._state.autoSchema=!1,r)}_whenReady(e){return this.idbdb&&(this._state.openComplete||P.letThrough||this._vip)?e():new S((n,r)=>{if(this._state.openComplete)return r(new I.DatabaseClosed(this._state.dbOpenError));if(!this._state.isBeingOpened){if(!this._options.autoOpen)return void r(new I.DatabaseClosed);this.open().catch(O)}this._state.dbReadyPromise.then(n,r)}).then(e)}use({stack:e,create:n,level:r,name:s}){s&&this.unuse({stack:e,name:s});const i=this._middlewares[e]||(this._middlewares[e]=[]);return i.push({stack:e,create:n,level:r??10,name:s}),i.sort((a,o)=>a.level-o.level),this}unuse({stack:e,name:n,create:r}){return e&&this._middlewares[e]&&(this._middlewares[e]=this._middlewares[e].filter(s=>r?s.create!==r:!!n&&s.name!==n)),this}open(){return Vs(this)}_close(){const e=this._state,n=Ve.indexOf(this);if(n>=0&&Ve.splice(n,1),this.idbdb){try{this.idbdb.close()}catch{}this._novip.idbdb=null}e.dbReadyPromise=new S(r=>{e.dbReadyResolve=r}),e.openCanceller=new S((r,s)=>{e.cancelOpen=s})}close(){this._close();const e=this._state;this._options.autoOpen=!1,e.dbOpenError=new I.DatabaseClosed,e.isBeingOpened&&e.cancelOpen(e.dbOpenError)}delete(){const e=arguments.length>0,n=this._state;return new S((r,s)=>{const i=()=>{this.close();var a=this._deps.indexedDB.deleteDatabase(this.name);a.onsuccess=K(()=>{(function({indexedDB:o,IDBKeyRange:l},d){!An(o)&&d!==Ot&&In(o,l).delete(d).catch(O)})(this._deps,this.name),r()}),a.onerror=Q(s),a.onblocked=this._fireOnBlocked};if(e)throw new I.InvalidArgument("Arguments not allowed in db.delete()");n.isBeingOpened?n.dbReadyPromise.then(i):i()})}backendDB(){return this.idbdb}isOpen(){return this.idbdb!==null}hasBeenClosed(){const e=this._state.dbOpenError;return e&&e.name==="DatabaseClosed"}hasFailed(){return this._state.dbOpenError!==null}dynamicallyOpened(){return this._state.autoSchema}get tables(){return j(this._allTables).map(e=>this._allTables[e])}transaction(){const e=zs.apply(this,arguments);return this._transaction.apply(this,e)}_transaction(e,n,r){let s=P.trans;s&&s.db===this&&e.indexOf("!")===-1||(s=null);const i=e.indexOf("?")!==-1;let a,o;e=e.replace("!","").replace("?","");try{if(o=n.map(d=>{var c=d instanceof this.Table?d.name:d;if(typeof c!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return c}),e=="r"||e===Bt)a=Bt;else{if(e!="rw"&&e!=Nt)throw new I.InvalidArgument("Invalid transaction mode: "+e);a=Nt}if(s){if(s.mode===Bt&&a===Nt){if(!i)throw new I.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");s=null}s&&o.forEach(d=>{if(s&&s.storeNames.indexOf(d)===-1){if(!i)throw new I.SubTransaction("Table "+d+" not included in parent transaction.");s=null}}),i&&s&&!s.active&&(s=null)}}catch(d){return s?s._promise(null,(c,h)=>{h(d)}):M(d)}const l=Tr.bind(null,this,a,o,s,r);return s?s._promise(a,l,"lock"):P.trans?Ne(P.transless,()=>this._whenReady(l)):this._whenReady(l)}table(e){if(!W(this._allTables,e))throw new I.InvalidTable(`Table ${e} does not exist`);return this._allTables[e]}}const Xs=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable";class Zs{constructor(e){this._subscribe=e}subscribe(e,n,r){return this._subscribe(e&&typeof e!="function"?e:{next:e,error:n,complete:r})}[Xs](){return this}}function Or(t,e){return j(e).forEach(n=>{It(t[n]||(t[n]=new ee),e[n])}),t}function ei(t){let e,n=!1;const r=new Zs(s=>{const i=_n(t);let a=!1,o={},l={};const d={get closed(){return a},unsubscribe:()=>{a=!0,pe.storagemutated.unsubscribe(f)}};s.start&&s.start(d);let c=!1,h=!1;function u(){return j(l).some(y=>o[y]&&Js(o[y],l[y]))}const f=y=>{Or(o,y),u()&&g()},g=()=>{if(c||a)return;o={};const y={},v=function(m){i&&Be();const p=()=>he(t,{subscr:m,trans:null}),_=P.trans?Ne(P.transless,p):p();return i&&_.then(ie,ie),_}(y);h||(pe(Xe,f),h=!0),c=!0,Promise.resolve(v).then(m=>{n=!0,e=m,c=!1,a||(u()?g():(o={},l=y,s.next&&s.next(m)))},m=>{c=!1,n=!1,s.error&&s.error(m),d.unsubscribe()})};return g(),d});return r.hasValue=()=>n,r.getValue=()=>e,r}let pn;try{pn={indexedDB:R.indexedDB||R.mozIndexedDB||R.webkitIndexedDB||R.msIndexedDB,IDBKeyRange:R.IDBKeyRange||R.webkitIDBKeyRange}}catch{pn={indexedDB:null,IDBKeyRange:null}}const ye=we;function vt(t){let e=ne;try{ne=!0,pe.storagemutated.fire(t)}finally{ne=e}}Ke(ye,{...ht,delete:t=>new ye(t,{addons:[]}).delete(),exists:t=>new ye(t,{addons:[]}).open().then(e=>(e.close(),!0)).catch("NoSuchDatabaseError",()=>!1),getDatabaseNames(t){try{return function({indexedDB:e,IDBKeyRange:n}){return An(e)?Promise.resolve(e.databases()).then(r=>r.map(s=>s.name).filter(s=>s!==Ot)):In(e,n).toCollection().primaryKeys()}(ye.dependencies).then(t)}catch{return M(new I.MissingAPI)}},defineClass:()=>function(t){V(this,t)},ignoreTransaction:t=>P.trans?Ne(P.transless,t):t(),vip:dn,async:function(t){return function(){try{var e=hn(t.apply(this,arguments));return e&&typeof e.then=="function"?e:S.resolve(e)}catch(n){return M(n)}}},spawn:function(t,e,n){try{var r=hn(t.apply(n,e||[]));return r&&typeof r.then=="function"?r:S.resolve(r)}catch(s){return M(s)}},currentTransaction:{get:()=>P.trans||null},waitFor:function(t,e){const n=S.resolve(typeof t=="function"?ye.ignoreTransaction(t):t).timeout(e||6e4);return P.trans?P.trans.waitFor(n):n},Promise:S,debug:{get:()=>X,set:t=>{cr(t,t==="dexie"?()=>!0:Er)}},derive:De,extend:V,props:Ke,override:rr,Events:ze,on:pe,liveQuery:ei,extendObservabilitySet:Or,getByKeyPath:se,setByKeyPath:Y,delByKeyPath:function(t,e){typeof e=="string"?Y(t,e,void 0):"length"in e&&[].map.call(e,function(n){Y(t,n,void 0)})},shallowClone:ar,deepClone:nt,getObjectDiff:Tn,cmp:H,asap:sr,minKey:nn,addons:[],connections:Ve,errnames:En,dependencies:pn,semVer:$n,version:$n.split(".").map(t=>parseInt(t)).reduce((t,e,n)=>t+e/Math.pow(10,2*n))}),ye.maxKey=Ze(ye.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(pe(Xe,t=>{if(!ne){let e;Dt?(e=document.createEvent("CustomEvent"),e.initCustomEvent(ce,!0,!0,t)):e=new CustomEvent(ce,{detail:t}),ne=!0,dispatchEvent(e),ne=!1}}),addEventListener(ce,({detail:t})=>{ne||vt(t)}));let ne=!1;if(typeof BroadcastChannel<"u"){const t=new BroadcastChannel(ce);typeof t.unref=="function"&&t.unref(),pe(Xe,e=>{ne||t.postMessage(e)}),t.onmessage=e=>{e.data&&vt(e.data)}}else if(typeof self<"u"&&typeof navigator<"u"){pe(Xe,e=>{try{ne||(typeof localStorage<"u"&&localStorage.setItem(ce,JSON.stringify({trig:Math.random(),changedParts:e})),typeof self.clients=="object"&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach(n=>n.postMessage({type:ce,changedParts:e})))}catch{}}),typeof addEventListener<"u"&&addEventListener("storage",e=>{if(e.key===ce){const n=JSON.parse(e.newValue);n&&vt(n.changedParts)}});const t=self.document&&navigator.serviceWorker;t&&t.addEventListener("message",function({data:e}){e&&e.type===ce&&vt(e.changedParts)})}S.rejectionMapper=function(t,e){if(!t||t instanceof Oe||t instanceof TypeError||t instanceof SyntaxError||!t.name||!Bn[t.name])return t;var n=new Bn[t.name](e||t.message,t);return"stack"in t&&re(n,"stack",{get:function(){return this.inner.stack}}),n},cr(X,Er);const Rr=async(t,e)=>{const n=performance.now();try{await t()}finally{const r=performance.now()-n;let s=b.PerformanceMetrics[e];s||(s=b.registerMetric(e)),s.report(r/1e3)}},Kr=(t,e)=>{const n=performance.now();try{t()}finally{const r=performance.now()-n;let s=b.PerformanceMetrics[e];s||(s=b.registerMetric(e)),s.report(r/1e3)}},ti=30,ni=3e4;let Ue=0;const Br=()=>{b.sessionStorageHelper.setItem("sprig.disableReplayRecording","disabled")},Ee=()=>!!b.sessionStorageHelper.getItem("sprig.disableReplayRecording"),ri=["did not allow mutations","called in an invalid security context"],si=t=>{if(!t)return!0;for(const e of ri)if(t.toLowerCase().includes(e))return!1;return!0},ii=(t,e,{reportError:n=!0,extraInfo:r})=>{Ee()||e instanceof Error&&(Br(),si(e==null?void 0:e.message)&&(n&&window.UserLeap.reportError(t,e,r),li()))},ai=async(t,e,{reportError:n}={reportError:!0})=>{var s;let r;try{if(n&&((s=window.navigator.storage)!=null&&s.estimate)){const{quota:i,usage:a}=await window.navigator.storage.estimate();r={availableSpaceInMB:i&&a?(i-a)/(1024*1024):void 0,quota:i,usage:a}}}catch(i){window.UserLeap.reportError("Error getting storage estimate",i,{originalMessage:t,originalError:e})}ii(t,e,{reportError:n,extraInfo:r})},oi=()=>{const t=b.sessionStorageHelper.getItem("sprig.sessionId");if(t)return b.info(`Found saved session id: ${t}`),b.sessionStorageHelper.removeItem("sprig.sessionId"),t;const e=b.v4();return b.info(`Generating new uuid: ${e}`),e},L=oi();window.addEventListener("beforeunload",()=>{b.info(`Before page unload saving session id: ${L}`),b.sessionStorageHelper.setItem("sprig.sessionId",L)});const li=async()=>{A.transaction("rw",A.events,A.chunkUploads,A.pendingCaptures,()=>{A.events.clear(),A.chunkUploads.clear(),A.pendingCaptures.clear()}).catch(()=>{})},Ft=(t,e,n=()=>!0)=>A.table(e).where("timestamp").below(t).and(n).delete(),ci=async(t,e)=>{let n=[];return await Rr(async()=>{n=await A.events.where("[sessionId+timestamp]").between([L,t],[L,e??Date.now()]).toArray()},"sdk_replay_get_events_between_seconds"),n},ui=(t,e,n)=>{const r=new Date,s=r.setMinutes(r.getMinutes()+(n??ti));return A.events.where("[sessionId+timestamp]").between([L,t],[L,e]).modify({expiredAt:s})},di=t=>A.chunkUploads.add({...t,sessionId:t.sessionId??L}),hi=(t,e)=>A.chunkUploads.update(t,{data:null,etag:e,status:"UploadComplete"}),fi=({status:t,uploadId:e})=>e?A.chunkUploads.where({uploadId:e,status:t}).toArray():A.chunkUploads.where({sessionId:L,status:t}).toArray(),pi=t=>A.chunkUploads.where({uploadId:t,status:"UploadComplete"}).toArray(),mi=t=>A.chunkUploads.where({uploadId:t,status:"UploadComplete"}).delete(),yi=t=>A.pendingCaptures.add({...t,sessionId:t.sessionId??L,canUpload:!1}),Nr=async t=>{let e=await A.pendingCaptures.where("sessionId").equals(L).toArray();return t.beforePresent&&(e=e.filter(n=>n.targetTimestamp<Date.now())),t.isHeatmap&&(e=e.filter(n=>n.captureParams.isHeatmap??!1)),e},gi=()=>A.pendingCaptures.where("sessionId").equals(L).toArray(),vi=t=>A.pendingCaptures.where("sessionId").equals(L).and(e=>e.captureParams.responseGroupId===t).modify({canUpload:!0}),bi=async t=>{var e;if((e=window.navigator.storage)!=null&&e.estimate){const{quota:n,usage:r}=await window.navigator.storage.estimate();if(n&&r&&(n-r)/1073741824<t)return!1}return!0},jr=async t=>{if(parseInt(b.sessionStorageHelper.getItem("sprig.pendingCount")??"0")===0)return;const n=Date.now();return ae(async()=>{await A.pendingCaptures.where("sessionId").equals(L).and(r=>r.captureParams.isHeatmap??!1).and(r=>t?t.includes(r.uuid):!0).modify(r=>{r.targetTimestamp=n,r.captureParams.triggerTimestamp=n,r.captureParams.replayParams.replayDurationSeconds=Math.floor((n-r.timestamp)/1e3)})},"Error marking pending heatmaps ready")},wi=async()=>{const e=(await Nr({isHeatmap:!0})).map(r=>({eventId:r.captureParams.eventId,uuid:r.uuid})),n=[];e.forEach(({eventId:r,uuid:s})=>{b.checkUrlStillMatching(r)||n.push(s)}),n.length&&jr(n)},_i=t=>{if(t>1){Ue=0;return}const e=Date.now();if(!Ue){Ue=e;return}e-Ue>=ni&&(jr(),Ue=0)};class ki extends we{constructor(){super("replayStorage",{autoOpen:!1});Pe(this,"events");Pe(this,"chunkUploads");Pe(this,"pendingCaptures")}}const A=new ki;A.version(1).stores({events:"uuid, timestamp, [sessionId+timestamp]",chunkUploads:"uuid, timestamp, [sessionId+status], [uploadId+status], [sessionId+status+uploadId]",pendingCaptures:"uuid, timestamp, [sessionId+targetTimestamp]"});A.open().catch(t=>{b.error(`Error opening replay storage: ${JSON.stringify(t)}`),Br()});const Ei=t=>{if(t instanceof Attr)return null;let e=1;for(let n=t.previousSibling;n;n=n.previousSibling)n.nodeName===t.nodeName&&++e;return e},Mr=t=>{if(t===null)return"";const e=[];if(t instanceof Document)return"/";for(let n=t;n&&!(n instanceof Document)&&n!==null;n=n instanceof Attr?n.ownerElement:n.parentElement){const r=e[e.length]={name:void 0,position:null};switch(n.nodeType){case Node.TEXT_NODE:r.name="text()";break;case Node.ATTRIBUTE_NODE:r.name="@"+n.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:r.name="processing-instruction()";break;case Node.COMMENT_NODE:r.name="comment()";break;case Node.ELEMENT_NODE:r.name=n.nodeName;break}r.position=Ei(n)}return"/"+e.reverse().map(n=>n.position!==null?`/${n.name}[${n.position}]`:`/${n.name}`).join("")},ue={capture:!0,passive:!0},xi=["a","button","input","option","li","link"],Si=["Escape","Enter","Backspace","F5","Tab"];let At=!1;const Ci=["label","type","role","title","placeholder","errormessage","valuetext","href"],Gn="aria-",Pi=t=>{if(!t.tagName)return"No tagName";const e=t.getAttribute("type");return e?`${e} ${t.tagName.toLowerCase()}`:t.tagName.toLowerCase()},Wn=t=>{var r;if(((r=t.tagName)==null?void 0:r.toLowerCase())==="html")return{element:"html"};const e=t.textContent,n=e?{text:e}:{};n.element=Pi(t);for(const s of t.attributes){let i=s.name;const a=s.value;i.startsWith(Gn)&&(i=i.substring(Gn.length)),Ci.includes(i)&&(n[i]=a)}return n},Ii=t=>{var s;if(!t)return{};const n={...Wn(t)},r=t.parentElement;if(r&&xi.includes((s=r.tagName)==null?void 0:s.toLowerCase())){const i=Wn(r);Object.assign(n,i)}return n},$r=(t,e)=>{var n;es({x:e.x,y:e.y,type:t,elementAttributes:Ii(e.target),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...e.target instanceof HTMLElement?{rect:(n=e.target)==null?void 0:n.getBoundingClientRect(),xPath:Mr(e.target)}:{}})},Ai=t=>e=>$r(t,e),Ur=t=>{Si.includes(t.key)&&rs({key:t.key})},Ti=()=>{window.performance.getEntriesByType("navigation").map(e=>e.type).includes("reload")&&ts({url:window.location.href,currentPageTitle:document.title})},Di=()=>{window.performance.getEntriesByType("navigation").map(e=>e.type).includes("back_forward")&&ns({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title})},Oi=(t,e)=>{let n;return r=>{clearTimeout(n),n=window.setTimeout(()=>t(r),e)}},Ri=t=>{if(!(t.target instanceof HTMLElement||t.target instanceof Document))return;let e=t.target;"scrollTop"in e||(e=e.documentElement),ss({xPath:Mr(e),x:e.scrollLeft,y:e.scrollTop,elementAttributes:{targetScrollWidth:e.scrollWidth,targetClientWidth:e.clientWidth,targetScrollHeight:e.scrollHeight,targetClientHeight:e.clientHeight}})},Fr=Oi(Ri,750),Lr=Ai("left_click"),qr=t=>{t.button===2&&$r("right_click",t)},Ki=()=>{At||(window.addEventListener("click",Lr,ue),window.addEventListener("mousedown",qr,ue),window.addEventListener("keydown",Ur,ue),window.addEventListener("scroll",Fr,ue),At=!0,Ti(),Di())},Bi=()=>{At&&(window.removeEventListener("click",Lr,ue),window.removeEventListener("mousedown",qr,ue),window.removeEventListener("keydown",Ur,ue),window.removeEventListener("scroll",Fr,ue),At=!1)},Ni=async(t,e,n)=>new Promise((r,s)=>{const i=t.createElement("script");i.src=e,i.onload=r,i.onerror=s,n&&(i.nonce=n),t.head.appendChild(i)});let Yn=1,mn=5e3,bt=6e4;const ji=5,Jn=1e3,Hr=30,Tt=Hr+ji;let yn,gn,Vr,Qn=Date.now(),tt=!1,wt;const zr={},Mi=async({viewDocument:t,maxReplayDurationSeconds:e,replayNonce:n,maxInflightRequests:r=2,replaySettings:s,teardownAfter:i=!1})=>{tt||(i&&b.sessionStorageHelper.setItem("sprig.teardownAfterCapture","true"),await ae(async()=>{if(Ee()){b.info("Not initializing replay because recording is disabled");return}if(!e){b.info("Not initializing replay because config didn't specify maxReplayDurationSeconds");return}if(s!=null&&s.minAvailableGb&&(Yn=s.minAvailableGb),!await bi(Yn)){b.warn("Minimum storage not available");return}if(b.info("Initializing replay"),s!=null&&s.minDuration&&(mn=s.minDuration),s!=null&&s.batchDuration&&(bt=s.batchDuration),ls(r),Vi(),Fi(e+Tt,30*60,e+Tt),Li(),!window.rrwebRecord){b.info("Loading recording script");const d=window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.6.min.js";await Ni(t,d,n),b.info("Recording script finished loading")}const a=window.rrwebRecord;if(!a){b.warn("Record script failed to set global function");return}let o=!0,l=0;wt=a({checkoutEveryNms:Hr*1e3,sampling:{input:"last",scroll:250,media:800},emit:(d,c)=>{if(Ee())return;if(Qn=Date.now(),c&&d.type===Lt.Meta)l=performance.now();else if(c&&l&&d.type===Lt.FullSnapshot){const u=performance.now()-l;b.reportAndRegister("sdk_replay_snapshot_seconds",u/1e3)}const h=o||!!c;o=!1,$i({uuid:b.v4(),event:JSON.stringify(d),isValidStart:h,timestamp:Date.now()})},...s}),tt=!0,gn||(gn=window.setInterval(()=>{Date.now()-Qn>Jn&&J("Sprig_Noop",{})},Jn)),b.eventEmitter.on("survey.complete",d=>{Zr({id:d,userAgent:window.navigator.userAgent})}),Ki()},"Error initializing replay"))};let de=b.sessionStorageHelper.getItem("sprig.pendingCount"),On=!!b.sessionStorageHelper.getItem("sprig.isCapturingHeatmap"),vn=!1,bn=[];const $i=t=>{var e,n,r,s;if((e=t.event)!=null&&e.includes("Sprig_Scroll")){const i=(s=(r=(n=JSON.parse(t.event))==null?void 0:n.data)==null?void 0:r.payload)==null?void 0:s.xPath;if(!i)return;const a=b.v4();zr[i]=a,t.uuid=a}bn.push(t),vn||Ui()},Gr=t=>{const e=t.map(n=>({...n,sessionId:n.sessionId??L}));if(On&&_i(e.length),e.length!==0)return A.transaction("rw",A.events,()=>{A.events.bulkAdd(e)}).catch(n=>{je("Error storing replay events",n)})},Ui=()=>{vn=!0,setTimeout(async()=>{if(Ee())return;const t=bn;bn=[],vn=!1,Kr(async()=>{await Gr(t)},"sdk_replay_add_event_batch_seconds")},500)},Fi=(t=6*60,e=30*60,n=4*60)=>{yn=window.setInterval(()=>{const r=Date.now();Ee()||(b.debug(`Performing periodic replay data cleanup / Event Seconds ${t} / Chunk Seconds ${e} / Pending Capture Seconds ${n}`),Rr(()=>A.transaction("rw!",A.events,A.chunkUploads,A.pendingCaptures,()=>{Ft(r-t*1e3,"events",s=>s.expiredAt===void 0||s.expiredAt<r-t*1e3),Ft(r-e*1e3,"chunkUploads"),Ft(r-n*1e3,"pendingCaptures",s=>s.canUpload===void 0||s.canUpload===!1)}).catch(s=>{clearInterval(yn),je("Error deleting table rows",s)}),"sdk_replay_cleanup_seconds"),b.info("Cleanup complete"))},30*1e3)},Li=(t=5)=>{Vr=window.setInterval(async()=>{ae(async()=>{const e=parseInt(de??"0");if(e===0)return;const n=await Nr({beforePresent:!0});n!=null&&n.length&&(await Promise.all(n.map(async r=>(await A.pendingCaptures.delete(r.uuid),Jr(r.captureParams,r.canUpload)))),de=(e-n.length).toString(),b.sessionStorageHelper.setItem("sprig.pendingCount",de))},"Error initiating pending captures")},t*1e3)},qi=async(t,e,n,r,s)=>{const i=Math.min(t+s,n),a=`from: ${new Date(t).toLocaleTimeString()} to ${new Date(i).toLocaleTimeString()}`;b.info(`Getting event batch ${a}`);const o=await ci(t,i);if(!(o!=null&&o.length))return b.info(`No events found ${a}`),{validStartFound:r,events:[]};if(!r){b.info(`Searching for valid start in ${o.length} events ${a}`);let l=-1;if(o==null||o.forEach((c,h)=>{if(!c.isValidStart)return;const u=c.timestamp<=e;(l<0||u)&&(l=h)}),l<0)return b.info(`No valid start found in ${o.length} events ${a}`),{validStartFound:r,events:[]};const d=o[l].timestamp;return b.info(`Found valid start at: ${new Date(d).toLocaleTimeString()} in events ${a}`),{validStartFound:!0,events:o==null?void 0:o.slice(l)}}return{validStartFound:r,events:o}},Hi=(t,e,n)=>{const r=t.length,s=e*1024*1024,i=Math.ceil(r/n),a=Math.max(s,i);b.info(`Total file bytes: ${r} / target chunk size: ${a}`);const o=[];let l=0;for(;l<r;)o.push(t.slice(l,l+a)),l+=a;return o},Wr=t=>Promise.all(t.map(async e=>{const n=await cs(e);return await hi(e.uuid,n),e.uploadId})),Yr=async t=>{b.info(`Marking upload complete if finished: ${t}`);const e=await pi(t);if(!(e!=null&&e.length)){b.info(`No finished chunks found for upload: ${t}`);return}const n=e.reduce((i,a)=>(i.find(o=>o.chunkIndex===a.chunkIndex)||i.push(a),i),[]);n.sort((i,a)=>i.chunkIndex-a.chunkIndex);const r=n.map(i=>({ETag:i.etag,PartNumber:i.chunkIndex})).filter(i=>i.ETag!==null),s=n[0];await tr({apiUrl:s.apiUrl,surveyId:s.surveyId,uploadId:t,responseGroupUuid:s.responseGroupId,etags:r,headers:s.completeUploadHeaders,replayDuration:s.replayDuration}),b.info(`Cleaning up chunks for ${t}`),await mi(t),b.info(`Done cleaning up chunks for ${t}`)},Vi=async()=>{ae(async()=>{const t=await fi({status:"ReadyForUpload"});if(!(t!=null&&t.length))return;const e=await Wr(t);b.info(`Finished uploading unfinished chunks for ${e}`),e!=null&&e.length&&await Promise.all(e.map(n=>{if(n)return Yr(n)}))},"Error uploading unfinished chunks")},zi=async(t,e)=>{await Wr(e),b.info(`Done uploading chunks for uploads: ${t.join(",")}`),await Promise.all(t.map(n=>Yr(n)))},Gi=t=>{let e=0;t.forEach(s=>{e+=s.length});const n=new Uint8Array(e);let r=0;return t.forEach(s=>{n.set(s,r),r+=s.length}),n},Xn=async(t,e,n)=>{const r=new TextEncoder;let s=null,i=null,a=null,o=!1,l=!1,[d,c]=[0,0];const h=t-Tt*1e3,u=[];let f=[];b.info(`Getting events between ${new Date(t).toLocaleTimeString()} and ${new Date(e).toLocaleTimeString()}`),b.info(`Using batch duration: ${bt}ms`);for(let y=h;y<e;y+=bt){if({validStartFound:l,events:f}=await qi(y,t,e,l,bt),!(f!=null&&f.length)){b.info("No events found");continue}d===0&&(d=f[0].timestamp),c=f[f.length-1].timestamp,b.info(`Last event time in batch: ${new Date(c).toLocaleTimeString()}`);const v=`${o?",":"["}${f.map(p=>p.event).join(",")}`,m=r.encode(v);n&&i===null&&(b.debug("Attempting compression"),a=new window.CompressionStream("gzip"),i=a.writable.getWriter()),Kr(()=>{n&&i?i.write(m):u.push(m)},"sdk_replay_compression_seconds"),o=!0}if(c-d<mn)return b.info(`Replay duration is shorter than minimum of ${mn}ms / Start:${d} / End:${c}`),null;const g=r.encode("]");return b.debug("Writing final close brace"),i&&a?(i.write(g),i.close(),s=new Uint8Array(await new Response(a.readable).arrayBuffer())):(u.push(g),s=Gi(u)),b.info("Finished generating file data"),s},Wi=async(t,e)=>{const n=window.CompressionStream!==void 0;let r=null;const s=e??Date.now(),i=s-t;try{r=await Xn(i,s,n)}catch(a){a instanceof Error&&window.UserLeap.reportError("Error compressing replay",a),n&&ae(async()=>{await Xn(i,s,!1)},"fileData fallback failed")}return r},Zn=async t=>{const{surveyId:e,responseGroupId:n,visitorId:r,apiUrl:s,completeUploadHeaders:i,replayParams:a,triggerTimestamp:o}=t,l=await Wi(a.replayDurationSeconds*1e3,o);if(l!=null&&l.length)b.info(`Found file data for survey: ${e}`);else{b.info(`File data is empty for survey: ${e}`);return}const d=Hi(l,a.minimumChunkSizeMb,a.signedUrls.length);b.info(`Got ${d.length} chunks for survey: ${e}`);const c=await Promise.all(d.map(async(h,u)=>{const f=b.v4(),g={apiUrl:s,chunkIndex:u+1,completeUploadHeaders:i,etag:null,responseGroupId:n,status:"ReadyForUpload",surveyId:e,timestamp:o,totalChunks:d.length,data:h,uploadId:a.uploadId,uploadUrl:a.signedUrls[u].url,uuid:f,visitorId:r};return b.info(`Recording chunk upload: ${JSON.stringify({index:g.chunkIndex,surveyId:g.surveyId,uploadId:g.uploadId,size:h.length,id:f},null,2)}`),await di(g),b.info(`Done creating chunk upload: ${f}`),g}));b.info(`All chunk records created. Beginning upload for survey: ${e}`),await zi([a.uploadId],c)},Jr=async(t,e)=>{if(b.info(`Attempting replay capture: ${JSON.stringify({isStandalone:t.isStandalone,duration:t.replayParams.replayDurationSeconds,type:t.replayParams.replayDurationType,responseGroupId:t.responseGroupId,surveyId:t.surveyId,triggerTimestamp:t.triggerTimestamp,visitorId:t.visitorId},null,2)}`),Ee()){b.info(`Replay recording is disabled: ${t.surveyId}`);return}b.info(`Replay recording enabled: ${t.surveyId}`);const{isHeatmap:n,isStandalone:r,replayParams:s,triggerTimestamp:i,responseGroupId:a}=t,o=async()=>{setTimeout(()=>b.eventEmitter.removeListener(b.SprigEvent.QuestionAnswered,o),0),ae(async()=>{s.replayDurationType==="before"?await Zn(t):await vi(a)},"Error in schedule/capture callback")};ae(async()=>{if(s.replayDurationType==="after"||s.replayDurationType==="beforeAndAfter"){!r&&!n&&(b.info("Attaching QuestionAnswered listener for non-standalone replay"),b.eventEmitter.on(b.SprigEvent.QuestionAnswered,o)),b.info(`Scheduling capture for replay of type: ${s.replayDurationType}`),await Xr(t);return}if(r||n||e)b.info(`Proceeding to capture replay for survey: ${t.surveyId} / standalone? ${r} / canUpload? ${e}`),await Zn(t),n&&Yi();else{const d=Tt+s.replayDurationSeconds,c=i-d*1e3,h=i;b.info(`Setting expiry minutes to ${s.expirationTimeLimitMinutes} for events from ${new Date(c).toLocaleTimeString()} to ${new Date(h).toLocaleTimeString()}`),await ui(c,h,s.expirationTimeLimitMinutes),b.info("Attaching QuestionAnswered listener"),b.eventEmitter.on(b.SprigEvent.QuestionAnswered,o)}},"Error in scheduling/capturing replay")},Yi=async()=>{parseInt(de??"0")||(b.sessionStorageHelper.removeItem("sprig.isCapturingHeatmap"),On=!1),b.sessionStorageHelper.getItem("sprig.teardownAfterCapture")&&(Rn(),Qr(),b.sessionStorageHelper.removeItem("sprig.teardownAfterCapture"))},Qr=()=>{if(Ee()){b.debug("Not clearing user data, replay is disabled");return}return A.transaction("rw",A.events,A.pendingCaptures,()=>{A.events.where("sessionId").equals(L).delete(),A.pendingCaptures.where("sessionId").equals(L).delete()}).catch(t=>{je("Error clearing session event data",t)})},Xr=async t=>{b.info(`Scheduling replay capture: ${JSON.stringify(t)}`);const{isHeatmap:e,surveyId:n}=t,r=await gi(),s=r==null?void 0:r.filter(o=>o.captureParams.surveyId===n);if(s!=null&&s.length){b.info(`Pending capture exists for survey: ${n}`);return}e&&(On=!0,b.sessionStorageHelper.setItem("sprig.isCapturingHeatmap","true"));const i={...t,replayParams:{...t.replayParams}};t.replayParams.replayDurationType==="beforeAndAfter"&&(i.replayParams.replayDurationSeconds*=2),i.replayParams.replayDurationType="before";const a=t.triggerTimestamp+t.replayParams.replayDurationSeconds*1e3;return i.triggerTimestamp=a,de=de?(parseInt(de)+1).toString():"1",b.sessionStorageHelper.setItem("sprig.pendingCount",de),yi({uuid:b.v4(),targetTimestamp:a,timestamp:Date.now(),captureParams:i})},J=(t,e)=>{var n,r;if(tt)try{(r=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||r.call(n,t,e)}catch(s){je("Error recording custom event",s)}},ae=async(t,e)=>{try{await t()}catch(n){je(e,n)}},Ji=t=>{t.description&&(t.description=Kn(t.description)),J("Sprig_PageView",t)},Qi=t=>{J("Sprig_TrackEvent",t)},Xi=t=>{J("Sprig_ShowSurvey",t)},Zr=t=>{J("Sprig_SubmitSurvey",t)},es=t=>{var e;(e=t==null?void 0:t.elementAttributes)!=null&&e.text&&(t.elementAttributes.text=Kn(t.elementAttributes.text)),J("Sprig_Click",t)},ts=t=>{J("Sprig_Refresh",t)},ns=t=>{t.currentPageTitle&&(t.currentPageTitle=Kn(t.currentPageTitle)),J("Sprig_BackForward",t)},rs=t=>{J("Sprig_Keystroke",t)},ss=async t=>{const{x:e,xPath:n,y:r}=t,s=zr[n];s?ae(async()=>{var a,o,l,d;const i=await A.events.get(s);if(i!=null&&i.event){const c=JSON.parse(i.event),h=e>((o=(a=c.data)==null?void 0:a.payload)==null?void 0:o.x)||0,u=r>((d=(l=c.data)==null?void 0:l.payload)==null?void 0:d.y)||0;if(!(h||u))return;h&&(c.data.payload.x=e),u&&(c.data.payload.y=r),c.data.payload.elementAttributes=t.elementAttributes,i.event=JSON.stringify(c),A.events.put(i)}else J("Sprig_Scroll",t)},"Error updating scroll event"):J("Sprig_Scroll",t)},Rn=()=>{wt&&(wt(),wt=void 0),tt=!1,[yn,gn,Vr].forEach(t=>{t&&clearInterval(t)}),Bi()},je=(t,e,{reportError:n}={reportError:!0})=>(Rn(),b.error(`${t} - ${JSON.stringify(e)}`),ai(t,e,{reportError:n})),Zi=()=>tt,Kn=t=>t&&t.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),ea=async({surveyId:t,responseGroupUuid:e,eventDigest:n,headers:r})=>{if(!t||!e)return!1;const s=window.UserLeap._API_URL;try{const i=await tr({surveyId:t,responseGroupUuid:e,eventDigest:n,apiUrl:s,headers:r},!0);return!(i!=null&&i.error)}catch(i){return console.warn("[Sprig] Error with completing session replay"),i instanceof Error&&window.UserLeap.reportError("completeSessionReplay",i),!1}},ta=Object.freeze(Object.defineProperty({__proto__:null,RecordBackForward:ns,RecordClick:es,RecordEvent:Qi,RecordKeystroke:rs,RecordPageView:Ji,RecordRefresh:ts,RecordScroll:ss,RecordSurveyComplete:Zr,RecordSurveyShown:Xi,_completeSessionReplay:ea,batchStoreEvents:Gr,checkPendingHeatmapsUrl:wi,clearUserReplayData:Qr,disableRecording:je,initializeReplay:Mi,isReplayRecording:Zi,scheduleCapture:Xr,scheduleOrCaptureReplay:Jr,teardownReplay:Rn,tryReplayAction:ae},Symbol.toStringTag,{value:"Module"}));b.registerReplay(ta);