@contentful/optimization-web 0.1.0-alpha
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/LICENSE +21 -0
- package/README.md +491 -0
- package/dist/AutoEntryViewTracking.d.ts +88 -0
- package/dist/AutoEntryViewTracking.d.ts.map +1 -0
- package/dist/Optimization.d.ts +146 -0
- package/dist/Optimization.d.ts.map +1 -0
- package/dist/analyzer.html +4 -0
- package/dist/builders/EventBuilder.d.ts +42 -0
- package/dist/builders/EventBuilder.d.ts.map +1 -0
- package/dist/builders/index.d.ts +2 -0
- package/dist/builders/index.d.ts.map +1 -0
- package/dist/contentful-optimization-web.umd.cjs +2 -0
- package/dist/contentful-optimization-web.umd.cjs.map +1 -0
- package/dist/global-constants.d.ts +37 -0
- package/dist/global-constants.d.ts.map +1 -0
- package/dist/handlers/beaconHandler.d.ts +24 -0
- package/dist/handlers/beaconHandler.d.ts.map +1 -0
- package/dist/handlers/createOnlineChangeListener.d.ts +34 -0
- package/dist/handlers/createOnlineChangeListener.d.ts.map +1 -0
- package/dist/handlers/createVisibilityChangeListener.d.ts +40 -0
- package/dist/handlers/createVisibilityChangeListener.d.ts.map +1 -0
- package/dist/handlers/index.d.ts +4 -0
- package/dist/handlers/index.d.ts.map +1 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6244 -0
- package/dist/index.js.map +1 -0
- package/dist/observers/ElementExistenceObserver.d.ts +195 -0
- package/dist/observers/ElementExistenceObserver.d.ts.map +1 -0
- package/dist/observers/ElementView.d.ts +178 -0
- package/dist/observers/ElementView.d.ts.map +1 -0
- package/dist/observers/ElementViewObserver.d.ts +164 -0
- package/dist/observers/ElementViewObserver.d.ts.map +1 -0
- package/dist/observers/index.d.ts +6 -0
- package/dist/observers/index.d.ts.map +1 -0
- package/dist/storage/LocalStore.d.ts +111 -0
- package/dist/storage/LocalStore.d.ts.map +1 -0
- package/dist/storage/index.d.ts +3 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/test/helpers.d.ts +41 -0
- package/dist/test/helpers.d.ts.map +1 -0
- package/dist/visualizer.html +4687 -0
- package/package.json +28 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../node_modules/.pnpm/@preact+signals-core@1.12.1/node_modules/@preact/signals-core/dist/signals-core.module.js","../../../../universal/core/src/personalization/resolvers/FlagsResolver.ts","../../../../node_modules/.pnpm/zod@4.1.5/node_modules/zod/v4/core/core.js","../../../../node_modules/.pnpm/zod@4.1.5/node_modules/zod/v4/core/util.js","../../../../node_modules/.pnpm/zod@4.1.5/node_modules/zod/v4/core/errors.js","../../../../node_modules/.pnpm/zod@4.1.5/node_modules/zod/v4/core/parse.js","../../../../node_modules/.pnpm/zod@4.1.5/node_modules/zod/v4/core/regexes.js","../../../../node_modules/.pnpm/zod@4.1.5/node_modules/zod/v4/core/checks.js","../../../../node_modules/.pnpm/zod@4.1.5/node_modules/zod/v4/core/versions.js","../../../../node_modules/.pnpm/zod@4.1.5/node_modules/zod/v4/core/schemas.js","../../../../node_modules/.pnpm/zod@4.1.5/node_modules/zod/v4/core/api.js","../../../../node_modules/.pnpm/zod@4.1.5/node_modules/zod/v4/mini/schemas.js","../../../../node_modules/.pnpm/zod@4.1.5/node_modules/zod/v4/mini/iso.js","../../../../universal/api-schemas/src/contentful/CtflEntry.ts","../../../../universal/api-schemas/src/contentful/AudienceEntry.ts","../../../../universal/api-schemas/src/contentful/MergeTagEntry.ts","../../../../universal/api-schemas/src/contentful/PersonalizationConfig.ts","../../../../universal/api-schemas/src/contentful/PersonalizationEntry.ts","../../../../universal/api-schemas/src/contentful/PersonalizedEntry.ts","../../../../universal/api-schemas/src/experience/event/properties/App.ts","../../../../universal/api-schemas/src/experience/event/properties/Campaign.ts","../../../../universal/api-schemas/src/experience/event/properties/Channel.ts","../../../../universal/api-schemas/src/experience/event/properties/Dictionary.ts","../../../../universal/api-schemas/src/experience/event/properties/GeoLocation.ts","../../../../universal/api-schemas/src/experience/event/properties/Library.ts","../../../../universal/api-schemas/src/experience/event/properties/Page.ts","../../../../universal/api-schemas/src/experience/event/properties/Properties.ts","../../../../universal/api-schemas/src/experience/event/properties/Screen.ts","../../../../universal/api-schemas/src/experience/event/properties/Traits.ts","../../../../universal/api-schemas/src/experience/profile/properties/SessionStatistics.ts","../../../../universal/api-schemas/src/experience/profile/Profile.ts","../../../../universal/api-schemas/src/experience/ResponseEnvelope.ts","../../../../universal/api-schemas/src/experience/BatchExperienceResponse.ts","../../../../universal/api-schemas/src/experience/change/Change.ts","../../../../universal/api-schemas/src/experience/event/UniversalEventProperties.ts","../../../../universal/api-schemas/src/experience/event/AliasEvent.ts","../../../../universal/api-schemas/src/experience/event/ComponentViewEvent.ts","../../../../universal/api-schemas/src/experience/event/GroupEvent.ts","../../../../universal/api-schemas/src/experience/event/IdentifyEvent.ts","../../../../universal/api-schemas/src/experience/event/PageViewEvent.ts","../../../../universal/api-schemas/src/experience/event/ScreenViewEvent.ts","../../../../universal/api-schemas/src/experience/event/TrackEvent.ts","../../../../universal/api-schemas/src/experience/event/BatchExperienceEvent.ts","../../../../universal/api-schemas/src/experience/event/ExperienceEvent.ts","../../../../universal/api-schemas/src/experience/ExperienceRequest.ts","../../../../universal/api-schemas/src/experience/personalization/SelectedPersonalization.ts","../../../../universal/api-schemas/src/experience/ExperienceResponse.ts","../../../../universal/api-schemas/src/insights/event/InsightsEvent.ts","../../../../universal/api-schemas/src/insights/event/BatchInsightsEvent.ts","../../../../node_modules/.pnpm/diary@0.4.5/node_modules/diary/browser.mjs","../../../../lib/logger/src/Logger.ts","../../../../lib/logger/src/LogSink.ts","../../../../node_modules/.pnpm/diary@0.4.5/node_modules/diary/utils.mjs","../../../../lib/logger/src/ConsoleLogSink.ts","../../../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js","../../../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js","../../../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js","../../../../node_modules/.pnpm/is-network-error@1.1.0/node_modules/is-network-error/index.js","../../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js","../../../../universal/api-client/src/fetch/createRetryFetchMethod.ts","../../../../universal/api-client/src/fetch/createTimeoutFetchMethod.ts","../../../../universal/api-client/src/fetch/createProtectedFetchMethod.ts","../../../../universal/api-client/src/fetch/Fetch.ts","../../../../universal/api-client/src/ApiClientBase.ts","../../../../universal/api-client/src/experience/ExperienceApiClient.ts","../../../../universal/api-client/src/insights/InsightsApiClient.ts","../../../../universal/api-client/src/ApiClient.ts","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/function/noop.mjs","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/compat/_internal/getSymbols.mjs","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/compat/_internal/getTag.mjs","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/compat/_internal/tags.mjs","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/predicate/isPlainObject.mjs","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/_internal/isUnsafeProperty.mjs","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/object/merge.mjs","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/compat/util/eq.mjs","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/predicate/isEqualWith.mjs","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/predicate/isEqual.mjs","../../../../universal/api-client/src/builders/EventBuilder.ts","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/compat/_internal/isDeepKey.mjs","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/compat/_internal/toKey.mjs","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/compat/util/toPath.mjs","../../../../node_modules/.pnpm/es-toolkit@1.39.10/node_modules/es-toolkit/dist/compat/object/get.mjs","../../../../universal/core/src/personalization/resolvers/MergeTagValueResolver.ts","../../../../universal/core/src/personalization/resolvers/PersonalizedEntryResolver.ts","../../../../universal/core/src/signals.ts","../../../../universal/core/src/lib/decorators/guardedBy.ts","../../../../universal/core/src/lib/value-presence/ValuePresence.ts","../../../../universal/core/src/ProductBase.ts","../../../../universal/core/src/analytics/AnalyticsBase.ts","../../../../universal/core/src/analytics/AnalyticsStateful.ts","../../../../universal/core/src/analytics/AnalyticsStateless.ts","../../../../universal/core/src/global-constants.ts","../../../../universal/core/src/lib/interceptor/InterceptorManager.ts","../../../../universal/core/src/CoreBase.ts","../../../../universal/core/src/personalization/PersonalizationBase.ts","../../../../universal/core/src/personalization/PersonalizationStateful.ts","../../../../universal/core/src/personalization/PersonalizationStateless.ts","../../../../universal/core/src/CoreStateful.ts","../../../../universal/core/src/CoreStateless.ts","../../../../node_modules/.pnpm/js-cookie@3.0.5/node_modules/js-cookie/dist/js.cookie.mjs","../src/AutoEntryViewTracking.ts","../src/builders/EventBuilder.ts","../src/global-constants.ts","../src/handlers/beaconHandler.ts","../src/handlers/createOnlineChangeListener.ts","../src/handlers/createVisibilityChangeListener.ts","../src/observers/ElementView.ts","../src/observers/ElementExistenceObserver.ts","../src/observers/ElementViewObserver.ts","../src/storage/LocalStore.ts","../src/Optimization.ts"],"sourcesContent":["var i=Symbol.for(\"preact-signals\");function t(){if(!(s>1)){var i,t=!1;while(void 0!==h){var r=h;h=void 0;f++;while(void 0!==r){var o=r.o;r.o=void 0;r.f&=-3;if(!(8&r.f)&&c(r))try{r.c()}catch(r){if(!t){i=r;t=!0}}r=o}}f=0;s--;if(t)throw i}else s--}function r(i){if(s>0)return i();s++;try{return i()}finally{t()}}var o=void 0;function n(i){var t=o;o=void 0;try{return i()}finally{o=t}}var h=void 0,s=0,f=0,v=0;function e(i){if(void 0!==o){var t=i.n;if(void 0===t||t.t!==o){t={i:0,S:i,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:t};if(void 0!==o.s)o.s.n=t;o.s=t;i.n=t;if(32&o.f)i.S(t);return t}else if(-1===t.i){t.i=0;if(void 0!==t.n){t.n.p=t.p;if(void 0!==t.p)t.p.n=t.n;t.p=o.s;t.n=void 0;o.s.n=t;o.s=t}return t}}}function u(i,t){this.v=i;this.i=0;this.n=void 0;this.t=void 0;this.W=null==t?void 0:t.watched;this.Z=null==t?void 0:t.unwatched;this.name=null==t?void 0:t.name}u.prototype.brand=i;u.prototype.h=function(){return!0};u.prototype.S=function(i){var t=this,r=this.t;if(r!==i&&void 0===i.e){i.x=r;this.t=i;if(void 0!==r)r.e=i;else n(function(){var i;null==(i=t.W)||i.call(t)})}};u.prototype.U=function(i){var t=this;if(void 0!==this.t){var r=i.e,o=i.x;if(void 0!==r){r.x=o;i.e=void 0}if(void 0!==o){o.e=r;i.x=void 0}if(i===this.t){this.t=o;if(void 0===o)n(function(){var i;null==(i=t.Z)||i.call(t)})}}};u.prototype.subscribe=function(i){var t=this;return E(function(){var r=t.value,n=o;o=void 0;try{i(r)}finally{o=n}},{name:\"sub\"})};u.prototype.valueOf=function(){return this.value};u.prototype.toString=function(){return this.value+\"\"};u.prototype.toJSON=function(){return this.value};u.prototype.peek=function(){var i=o;o=void 0;try{return this.value}finally{o=i}};Object.defineProperty(u.prototype,\"value\",{get:function(){var i=e(this);if(void 0!==i)i.i=this.i;return this.v},set:function(i){if(i!==this.v){if(f>100)throw new Error(\"Cycle detected\");this.v=i;this.i++;v++;s++;try{for(var r=this.t;void 0!==r;r=r.x)r.t.N()}finally{t()}}}});function d(i,t){return new u(i,t)}function c(i){for(var t=i.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function a(i){for(var t=i.s;void 0!==t;t=t.n){var r=t.S.n;if(void 0!==r)t.r=r;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break}}}function l(i){var t=i.s,r=void 0;while(void 0!==t){var o=t.p;if(-1===t.i){t.S.U(t);if(void 0!==o)o.n=t.n;if(void 0!==t.n)t.n.p=o}else r=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=o}i.s=r}function y(i,t){u.call(this,void 0);this.x=i;this.s=void 0;this.g=v-1;this.f=4;this.W=null==t?void 0:t.watched;this.Z=null==t?void 0:t.unwatched;this.name=null==t?void 0:t.name}y.prototype=new u;y.prototype.h=function(){this.f&=-3;if(1&this.f)return!1;if(32==(36&this.f))return!0;this.f&=-5;if(this.g===v)return!0;this.g=v;this.f|=1;if(this.i>0&&!c(this)){this.f&=-2;return!0}var i=o;try{a(this);o=this;var t=this.x();if(16&this.f||this.v!==t||0===this.i){this.v=t;this.f&=-17;this.i++}}catch(i){this.v=i;this.f|=16;this.i++}o=i;l(this);this.f&=-2;return!0};y.prototype.S=function(i){if(void 0===this.t){this.f|=36;for(var t=this.s;void 0!==t;t=t.n)t.S.S(t)}u.prototype.S.call(this,i)};y.prototype.U=function(i){if(void 0!==this.t){u.prototype.U.call(this,i);if(void 0===this.t){this.f&=-33;for(var t=this.s;void 0!==t;t=t.n)t.S.U(t)}}};y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;void 0!==i;i=i.x)i.t.N()}};Object.defineProperty(y.prototype,\"value\",{get:function(){if(1&this.f)throw new Error(\"Cycle detected\");var i=e(this);this.h();if(void 0!==i)i.i=this.i;if(16&this.f)throw this.v;return this.v}});function w(i,t){return new y(i,t)}function _(i){var r=i.u;i.u=void 0;if(\"function\"==typeof r){s++;var n=o;o=void 0;try{r()}catch(t){i.f&=-2;i.f|=8;b(i);throw t}finally{o=n;t()}}}function b(i){for(var t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;_(i)}function g(i){if(o!==this)throw new Error(\"Out-of-order effect\");l(this);o=i;this.f&=-2;if(8&this.f)b(this);t()}function p(i,t){this.x=i;this.u=void 0;this.s=void 0;this.o=void 0;this.f=32;this.name=null==t?void 0:t.name}p.prototype.c=function(){var i=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();if(\"function\"==typeof t)this.u=t}finally{i()}};p.prototype.S=function(){if(1&this.f)throw new Error(\"Cycle detected\");this.f|=1;this.f&=-9;_(this);a(this);s++;var i=o;o=this;return g.bind(this,i)};p.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.o=h;h=this}};p.prototype.d=function(){this.f|=8;if(!(1&this.f))b(this)};p.prototype.dispose=function(){this.d()};function E(i,t){var r=new p(i,t);try{r.c()}catch(i){r.d();throw i}var o=r.d.bind(r);o[Symbol.dispose]=o;return o}export{y as Computed,p as Effect,u as Signal,r as batch,w as computed,E as effect,d as signal,n as untracked};//# sourceMappingURL=signals-core.module.js.map\n","import type { ChangeArray, Flags } from '@contentful/optimization-api-client'\n\n/**\n * Resolves a {@link Flags} map from a list of optimization changes.\n *\n * @public\n * @remarks\n * Given an Optimization {@link ChangeArray}, this utility flattens the list into a\n * simple key–value object suitable for quick lookups in client code. When `changes`\n * is `undefined`, an empty object is returned. If a change value is wrapped in an\n * object like `{ value: { ... } }`, this resolver unwraps it to the underlying object.\n */\nconst FlagsResolver = {\n /**\n * Build a flattened map of flag keys to values from a change list.\n *\n * @param changes - The change list returned by the optimization service.\n * @returns A map of flag keys to their resolved values.\n * @example\n * ```ts\n * const flags = FlagsResolver.resolve(data.changes)\n * if (flags['theme'] === 'dark') enableDarkMode()\n * ```\n * @example\n * // Handles wrapped values produced by the API\n * ```ts\n * const flags = FlagsResolver.resolve([\n * { type: 'Variable', key: 'price', value: { value: { amount: 10, currency: 'USD' } } }\n * ])\n * console.log(flags.price.amount) // 10\n * ```\n */\n resolve(changes?: ChangeArray): Flags {\n if (!changes) return {}\n\n return changes.reduce<Flags>((acc, { key, value }) => {\n const actualValue =\n typeof value === 'object' &&\n value !== null &&\n 'value' in value &&\n typeof value.value === 'object'\n ? value.value\n : value\n\n acc[key] = actualValue\n\n return acc\n }, {})\n },\n}\n\nexport default FlagsResolver\n","/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n var _a;\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod ?? {},\n enumerable: false,\n });\n (_a = inst._zod).traits ?? (_a.traits = new Set());\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n for (const k in _.prototype) {\n if (!(k in inst))\n Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });\n }\n inst._zod.constr = _;\n inst._zod.def = def;\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error();\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\"Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = {\n ...schema._zod.def,\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n checks: schema._zod.def.checks,\n };\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, _mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, _mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? Object.assign(_ctx, { direction: \"backward\" }) : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","export const cuid = /^[cC][^\\s-]{8,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\nexport const e164 = /^\\+(?:[0-9]){6,14}[0-9]$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^\\d+n?$/;\nexport const integer = /^\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?/i;\nexport const boolean = /true|false/i;\nconst _null = /null/i;\nexport { _null as null };\nconst _undefined = /undefined/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9-_]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inst,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inst,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export const version = {\n major: 4,\n minor: 1,\n patch: 5,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n // const handleChecksResult = (\n // checkResult: ParsePayload,\n // originalResult: ParsePayload,\n // ctx: ParseContextInternal\n // ): util.MaybeAsync<ParsePayload> => {\n // // if the checks mutated the value && there are no issues, re-parse the result\n // if (checkResult.value !== originalResult.value && !checkResult.issues.length)\n // return inst._zod.parse(checkResult, ctx);\n // return originalResult;\n // };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n inst[\"~standard\"] = {\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n };\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: regexes.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = `ipv4`;\n });\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = `ipv6`;\n });\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const [address, prefix] = payload.value.split(\"/\");\n try {\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.contentEncoding = \"base64\";\n });\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.contentEncoding = \"base64url\";\n });\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checksp\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (result.value === undefined) {\n if (key in input) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape[k]._zod.traits.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n // iterate over input keys\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n for (const key of Object.keys(input)) {\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));\n }\n else {\n handlePropertyResult(r, payload, key, input);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));\n }\n else {\n handlePropertyResult(r, payload, key, input);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {}`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n doc.write(`const ${id} = ${parseStr(key)};`);\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n if (def.unionFallback) {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n if (left.issues.length) {\n result.issues.push(...left.issues);\n }\n if (right.issues.length) {\n result.issues.push(...right.issues);\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== \"optional\");\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n if (!def.rest) {\n const tooBig = input.length > items.length;\n const tooSmall = input.length < optStart - 1;\n if (tooBig || tooSmall) {\n payload.issues.push({\n ...(tooBig ? { code: \"too_big\", maximum: items.length } : { code: \"too_small\", minimum: items.length }),\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n }\n let i = -1;\n for (const item of items) {\n i++;\n if (i >= input.length)\n if (i >= optStart)\n continue;\n const result = item._zod.run({\n value: input[i],\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n if (def.rest) {\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({\n value: el,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n if (def.keyType._zod.values) {\n const values = def.keyType._zod.values;\n payload.value = {};\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!values.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n payload.value[keyResult.value] = keyResult.value;\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n inst._zod.values = new Set(def.values);\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (inst._zod.values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (result.issues.length && input === undefined) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, payload.value));\n return handleOptionalResult(result, payload.value);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"template_literal\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // let _innerType!: any;\n // util.defineLazy(def, \"getter\", () => {\n // if (!_innerType) {\n // _innerType = def.getter();\n // }\n // return () => _innerType;\n // });\n util.defineLazy(inst._zod, \"innerType\", () => def.getter());\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType._zod.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType._zod.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType._zod.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","import * as checks from \"./checks.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\nexport function _superRefine(fn) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n });\n return ch;\n}\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodMiniType = /*@__PURE__*/ core.$constructor(\"ZodMiniType\", (inst, def) => {\n if (!inst._zod)\n throw new Error(\"Uninitialized schema in ZodMiniType.\");\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.check = (...checks) => {\n return inst.clone({\n ...def,\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }\n // { parent: true }\n );\n };\n inst.clone = (_def, params) => core.clone(inst, _def, params);\n inst.brand = () => inst;\n inst.register = ((reg, meta) => {\n reg.add(inst, meta);\n return inst;\n });\n});\nexport const ZodMiniString = /*@__PURE__*/ core.$constructor(\"ZodMiniString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function string(params) {\n return core._string(ZodMiniString, params);\n}\nexport const ZodMiniStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n ZodMiniString.init(inst, def);\n});\nexport const ZodMiniEmail = /*@__PURE__*/ core.$constructor(\"ZodMiniEmail\", (inst, def) => {\n core.$ZodEmail.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodMiniEmail, params);\n}\nexport const ZodMiniGUID = /*@__PURE__*/ core.$constructor(\"ZodMiniGUID\", (inst, def) => {\n core.$ZodGUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodMiniGUID, params);\n}\nexport const ZodMiniUUID = /*@__PURE__*/ core.$constructor(\"ZodMiniUUID\", (inst, def) => {\n core.$ZodUUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodMiniUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodMiniUUID, params);\n}\nexport const ZodMiniURL = /*@__PURE__*/ core.$constructor(\"ZodMiniURL\", (inst, def) => {\n core.$ZodURL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodMiniURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodMiniURL, {\n protocol: /^https?$/,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEmoji = /*@__PURE__*/ core.$constructor(\"ZodMiniEmoji\", (inst, def) => {\n core.$ZodEmoji.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodMiniEmoji, params);\n}\nexport const ZodMiniNanoID = /*@__PURE__*/ core.$constructor(\"ZodMiniNanoID\", (inst, def) => {\n core.$ZodNanoID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodMiniNanoID, params);\n}\nexport const ZodMiniCUID = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID\", (inst, def) => {\n core.$ZodCUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function cuid(params) {\n return core._cuid(ZodMiniCUID, params);\n}\nexport const ZodMiniCUID2 = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID2\", (inst, def) => {\n core.$ZodCUID2.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodMiniCUID2, params);\n}\nexport const ZodMiniULID = /*@__PURE__*/ core.$constructor(\"ZodMiniULID\", (inst, def) => {\n core.$ZodULID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodMiniULID, params);\n}\nexport const ZodMiniXID = /*@__PURE__*/ core.$constructor(\"ZodMiniXID\", (inst, def) => {\n core.$ZodXID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodMiniXID, params);\n}\nexport const ZodMiniKSUID = /*@__PURE__*/ core.$constructor(\"ZodMiniKSUID\", (inst, def) => {\n core.$ZodKSUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodMiniKSUID, params);\n}\nexport const ZodMiniIPv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv4\", (inst, def) => {\n core.$ZodIPv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodMiniIPv4, params);\n}\nexport const ZodMiniIPv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv6\", (inst, def) => {\n core.$ZodIPv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodMiniIPv6, params);\n}\nexport const ZodMiniCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodMiniCIDRv4, params);\n}\nexport const ZodMiniCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodMiniCIDRv6, params);\n}\nexport const ZodMiniBase64 = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64\", (inst, def) => {\n core.$ZodBase64.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodMiniBase64, params);\n}\nexport const ZodMiniBase64URL = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64URL\", (inst, def) => {\n core.$ZodBase64URL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodMiniBase64URL, params);\n}\nexport const ZodMiniE164 = /*@__PURE__*/ core.$constructor(\"ZodMiniE164\", (inst, def) => {\n core.$ZodE164.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodMiniE164, params);\n}\nexport const ZodMiniJWT = /*@__PURE__*/ core.$constructor(\"ZodMiniJWT\", (inst, def) => {\n core.$ZodJWT.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodMiniJWT, params);\n}\nexport const ZodMiniCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniCustomStringFormat\", (inst, def) => {\n core.$ZodCustomStringFormat.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodMiniCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n // check for unrecognized format\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodMiniCustomStringFormat, format, regex, params);\n}\nexport const ZodMiniNumber = /*@__PURE__*/ core.$constructor(\"ZodMiniNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function number(params) {\n return core._number(ZodMiniNumber, params);\n}\nexport const ZodMiniNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodMiniNumber.init(inst, def);\n});\n// int\nexport function int(params) {\n return core._int(ZodMiniNumberFormat, params);\n}\n// float32\nexport function float32(params) {\n return core._float32(ZodMiniNumberFormat, params);\n}\n// float64\nexport function float64(params) {\n return core._float64(ZodMiniNumberFormat, params);\n}\n// int32\nexport function int32(params) {\n return core._int32(ZodMiniNumberFormat, params);\n}\n// uint32\nexport function uint32(params) {\n return core._uint32(ZodMiniNumberFormat, params);\n}\nexport const ZodMiniBoolean = /*@__PURE__*/ core.$constructor(\"ZodMiniBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function boolean(params) {\n return core._boolean(ZodMiniBoolean, params);\n}\nexport const ZodMiniBigInt = /*@__PURE__*/ core.$constructor(\"ZodMiniBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function bigint(params) {\n return core._bigint(ZodMiniBigInt, params);\n}\nexport const ZodMiniBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodMiniBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodMiniBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodMiniBigIntFormat, params);\n}\nexport const ZodMiniSymbol = /*@__PURE__*/ core.$constructor(\"ZodMiniSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function symbol(params) {\n return core._symbol(ZodMiniSymbol, params);\n}\nexport const ZodMiniUndefined = /*@__PURE__*/ core.$constructor(\"ZodMiniUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nfunction _undefined(params) {\n return core._undefined(ZodMiniUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodMiniNull = /*@__PURE__*/ core.$constructor(\"ZodMiniNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nfunction _null(params) {\n return core._null(ZodMiniNull, params);\n}\nexport { _null as null };\nexport const ZodMiniAny = /*@__PURE__*/ core.$constructor(\"ZodMiniAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function any() {\n return core._any(ZodMiniAny);\n}\nexport const ZodMiniUnknown = /*@__PURE__*/ core.$constructor(\"ZodMiniUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function unknown() {\n return core._unknown(ZodMiniUnknown);\n}\nexport const ZodMiniNever = /*@__PURE__*/ core.$constructor(\"ZodMiniNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function never(params) {\n return core._never(ZodMiniNever, params);\n}\nexport const ZodMiniVoid = /*@__PURE__*/ core.$constructor(\"ZodMiniVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nfunction _void(params) {\n return core._void(ZodMiniVoid, params);\n}\nexport { _void as void };\nexport const ZodMiniDate = /*@__PURE__*/ core.$constructor(\"ZodMiniDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function date(params) {\n return core._date(ZodMiniDate, params);\n}\nexport const ZodMiniArray = /*@__PURE__*/ core.$constructor(\"ZodMiniArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function array(element, params) {\n return new ZodMiniArray({\n type: \"array\",\n element: element,\n ...util.normalizeParams(params),\n });\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodMiniObject = /*@__PURE__*/ core.$constructor(\"ZodMiniObject\", (inst, def) => {\n core.$ZodObject.init(inst, def);\n ZodMiniType.init(inst, def);\n util.defineLazy(inst, \"shape\", () => def.shape);\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n get shape() {\n util.assignProp(this, \"shape\", { ...shape });\n return this.shape;\n },\n ...util.normalizeParams(params),\n };\n return new ZodMiniObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n // shape: shape as core.$ZodLooseShape,\n get shape() {\n util.assignProp(this, \"shape\", { ...shape });\n return this.shape;\n },\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n // shape: shape as core.$ZodLooseShape,\n get shape() {\n util.assignProp(this, \"shape\", { ...shape });\n return this.shape;\n },\n // get optional() {\n // return util.optionalKeys(shape);\n // },\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\n// object methods\nexport function extend(schema, shape) {\n return util.extend(schema, shape);\n}\nexport function safeExtend(schema, shape) {\n return util.safeExtend(schema, shape);\n}\nexport function merge(schema, shape) {\n return util.extend(schema, shape);\n}\nexport function pick(schema, mask) {\n return util.pick(schema, mask);\n}\n// .omit\nexport function omit(schema, mask) {\n return util.omit(schema, mask);\n}\nexport function partial(schema, mask) {\n return util.partial(ZodMiniOptional, schema, mask);\n}\nexport function required(schema, mask) {\n return util.required(ZodMiniNonOptional, schema, mask);\n}\nexport function catchall(inst, catchall) {\n return inst.clone({ ...inst._zod.def, catchall: catchall });\n}\nexport const ZodMiniUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function union(options, params) {\n return new ZodMiniUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniDiscriminatedUnion\", (inst, def) => {\n core.$ZodDiscriminatedUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n return new ZodMiniDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniIntersection = /*@__PURE__*/ core.$constructor(\"ZodMiniIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function intersection(left, right) {\n return new ZodMiniIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodMiniTuple = /*@__PURE__*/ core.$constructor(\"ZodMiniTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodMiniTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniRecord = /*@__PURE__*/ core.$constructor(\"ZodMiniRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function record(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodMiniRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniMap = /*@__PURE__*/ core.$constructor(\"ZodMiniMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function map(keyType, valueType, params) {\n return new ZodMiniMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSet = /*@__PURE__*/ core.$constructor(\"ZodMiniSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function set(valueType, params) {\n return new ZodMiniSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEnum = /*@__PURE__*/ core.$constructor(\"ZodMiniEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodMiniType.init(inst, def);\n inst.options = Object.values(def.entries);\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function literal(value, params) {\n return new ZodMiniLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniFile = /*@__PURE__*/ core.$constructor(\"ZodMiniFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function file(params) {\n return core._file(ZodMiniFile, params);\n}\nexport const ZodMiniTransform = /*@__PURE__*/ core.$constructor(\"ZodMiniTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function transform(fn) {\n return new ZodMiniTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodMiniOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function optional(innerType) {\n return new ZodMiniOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniNullable = /*@__PURE__*/ core.$constructor(\"ZodMiniNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function nullable(innerType) {\n return new ZodMiniNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodMiniDefault = /*@__PURE__*/ core.$constructor(\"ZodMiniDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function _default(innerType, defaultValue) {\n return new ZodMiniDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniPrefault = /*@__PURE__*/ core.$constructor(\"ZodMiniPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodMiniPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniNonOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function nonoptional(innerType, params) {\n return new ZodMiniNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSuccess = /*@__PURE__*/ core.$constructor(\"ZodMiniSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function success(innerType) {\n return new ZodMiniSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCatch = /*@__PURE__*/ core.$constructor(\"ZodMiniCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nfunction _catch(innerType, catchValue) {\n return new ZodMiniCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodMiniNaN = /*@__PURE__*/ core.$constructor(\"ZodMiniNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function nan(params) {\n return core._nan(ZodMiniNaN, params);\n}\nexport const ZodMiniPipe = /*@__PURE__*/ core.$constructor(\"ZodMiniPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function pipe(in_, out) {\n return new ZodMiniPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n });\n}\nexport const ZodMiniCodec = /*@__PURE__*/ core.$constructor(\"ZodMiniCodec\", (inst, def) => {\n ZodMiniPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodMiniCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport const ZodMiniReadonly = /*@__PURE__*/ core.$constructor(\"ZodMiniReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function readonly(innerType) {\n return new ZodMiniReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodMiniTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function templateLiteral(parts, params) {\n return new ZodMiniTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLazy = /*@__PURE__*/ core.$constructor(\"ZodMiniLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// export function lazy<T extends object>(getter: () => T): T {\n// return util.createTransparentProxy<T>(getter);\n// }\nfunction _lazy(getter) {\n return new ZodMiniLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport { _lazy as lazy };\nexport const ZodMiniPromise = /*@__PURE__*/ core.$constructor(\"ZodMiniPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function promise(innerType) {\n return new ZodMiniPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCustom = /*@__PURE__*/ core.$constructor(\"ZodMiniCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// custom checks\nexport function check(fn, params) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// ZodCustom\n// custom schema\nexport function custom(fn, _params) {\n return core._custom(ZodMiniCustom, fn ?? (() => true), _params);\n}\n// refine\nexport function refine(fn, _params = {}) {\n return core._refine(ZodMiniCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn) {\n return core._superRefine(fn);\n}\n// instanceof\nclass Class {\n constructor(..._args) { }\n}\nfunction _instanceof(cls, params = {\n error: `Input not instance of ${cls.name}`,\n}) {\n const inst = custom((data) => data instanceof cls, params);\n inst._zod.bag.Class = cls;\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodMiniCodec,\n Boolean: ZodMiniBoolean,\n String: ZodMiniString,\n}, ...args);\nexport function json() {\n const jsonSchema = _lazy(() => {\n return union([string(), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\nexport const ZodMiniFunction = /*@__PURE__*/ core.$constructor(\"ZodMiniFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodMiniType.init(inst, def);\n});\nexport function _function(params) {\n return new ZodMiniFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodMiniISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodMiniStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodMiniISODateTime, params);\n}\nexport const ZodMiniISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodMiniStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodMiniISODate, params);\n}\nexport const ZodMiniISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodMiniStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodMiniISOTime, params);\n}\nexport const ZodMiniISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodMiniStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodMiniISODuration, params);\n}\n","import type { ChainModifiers, Entry, EntrySkeletonType, LocaleCode } from 'contentful'\nimport * as z from 'zod/mini'\n\n/**\n * Base Zod schema for entry fields.\n *\n * @remarks\n * This is modeled as a catch-all map from string keys to JSON-compatible values.\n * The strong typing ot consumer-specified Contentful Entry fields is not\n * validated by these schemas.\n */\nexport const EntryFields = z.catchall(z.object({}), z.json())\n\n/**\n * TypeScript type inferred from {@link EntryFields}.\n */\nexport type EntryFields = z.infer<typeof EntryFields>\n\n/**\n * Zod schema representing a generic Contentful Link object.\n *\n * @remarks\n * This is used for references to other Contentful resources where `linkType` is not constrained.\n */\nexport const Link = z.object({\n sys: z.object({\n type: z.literal('Link'),\n linkType: z.string(),\n id: z.string(),\n }),\n})\n\n/**\n * TypeScript type inferred from {@link Link}.\n */\nexport type Link = z.infer<typeof Link>\n\n/**\n * Zod schema representing a Contentful ContentType link.\n */\nexport const ContentTypeLink = z.object({\n sys: z.object({\n type: z.literal('Link'),\n linkType: z.literal('ContentType'),\n id: z.string(),\n }),\n})\n\n/**\n * TypeScript type inferred from {@link ContentTypeLink}.\n */\nexport type ContentTypeLink = z.infer<typeof ContentTypeLink>\n\n/**\n * Zod schema representing a Contentful Environment link.\n */\nexport const EnvironmentLink = z.object({\n sys: z.object({\n type: z.literal('Link'),\n linkType: z.literal('Environment'),\n id: z.string(),\n }),\n})\n\n/**\n * TypeScript type inferred from {@link EnvironmentLink}.\n */\nexport type EnvironmentLink = z.infer<typeof EnvironmentLink>\n\n/**\n * Zod schema representing a Contentful Space link.\n */\nexport const SpaceLink = z.object({\n sys: z.object({\n type: z.literal('Link'),\n linkType: z.literal('Space'),\n id: z.string(),\n }),\n})\n\n/**\n * TypeScript type inferred from {@link SpaceLink}.\n */\nexport type SpaceLink = z.infer<typeof SpaceLink>\n\n/**\n * Zod schema representing a Contentful Tag link.\n */\nexport const TagLink = z.object({\n sys: z.object({\n type: z.literal('Link'),\n linkType: z.literal('Tag'),\n id: z.string(),\n }),\n})\n\n/**\n * TypeScript type inferred from {@link TagLink}.\n */\nexport type TagLink = z.infer<typeof TagLink>\n\n/**\n * Zod schema describing the `sys` block for a Contentful entry.\n *\n * @remarks\n * This mirrors the structure of `Entry['sys']` from the Contentful SDK with\n * a subset of fields used by this library.\n */\nexport const EntrySys = z.object({\n type: z.literal('Entry'),\n contentType: ContentTypeLink,\n publishedVersion: z.number(),\n id: z.string(),\n createdAt: z.any(),\n updatedAt: z.any(),\n locale: z.optional(z.string()),\n revision: z.number(),\n space: SpaceLink,\n environment: EnvironmentLink,\n})\n\n/**\n * TypeScript type inferred from {@link EntrySys}.\n */\nexport type EntrySys = z.infer<typeof EntrySys>\n\n/**\n * Zod schema describing a generic Contentful entry.\n *\n * @remarks\n * This model is intentionally loose: `fields` is any JSON-compliant object and\n * `metadata` is modeled as a catch-all object that must contain an array of\n * {@link TagLink} tags.\n */\nexport const CtflEntry = z.object({\n /**\n * The entry fields payload.\n */\n fields: EntryFields,\n\n /**\n * Contentful metadata, including tags.\n */\n metadata: z.catchall(\n z.object({\n tags: z.array(TagLink),\n }),\n z.json(),\n ),\n\n /**\n * System-managed properties describing the entry.\n */\n sys: EntrySys,\n})\n\n/**\n * TypeScript type inferred from {@link CtflEntry}.\n */\nexport type CtflEntry = z.infer<typeof CtflEntry>\n\n/**\n * Type guard that checks whether the given value is a Contentful {@link Entry},\n * passing through the specified skeleton, chain modifiers, and locale.\n *\n * @typeParam S - The entry skeleton type.\n * @typeParam M - The chain modifiers type. Defaults to {@link ChainModifiers}.\n * @typeParam L - The locale code type. Defaults to {@link LocaleCode}.\n *\n * @param entry - The value to test.\n * @returns `true` if the object conforms to {@link CtflEntry} and can be treated\n * as a typed {@link Entry}, otherwise `false`.\n */\nexport function isEntry<\n S extends EntrySkeletonType,\n M extends ChainModifiers = ChainModifiers,\n L extends LocaleCode = LocaleCode,\n>(entry: Entry | undefined): entry is Entry<S, M, L> {\n return CtflEntry.safeParse(entry).success\n}\n","import * as z from 'zod/mini'\nimport { CtflEntry, EntryFields } from './CtflEntry'\n\n/**\n * Zod schema describing the fields of an Audience entry.\n *\n * @remarks\n * Extends the base {@link EntryFields} with audience-specific properties.\n */\nexport const AudienceEntryFields = z.extend(EntryFields, {\n /**\n * The internal id of the audience (Short Text).\n *\n * @remarks\n * This usually corresponds to a stable identifier used by the personalization system.\n */\n nt_audience_id: z.string(),\n\n /**\n * The name of the audience (Short Text).\n *\n * @remarks\n * Optional field used for display purposes in tools and UI.\n */\n nt_name: z.optional(z.string()),\n\n /**\n * The description of the audience (Short Text).\n *\n * @remarks\n * Optional field intended for internal documentation and operator context.\n */\n nt_description: z.optional(z.string()),\n})\n\n/**\n * TypeScript type inferred from {@link AudienceEntryFields}.\n */\nexport type AudienceEntryFields = z.infer<typeof AudienceEntryFields>\n\n/**\n * Zod schema for a Contentful Audience entry, including system metadata.\n *\n * @remarks\n * Extends the generic {@link CtflEntry} with {@link AudienceEntryFields} as the `fields` payload.\n */\nexport const AudienceEntry = z.extend(CtflEntry, {\n fields: AudienceEntryFields,\n})\n\n/**\n * TypeScript type inferred from {@link AudienceEntry}.\n */\nexport type AudienceEntry = z.infer<typeof AudienceEntry>\n","import * as z from 'zod/mini'\nimport { CtflEntry, EntrySys } from './CtflEntry'\n\n/**\n * Zod schema for a Merge Tag Contentful entry.\n *\n * @remarks\n * Extends {@link CtflEntry} with merge-tag-specific fields and constrains the\n * `contentType` to the `nt_mergetag` content type.\n */\nexport const MergeTagEntry = z.extend(CtflEntry, {\n fields: z.object({\n /**\n * Human-readable name of the merge tag.\n */\n nt_name: z.string(),\n\n /**\n * Fallback value to use when the merge tag cannot be resolved.\n */\n nt_fallback: z.optional(z.string()),\n\n /**\n * Internal identifier of the merge tag.\n */\n nt_mergetag_id: z.string(),\n }),\n\n /**\n * System fields extended to constrain the content type to `nt_mergetag`.\n */\n sys: z.extend(EntrySys, {\n contentType: z.object({\n sys: z.object({\n type: z.literal('Link'),\n linkType: z.literal('ContentType'),\n id: z.literal('nt_mergetag'),\n }),\n }),\n }),\n})\n\n/**\n * TypeScript type inferred from {@link MergeTagEntry}.\n */\nexport type MergeTagEntry = z.infer<typeof MergeTagEntry>\n","import * as z from 'zod/mini'\n\n/**\n * Zod schema describing a single entry replacement variant.\n *\n * @remarks\n * Each variant is identified by an `id` and may be marked as `hidden`.\n */\nexport const EntryReplacementVariant = z.object({\n /**\n * Unique identifier for the variant.\n */\n id: z.string(),\n\n /**\n * Indicates whether this variant is hidden from allocation/traffic.\n *\n * @defaultValue false\n */\n hidden: z.prefault(z.boolean(), false),\n})\n\n/**\n * TypeScript type inferred from {@link EntryReplacementVariant}.\n */\nexport type EntryReplacementVariant = z.infer<typeof EntryReplacementVariant>\n\n/**\n * Type guard for {@link EntryReplacementVariant}.\n *\n * @param variant - Value to test.\n * @returns `true` if `variant` conforms to {@link EntryReplacementVariant}, otherwise `false`.\n */\nexport function isEntryReplacementVariant(variant: unknown): variant is EntryReplacementVariant {\n return EntryReplacementVariant.safeParse(variant).success\n}\n\n/**\n * Zod schema describing an entry replacement personalization component.\n *\n * @remarks\n * This component replaces a baseline entry with one of several variants.\n */\nexport const EntryReplacementComponent = z.object({\n /**\n * Discriminator for the component type.\n *\n * @remarks\n * May be omitted, in which case the component is treated as an EntryReplacement.\n */\n type: z.optional(z.literal('EntryReplacement')),\n\n /**\n * Baseline variant used when no targeting or allocation selects another variant.\n */\n baseline: EntryReplacementVariant,\n\n /**\n * Additional variants that may be served.\n */\n variants: z.array(EntryReplacementVariant),\n})\n\n/**\n * TypeScript type inferred from {@link EntryReplacementComponent}.\n */\nexport type EntryReplacementComponent = z.infer<typeof EntryReplacementComponent>\n\n/**\n * Type guard for {@link EntryReplacementComponent}.\n *\n * @param component - Personalization component to test.\n * @returns `true` if the component is an EntryReplacement component, otherwise `false`.\n */\nexport function isEntryReplacementComponent(\n component: PersonalizationComponent,\n): component is EntryReplacementComponent {\n return component.type === 'EntryReplacement' || component.type === undefined\n}\n\n/**\n * Zod schema describing a variant for inline variables.\n *\n * @remarks\n * The value may be a primitive or a JSON object.\n */\nexport const InlineVariableVariant = z.object({\n /**\n * Variant value for the inline variable.\n */\n value: z.union([z.string(), z.boolean(), z.null(), z.number(), z.record(z.string(), z.json())]),\n})\n\n/**\n * Enumeration of supported inline variable value types.\n */\nexport const InlineVariableComponentValueType = z.enum(['Boolean', 'Number', 'Object', 'String'])\n\n/**\n * Zod schema describing an inline variable personalization component.\n *\n * @remarks\n * Used to vary scalar or object values in templates.\n */\nexport const InlineVariableComponent = z.object({\n /**\n * Discriminator for the inline variable component.\n */\n type: z.literal('InlineVariable'),\n\n /**\n * Key under which this variable is exposed to the template.\n */\n key: z.string(),\n\n /**\n * Describes the runtime type of the values for this variable.\n */\n valueType: InlineVariableComponentValueType,\n\n /**\n * Baseline value used when no targeting or allocation selects another variant.\n */\n baseline: InlineVariableVariant,\n\n /**\n * Additional variable variants for experimentation or personalization.\n */\n variants: z.array(InlineVariableVariant),\n})\n\n/**\n * TypeScript type inferred from {@link InlineVariableComponent}.\n */\nexport type InlineVariableComponent = z.infer<typeof InlineVariableComponent>\n\n/**\n * Type guard for {@link InlineVariableComponent}.\n *\n * @param component - Personalization component to test.\n * @returns `true` if the component is an InlineVariable component, otherwise `false`.\n */\nexport function isInlineVariableComponent(\n component: PersonalizationComponent,\n): component is InlineVariableComponent {\n return component.type === 'InlineVariable'\n}\n\n/**\n * Discriminated union of all supported personalization components.\n */\nexport const PersonalizationComponent = z.discriminatedUnion('type', [\n EntryReplacementComponent,\n InlineVariableComponent,\n])\n\n/**\n * TypeScript type inferred from {@link PersonalizationComponent}.\n */\nexport type PersonalizationComponent = z.infer<typeof PersonalizationComponent>\n\n/**\n * Zod schema representing an array of {@link PersonalizationComponent} items.\n */\nexport const PersonalizationComponentArray = z.array(PersonalizationComponent)\n\n/**\n * TypeScript type inferred from {@link PersonalizationComponentArray}.\n */\nexport type PersonalizationComponentArray = z.infer<typeof PersonalizationComponentArray>\n\n/**\n * Zod schema describing the full configuration for a personalization.\n *\n * @remarks\n * Provides distribution, traffic allocation, component definitions, and sticky behavior.\n */\nexport const PersonalizationConfig = z.object({\n /**\n * Variant distribution used for traffic allocation.\n *\n * @defaultValue [0.5, 0.5]\n */\n distribution: z.optional(z.prefault(z.array(z.number()), [0.5, 0.5])),\n\n /**\n * Percentage of total traffic that should enter the personalization.\n *\n * @defaultValue 0\n */\n traffic: z.optional(z.prefault(z.number(), 0)),\n\n /**\n * Personalization components that define how content is varied.\n *\n * @defaultValue\n * A single {@link EntryReplacementComponent} with an empty `baseline` and `variants` ID.\n */\n components: z.optional(\n z.prefault(PersonalizationComponentArray, [\n {\n type: 'EntryReplacement',\n baseline: { id: '' },\n variants: [{ id: '' }],\n },\n ]),\n ),\n\n /**\n * Controls whether the assignment should be sticky for a given user.\n *\n * @defaultValue false\n */\n sticky: z.optional(z.prefault(z.boolean(), false)),\n})\n\n/**\n * TypeScript type inferred from {@link PersonalizationConfig}.\n */\nexport type PersonalizationConfig = z.infer<typeof PersonalizationConfig>\n","import type { Entry } from 'contentful'\nimport * as z from 'zod/mini'\nimport { AudienceEntry } from './AudienceEntry'\nimport { CtflEntry, EntryFields, Link } from './CtflEntry'\nimport { PersonalizationConfig } from './PersonalizationConfig'\n\n/**\n * Union of supported personalization types.\n *\n * @remarks\n * `nt_experiment` represents experiments (A/B tests), and `nt_personalization`\n * represents always-on personalized experiences.\n */\nexport const PersonalizationType = z.union([\n z.literal('nt_experiment'),\n z.literal('nt_personalization'),\n])\n\n/**\n * TypeScript type inferred from {@link PersonalizationType}.\n */\nexport type PersonalizationType = z.infer<typeof PersonalizationType>\n\n/**\n * Zod schema describing the fields of a Personalization entry.\n *\n * @remarks\n * Extends the generic {@link EntryFields} with personalization-specific\n * properties such as name, description, type, config, audience, and variants.\n */\nexport const PersonalizationFields = z.extend(EntryFields, {\n /**\n * The name of the personalization (Short Text).\n */\n nt_name: z.string(),\n\n /**\n * The description of the personalization (Short Text).\n *\n * @remarks\n * Optional, may be `null` if no description is provided.\n */\n nt_description: z.optional(z.nullable(z.string())),\n\n /**\n * The type of the personalization (`nt_experiment` | `nt_personalization`).\n */\n nt_type: PersonalizationType,\n\n /**\n * The configuration of a {@link PersonalizationEntry } (JSON).\n *\n * @remarks\n * Accepts `null` or an explicit {@link PersonalizationConfig} and converts\n * falsy/undefined values into a default configuration.\n */\n nt_config: z.pipe(\n z.optional(z.prefault(z.nullable(PersonalizationConfig), null)),\n z.transform<PersonalizationConfig | null>(\n (v) =>\n v ?? {\n traffic: 0,\n distribution: [0.5, 0.5],\n components: [],\n sticky: false,\n },\n ),\n ),\n\n /**\n * The audience of the personalization (Audience).\n *\n * @remarks\n * Optional and nullable; when omitted or `null`, the personalization may apply\n * to all users.\n */\n nt_audience: z.optional(z.nullable(AudienceEntry)),\n\n /**\n * All used variants of the personalization (Contentful references to other Content Types).\n *\n * @remarks\n * Modeled as an array of untyped Contentful entries and defaults to an empty\n * array when omitted.\n */\n nt_variants: z.optional(z.prefault(z.array(z.custom<Entry>()), [])),\n\n /**\n * The personalization/experience ID related to this personalization entry.\n */\n nt_experience_id: z.string(),\n})\n\n/**\n * TypeScript type inferred from {@link PersonalizationFields}.\n */\nexport type PersonalizationFields = z.infer<typeof PersonalizationFields>\n\n/**\n * Zod schema describing a Personalization entry, which is associated with a {@link PersonalizedEntry } via its `fields.nt_experiences`.\n */\nexport const PersonalizationEntry = z.extend(CtflEntry, {\n fields: PersonalizationFields,\n})\n\n/**\n * TypeScript type inferred from {@link PersonalizationEntry}.\n */\nexport type PersonalizationEntry = z.infer<typeof PersonalizationEntry>\n\n/**\n * Type guard for {@link PersonalizationEntry}.\n *\n * @param entry - Contentful entry or link to test.\n * @returns `true` if the value conforms to {@link PersonalizationEntry}, otherwise `false`.\n */\nexport function isPersonalizationEntry(entry: CtflEntry | Link): entry is PersonalizationEntry {\n return PersonalizationEntry.safeParse(entry).success\n}\n\n/**\n * Zod schema describing an array of personalization entries or links.\n *\n * @remarks\n * Each element may be a {@link Link} or a fully resolved {@link PersonalizationEntry}.\n */\nexport const PersonalizationEntryArray = z.array(z.union([Link, PersonalizationEntry]))\n\n/**\n * TypeScript type inferred from {@link PersonalizationEntryArray}.\n */\nexport type PersonalizationEntryArray = z.infer<typeof PersonalizationEntryArray>\n","import type { Entry } from 'contentful'\nimport * as z from 'zod/mini'\nimport { CtflEntry, EntryFields } from './CtflEntry'\nimport { PersonalizationEntryArray } from './PersonalizationEntry'\n\n/**\n * Zod schema describing a Contentful entry that has attached personalizations.\n *\n * @remarks\n * Extends {@link CtflEntry} and adds `nt_experiences` to the `fields` object.\n */\nexport const PersonalizedEntry = z.extend(CtflEntry, {\n fields: z.extend(EntryFields, {\n /**\n * Personalization or experimentation experiences attached to this entry.\n */\n nt_experiences: PersonalizationEntryArray,\n }),\n})\n\n/**\n * TypeScript type inferred from {@link PersonalizedEntry}.\n */\nexport type PersonalizedEntry = z.infer<typeof PersonalizedEntry>\n\n/**\n * Type guard for {@link PersonalizedEntry}.\n *\n * @param entry - Contentful entry to test.\n * @returns `true` if the entry conforms to {@link PersonalizedEntry}, otherwise `false`.\n */\nexport function isPersonalizedEntry(entry: Entry | undefined): entry is PersonalizedEntry {\n return PersonalizedEntry.safeParse(entry).success\n}\n","import * as z from 'zod/mini'\n\n/**\n * Zod schema describing app-level properties.\n *\n * @remarks\n * These properties typically describe the application that is emitting\n * analytics events, such as its name and version.\n *\n * The entire object is optional; when omitted, no app context is attached.\n */\nexport const App = z.optional(\n z.object({\n /**\n * Name of the application.\n */\n name: z.string(),\n\n /**\n * Version of the application.\n */\n version: z.string(),\n }),\n)\n\n/**\n * TypeScript type inferred from {@link App}.\n */\nexport type App = z.infer<typeof App>\n","import * as z from 'zod/mini'\n\n/**\n * Zod schema describing campaign attribution properties.\n *\n * @remarks\n * These fields typically mirror UTM parameters used for marketing campaigns.\n */\nexport const Campaign = z.object({\n /**\n * Name of the campaign (e.g., `utm_campaign`).\n */\n name: z.optional(z.string()),\n\n /**\n * Campaign source (e.g., `utm_source`).\n */\n source: z.optional(z.string()),\n\n /**\n * Campaign medium (e.g., `utm_medium`).\n */\n medium: z.optional(z.string()),\n\n /**\n * Campaign term (e.g., `utm_term`).\n */\n term: z.optional(z.string()),\n\n /**\n * Campaign content (e.g., `utm_content`).\n */\n content: z.optional(z.string()),\n})\n\n/**\n * TypeScript type inferred from {@link Campaign}.\n */\nexport type Campaign = z.infer<typeof Campaign>\n","import * as z from 'zod/mini'\n\n/**\n * Zod schema describing the analytics channel.\n *\n * @remarks\n * Indicates the execution environment where the event originated.\n *\n * - `'mobile'` — Events from native or hybrid mobile apps.\n * - `'server'` — Events emitted from backend/server-side code.\n * - `'web'` — Events from web browsers or web-based clients.\n */\nexport const Channel = z.union([z.literal('mobile'), z.literal('server'), z.literal('web')])\n\n/**\n * TypeScript type inferred from {@link Channel}.\n */\nexport type Channel = z.infer<typeof Channel>\n","import * as z from 'zod/mini'\n\n/**\n * Zod schema describing a simple string-to-string dictionary.\n *\n * @remarks\n * Commonly used for query parameters or other small key–value maps.\n */\nexport const Dictionary = z.record(z.string(), z.string())\n\n/**\n * TypeScript type inferred from {@link Dictionary}.\n */\nexport type Dictionary = z.infer<typeof Dictionary>\n","import * as z from 'zod/mini'\n\n/**\n * Length (in characters) of the expected country code.\n *\n * @remarks\n * Typically corresponds to ISO 3166-1 alpha-2 country codes.\n */\nconst COUNTRY_CODE_LENGTH = 2\n\n/**\n * Zod schema describing geographical coordinates.\n *\n * @remarks\n * Latitude and longitude are expressed in decimal degrees.\n */\nconst Coordinates = z.object({\n /**\n * Latitude component of the coordinates.\n */\n latitude: z.number(),\n\n /**\n * Longitude component of the coordinates.\n */\n longitude: z.number(),\n})\n\n/**\n * Zod schema describing geo-location properties associated with an event.\n *\n * @remarks\n * All properties are optional and may be derived from IP or device data.\n */\nexport const GeoLocation = z.object({\n /**\n * Geographical coordinates for the location.\n */\n coordinates: z.optional(Coordinates),\n\n /**\n * City name associated with the location.\n */\n city: z.optional(z.string()),\n\n /**\n * Postal or ZIP code associated with the location.\n */\n postalCode: z.optional(z.string()),\n\n /**\n * Region or state name associated with the location.\n */\n region: z.optional(z.string()),\n\n /**\n * Region or state code associated with the location.\n */\n regionCode: z.optional(z.string()),\n\n /**\n * Country name associated with the location.\n */\n country: z.optional(z.string()),\n\n /**\n * Country code associated with the location.\n *\n * @remarks\n * Validated to exactly COUNTRY_CODE_LENGTH characters, typically\n * an ISO 3166-1 alpha-2 code.\n */\n countryCode: z.optional(z.string().check(z.length(COUNTRY_CODE_LENGTH))),\n\n /**\n * Continent name associated with the location.\n */\n continent: z.optional(z.string()),\n\n /**\n * Time zone identifier associated with the location.\n *\n * @remarks\n * Typically an IANA time zone string (e.g., `\"Europe/Berlin\"`).\n */\n timezone: z.optional(z.string()),\n})\n\n/**\n * TypeScript type inferred from {@link GeoLocation}.\n */\nexport type GeoLocation = z.infer<typeof GeoLocation>\n","import * as z from 'zod/mini'\n\n/**\n * Zod schema describing analytics library metadata.\n *\n * @remarks\n * Identifies the client library that produced the event.\n */\nexport const Library = z.object({\n /**\n * Name of the SDK/library (e.g., `\"@contentful/optimization-web\"`).\n */\n name: z.string(),\n\n /**\n * Version of the analytics library.\n */\n version: z.string(),\n})\n\n/**\n * TypeScript type inferred from {@link Library}.\n */\nexport type Library = z.infer<typeof Library>\n","import * as z from 'zod/mini'\nimport { Dictionary } from './Dictionary'\n\n/**\n * Zod schema describing Web page-level properties for events.\n *\n * @remarks\n * The base object describes standard page attributes, while additional\n * JSON properties may be present due to the use of `z.catchall`.\n */\nexport const Page = z.catchall(\n z.object({\n /**\n * Path component of the page URL (e.g., `/products/123`).\n */\n path: z.string(),\n\n /**\n * Parsed query parameters for the page.\n */\n query: Dictionary,\n\n /**\n * Referrer URL that led to the current page.\n */\n referrer: z.string(),\n\n /**\n * Raw search string including the leading `?` (e.g., `\"?q=test\"`).\n */\n search: z.string(),\n\n /**\n * Title of the page as seen by the user.\n */\n title: z.optional(z.string()),\n\n /**\n * Full URL of the page.\n */\n url: z.string(),\n }),\n z.json(),\n)\n\n/**\n * TypeScript type inferred from {@link Page}.\n */\nexport type Page = z.infer<typeof Page>\n","import * as z from 'zod/mini'\n\n/**\n * Zod schema describing a generic collection of event properties.\n *\n * @remarks\n * Represents an arbitrary JSON-serializable map from string keys to values.\n */\nexport const Properties = z.record(z.string(), z.json())\n\n/**\n * TypeScript type inferred from {@link Properties}.\n */\nexport type Properties = z.infer<typeof Properties>\n","import * as z from 'zod/mini'\n\n/**\n * Zod schema describing Web page-level properties for events.\n *\n * @remarks\n * The base object describes standard page attributes, while additional\n * JSON properties may be present due to the use of `z.catchall`.\n */\nexport const Screen = z.catchall(\n z.object({\n /**\n * Name or label for the screen.\n */\n name: z.string(),\n }),\n z.json(),\n)\n\n/**\n * TypeScript type inferred from {@link Page}.\n */\nexport type Screen = z.infer<typeof Screen>\n","import * as z from 'zod/mini'\n\n/**\n * Zod schema describing user traits / identity properties.\n *\n * @remarks\n * Represents an arbitrary JSON-serializable map from string keys to values.\n * Common traits may include `name`, `plan`, and custom attributes.\n */\nexport const Traits = z.record(z.string(), z.json())\n\n/**\n * TypeScript type inferred from {@link Traits}.\n */\nexport type Traits = z.infer<typeof Traits>\n","import * as z from 'zod/mini'\nimport { Page } from '../../event/properties'\n\n/**\n * Zod schema describing aggregated statistics for a user session.\n *\n * @remarks\n * Captures both per-session metrics (such as `activeSessionLength`) and\n * aggregate metrics (such as `averageSessionLength`) for a given profile.\n */\nexport const SessionStatistics = z.object({\n /**\n * Unique identifier for this session statistics record.\n */\n id: z.string(),\n\n /**\n * Indicates whether the visitor has been seen before.\n *\n * @remarks\n * `true` typically means the visitor has at least one prior session.\n */\n isReturningVisitor: z.boolean(),\n\n /**\n * Landing page for the session.\n *\n * @remarks\n * Represents the first page the user visited in this session.\n *\n * @see Page\n */\n landingPage: Page,\n\n /**\n * Number of sessions associated with this profile or identifier.\n *\n * @remarks\n * Often used in combination with {@link SessionStatistics.averageSessionLength}.\n */\n count: z.number(),\n\n /**\n * Duration of the active session.\n */\n activeSessionLength: z.number(),\n\n /**\n * Average session duration across all sessions represented by this record.\n *\n * @remarks\n * The unit should match {@link SessionStatistics.activeSessionLength}.\n */\n averageSessionLength: z.number(),\n})\n\n/**\n * TypeScript type inferred from {@link SessionStatistics}.\n */\nexport type SessionStatistics = z.infer<typeof SessionStatistics>\n","import * as z from 'zod/mini'\nimport { GeoLocation } from '../event/properties'\nimport { Traits } from '../event/properties/Traits'\nimport { SessionStatistics } from './properties'\n\n/**\n * Zod schema describing a full user profile as received from the Experience API.\n *\n * @remarks\n * Represents the server-side view of a profile, including identifiers,\n * traits, audiences, location, and session statistics.\n */\nexport const Profile = z.object({\n /**\n * Primary identifier of the profile.\n */\n id: z.string(),\n\n /**\n * Stable, long-lived identifier of the profile.\n *\n * @remarks\n * Intended to remain constant across sessions and devices when possible.\n * Usually equal to `id`.\n */\n stableId: z.string(),\n\n /**\n * Random value associated with the profile.\n *\n * @remarks\n * Often used for deterministic bucketing (e.g., in experiments).\n */\n random: z.number(),\n\n /**\n * List of audience identifiers that this profile currently belongs to.\n */\n audiences: z.array(z.string()),\n\n /**\n * Traits describing the profile (user-level attributes).\n *\n * @see Traits\n */\n traits: Traits,\n\n /**\n * Geo-location information associated with the profile.\n *\n * @see GeoLocation\n */\n location: GeoLocation,\n\n /**\n * Aggregated session statistics for the profile.\n *\n * @see SessionStatistics\n */\n session: SessionStatistics,\n})\n\n/**\n * TypeScript type inferred from {@link Profile}.\n */\nexport type Profile = z.infer<typeof Profile>\n\n/**\n * Zod schema describing a partial profile payload used for sending events\n * to the Experience & Insights APIs.\n *\n * @remarks\n * This schema enforces the presence of an `id` field and allows additional\n * JSON-serializable properties via `z.catchall`.\n */\nexport const PartialProfile = z.catchall(\n z.object({\n /**\n * Identifier of the profile.\n *\n * @remarks\n * Used to associate events with an existing profile.\n */\n id: z.string(),\n }),\n z.json(),\n)\n\n/**\n * TypeScript type inferred from {@link PartialProfile}.\n */\nexport type PartialProfile = z.infer<typeof PartialProfile>\n","import * as z from 'zod/mini'\n\n/**\n * Zod schema describing the common envelope structure of responses\n * from the Experience API.\n *\n * @remarks\n * Concrete responses extend this schema and refine the `data` property\n * to a more specific shape.\n */\nexport const ResponseEnvelope = z.object({\n /**\n * Response payload.\n *\n * @remarks\n * The base schema uses an empty object; specific responses extend this\n * with more detailed structures.\n */\n data: z.object(),\n\n /**\n * Human-readable message accompanying the response.\n */\n message: z.string(),\n\n /**\n * Indicates whether an error occurred.\n *\n * @remarks\n * May be `null` when the error state is unknown or not applicable.\n */\n error: z.nullable(z.boolean()),\n})\n\n/**\n * TypeScript type inferred from {@link ResponseEnvelope}.\n */\nexport type ResponseEnvelope = z.infer<typeof ResponseEnvelope>\n","import * as z from 'zod/mini'\nimport { Profile } from './profile'\nimport { ResponseEnvelope } from './ResponseEnvelope'\n\n/**\n * Zod schema describing the `data` property of a batch experience response.\n *\n * @remarks\n * A batch request may return zero or more profiles. When no profiles are\n * returned, `profiles` may be omitted or an empty array.\n */\nexport const BatchExperienceData = z.object({\n /**\n * Profiles evaluated or affected by the batch experience request.\n */\n profiles: z.optional(z.array(Profile)),\n})\n\n/**\n * TypeScript type inferred from {@link BatchExperienceData}.\n */\nexport type BatchExperienceData = z.infer<typeof BatchExperienceData>\n\n/**\n * Zod schema describing a batch experience response from the Experience API.\n *\n * @remarks\n * Extends {@link ResponseEnvelope} with {@link BatchExperienceData} as the\n * `data` payload.\n */\nexport const BatchExperienceResponse = z.extend(ResponseEnvelope, { data: BatchExperienceData })\n\n/**\n * TypeScript type inferred from {@link BatchExperienceResponse}.\n */\nexport type BatchExperienceResponse = z.infer<typeof BatchExperienceResponse>\n","import * as z from 'zod/mini'\n\n/**\n * Enumeration of supported change types.\n *\n * @remarks\n * Currently only the `'Variable'` change type is supported, but the union\n * in {@link ChangeBase} allows for additional types to be introduced.\n */\nexport const ChangeType = ['Variable'] as const\n\n/**\n * Zod schema describing the base shape for a change.\n *\n * @remarks\n * This base is extended by specific change types such as {@link VariableChange}.\n */\nconst ChangeBase = z.object({\n /**\n * Key identifying the subject of the change.\n */\n key: z.string(),\n\n /**\n * Discriminator for the change type.\n *\n * @remarks\n * May be one of {@link ChangeType} or an arbitrary string for unknown types.\n */\n type: z.union([z.enum(ChangeType), z.string()]),\n\n /**\n * Metadata describing the originating experience and variant index.\n */\n meta: z.object({\n /**\n * Identifier of the personalization or experiment experience.\n */\n experienceId: z.string(),\n\n /**\n * Index of the variant within the experience configuration.\n *\n * @remarks\n * Typically corresponds to the array index in the experience's distribution.\n */\n variantIndex: z.number(),\n }),\n})\n\n/**\n * Zod schema for the allowed value types of a variable change.\n *\n * @remarks\n * Supports primitives and JSON objects keyed by strings.\n */\nexport const VariableChangeValue = z.union([\n z.string(),\n z.boolean(),\n z.null(),\n z.number(),\n z.record(z.string(), z.json()),\n])\n\n/**\n * Zod schema representing an unknown change type.\n *\n * @remarks\n * This can be used to handle forward-compatible change payloads where\n * the `type` is not recognized.\n */\nexport const UnknownChange = z.extend(ChangeBase, {\n /**\n * Unconstrained change type string.\n */\n type: z.string(),\n\n /**\n * Payload for the change value, with unknown structure.\n */\n value: z.unknown(),\n})\n\n/**\n * TypeScript type inferred from {@link UnknownChange}.\n */\nexport type UnknownChange = z.infer<typeof UnknownChange>\n\n/**\n * Zod schema representing a change whose type is `'Variable'`.\n *\n * @remarks\n * The `value` must conform to {@link VariableChangeValue}.\n */\nexport const VariableChange = z.extend(ChangeBase, {\n /**\n * Discriminator for a variable change.\n */\n type: z.literal('Variable'),\n\n /**\n * New value for the variable identified by {@link ChangeBase.key}.\n */\n value: VariableChangeValue,\n})\n\n/**\n * TypeScript type inferred from {@link VariableChange}.\n */\nexport type VariableChange = z.infer<typeof VariableChange>\n\n/**\n * JSON value type inferred from {@link z.json}.\n *\n * @remarks\n * Represents any JSON-serializable value.\n */\nexport type Json = z.infer<typeof z.json>\n\n/**\n * Map of Custom Flag keys to JSON values.\n */\nexport type Flags = Record<string, Json>\n\n/**\n * Union of supported change types.\n *\n * @remarks\n * Currently only {@link VariableChange} is included.\n */\nexport const Change = z.discriminatedUnion('type', [VariableChange])\n\n/**\n * TypeScript type inferred from {@link Change}.\n */\nexport type Change = z.infer<typeof Change>\n\n/**\n * Zod schema representing an array of {@link Change} items.\n */\nexport const ChangeArray = z.array(Change)\n\n/**\n * TypeScript type inferred from {@link ChangeArray}.\n */\nexport type ChangeArray = z.infer<typeof ChangeArray>\n","import * as z from 'zod/mini'\nimport { App, Campaign, Channel, GeoLocation, Library, Page, Screen } from './properties'\n\n/**\n * Zod schema describing universal event context properties shared by all\n * analytics events.\n *\n * @remarks\n * The `page` and screen` properties are optional, but should usually be\n * omitted for event types that are not `page` or `screen`\n */\nexport const UniversalEventContext = z.object({\n /**\n * Application-level metadata.\n */\n app: App,\n\n /**\n * Campaign attribution metadata.\n */\n campaign: Campaign,\n\n /**\n * GDPR-related consent information.\n */\n gdpr: z.object({\n /**\n * Indicates whether the user has given consent.\n */\n isConsentGiven: z.boolean(),\n }),\n\n /**\n * Analytics library metadata.\n */\n library: Library,\n\n /**\n * Locale identifier of the event (e.g., `\"en-US\"`).\n */\n locale: z.string(),\n\n /**\n * Optional geo-location information associated with the event.\n */\n location: z.optional(GeoLocation),\n\n /**\n * User agent string of the client, if available.\n */\n userAgent: z.optional(z.string()),\n})\nexport type UniversalEventContext = z.infer<typeof UniversalEventContext>\n\n/**\n * Zod schema describing universal properties shared by all analytics events.\n *\n * @remarks\n * These properties capture common metadata such as channel, context,\n * timestamps, and user identifiers.\n */\nexport const UniversalEventProperties = z.object({\n /**\n * Channel from which the event originated.\n *\n * @see Channel\n */\n channel: Channel,\n\n /**\n * Context object carrying environment and client metadata.\n */\n context: z.extend(UniversalEventContext, {\n page: z.optional(Page),\n screen: z.optional(Screen),\n }),\n\n /**\n * Unique identifier for this message.\n *\n * @remarks\n * Used to deduplicate events across retries and transports.\n */\n messageId: z.string(),\n\n /**\n * Timestamp when the event originally occurred.\n *\n * @remarks\n * ISO 8601 datetime string.\n */\n originalTimestamp: z.iso.datetime(),\n\n /**\n * Timestamp when the event payload was sent.\n *\n * @remarks\n * ISO 8601 datetime string.\n */\n sentAt: z.iso.datetime(),\n\n /**\n * Timestamp when the event was recorded or processed.\n *\n * @remarks\n * ISO 8601 datetime string.\n */\n timestamp: z.iso.datetime(),\n\n /**\n * Identifier of the authenticated user, if known.\n */\n userId: z.optional(z.string()),\n})\n\n/**\n * TypeScript type inferred from {@link UniversalEventProperties}.\n */\nexport type UniversalEventProperties = z.infer<typeof UniversalEventProperties>\n","import * as z from 'zod/mini'\nimport { UniversalEventProperties } from './UniversalEventProperties'\n\n/**\n * Zod schema describing an `alias` event.\n *\n * @remarks\n * Currently unused.\n *\n * Alias events are typically used to associate multiple identifiers\n * (for example, anonymous and authenticated IDs) with the same user.\n *\n * Extends {@link UniversalEventProperties} with a fixed `type` field.\n */\nexport const AliasEvent = z.extend(UniversalEventProperties, {\n /**\n * Discriminator indicating that this event is an alias event.\n */\n type: z.literal('alias'),\n})\n\n/**\n * TypeScript type inferred from {@link AliasEvent}.\n */\nexport type AliasEvent = z.infer<typeof AliasEvent>\n","import * as z from 'zod/mini'\nimport { UniversalEventProperties } from './UniversalEventProperties'\n\n/**\n * Zod schema describing a `component` view event.\n *\n * @remarks\n * Component view events track exposure of individual components such as\n * entries or variables within a personalized experience.\n *\n * Extends {@link UniversalEventProperties}.\n */\nexport const ComponentViewEvent = z.extend(UniversalEventProperties, {\n /**\n * Discriminator indicating that this event is a component view.\n */\n type: z.literal('component'),\n\n /**\n * Type of component that was viewed.\n *\n * - `'Entry'` — A content entry component.\n * - `'Variable'` — A variable or inline value component.\n */\n componentType: z.union([z.literal('Entry'), z.literal('Variable')]),\n\n /**\n * Contentful entry ID corresponding to the component that was viewed.\n */\n componentId: z.string(),\n\n /**\n * Identifier of the experience that rendered this component.\n *\n * @remarks\n * Optional; component views may occur outside of a specific experience/personalization.\n */\n experienceId: z.optional(z.string()),\n\n /**\n * Index of the variant associated with this component view.\n *\n * @remarks\n * Typically corresponds to the index of the selected personalization entry.\n */\n variantIndex: z.number(),\n})\n\n/**\n * TypeScript type inferred from {@link ComponentViewEvent}.\n */\nexport type ComponentViewEvent = z.infer<typeof ComponentViewEvent>\n","import * as z from 'zod/mini'\nimport { UniversalEventProperties } from './UniversalEventProperties'\n\n/**\n * Zod schema describing a `group` event.\n *\n * @remarks\n * Currently unused.\n *\n * Group events typically associate a user with an organization, account,\n * or other grouping construct.\n *\n * Extends {@link UniversalEventProperties}.\n */\nexport const GroupEvent = z.extend(UniversalEventProperties, {\n /**\n * Discriminator indicating that this event is a group event.\n */\n type: z.literal('group'),\n})\n\n/**\n * TypeScript type inferred from {@link GroupEvent}.\n */\nexport type GroupEvent = z.infer<typeof GroupEvent>\n","import * as z from 'zod/mini'\nimport { UniversalEventProperties } from './UniversalEventProperties'\nimport { Traits } from './properties/Traits'\n\n/**\n * Zod schema describing an `identify` event.\n *\n * @remarks\n * Identify events attach user traits to a known identity.\n *\n * Extends {@link UniversalEventProperties} with a `traits` payload.\n */\nexport const IdentifyEvent = z.extend(UniversalEventProperties, {\n /**\n * Discriminator indicating that this event is an identify event.\n */\n type: z.literal('identify'),\n\n /**\n * Traits describing the user.\n *\n * @see {@link Traits}\n */\n traits: Traits,\n})\n\n/**\n * TypeScript type inferred from {@link IdentifyEvent}.\n */\nexport type IdentifyEvent = z.infer<typeof IdentifyEvent>\n","import * as z from 'zod/mini'\nimport { UniversalEventContext, UniversalEventProperties } from './UniversalEventProperties'\nimport { Page } from './properties'\n\n/**\n * Zod schema describing event context properties specific to page events\n */\nexport const PageEventContext = z.extend(UniversalEventContext, {\n /**\n * Page context for events that occur within a web page.\n */\n page: Page,\n})\n\n/**\n * TypeScript type inferred from {@link PageEventContext}.\n */\nexport type PageEventContext = z.infer<typeof PageEventContext>\n\n/**\n * Zod schema describing a `page` view event.\n *\n * @remarks\n * Page view events track visits to web pages and associated context.\n *\n * Extends {@link UniversalEventProperties} with optional `name` and\n * page-level {@link Page} properties.\n */\nexport const PageViewEvent = z.extend(UniversalEventProperties, {\n /**\n * Discriminator indicating that this event is a page view.\n */\n type: z.literal('page'),\n\n /**\n * Optional name for the page.\n *\n * @remarks\n * Useful when the logical page name differs from the URL or title.\n */\n name: z.optional(z.string()),\n\n /**\n * Page-level properties such as URL, path, and referrer.\n */\n properties: Page,\n\n /*\n * Override the context property of {@link UniversalEventProperties}\n * with a page-specific context\n */\n context: PageEventContext,\n})\n\n/**\n * TypeScript type inferred from {@link PageViewEvent}.\n */\nexport type PageViewEvent = z.infer<typeof PageViewEvent>\n","import * as z from 'zod/mini'\nimport { UniversalEventContext, UniversalEventProperties } from './UniversalEventProperties'\nimport { Properties, Screen } from './properties'\n\n/**\n * Zod schema describing event context properties specific to screen events\n */\nexport const ScreenEventContext = z.extend(UniversalEventContext, {\n /**\n * Screen context for events that occur within a web page.\n */\n screen: Screen,\n})\n\n/**\n * TypeScript type inferred from {@link ScreenEventContext}.\n */\nexport type ScreenEventContext = z.infer<typeof ScreenEventContext>\n\n/**\n * Zod schema describing a `screen` view event.\n *\n * @remarks\n * Screen view events are typically used by mobile or TV applications\n * to track navigation between screens.\n *\n * Extends {@link UniversalEventProperties}.\n */\nexport const ScreenViewEvent = z.extend(UniversalEventProperties, {\n /**\n * Discriminator indicating that this event is a screen view.\n */\n type: z.literal('screen'),\n\n /**\n * Name of the screen being viewed.\n */\n name: z.string(),\n\n /**\n * Optional properties describing the screen context.\n *\n * @see Properties\n */\n properties: z.optional(Properties),\n\n /*\n * Override the context property of {@link UniversalEventProperties}\n * with a screen-specific context\n */\n context: ScreenEventContext,\n})\n\n/**\n * TypeScript type inferred from {@link ScreenViewEvent}.\n */\nexport type ScreenViewEvent = z.infer<typeof ScreenViewEvent>\n","import * as z from 'zod/mini'\nimport { UniversalEventProperties } from './UniversalEventProperties'\nimport { Properties } from './properties'\n\n/**\n * Zod schema describing a custom `track` event.\n *\n * @remarks\n * Track events capture arbitrary user actions that do not fit into\n * the more specific event types (page, screen, identify, etc.).\n *\n * Extends {@link UniversalEventProperties}.\n */\nexport const TrackEvent = z.extend(UniversalEventProperties, {\n /**\n * Discriminator indicating that this event is a track event.\n */\n type: z.literal('track'),\n\n /**\n * Name of the event being tracked.\n */\n event: z.string(),\n\n /**\n * Additional properties describing the event.\n */\n properties: Properties,\n})\n\n/**\n * TypeScript type inferred from {@link TrackEvent}.\n */\nexport type TrackEvent = z.infer<typeof TrackEvent>\n","import * as z from 'zod/mini'\nimport { AliasEvent } from './AliasEvent'\nimport { ComponentViewEvent } from './ComponentViewEvent'\nimport { GroupEvent } from './GroupEvent'\nimport { IdentifyEvent } from './IdentifyEvent'\nimport { PageViewEvent } from './PageViewEvent'\nimport { ScreenViewEvent } from './ScreenViewEvent'\nimport { TrackEvent } from './TrackEvent'\n\n/**\n * Partial schema capturing an anonymous identifier.\n *\n * @remarks\n * This object is merged into each event type in a batch to associate the\n * event with an `anonymousId`.\n */\nconst Anon = { anonymousId: z.string() }\n\n/**\n * Zod schema describing each valid experience/personalization event within a batch.\n *\n * @remarks\n * This is a discriminated union on the `type` field that supports all event\n * types used in batch ingestion, each extended with an `anonymousId`.\n */\nexport const BatchExperienceEvent = z.discriminatedUnion('type', [\n z.extend(AliasEvent, Anon),\n z.extend(ComponentViewEvent, Anon),\n z.extend(GroupEvent, Anon),\n z.extend(IdentifyEvent, Anon),\n z.extend(PageViewEvent, Anon),\n z.extend(ScreenViewEvent, Anon),\n z.extend(TrackEvent, Anon),\n])\n\n/**\n * TypeScript type inferred from {@link BatchExperienceEvent}.\n */\nexport type BatchExperienceEvent = z.infer<typeof BatchExperienceEvent>\n\n/**\n * Zod schema describing an array of {@link BatchExperienceEvent} items.\n */\nexport const BatchExperienceEventArray = z.array(BatchExperienceEvent)\n\n/**\n * TypeScript type inferred from {@link BatchExperienceEventArray}.\n */\nexport type BatchExperienceEventArray = z.infer<typeof BatchExperienceEventArray>\n","import * as z from 'zod/mini'\nimport { AliasEvent } from './AliasEvent'\nimport { ComponentViewEvent } from './ComponentViewEvent'\nimport { GroupEvent } from './GroupEvent'\nimport { IdentifyEvent } from './IdentifyEvent'\nimport { PageViewEvent } from './PageViewEvent'\nimport { ScreenViewEvent } from './ScreenViewEvent'\nimport { TrackEvent } from './TrackEvent'\n\n/**\n * Zod schema describing any supported experience/personalization event.\n *\n * @remarks\n * This discriminated union aggregates all event types used by the\n * personalization/experience tracking system.\n */\nexport const ExperienceEvent = z.discriminatedUnion('type', [\n AliasEvent,\n ComponentViewEvent,\n GroupEvent,\n IdentifyEvent,\n PageViewEvent,\n ScreenViewEvent,\n TrackEvent,\n])\n\n/**\n * TypeScript type inferred from {@link ExperienceEvent}.\n */\nexport type ExperienceEvent = z.infer<typeof ExperienceEvent>\n\n/**\n * Union of all possible `type` values for {@link ExperienceEvent}.\n */\nexport type ExperienceEventType = ExperienceEvent['type']\n\n/**\n * Zod schema describing an array of {@link ExperienceEvent} items.\n */\nexport const ExperienceEventArray = z.array(ExperienceEvent)\n\n/**\n * TypeScript type inferred from {@link ExperienceEventArray}.\n */\nexport type ExperienceEventArray = z.infer<typeof ExperienceEventArray>\n","import * as z from 'zod/mini'\nimport { ExperienceEventArray } from './event'\n\n/**\n * Zod schema describing optional configuration for an experience request.\n *\n * @remarks\n * These options can be used to enable or filter specific features when\n * evaluating experiences.\n */\nexport const ExperienceRequestOptions = z.object({\n /**\n * Features or capabilities to enable for this request.\n */\n features: z.optional(z.array(z.string())),\n})\n\n/**\n * TypeScript type inferred from {@link ExperienceRequestOptions}.\n */\nexport type ExperienceRequestOptions = z.infer<typeof ExperienceRequestOptions>\n\n/**\n * Zod schema describing the data payload for an experience request.\n *\n * @remarks\n * Contains the list of events to be evaluated plus optional request\n * configuration.\n */\nexport const ExperienceRequestData = z.object({\n /**\n * Experience events that should be evaluated by the Experience API.\n *\n * @remarks\n * Must contain at least one event.\n */\n events: ExperienceEventArray.check(z.minLength(1)),\n\n /**\n * Optional configuration for this experience request.\n */\n options: z.optional(ExperienceRequestOptions),\n})\n\n/**\n * TypeScript type inferred from {@link ExperienceRequestData}.\n */\nexport type ExperienceRequestData = z.infer<typeof ExperienceRequestData>\n","import * as z from 'zod/mini'\n\n/**\n * Zod schema describing a selected personalization outcome for a user.\n *\n * @remarks\n * Represents the result of choosing a specific variant for a given\n * experience, along with additional metadata such as whether the\n * selection is sticky.\n */\nexport const SelectedPersonalization = z.object({\n /**\n * Identifier of the personalization or experiment experience.\n */\n experienceId: z.string(),\n\n /**\n * Index of the selected variant within the experience configuration.\n *\n * @remarks\n * Typically corresponds to the index of the selected {@link PersonalizationConfig } entry.\n */\n variantIndex: z.number(),\n\n /**\n * Mapping of baseline entry IDs to their selected variant entry IDs.\n *\n * @remarks\n * The keys are component identifiers and the values are the\n * identifiers of the selected variant for that component.\n */\n variants: z.record(z.string(), z.string()),\n\n /**\n * Indicates whether this personalization selection is sticky for the user.\n *\n * @defaultValue false\n *\n * @remarks\n * Sticky selections should be reused on subsequent requests for the\n * same user, rather than re-allocating a new variant.\n */\n sticky: z.optional(z.prefault(z.boolean(), false)),\n})\n\n/**\n * TypeScript type inferred from {@link SelectedPersonalization}.\n */\nexport type SelectedPersonalization = z.infer<typeof SelectedPersonalization>\n\n/**\n * Zod schema describing an array of {@link SelectedPersonalization} items.\n *\n * @remarks\n * Useful when multiple experiences are evaluated at once.\n */\nexport const SelectedPersonalizationArray = z.array(SelectedPersonalization)\n\n/**\n * TypeScript type inferred from {@link SelectedPersonalizationArray}.\n */\nexport type SelectedPersonalizationArray = z.infer<typeof SelectedPersonalizationArray>\n","import * as z from 'zod/mini'\nimport { ChangeArray } from './change'\nimport { SelectedPersonalizationArray } from './personalization'\nimport { Profile } from './profile'\nimport { ResponseEnvelope } from './ResponseEnvelope'\n\n/**\n * Zod schema describing the `data` payload of a standard Experience API response.\n *\n * @remarks\n * Contains the evaluated profile, selected personalizations, and computed\n * changes that should be applied on the client.\n */\nexport const ExperienceData = z.object({\n /**\n * Profile associated with the evaluated events.\n */\n profile: Profile,\n\n /**\n * Selected experiences and variants for the profile.\n *\n * @see {@link SelectedPersonalizationArray}\n */\n experiences: SelectedPersonalizationArray,\n\n /**\n * Currently used for Custom Flags.\n *\n * @see {@link ChangeArray}\n */\n changes: ChangeArray,\n})\n\n/**\n * TypeScript type inferred from {@link ExperienceData}.\n */\nexport type ExperienceData = z.infer<typeof ExperienceData>\n\n/**\n * Zod schema describing a full Experience API response.\n *\n * @remarks\n * Extends {@link ResponseEnvelope} with {@link ExperienceData} as the `data` payload.\n */\nexport const ExperienceResponse = z.extend(ResponseEnvelope, { data: ExperienceData })\n\n/**\n * TypeScript type inferred from {@link ExperienceResponse}.\n */\nexport type ExperienceResponse = z.infer<typeof ExperienceResponse>\n\n/**\n * Optimization data shape used for compatibility outside the API adapter.\n *\n * @remarks\n * This type mirrors {@link ExperienceData} but replaces the `experiences`\n * field with `personalizations` while preserving the rest of the structure.\n */\nexport type OptimizationData = Omit<ExperienceData, 'experiences'> & {\n /**\n * Selected personalizations for the profile.\n */\n personalizations: SelectedPersonalizationArray\n}\n","import * as z from 'zod/mini'\nimport { ComponentViewEvent } from '../../experience/event'\n\n/**\n * Zod schema describing an Insights event.\n *\n * @remarks\n * Currently, Insights events are limited to {@link ComponentViewEvent},\n * but this discriminated union can be extended with additional event\n * types in the future.\n */\nexport const InsightsEvent = z.discriminatedUnion('type', [ComponentViewEvent])\n\n/**\n * TypeScript type inferred from {@link InsightsEvent}.\n */\nexport type InsightsEvent = z.infer<typeof InsightsEvent>\n\n/**\n * Union of all possible `type` values for {@link InsightsEvent}.\n */\nexport type InsightsEventType = InsightsEvent['type']\n\n/**\n * Zod schema describing an array of {@link InsightsEvent} items.\n */\nexport const InsightsEventArray = z.array(InsightsEvent)\n\n/**\n * TypeScript type inferred from {@link InsightsEventArray}.\n */\nexport type InsightsEventArray = z.infer<typeof InsightsEventArray>\n","import * as z from 'zod/mini'\nimport { PartialProfile } from '../../experience/profile'\nimport { InsightsEventArray } from './InsightsEvent'\n\n/**\n * Zod schema describing a batched Insights event payload.\n *\n * @remarks\n * Combines a {@link PartialProfile} with one or more Insights events\n * to be sent to the Contentful Insights API.\n */\nexport const BatchInsightsEvent = z.object({\n /**\n * Partial profile information used to associate events with a user.\n *\n * @see PartialProfile\n */\n profile: PartialProfile,\n\n /**\n * Insights events that should be recorded for this profile.\n *\n * @see InsightsEventArray\n */\n events: InsightsEventArray,\n})\n\n/**\n * TypeScript type inferred from {@link BatchInsightsEvent}.\n */\nexport type BatchInsightsEvent = z.infer<typeof BatchInsightsEvent>\n\n/**\n * Zod schema describing an array of {@link BatchInsightsEvent} items.\n *\n * @remarks\n * Useful when sending multiple profile/event batches in a single request.\n */\nexport const BatchInsightsEventArray = z.array(BatchInsightsEvent)\n\n/**\n * TypeScript type inferred from {@link BatchInsightsEventArray}.\n */\nexport type BatchInsightsEventArray = z.infer<typeof BatchInsightsEventArray>\n","var e=[],a=e=>new RegExp(e.replace(/\\*/g,\".*\")+\"$\"),r=r=>{e=r.split(/[\\s,]+/).map(a)};var s=(a,r,s,...l)=>{for(let n=e.length;n--;)if(e[n].test(a))return r({name:a,level:s,messages:l})},l=e=>{let a=\"\";const r=console[\"fatal\"===e.level?\"error\":e.level];if(e.name&&(a+=`[${e.name}] `),\"object\"==typeof e.messages[0])r(a,...e.messages);else{r(a+e.messages.shift(),...e.messages)}},n=(e,a)=>({fatal:s.bind(0,e,a=a||l,\"fatal\"),error:s.bind(0,e,a,\"error\"),warn:s.bind(0,e,a,\"warn\"),debug:s.bind(0,e,a,\"debug\"),info:s.bind(0,e,a,\"info\"),log:s.bind(0,e,a,\"log\")}),o=n(\"\"),t=o.fatal,g=o.error,i=o.warn,f=o.debug,b=o.info,d=o.log;export{f as debug,l as default_reporter,n as diary,r as enable,g as error,t as fatal,b as info,d as log,i as warn};","import { diary, enable, type Diary, type LogEvent } from 'diary'\n\nimport type LogSink from './LogSink'\n\nexport class Logger {\n readonly name = '@contentful/optimization'\n\n private readonly PREFIX_PARTS = ['Ctfl', 'O10n']\n private readonly DELIMITER = ':'\n private readonly diary: Diary\n private sinks: LogSink[] = []\n\n constructor() {\n this.diary = diary(this.name, this.onLogEvent.bind(this))\n enable(this.name)\n }\n\n private assembleLocationPrefix(logLocation: string): string {\n return `[${[...this.PREFIX_PARTS, logLocation].join(this.DELIMITER)}]`\n }\n\n public addSink(sink: LogSink): void {\n this.sinks = [...this.sinks.filter((existingSink) => existingSink.name !== sink.name), sink]\n }\n\n public removeSink(name: string): void {\n this.sinks = this.sinks.filter((sink) => sink.name !== name)\n }\n\n public removeSinks(): void {\n this.sinks = []\n }\n\n public debug(logLocation: string, message: string, ...args: unknown[]): void {\n this.diary.debug(`${this.assembleLocationPrefix(logLocation)} ${message}`, ...args)\n }\n\n public info(logLocation: string, message: string, ...args: unknown[]): void {\n this.diary.info(`${this.assembleLocationPrefix(logLocation)} ${message}`, ...args)\n }\n\n public log(logLocation: string, message: string, ...args: unknown[]): void {\n this.diary.log(`${this.assembleLocationPrefix(logLocation)} ${message}`, ...args)\n }\n\n public warn(logLocation: string, message: string, ...args: unknown[]): void {\n this.diary.warn(`${this.assembleLocationPrefix(logLocation)} ${message}`, ...args)\n }\n\n public error(logLocation: string, message: string | Error, ...args: unknown[]): void {\n this.diary.error(`${this.assembleLocationPrefix(logLocation)} ${message}`, ...args)\n }\n\n public fatal(logLocation: string, message: string | Error, ...args: unknown[]): void {\n this.diary.fatal(`${this.assembleLocationPrefix(logLocation)} ${message}`, ...args)\n }\n\n private onLogEvent(event: LogEvent): void {\n this.sinks.forEach((sink) => {\n sink.ingest(event)\n })\n }\n}\n\nexport const logger = new Logger()\n\nexport interface ScopedLogger {\n debug: (message: string, ...args: unknown[]) => void\n info: (message: string, ...args: unknown[]) => void\n log: (message: string, ...args: unknown[]) => void\n warn: (message: string, ...args: unknown[]) => void\n error: (message: string | Error, ...args: unknown[]) => void\n fatal: (message: string | Error, ...args: unknown[]) => void\n}\n\nexport function createScopedLogger(location: string): ScopedLogger {\n return {\n debug: (message: string, ...args: unknown[]) => {\n logger.debug(location, message, ...args)\n },\n info: (message: string, ...args: unknown[]) => {\n logger.info(location, message, ...args)\n },\n log: (message: string, ...args: unknown[]) => {\n logger.log(location, message, ...args)\n },\n warn: (message: string, ...args: unknown[]) => {\n logger.warn(location, message, ...args)\n },\n error: (message: string | Error, ...args: unknown[]) => {\n logger.error(location, message, ...args)\n },\n fatal: (message: string | Error, ...args: unknown[]) => {\n logger.fatal(location, message, ...args)\n },\n }\n}\n","import type { LogEvent } from 'diary'\n\nexport type { LogEvent }\n\nabstract class LogSink {\n abstract name: string\n\n abstract ingest(event: LogEvent): void\n}\n\nexport default LogSink\n","var t=(t,...e)=>t.replace(/(\\s+)(%[Oodifs](?=[^a-z0-9A-Z]|$))/g,((t,r,i)=>{let o=e.shift();return/[Oo]/.test(i)&&\"object\"==typeof o?o=JSON.stringify(o):/[di]/.test(i)&&o&&(o=o.toString().replace(/\\..*$/,\"\")),r+o})),e={fatal:60,error:50,warn:40,info:30,debug:20,log:10},r=(t,r)=>r in e&&t in e?e[r]===e[t]?0:e[r]<e[t]?1:-1:0;export{r as compare,t as sprintf};","/* eslint-disable no-console -- using console */\nimport type { LogEvent, LogLevels } from 'diary'\nimport { compare } from 'diary/utils'\nimport LogSink from './LogSink'\n\nconst consoleMap = {\n debug: (...args: unknown[]) => {\n console.debug(...args)\n },\n info: (...args: unknown[]) => {\n console.info(...args)\n },\n log: (...args: unknown[]) => {\n console.log(...args)\n },\n warn: (...args: unknown[]) => {\n console.warn(...args)\n },\n error: (...args: unknown[]) => {\n console.error(...args)\n },\n fatal: (...args: unknown[]) => {\n console.error(...args)\n },\n}\n\nconst COMPARISON_EQUALITY = 0\n\nexport class ConsoleLogSink extends LogSink {\n public name = 'ConsoleLogSink'\n\n readonly verbosity: LogLevels\n\n constructor(verbosity?: LogLevels) {\n super()\n\n this.verbosity = verbosity ?? 'error'\n }\n\n ingest(event: LogEvent): void {\n if (compare(this.verbosity, event.level) > COMPARISON_EQUALITY) return\n\n consoleMap[event.level](...event.messages)\n }\n}\n","function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n","var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n","module.exports = require('./lib/retry');","const objectToString = Object.prototype.toString;\n\nconst isError = value => objectToString.call(value) === '[object Error]';\n\nconst errorMessages = new Set([\n\t'network error', // Chrome\n\t'Failed to fetch', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari 16\n\t'Load failed', // Safari 17+\n\t'Network request failed', // `cross-fetch`\n\t'fetch failed', // Undici (Node.js)\n\t'terminated', // Undici (Node.js)\n]);\n\nexport default function isNetworkError(error) {\n\tconst isValid = error\n\t\t&& isError(error)\n\t\t&& error.name === 'TypeError'\n\t\t&& typeof error.message === 'string';\n\n\tif (!isValid) {\n\t\treturn false;\n\t}\n\n\t// We do an extra check for Safari 17+ as it has a very generic error message.\n\t// Network errors in Safari have no stack.\n\tif (error.message === 'Load failed') {\n\t\treturn error.stack === undefined;\n\t}\n\n\treturn errorMessages.has(error.message);\n}\n","import retry from 'retry';\nimport isNetworkError from 'is-network-error';\n\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nconst decorateErrorWithCounts = (error, attemptNumber, options) => {\n\t// Minus 1 from attemptNumber because the first attempt does not count as a retry\n\tconst retriesLeft = options.retries - (attemptNumber - 1);\n\n\terror.attemptNumber = attemptNumber;\n\terror.retriesLeft = retriesLeft;\n\treturn error;\n};\n\nexport default async function pRetry(input, options) {\n\treturn new Promise((resolve, reject) => {\n\t\toptions = {...options};\n\t\toptions.onFailedAttempt ??= () => {};\n\t\toptions.shouldRetry ??= () => true;\n\t\toptions.retries ??= 10;\n\n\t\tconst operation = retry.operation(options);\n\n\t\tconst abortHandler = () => {\n\t\t\toperation.stop();\n\t\t\treject(options.signal?.reason);\n\t\t};\n\n\t\tif (options.signal && !options.signal.aborted) {\n\t\t\toptions.signal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tconst cleanUp = () => {\n\t\t\toptions.signal?.removeEventListener('abort', abortHandler);\n\t\t\toperation.stop();\n\t\t};\n\n\t\toperation.attempt(async attemptNumber => {\n\t\t\ttry {\n\t\t\t\tconst result = await input(attemptNumber);\n\t\t\t\tcleanUp();\n\t\t\t\tresolve(result);\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!(error instanceof Error)) {\n\t\t\t\t\t\tthrow new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (error instanceof AbortError) {\n\t\t\t\t\t\tthrow error.originalError;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (error instanceof TypeError && !isNetworkError(error)) {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\n\t\t\t\t\tdecorateErrorWithCounts(error, attemptNumber, options);\n\n\t\t\t\t\tif (!(await options.shouldRetry(error))) {\n\t\t\t\t\t\toperation.stop();\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\n\t\t\t\t\tawait options.onFailedAttempt(error);\n\n\t\t\t\t\tif (!operation.retry(error)) {\n\t\t\t\t\t\tthrow operation.mainError();\n\t\t\t\t\t}\n\t\t\t\t} catch (finalError) {\n\t\t\t\t\tdecorateErrorWithCounts(finalError, attemptNumber, options);\n\t\t\t\t\tcleanUp();\n\t\t\t\t\treject(finalError);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t});\n}\n","import { createScopedLogger } from 'logger'\nimport retry from 'p-retry'\nimport type { BaseFetchMethodOptions, FetchMethod, FetchMethodCallbackOptions } from './Fetch'\n\nconst logger = createScopedLogger('ApiClient:Retry')\n\n/**\n * Default interval (in milliseconds) between retry attempts.\n *\n * @internal\n */\nconst DEFAULT_INTERVAL_TIMEOUT = 0\n\n/**\n * Default number of retry attempts.\n *\n * @internal\n */\nconst DEFAULT_RETRY_COUNT = 1\n\n/**\n * HTTP status code that triggers a retry.\n *\n * @internal\n *\n * @remarks\n * This value is currently fixed to `503 Service Unavailable`.\n */\nconst RETRY_RESPONSE_STATUS = 503\n\n/**\n * Default HTTP status code used for {@link HttpError}.\n *\n * @internal\n */\nconst HTTP_ERROR_RESPONSE_STATUS = 500\n\n/**\n * Error type representing HTTP failures with an associated status code.\n *\n * @internal\n */\nclass HttpError extends Error {\n /**\n * The HTTP status code associated with the error.\n */\n public status: number\n\n /**\n * Creates a new {@link HttpError}.\n *\n * @param message - Description of the error.\n * @param status - HTTP status code associated with the error.\n */\n constructor(message: string, status: number = HTTP_ERROR_RESPONSE_STATUS) {\n super(message)\n Object.setPrototypeOf(this, HttpError.prototype)\n this.status = status\n }\n}\n\n/**\n * Configuration options for {@link createRetryFetchMethod}.\n */\nexport interface RetryFetchMethodOptions extends BaseFetchMethodOptions {\n /**\n * Delay (in milliseconds) between retry attempts.\n *\n * @remarks\n * Defaults to {@link DEFAULT_INTERVAL_TIMEOUT}.\n */\n intervalTimeout?: number\n\n /**\n * Callback invoked whenever a retry attempt fails.\n *\n * @param options - Information about the failed attempt.\n *\n * @remarks\n * This callback is invoked with additional metadata such as the attempt\n * number and the number of retries left.\n */\n onFailedAttempt?: (options: FetchMethodCallbackOptions) => void\n\n /**\n * Maximum number of retry attempts.\n *\n * @remarks\n * Defaults to {@link DEFAULT_RETRY_COUNT}.\n */\n retries?: number\n}\n\n/**\n * Internal configuration passed to the retry callback.\n *\n * @internal\n */\ninterface RetryFetchCallbackOptions extends RetryFetchMethodOptions {\n /**\n * Abort controller used to cancel the underlying fetch requests.\n */\n controller: AbortController\n\n /**\n * Initialization options passed to the `fetch` implementation.\n */\n init: RequestInit\n\n /**\n * Request URL.\n */\n url: string | URL\n}\n\n/**\n * Creates a callback function used by `p-retry` to perform a fetch with retry logic.\n *\n * @param options - Internal options controlling the retry behavior.\n * @returns A function that, when invoked, performs the fetch and applies retry rules.\n *\n * @internal\n */\nfunction createRetryFetchCallback({\n apiName = 'Optimization',\n controller,\n fetchMethod = fetch,\n init,\n url,\n}: RetryFetchCallbackOptions) {\n return async () => {\n try {\n const response = await fetchMethod(url, init)\n\n if (response.status === RETRY_RESPONSE_STATUS) {\n throw new HttpError(\n `${apiName} API request to \"${url.toString()}\" failed with status: \"[${response.status}] ${response.statusText}\".`,\n RETRY_RESPONSE_STATUS,\n )\n }\n\n if (!response.ok) {\n const httpError = new Error(\n `Request to \"${url.toString()}\" failed with status: [${response.status}] ${response.statusText} - traceparent: ${response.headers.get('traceparent')}`,\n )\n logger.error('Request failed with non-OK status:', httpError)\n\n controller.abort()\n\n return\n }\n\n logger.debug(`Response from \"${url.toString()}\":`, response)\n\n return response\n } catch (error) {\n if (error instanceof HttpError && error.status === RETRY_RESPONSE_STATUS) {\n throw error\n }\n\n logger.error(`Request to \"${url.toString()}\" failed:`, error)\n\n controller.abort()\n }\n }\n}\n\n/**\n * Creates a {@link FetchMethod} that retries failed requests according to the\n * provided configuration.\n *\n * @param options - Configuration options that control retry behavior.\n * @returns A {@link FetchMethod} that automatically retries qualifying failures.\n *\n * @remarks\n * This wrapper integrates with `p-retry` and uses an {@link AbortController}\n * to cancel pending requests when a non-retriable error occurs.\n *\n * @throws {@link Error}\n * Thrown when the request cannot be retried and no successful response is obtained.\n *\n * @example\n * ```ts\n * const fetchWithRetry = createRetryFetchMethod({\n * apiName: 'Optimization',\n * retries: 3,\n * intervalTimeout: 200,\n * onFailedAttempt: ({ attemptNumber, retriesLeft }) => {\n * console.warn(`Attempt ${attemptNumber} failed. Retries left: ${retriesLeft}`)\n * },\n * })\n *\n * const response = await fetchWithRetry('https://example.com', { method: 'GET' })\n * ```\n */\nexport function createRetryFetchMethod({\n apiName = 'Optimization',\n fetchMethod = fetch,\n intervalTimeout = DEFAULT_INTERVAL_TIMEOUT,\n onFailedAttempt,\n retries = DEFAULT_RETRY_COUNT,\n}: RetryFetchMethodOptions = {}): FetchMethod {\n return async (url: string | URL, init: RequestInit) => {\n const controller = new AbortController()\n\n let retryResponse: Response | undefined = undefined\n\n try {\n retryResponse = await retry<Response | undefined>(\n createRetryFetchCallback({ apiName, controller, fetchMethod, init, url }),\n {\n minTimeout: intervalTimeout,\n onFailedAttempt: (options: FetchMethodCallbackOptions) =>\n onFailedAttempt?.({ ...options, apiName }),\n retries,\n signal: controller.signal,\n },\n )\n } catch (error) {\n // Abort errors caused by timeouts should not bubble up and be reported by third-party tools (e.g. Sentry)\n if (!(error instanceof Error) || error.name !== 'AbortError') {\n throw error\n }\n }\n\n if (!retryResponse) {\n throw new Error(`${apiName} API request to \"${url.toString()}\" may not be retried.`)\n }\n\n return retryResponse\n }\n}\n","import { createScopedLogger } from 'logger'\nimport type { BaseFetchMethodOptions, FetchMethod, FetchMethodCallbackOptions } from './Fetch'\n\nconst logger = createScopedLogger('ApiClient:Timeout')\n\n/**\n * Default timeout (in milliseconds) for outgoing requests.\n *\n * @internal\n */\nconst DEFAULT_REQUEST_TIMEOUT = 3000\n\n/**\n * Configuration options for {@link createTimeoutFetchMethod}.\n */\nexport interface TimeoutFetchMethodOptions extends BaseFetchMethodOptions {\n /**\n * Callback invoked when a request exceeds the configured timeout.\n *\n * @param options - Information about the timed-out request.\n *\n * @remarks\n * If this callback is not provided, a default error is logged.\n *\n * @see {@link FetchMethodCallbackOptions}\n */\n onRequestTimeout?: (options: FetchMethodCallbackOptions) => void\n\n /**\n * Maximum time (in milliseconds) to wait for a response before aborting the request.\n *\n * @remarks\n * Defaults to {@link DEFAULT_REQUEST_TIMEOUT}.\n */\n requestTimeout?: number\n}\n\n/**\n * Creates a {@link FetchMethod} that aborts requests after a configurable timeout.\n *\n * @param options - Configuration options controlling timeout behavior.\n * @returns A {@link FetchMethod} that enforces a timeout for each request.\n *\n * @remarks\n * When a timeout occurs, the request is aborted using an {@link AbortController}.\n * If `onRequestTimeout` is not provided, an error is logged by the {@link logger}.\n *\n * @example\n * ```ts\n * const fetchWithTimeout = createTimeoutFetchMethod({\n * apiName: 'Optimization',\n * requestTimeout: 5000,\n * onRequestTimeout: ({ apiName }) => {\n * console.warn(`${apiName} request timed out`)\n * },\n * })\n *\n * const response = await fetchWithTimeout('https://example.com', { method: 'GET' })\n * ```\n *\n * @see {@link TimeoutFetchMethodOptions}\n */\nexport function createTimeoutFetchMethod({\n apiName = 'Optimization',\n fetchMethod = fetch,\n onRequestTimeout,\n requestTimeout = DEFAULT_REQUEST_TIMEOUT,\n}: TimeoutFetchMethodOptions = {}): FetchMethod {\n return async (url: string | URL, init: RequestInit) => {\n const controller = new AbortController()\n\n const id = setTimeout(() => {\n if (typeof onRequestTimeout === 'function') {\n onRequestTimeout({ apiName })\n } else {\n logger.error(`Request to \"${url.toString()}\" timed out`, new Error('Request timeout'))\n }\n\n controller.abort()\n }, requestTimeout)\n\n const response = await fetchMethod(url, { ...init, signal: controller.signal })\n\n clearTimeout(id)\n\n return response\n }\n}\n","import { createScopedLogger } from 'logger'\nimport { createRetryFetchMethod, type RetryFetchMethodOptions } from './createRetryFetchMethod'\nimport {\n createTimeoutFetchMethod,\n type TimeoutFetchMethodOptions,\n} from './createTimeoutFetchMethod'\nimport type { FetchMethod } from './Fetch'\n\nconst logger = createScopedLogger('ApiClient:Fetch')\n\n/**\n * Options for {@link createProtectedFetchMethod}, combining timeout and retry behavior.\n */\nexport interface ProtectedFetchMethodOptions\n extends RetryFetchMethodOptions,\n TimeoutFetchMethodOptions {}\n\n/**\n * Creates a {@link FetchMethod} that combines timeout and retry protection.\n *\n * @param options - Configuration options for both timeout and retry behavior.\n * @returns A {@link FetchMethod} that applies timeout and retry logic to requests.\n *\n * @remarks\n * The resulting method first wraps the base fetch with a timeout (via\n * {@link createTimeoutFetchMethod}), then applies retry behavior (via\n * {@link createRetryFetchMethod}).\n *\n * If an error is thrown during configuration or request execution, it is logged\n * using {@link logger}.\n *\n * @throws {@link Error}\n * Rethrows the original error after logging, including abort errors.\n *\n * @example\n * ```ts\n * const fetchProtected = createProtectedFetchMethod({\n * apiName: 'Optimization',\n * requestTimeout: 4000,\n * retries: 2,\n * })\n *\n * const response = await fetchProtected('https://example.com/experiences', {\n * method: 'GET',\n * })\n * ```\n */\nexport function createProtectedFetchMethod(options: ProtectedFetchMethodOptions): FetchMethod {\n try {\n const timeoutFetchMethod = createTimeoutFetchMethod(options)\n const retryFetchMethod = createRetryFetchMethod({ ...options, fetchMethod: timeoutFetchMethod })\n\n return retryFetchMethod\n } catch (error) {\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n logger.warn('Request aborted due to network issues. This request may not be retried.')\n } else {\n logger.error('Request failed:', error)\n }\n }\n throw error\n }\n}\n","import { createProtectedFetchMethod } from './createProtectedFetchMethod'\n\n/**\n * Signature of a fetch method used by the API clients.\n *\n * @param url - The request URL.\n * @param init - Initialization options passed to `fetch`.\n * @returns A promise that resolves with the {@link Response}.\n *\n * @public\n *\n * @remarks\n * This abstraction allows the underlying implementation to be replaced,\n * for example in tests or different runtime environments.\n *\n * @example\n * ```ts\n * const method: FetchMethod = async (url, init) => {\n * return fetch(url, init)\n * }\n * ```\n */\nexport type FetchMethod = (url: string | URL, init: RequestInit) => Promise<Response>\n\n/**\n * Base options shared across fetch method factories.\n *\n * @public\n */\nexport interface BaseFetchMethodOptions {\n /**\n * Human-readable name of the API being called.\n *\n * @remarks\n * Used primarily for logging and error messages.\n */\n apiName?: string\n\n /**\n * Custom fetch implementation to use instead of the global `fetch`.\n *\n * @remarks\n * This is useful for providing polyfills, mocks, or instrumented fetch\n * implementations.\n */\n fetchMethod?: FetchMethod\n}\n\n/**\n * Options passed to callback functions invoked by fetch wrappers.\n *\n * @public\n *\n * @remarks\n * Not all fields are guaranteed to be present in all callback scenarios.\n */\nexport interface FetchMethodCallbackOptions {\n /**\n * Name of the API associated with the request.\n */\n apiName?: string\n\n /**\n * Error that caused the callback to be invoked, if available.\n */\n error?: Error\n\n /**\n * The current attempt number (for retry callbacks).\n */\n attemptNumber?: number\n\n /**\n * Number of retry attempts remaining (for retry callbacks).\n */\n retriesLeft?: number\n}\n\n/**\n * Namespace-like object providing factory methods for protected fetch functions.\n *\n * @public\n */\nconst Fetch = {\n /**\n * Creates a fully protected fetch method with timeout and retry behavior.\n *\n * @example\n * ```ts\n * const fetchMethod = Fetch.create({\n * apiName: 'Optimization',\n * requestTimeout: 3000,\n * retries: 2,\n * })\n *\n * const response = await fetchMethod('https://example.com', { method: 'GET' })\n * ```\n *\n * @see createProtectedFetchMethod\n */\n create: createProtectedFetchMethod,\n}\n\nexport default Fetch\n","import { createScopedLogger } from 'logger'\nimport Fetch, { type FetchMethod, type ProtectedFetchMethodOptions } from './fetch'\n\nconst logger = createScopedLogger('ApiClient')\n\n/**\n * Default Contentful environment used when none is explicitly provided.\n *\n * @internal\n */\nconst DEFAULT_ENVIRONMENT = 'main'\n\n/**\n * Configuration options for API clients extending {@link ApiClientBase}.\n *\n * @public\n */\nexport interface ApiConfig {\n /**\n * Base URL for the API.\n *\n * @remarks\n * When omitted, the concrete client is expected to construct full URLs\n * internally.\n */\n baseUrl?: string\n\n /**\n * Contentful environment identifier.\n *\n * @remarks\n * Defaults to `main` when not provided.\n */\n environment?: string\n\n /**\n * Options used to configure the underlying protected fetch method.\n *\n * @remarks\n * `apiName` is derived from the client name and must not be provided here.\n */\n fetchOptions?: Omit<ProtectedFetchMethodOptions, 'apiName'>\n\n /**\n * Client identifier used for authentication or tracking.\n */\n clientId: string\n}\n\n/**\n * Properties that may be shared between global and per-client API configuration.\n *\n * @public\n */\nexport type GlobalApiConfigProperties = 'environment' | 'fetchOptions' | 'clientId'\n\n/**\n * Base class for API clients that provides shared configuration and error logging.\n *\n * @internal\n *\n * @remarks\n * This abstract class is intended for internal use within the package and\n * should not be treated as part of the public API surface.\n *\n * Concrete API clients should extend this class to inherit consistent logging\n * behavior and fetch configuration.\n *\n * @example\n * ```ts\n * interface MyClientConfig extends ApiConfig {\n * // additional config\n * }\n *\n * class MyClient extends ApiClientBase {\n * constructor(config: MyClientConfig) {\n * super('MyClient', config)\n * }\n *\n * async getSomething() {\n * const response = await this.fetch('https://example.com', { method: 'GET' })\n * return response.json()\n * }\n * }\n * ```\n */\nabstract class ApiClientBase {\n /**\n * Name of the API client, used in log messages and as the `apiName` for fetch.\n */\n protected readonly name: string\n\n /**\n * Client identifier used for authentication or tracking.\n */\n protected readonly clientId: string\n\n /**\n * Contentful environment associated with this client.\n */\n protected readonly environment: string\n\n /**\n * Protected fetch method used by the client to perform HTTP requests.\n */\n protected readonly fetch: FetchMethod\n\n /**\n * Creates a new API client base instance.\n *\n * @param name - Human-readable name of the client (used for logging and `apiName`).\n * @param config - Configuration options for the client.\n */\n constructor(name: string, { fetchOptions, clientId, environment }: ApiConfig) {\n this.clientId = clientId\n this.environment = environment ?? DEFAULT_ENVIRONMENT\n this.name = name\n\n this.fetch = Fetch.create({ ...(fetchOptions ?? {}), apiName: name })\n }\n\n /**\n * Logs errors that occur during API requests with standardized messages.\n *\n * @param error - The error thrown by the underlying operation.\n * @param options - Additional metadata about the request.\n * @param options.requestName - Human-readable name of the request operation.\n *\n * @protected\n *\n * @remarks\n * Abort errors are logged at `warn` level and other errors at `error` level.\n * The log message includes the client name for better debugging context.\n */\n protected logRequestError(error: unknown, { requestName }: { requestName: string }): void {\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n logger.warn(\n `[${this.name}] \"${requestName}\" request aborted due to network issues. This request may not be retried.`,\n )\n } else {\n logger.error(`[${this.name}] \"${requestName}\" request failed:`, error)\n }\n }\n }\n}\n\nexport default ApiClientBase\n","import {\n BatchExperienceResponse,\n ExperienceEventArray,\n ExperienceResponse,\n type BatchExperienceData,\n type BatchExperienceEventArray,\n type ExperienceRequestData,\n type ExperienceRequestOptions,\n type OptimizationData,\n} from '@contentful/optimization-api-schemas'\nimport { createScopedLogger } from 'logger'\nimport ApiClientBase, { type ApiConfig } from '../ApiClientBase'\n\nconst logger = createScopedLogger('ApiClient:Experience')\n\n/**\n * Default base URL for the Experience API.\n *\n * @public\n */\nexport const EXPERIENCE_BASE_URL = 'https://experience.ninetailed.co/'\n\n/**\n * Feature flags supported by the Experience API.\n */\ntype Feature = 'ip-enrichment' | 'location'\n\n/**\n * Options that control how requests to the Experience API are handled.\n */\ninterface RequestOptions {\n /**\n * Enabled features (for example, `\"ip-enrichment\"`) which the API should use for this request.\n *\n * @remarks\n * When omitted, a default set of features may be applied.\n */\n enabledFeatures?: Feature[]\n\n /**\n * IP address to override the API behavior for IP analysis.\n *\n * @remarks\n * Commonly used in ESR or SSR environments, as the API would otherwise use\n * the server IP.\n */\n ip?: string\n\n /**\n * Locale used to translate `location.city` and `location.country`.\n *\n * @remarks\n * When omitted, a server-side default may be used.\n */\n locale?: string\n\n /**\n * When `true`, sends performance-critical endpoints in plain text.\n *\n * @remarks\n * The Ninetailed API accepts certain endpoints in plain text to avoid CORS\n * preflight requests, which can improve performance in browser environments.\n */\n plainText?: boolean\n\n /**\n * When `true`, instructs the API to aggregate a new profile state but not store it.\n *\n * @remarks\n * This is commonly used in ESR or SSR environments where you want to\n * preview the result without persisting changes.\n */\n preflight?: boolean\n}\n\n/**\n * Internal options for profile mutation requests.\n *\n * @internal\n */\ninterface ProfileMutationRequestOptions {\n url: string\n body: unknown\n options: RequestOptions\n}\n\n/**\n * Parameters used when creating a profile.\n */\ninterface CreateProfileParams {\n /**\n * Events used to aggregate the profile state.\n */\n events: ExperienceEventArray\n}\n\n/**\n * Parameters used when updating an existing profile.\n */\ninterface UpdateProfileParams extends CreateProfileParams {\n /**\n * ID of the profile to update.\n */\n profileId: string\n}\n\n/**\n * Parameters used when creating or updating a profile.\n */\ninterface UpsertProfileParams extends CreateProfileParams {\n /**\n * Optional ID of the profile; when omitted, a new profile is created.\n */\n profileId?: string\n}\n\n/**\n * Parameters used when performing a batch profile update.\n */\ninterface BatchUpdateProfileParams {\n /**\n * Batch of events to process.\n */\n events: BatchExperienceEventArray\n}\n\n/**\n * Configuration for {@link ExperienceApiClient}.\n */\nexport interface ExperienceApiClientConfig extends ApiConfig, RequestOptions {}\n\n/**\n * Client for interacting with the Experience API.\n *\n * @public\n *\n * @remarks\n * This client is responsible for reading and mutating Ninetailed profiles\n * using the Experience API.\n *\n * @example\n * ```ts\n * const client = new ExperienceApiClient({\n * clientId: 'org-id',\n * environment: 'main',\n * })\n *\n * const profile = await client.getProfile('profile-id')\n * ```\n */\nexport default class ExperienceApiClient extends ApiClientBase {\n /**\n * Base URL used for Experience API requests.\n */\n protected readonly baseUrl: string\n\n private readonly enabledFeatures?: RequestOptions['enabledFeatures']\n private readonly ip?: RequestOptions['ip']\n private readonly locale?: RequestOptions['locale']\n private readonly plainText?: RequestOptions['plainText']\n private readonly preflight?: RequestOptions['preflight']\n\n /**\n * Creates a new {@link ExperienceApiClient} instance.\n *\n * @param config - Configuration for the Experience API client.\n */\n constructor(config: ExperienceApiClientConfig) {\n super('Experience', config)\n\n const { baseUrl, enabledFeatures, ip, locale, plainText, preflight } = config\n\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- Set default for anything falsey\n this.baseUrl = baseUrl || EXPERIENCE_BASE_URL\n this.enabledFeatures = enabledFeatures\n this.ip = ip\n this.locale = locale\n this.plainText = plainText\n this.preflight = preflight\n }\n\n /**\n * Retrieves a profile by ID.\n *\n * @param id - The profile ID to retrieve.\n * @param options - Optional request options. `preflight` and `plainText` are not allowed here.\n * @returns The current optimization data for the profile.\n *\n * @throws {@link Error}\n * Thrown if `id` is missing or the underlying request fails.\n *\n * @example\n * ```ts\n * const profile = await client.getProfile('profile-id', {\n * locale: 'en-US',\n * })\n * ```\n */\n public async getProfile(\n id: string,\n options: Omit<RequestOptions, 'preflight' | 'plainText'> = {},\n ): Promise<OptimizationData> {\n if (!id) throw new Error('Valid profile ID required.')\n\n const requestName = 'Get Profile'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n try {\n const response = await this.fetch(\n this.constructUrl(\n `v2/organizations/${this.clientId}/environments/${this.environment}/profiles/${id}`,\n options,\n ),\n {\n method: 'GET',\n },\n )\n\n const {\n data: { changes, experiences, profile },\n } = ExperienceResponse.parse(await response.json())\n\n const data = { changes, personalizations: experiences, profile }\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return data\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n throw error\n }\n }\n\n /**\n * Sends a POST request to mutate a profile or profiles.\n *\n * @param request - Mutation request options including URL, body, and request options.\n * @returns The raw {@link Response} from the underlying fetch.\n *\n * @internal\n */\n private async makeProfileMutationRequest({\n url,\n body,\n options,\n }: ProfileMutationRequestOptions): Promise<Response> {\n return await this.fetch(this.constructUrl(url, options), {\n method: 'POST',\n headers: this.constructHeaders(options),\n body: JSON.stringify(body),\n keepalive: true,\n })\n }\n\n /**\n * Creates a profile and returns the resulting optimization data.\n *\n * @param params - Parameters containing the events to aggregate into the profile.\n * @param options - Optional request options.\n * @returns The optimization data for the newly created profile.\n *\n * @remarks\n * The returned profile ID can be used for subsequent update requests.\n *\n * @example\n * ```ts\n * const data = await client.createProfile({\n * events: [{ type: 'identify', userId: 'user-123' }],\n * })\n * ```\n */\n public async createProfile(\n { events }: CreateProfileParams,\n options: RequestOptions = {},\n ): Promise<OptimizationData> {\n const requestName = 'Create Profile'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n const body: ExperienceRequestData = {\n events: ExperienceEventArray.parse(events),\n options: this.constructBodyOptions(options),\n }\n\n logger.debug(`\"${requestName}\" request body:`, body)\n\n try {\n const response = await this.makeProfileMutationRequest({\n url: `v2/organizations/${this.clientId}/environments/${this.environment}/profiles`,\n body,\n options,\n })\n\n const {\n data: { changes, experiences, profile },\n } = ExperienceResponse.parse(await response.json())\n\n const data = { changes, personalizations: experiences, profile }\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return data\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n throw error\n }\n }\n\n /**\n * Updates an existing profile with the given profile ID.\n *\n * @param params - Parameters including the profile ID and events.\n * @param options - Optional request options.\n * @returns The updated optimization data for the profile.\n *\n * @throws {@link Error}\n * Thrown if `profileId` is missing or the underlying request fails.\n *\n * @example\n * ```ts\n * const data = await client.updateProfile({\n * profileId: 'profile-id',\n * events: [{ type: 'track', event: 'viewed_video' }],\n * })\n * ```\n */\n public async updateProfile(\n { profileId, events }: UpdateProfileParams,\n options: RequestOptions = {},\n ): Promise<OptimizationData> {\n if (!profileId) throw new Error('Valid profile ID required.')\n\n const requestName = 'Update Profile'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n const body: ExperienceRequestData = {\n events: ExperienceEventArray.parse(events),\n options: this.constructBodyOptions(options),\n }\n\n logger.debug(`\"${requestName}\" request body:`, body)\n\n try {\n const response = await this.makeProfileMutationRequest({\n url: `v2/organizations/${this.clientId}/environments/${this.environment}/profiles/${profileId}`,\n body,\n options,\n })\n\n const {\n data: { changes, experiences, profile },\n } = ExperienceResponse.parse(await response.json())\n\n const data = { changes, personalizations: experiences, profile }\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return data\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n throw error\n }\n }\n\n /**\n * Creates or updates a profile depending on whether a `profileId` is provided.\n *\n * @param params - Parameters including optional profile ID and events.\n * @param options - Optional request options.\n * @returns The resulting optimization data.\n *\n * @example\n * ```ts\n * // Create\n * await client.upsertProfile({ events })\n *\n * // Update\n * await client.upsertProfile({ profileId: 'profile-id', events })\n * ```\n */\n public async upsertProfile(\n { profileId, events }: UpsertProfileParams,\n options?: RequestOptions,\n ): Promise<OptimizationData> {\n if (!profileId) {\n return await this.createProfile({ events }, options)\n } else {\n return await this.updateProfile({ profileId, events }, options)\n }\n }\n\n /**\n * Sends multiple events to the Ninetailed Experience API to upsert many profiles.\n *\n * @param params - Parameters containing the batch of events.\n * @param options - Optional request options.\n * @returns The list of profiles affected by the batch operation.\n *\n * @remarks\n * Every event must contain an anonymous ID. Profiles will be created or\n * updated according to the anonymous ID.\n *\n * This method is intended to be used from server environments.\n *\n * @example\n * ```ts\n * const profiles = await client.upsertManyProfiles({\n * events: [\n * [{ type: 'identify', userId: 'user-1' }],\n * [{ type: 'identify', userId: 'user-2' }],\n * ],\n * })\n * ```\n */\n public async upsertManyProfiles(\n { events }: BatchUpdateProfileParams,\n options: RequestOptions = {},\n ): Promise<BatchExperienceData['profiles']> {\n const requestName = 'Upsert Many Profiles'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n const body: ExperienceRequestData = {\n events: ExperienceEventArray.parse(events),\n options: this.constructBodyOptions(options),\n }\n\n logger.debug(`\"${requestName}\" request body:`, body)\n\n try {\n const response = await this.makeProfileMutationRequest({\n url: `v2/organizations/${this.clientId}/environments/${this.environment}/events`,\n body,\n options: { plainText: false, ...options },\n })\n\n const {\n data: { profiles },\n } = BatchExperienceResponse.parse(await response.json())\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return profiles\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n throw error\n }\n }\n\n /**\n * Constructs a request URL with query parameters derived from request options.\n *\n * @param path - Path relative to the Experience API base URL.\n * @param options - Request options that may influence query parameters.\n * @returns The fully constructed URL as a string.\n *\n * @internal\n */\n private constructUrl(path: string, options: RequestOptions): string {\n const url = new URL(path, this.baseUrl)\n const locale = options.locale ?? this.locale\n const preflight = options.preflight ?? this.preflight\n\n if (locale) {\n url.searchParams.set('locale', locale)\n }\n\n if (preflight) {\n url.searchParams.set('type', 'preflight')\n }\n\n return url.toString()\n }\n\n /**\n * Constructs request headers based on request options and default configuration.\n *\n * @param options - Request options that may influence headers.\n * @returns A record of HTTP headers to send with the request.\n *\n * @internal\n */\n private constructHeaders({\n ip = this.ip,\n plainText = this.plainText,\n }: RequestOptions): Record<string, string> {\n const headers = new Map<string, string>()\n\n if (ip) {\n headers.set('X-Force-IP', ip)\n }\n\n if (plainText ?? this.plainText ?? true) {\n headers.set('Content-Type', 'text/plain')\n } else {\n headers.set('Content-Type', 'application/json')\n }\n\n return Object.fromEntries(headers)\n }\n\n /**\n * Constructs the `options` section of the request body for profile mutations.\n *\n * @param options - Request options that may specify enabled features.\n * @returns Experience API body options including feature flags.\n *\n * @internal\n */\n private readonly constructBodyOptions = ({\n enabledFeatures = this.enabledFeatures,\n }: RequestOptions): ExperienceRequestOptions => {\n const bodyOptions: ExperienceRequestOptions = {}\n\n if (enabledFeatures && Array.isArray(enabledFeatures) && enabledFeatures.length > 0) {\n bodyOptions.features = enabledFeatures\n } else {\n bodyOptions.features = ['ip-enrichment', 'location']\n }\n\n return bodyOptions\n }\n}\n","import { BatchInsightsEventArray } from '@contentful/optimization-api-schemas'\nimport { createScopedLogger } from 'logger'\nimport ApiClientBase, { type ApiConfig } from '../ApiClientBase'\n\nconst logger = createScopedLogger('ApiClient:Insights')\n\n/**\n * Default base URL for the Insights ingest API.\n *\n * @public\n */\nexport const INSIGHTS_BASE_URL = 'https://ingest.insights.ninetailed.co/'\n\n/**\n * Options that control how Insights events are sent.\n *\n * @public\n */\ninterface RequestOptions {\n /**\n * Handler used to enqueue events via the Beacon API or a similar mechanism.\n *\n * @param url - Target URL for the batched events.\n * @param data - Array of batched insights events to be sent.\n * @returns `true` if the events were successfully queued, `false` otherwise.\n *\n * @remarks\n * When provided, this handler is preferred over direct `fetch` calls. If it\n * returns `false`, the client falls back to emitting events immediately via\n * `fetch`.\n */\n beaconHandler?: (url: string | URL, data: BatchInsightsEventArray) => boolean\n}\n\n/**\n * Configuration for {@link InsightsApiClient}.\n *\n * @public\n */\nexport interface InsightsApiClientConfig extends ApiConfig, RequestOptions {}\n\n/**\n * Client for sending analytics and insights events to the Ninetailed Insights API.\n *\n * @public\n *\n * @remarks\n * This client is optimized for sending batched events, optionally using a\n * custom beacon-like handler when available.\n *\n * @example\n * ```ts\n * const insightsClient = new InsightsApiClient({\n * clientId: 'org-id',\n * environment: 'main',\n * preview: false,\n * })\n *\n * await insightsClient.sendBatchEvents([\n * {\n * profile: { id: 'profile-123', ... },\n * events: [\n * {\n * type: 'track',\n * event: 'button_clicked',\n * properties: { id: 'primary-cta' },\n * },\n * ],\n * }\n * ])\n * ```\n */\nexport default class InsightsApiClient extends ApiClientBase {\n /**\n * Base URL used for Insights API requests.\n */\n protected readonly baseUrl: string\n\n /**\n * Optional handler used to enqueue events via the Beacon API or a similar mechanism.\n */\n private readonly beaconHandler: RequestOptions['beaconHandler']\n\n /**\n * Creates a new {@link InsightsApiClient} instance.\n *\n * @param config - Configuration for the Insights API client.\n *\n * @example\n * ```ts\n * const client = new InsightsApiClient({\n * clientId: 'org-id',\n * environment: 'main',\n * beaconHandler: (url, data) => {\n * return navigator.sendBeacon(url.toString(), JSON.stringify(data))\n * },\n * })\n * ```\n */\n constructor(config: InsightsApiClientConfig) {\n super('Insights', config)\n\n const { baseUrl, beaconHandler } = config\n\n this.baseUrl = baseUrl ?? INSIGHTS_BASE_URL\n this.beaconHandler = beaconHandler\n }\n\n /**\n * Sends batches of insights events to the Ninetailed Insights API.\n *\n * @param batches - Array of event batches to send.\n * @param options - Optional request options, including a per-call `beaconHandler`.\n * @returns A promise that resolves when the events have been sent or queued.\n *\n * @remarks\n * If a `beaconHandler` is provided (either in the method call or in the\n * client configuration) it will be invoked first. When the handler returns\n * `true`, the events are considered successfully queued and no network\n * request is made by this method.\n *\n * If the handler is missing or returns `false`, the events are emitted\n * immediately via `fetch`.\n *\n * @returns A boolean value that is true when either the event batch is successfully\n * queued by the beacon handler or a direct request is successfully sent.\n *\n * @example\n * ```ts\n * const success = await insightsClient.sendBatchEvents(batches)\n * ```\n *\n * @example\n * ```ts\n * // Override beaconHandler for a single call\n * const success = await insightsClient.sendBatchEvents(batches, {\n * beaconHandler: (url, data) => {\n * return navigator.sendBeacon(url.toString(), JSON.stringify(data))\n * },\n * })\n * ```\n */\n public async sendBatchEvents(\n batches: BatchInsightsEventArray,\n options: RequestOptions = {},\n ): Promise<boolean> {\n const { beaconHandler = this.beaconHandler } = options\n\n const url = new URL(\n `v1/organizations/${this.clientId}/environments/${this.environment}/events`,\n this.baseUrl,\n )\n\n const body = BatchInsightsEventArray.parse(batches)\n\n if (typeof beaconHandler === 'function') {\n logger.debug('Queueing events via beaconHandler')\n\n const beaconSuccessfullyQueued = beaconHandler(url, body)\n\n if (beaconSuccessfullyQueued) {\n return true\n } else {\n logger.warn(\n 'beaconHandler failed to queue events; events will be emitted immediately via fetch',\n )\n }\n }\n\n const requestName = 'Event Batches'\n\n logger.info(`Sending \"${requestName}\" request`)\n\n logger.debug(`\"${requestName}\" request body:`, body)\n\n try {\n await this.fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n keepalive: true,\n })\n\n logger.debug(`\"${requestName}\" request successfully completed`)\n\n return true\n } catch (error) {\n this.logRequestError(error, { requestName })\n\n return false\n }\n }\n}\n","import type { ApiConfig, GlobalApiConfigProperties } from './ApiClientBase'\nimport ExperienceApiClient, { type ExperienceApiClientConfig } from './experience'\nimport InsightsApiClient, { type InsightsApiClientConfig } from './insights'\n\n/**\n * Configuration for the high-level {@link ApiClient}.\n *\n * @public\n */\nexport interface ApiClientConfig extends Pick<ApiConfig, GlobalApiConfigProperties> {\n /**\n * Configuration for the personalization (Experience) API client.\n *\n * @remarks\n * Any properties shared with {@link ApiConfig} are taken from the top-level\n * config and overridden by this object when specified.\n */\n personalization?: Omit<ExperienceApiClientConfig, GlobalApiConfigProperties>\n\n /**\n * Configuration for the analytics (Insights) API client.\n *\n * @remarks\n * Any properties shared with {@link ApiConfig} are taken from the top-level\n * config and overridden by this object when specified.\n */\n analytics?: Omit<InsightsApiClientConfig, GlobalApiConfigProperties>\n}\n\n/**\n * Aggregated API client providing access to Experience and Insights APIs.\n *\n * @public\n *\n * @remarks\n * This client encapsulates shared configuration and exposes dedicated\n * sub-clients for personalization and analytics use cases.\n *\n * @example\n * ```ts\n * const client = new ApiClient({\n * clientId: 'org-id',\n * environment: 'main',\n * preview: false,\n * personalization: {\n * // experience-specific overrides\n * },\n * analytics: {\n * // insights-specific overrides\n * },\n * })\n *\n * const profile = await client.experience.getProfile('profile-id')\n * const batch = await client.insights.upsertManyProfiles({ events: batchEvents })\n * ```\n */\nexport default class ApiClient {\n /**\n * Shared configuration applied to both Experience and Insights clients.\n */\n readonly config: ApiConfig\n\n /**\n * Client for personalization and experience-related operations.\n */\n readonly experience: ExperienceApiClient\n\n /**\n * Client for analytics and insights-related operations.\n */\n readonly insights: InsightsApiClient\n\n /**\n * Creates a new aggregated {@link ApiClient} instance.\n *\n * @param config - Global API client configuration with optional per-client overrides.\n */\n constructor(config: ApiClientConfig) {\n const { personalization, analytics, ...apiConfig } = config\n\n this.config = apiConfig\n\n this.experience = new ExperienceApiClient({\n ...apiConfig,\n ...personalization,\n })\n\n this.insights = new InsightsApiClient({\n ...apiConfig,\n ...analytics,\n })\n }\n}\n","function noop() { }\n\nexport { noop };\n","function getSymbols(object) {\n return Object.getOwnPropertySymbols(object).filter(symbol => Object.prototype.propertyIsEnumerable.call(object, symbol));\n}\n\nexport { getSymbols };\n","function getTag(value) {\n if (value == null) {\n return value === undefined ? '[object Undefined]' : '[object Null]';\n }\n return Object.prototype.toString.call(value);\n}\n\nexport { getTag };\n","const regexpTag = '[object RegExp]';\nconst stringTag = '[object String]';\nconst numberTag = '[object Number]';\nconst booleanTag = '[object Boolean]';\nconst argumentsTag = '[object Arguments]';\nconst symbolTag = '[object Symbol]';\nconst dateTag = '[object Date]';\nconst mapTag = '[object Map]';\nconst setTag = '[object Set]';\nconst arrayTag = '[object Array]';\nconst functionTag = '[object Function]';\nconst arrayBufferTag = '[object ArrayBuffer]';\nconst objectTag = '[object Object]';\nconst errorTag = '[object Error]';\nconst dataViewTag = '[object DataView]';\nconst uint8ArrayTag = '[object Uint8Array]';\nconst uint8ClampedArrayTag = '[object Uint8ClampedArray]';\nconst uint16ArrayTag = '[object Uint16Array]';\nconst uint32ArrayTag = '[object Uint32Array]';\nconst bigUint64ArrayTag = '[object BigUint64Array]';\nconst int8ArrayTag = '[object Int8Array]';\nconst int16ArrayTag = '[object Int16Array]';\nconst int32ArrayTag = '[object Int32Array]';\nconst bigInt64ArrayTag = '[object BigInt64Array]';\nconst float32ArrayTag = '[object Float32Array]';\nconst float64ArrayTag = '[object Float64Array]';\n\nexport { argumentsTag, arrayBufferTag, arrayTag, bigInt64ArrayTag, bigUint64ArrayTag, booleanTag, dataViewTag, dateTag, errorTag, float32ArrayTag, float64ArrayTag, functionTag, int16ArrayTag, int32ArrayTag, int8ArrayTag, mapTag, numberTag, objectTag, regexpTag, setTag, stringTag, symbolTag, uint16ArrayTag, uint32ArrayTag, uint8ArrayTag, uint8ClampedArrayTag };\n","function isPlainObject(value) {\n if (!value || typeof value !== 'object') {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n const hasObjectPrototype = proto === null ||\n proto === Object.prototype ||\n Object.getPrototypeOf(proto) === null;\n if (!hasObjectPrototype) {\n return false;\n }\n return Object.prototype.toString.call(value) === '[object Object]';\n}\n\nexport { isPlainObject };\n","function isUnsafeProperty(key) {\n return key === '__proto__';\n}\n\nexport { isUnsafeProperty };\n","import { isUnsafeProperty } from '../_internal/isUnsafeProperty.mjs';\nimport { isPlainObject } from '../predicate/isPlainObject.mjs';\n\nfunction merge(target, source) {\n const sourceKeys = Object.keys(source);\n for (let i = 0; i < sourceKeys.length; i++) {\n const key = sourceKeys[i];\n if (isUnsafeProperty(key)) {\n continue;\n }\n const sourceValue = source[key];\n const targetValue = target[key];\n if (Array.isArray(sourceValue)) {\n if (Array.isArray(targetValue)) {\n target[key] = merge(targetValue, sourceValue);\n }\n else {\n target[key] = merge([], sourceValue);\n }\n }\n else if (isPlainObject(sourceValue)) {\n if (isPlainObject(targetValue)) {\n target[key] = merge(targetValue, sourceValue);\n }\n else {\n target[key] = merge({}, sourceValue);\n }\n }\n else if (targetValue === undefined || sourceValue !== undefined) {\n target[key] = sourceValue;\n }\n }\n return target;\n}\n\nexport { merge };\n","function eq(value, other) {\n return value === other || (Number.isNaN(value) && Number.isNaN(other));\n}\n\nexport { eq };\n","import { isPlainObject } from './isPlainObject.mjs';\nimport { getSymbols } from '../compat/_internal/getSymbols.mjs';\nimport { getTag } from '../compat/_internal/getTag.mjs';\nimport { functionTag, regexpTag, symbolTag, dateTag, booleanTag, numberTag, stringTag, objectTag, errorTag, dataViewTag, arrayBufferTag, float64ArrayTag, float32ArrayTag, bigInt64ArrayTag, int32ArrayTag, int16ArrayTag, int8ArrayTag, bigUint64ArrayTag, uint32ArrayTag, uint16ArrayTag, uint8ClampedArrayTag, uint8ArrayTag, arrayTag, setTag, mapTag, argumentsTag } from '../compat/_internal/tags.mjs';\nimport { eq } from '../compat/util/eq.mjs';\n\nfunction isEqualWith(a, b, areValuesEqual) {\n return isEqualWithImpl(a, b, undefined, undefined, undefined, undefined, areValuesEqual);\n}\nfunction isEqualWithImpl(a, b, property, aParent, bParent, stack, areValuesEqual) {\n const result = areValuesEqual(a, b, property, aParent, bParent, stack);\n if (result !== undefined) {\n return result;\n }\n if (typeof a === typeof b) {\n switch (typeof a) {\n case 'bigint':\n case 'string':\n case 'boolean':\n case 'symbol':\n case 'undefined': {\n return a === b;\n }\n case 'number': {\n return a === b || Object.is(a, b);\n }\n case 'function': {\n return a === b;\n }\n case 'object': {\n return areObjectsEqual(a, b, stack, areValuesEqual);\n }\n }\n }\n return areObjectsEqual(a, b, stack, areValuesEqual);\n}\nfunction areObjectsEqual(a, b, stack, areValuesEqual) {\n if (Object.is(a, b)) {\n return true;\n }\n let aTag = getTag(a);\n let bTag = getTag(b);\n if (aTag === argumentsTag) {\n aTag = objectTag;\n }\n if (bTag === argumentsTag) {\n bTag = objectTag;\n }\n if (aTag !== bTag) {\n return false;\n }\n switch (aTag) {\n case stringTag:\n return a.toString() === b.toString();\n case numberTag: {\n const x = a.valueOf();\n const y = b.valueOf();\n return eq(x, y);\n }\n case booleanTag:\n case dateTag:\n case symbolTag:\n return Object.is(a.valueOf(), b.valueOf());\n case regexpTag: {\n return a.source === b.source && a.flags === b.flags;\n }\n case functionTag: {\n return a === b;\n }\n }\n stack = stack ?? new Map();\n const aStack = stack.get(a);\n const bStack = stack.get(b);\n if (aStack != null && bStack != null) {\n return aStack === b;\n }\n stack.set(a, b);\n stack.set(b, a);\n try {\n switch (aTag) {\n case mapTag: {\n if (a.size !== b.size) {\n return false;\n }\n for (const [key, value] of a.entries()) {\n if (!b.has(key) || !isEqualWithImpl(value, b.get(key), key, a, b, stack, areValuesEqual)) {\n return false;\n }\n }\n return true;\n }\n case setTag: {\n if (a.size !== b.size) {\n return false;\n }\n const aValues = Array.from(a.values());\n const bValues = Array.from(b.values());\n for (let i = 0; i < aValues.length; i++) {\n const aValue = aValues[i];\n const index = bValues.findIndex(bValue => {\n return isEqualWithImpl(aValue, bValue, undefined, a, b, stack, areValuesEqual);\n });\n if (index === -1) {\n return false;\n }\n bValues.splice(index, 1);\n }\n return true;\n }\n case arrayTag:\n case uint8ArrayTag:\n case uint8ClampedArrayTag:\n case uint16ArrayTag:\n case uint32ArrayTag:\n case bigUint64ArrayTag:\n case int8ArrayTag:\n case int16ArrayTag:\n case int32ArrayTag:\n case bigInt64ArrayTag:\n case float32ArrayTag:\n case float64ArrayTag: {\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(a) !== Buffer.isBuffer(b)) {\n return false;\n }\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (!isEqualWithImpl(a[i], b[i], i, a, b, stack, areValuesEqual)) {\n return false;\n }\n }\n return true;\n }\n case arrayBufferTag: {\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n return areObjectsEqual(new Uint8Array(a), new Uint8Array(b), stack, areValuesEqual);\n }\n case dataViewTag: {\n if (a.byteLength !== b.byteLength || a.byteOffset !== b.byteOffset) {\n return false;\n }\n return areObjectsEqual(new Uint8Array(a), new Uint8Array(b), stack, areValuesEqual);\n }\n case errorTag: {\n return a.name === b.name && a.message === b.message;\n }\n case objectTag: {\n const areEqualInstances = areObjectsEqual(a.constructor, b.constructor, stack, areValuesEqual) ||\n (isPlainObject(a) && isPlainObject(b));\n if (!areEqualInstances) {\n return false;\n }\n const aKeys = [...Object.keys(a), ...getSymbols(a)];\n const bKeys = [...Object.keys(b), ...getSymbols(b)];\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n for (let i = 0; i < aKeys.length; i++) {\n const propKey = aKeys[i];\n const aProp = a[propKey];\n if (!Object.hasOwn(b, propKey)) {\n return false;\n }\n const bProp = b[propKey];\n if (!isEqualWithImpl(aProp, bProp, propKey, a, b, stack, areValuesEqual)) {\n return false;\n }\n }\n return true;\n }\n default: {\n return false;\n }\n }\n }\n finally {\n stack.delete(a);\n stack.delete(b);\n }\n}\n\nexport { isEqualWith };\n","import { isEqualWith } from './isEqualWith.mjs';\nimport { noop } from '../function/noop.mjs';\n\nfunction isEqual(a, b) {\n return isEqualWith(a, b, noop);\n}\n\nexport { isEqual };\n","import {\n type App,\n Campaign,\n type Channel,\n type ComponentViewEvent,\n GeoLocation,\n type IdentifyEvent,\n type Library,\n Page,\n PageEventContext,\n type PageViewEvent,\n Properties,\n Screen,\n ScreenEventContext,\n type ScreenViewEvent,\n type TrackEvent,\n Traits,\n type UniversalEventProperties,\n} from '@contentful/optimization-api-schemas'\nimport { merge } from 'es-toolkit'\nimport * as z from 'zod/mini'\n\n/**\n * Configuration options for creating an {@link EventBuilder} instance.\n *\n * @public\n * @remarks\n * The configuration is typically provided by the host application to adapt\n * event payloads to the runtime environment (browser, framework, etc.).\n *\n * @example\n * ```ts\n * const builder = new EventBuilder({\n * app: { name: 'my-app', version: '1.0.0' },\n * channel: 'web',\n * library: { name: '@contentful/optimization-sdk', version: '1.2.3' },\n * getLocale: () => navigator.language,\n * getPageProperties: () => ({\n * path: window.location.pathname,\n * url: window.location.href,\n * title: document.title,\n * query: {},\n * referrer: document.referrer,\n * search: window.location.search,\n * }),\n * })\n * ```\n */\nexport interface EventBuilderConfig {\n /**\n * The application definition used to attribute events to a specific consumer app.\n *\n * @remarks\n * When not provided, events will not contain app metadata in their context.\n */\n app?: App\n\n /**\n * The channel that identifies where events originate from (e.g. web, mobile).\n *\n * @see {@link Channel}\n */\n channel: Channel\n\n /**\n * The client library metadata that is attached to all events.\n *\n * @remarks\n * This is typically used to record the library name and version.\n */\n library: Library\n\n /**\n * Function used to resolve the locale for outgoing events.\n *\n * @remarks\n * If not provided, the builder falls back to the default `'en-US'`. Locale\n * values supplied directly as arguments to event builder methods take\n * precedence.\n *\n * @returns The locale string (e.g. `'en-US'`), or `undefined` if unavailable.\n */\n getLocale?: () => string | undefined\n\n /**\n * Function that returns the current page properties.\n *\n * @remarks\n * Page properties are currently added to the context of all events, as well\n * as the `properties` of the page event. When specified, all properties of\n * the `Page` type are required, but may contain empty values.\n *\n * @returns A {@link Page} object containing information about the current page.\n * @see {@link Page}\n */\n getPageProperties?: () => Page\n\n /**\n * Function used to obtain the current user agent string when applicable.\n *\n * @returns A user agent string, or `undefined` if unavailable.\n */\n getUserAgent?: () => string | undefined\n}\n\nconst UniversalEventBuilderArgs = z.object({\n campaign: z.optional(Campaign),\n locale: z.optional(z.string()),\n location: z.optional(GeoLocation),\n page: z.optional(Page),\n screen: z.optional(Screen),\n userAgent: z.optional(z.string()),\n})\n\n/**\n * Arguments used to construct the universal (shared) portion of all events.\n *\n * @public\n */\nexport type UniversalEventBuilderArgs = z.infer<typeof UniversalEventBuilderArgs>\n\nconst ComponentViewBuilderArgs = z.extend(UniversalEventBuilderArgs, {\n componentId: z.string(),\n experienceId: z.optional(z.string()),\n variantIndex: z.optional(z.number()),\n sticky: z.optional(z.boolean()),\n})\n\n/**\n * Arguments for constructing component view events.\n *\n * @public\n */\nexport type ComponentViewBuilderArgs = z.infer<typeof ComponentViewBuilderArgs>\n\nconst IdentifyBuilderArgs = z.extend(UniversalEventBuilderArgs, {\n traits: z.optional(Traits),\n userId: z.string(),\n})\n\n/**\n * Arguments for constructing identify events.\n *\n * @public\n * @remarks\n * Traits are merged by the API; only specified properties may be overwritten.\n */\nexport type IdentifyBuilderArgs = z.infer<typeof IdentifyBuilderArgs>\n\nconst PageViewBuilderArgs = z.extend(UniversalEventBuilderArgs, {\n properties: z.optional(z.partial(Page)),\n})\n\n/**\n * Arguments for constructing page view events.\n *\n * @public\n * @remarks\n * Any properties passed here are merged with the base page properties from\n * {@link EventBuilderConfig.getPageProperties}.\n */\nexport type PageViewBuilderArgs = z.infer<typeof PageViewBuilderArgs>\n\nconst ScreenViewBuilderArgs = z.extend(UniversalEventBuilderArgs, {\n name: z.string(),\n properties: Properties,\n})\n\n/**\n * Arguments for constructing screen view events.\n *\n * @public\n * @remarks\n * Any properties passed here are merged with the base screen properties from\n * {@link EventBuilderConfig.getScreenProperties}.\n */\nexport type ScreenViewBuilderArgs = z.infer<typeof ScreenViewBuilderArgs>\n\nconst TrackBuilderArgs = z.extend(UniversalEventBuilderArgs, {\n event: z.string(),\n properties: z.optional(z.prefault(Properties, {})),\n})\n\n/**\n * Arguments for constructing track events.\n *\n * @public\n */\nexport type TrackBuilderArgs = z.infer<typeof TrackBuilderArgs>\n\n/**\n * Default page properties used when no explicit page information is available.\n *\n * @public\n *\n * @defaultValue\n * ```ts\n * {\n * path: '',\n * query: {},\n * referrer: '',\n * search: '',\n * title: '',\n * url: '',\n * }\n * ```\n *\n * @remarks\n * Values are required by the API; values may not be `undefined`. Empty values are valid.\n */\nexport const DEFAULT_PAGE_PROPERTIES = {\n path: '',\n query: {},\n referrer: '',\n search: '',\n title: '',\n url: '',\n}\n\n/**\n * Internal helper class for building analytics and personalization events.\n *\n * @remarks\n * This class coordinates configuration and argument validation to produce\n * strongly-typed event payloads compatible with\n * `@contentful/optimization-api-schemas`.\n *\n * @public\n */\nclass EventBuilder {\n /**\n * Application metadata attached to each event.\n *\n * @internal\n */\n app?: App\n\n /**\n * Channel value attached to each event.\n *\n * @internal\n */\n channel: Channel\n\n /**\n * Library metadata attached to each event.\n *\n * @internal\n */\n library: Library\n\n /**\n * Function that provides the locale when available.\n *\n * @internal\n */\n getLocale: () => string | undefined\n\n /**\n * Function that provides baseline page properties.\n *\n * @internal\n */\n getPageProperties: () => Page\n\n /**\n * Function that provides the user agent string when available.\n *\n * @internal\n */\n getUserAgent: () => string | undefined\n\n /**\n * Creates a new {@link EventBuilder} instance.\n *\n * @param config - Configuration used to customize event payloads.\n *\n * @internal\n * @remarks\n * Callers are expected to reuse a single instance when possible to avoid\n * repeatedly reconfiguring the builder.\n *\n * @example\n * ```ts\n * const builder = new EventBuilder({\n * channel: 'web',\n * library: { name: '@contentful/optimization-sdk', version: '1.0.0' },\n * })\n * ```\n */\n constructor(config: EventBuilderConfig) {\n const { app, channel, library, getLocale, getPageProperties, getUserAgent } = config\n this.app = app\n this.channel = channel\n this.library = library\n this.getLocale = getLocale ?? (() => 'en-US')\n this.getPageProperties = getPageProperties ?? (() => DEFAULT_PAGE_PROPERTIES)\n this.getUserAgent = getUserAgent ?? (() => undefined)\n }\n\n /**\n * Builds the universal event properties shared across all event types.\n *\n * @param args - Arguments overriding the default context values.\n * @returns A fully populated {@link UniversalEventProperties} object.\n *\n * @protected\n *\n * @remarks\n * This method is used internally by the specific event-builder methods\n * (e.g. {@link EventBuilder.buildPageView}).\n */\n protected buildUniversalEventProperties({\n campaign = {},\n locale,\n location,\n page,\n screen,\n userAgent,\n }: UniversalEventBuilderArgs): UniversalEventProperties {\n const timestamp = new Date().toISOString()\n\n return {\n channel: this.channel,\n context: {\n app: this.app,\n campaign,\n gdpr: { isConsentGiven: true },\n library: this.library,\n locale: locale ?? this.getLocale() ?? 'en-US',\n location,\n page: page ?? this.getPageProperties(),\n screen,\n userAgent: userAgent ?? this.getUserAgent(),\n },\n messageId: crypto.randomUUID(),\n originalTimestamp: timestamp,\n sentAt: timestamp,\n timestamp,\n }\n }\n\n /**\n * Builds a component view event payload for a Contentful entry-based component.\n *\n * @param args - {@link ComponentViewBuilderArgs} arguments describing the component view.\n * @returns A {@link ComponentViewEvent} describing the view.\n *\n * @public\n *\n * @example\n * ```ts\n * const event = builder.buildComponentView({\n * componentId: 'entry-123',\n * experienceId: 'personalization-123',\n * variantIndex: 1,\n * })\n * ```\n */\n buildComponentView(args: ComponentViewBuilderArgs): ComponentViewEvent {\n const { componentId, experienceId, variantIndex, ...universal } =\n ComponentViewBuilderArgs.parse(args)\n\n return {\n ...this.buildUniversalEventProperties(universal),\n type: 'component',\n componentType: 'Entry',\n componentId,\n experienceId,\n variantIndex: variantIndex ?? 0,\n }\n }\n\n /**\n * Builds a component view event payload for a Custom Flag component.\n *\n * @param args - {@link ComponentViewBuilderArgs} arguments describing the Custom Flag view.\n * @returns A {@link ComponentViewEvent} describing the view.\n *\n * @public\n *\n * @remarks\n * This is a specialized variant of {@link EventBuilder.buildComponentView}\n * that sets `componentType` to `'Variable'`.\n *\n * @example\n * ```ts\n * const event = builder.buildFlagView({\n * componentId: 'feature-flag-key',\n * experienceId: 'personalization-123',\n * })\n * ```\n */\n buildFlagView(args: ComponentViewBuilderArgs): ComponentViewEvent {\n return {\n ...this.buildComponentView(args),\n componentType: 'Variable',\n }\n }\n\n /**\n * Builds an identify event payload to associate a user ID with traits.\n *\n * @param args - {@link IdentifyBuilderArgs} arguments describing the identified user.\n * @returns An {@link IdentifyEvent} payload.\n *\n * @public\n *\n * @remarks\n * - Traits are merged by the API; only specified properties may be overwritten.\n * - The User ID is consumer-specified and should not contain the value of any\n * ID generated by the Experience API.\n *\n * @example\n * ```ts\n * const event = builder.buildIdentify({\n * userId: 'user-123',\n * traits: { plan: 'pro' },\n * })\n * ```\n */\n buildIdentify(args: IdentifyBuilderArgs): IdentifyEvent {\n const { traits = {}, userId, ...universal } = IdentifyBuilderArgs.parse(args)\n\n return {\n ...this.buildUniversalEventProperties(universal),\n type: 'identify',\n traits,\n userId,\n }\n }\n\n /**\n * Builds a page view event payload.\n *\n * @param args - Optional {@link PageViewBuilderArgs} overrides for the page view event.\n * @returns A {@link PageViewEvent} payload.\n *\n * @public\n *\n * @remarks\n * Page properties are created by merging:\n * 1. The base page properties from {@link EventBuilderConfig.getPageProperties}, and\n * 2. The partial `properties` argument passed in.\n *\n * The title always falls back to {@link DEFAULT_PAGE_PROPERTIES}.title when undefined.\n *\n * @example\n * ```ts\n * const event = builder.buildPageView({\n * properties: {\n * title: 'Homepage',\n * },\n * })\n * ```\n */\n buildPageView(args: PageViewBuilderArgs = {}): PageViewEvent {\n const { properties = {}, ...universal } = PageViewBuilderArgs.parse(args)\n\n const pageProperties = this.getPageProperties()\n\n const merged = merge(\n {\n ...pageProperties,\n title: pageProperties.title ?? DEFAULT_PAGE_PROPERTIES.title,\n },\n properties,\n )\n\n const {\n context: { screen: _, ...universalContext },\n ...universalProperties\n } = this.buildUniversalEventProperties(universal)\n\n const context = PageEventContext.parse(universalContext)\n\n return {\n ...universalProperties,\n context,\n type: 'page',\n properties: merged,\n }\n }\n\n /**\n * Builds a screen view event payload.\n *\n * @param args - {@link ScreenViewBuilderArgs} arguments for the screen view event.\n * @returns A {@link ScreenViewEvent} payload.\n *\n * @public\n *\n * @example\n * ```ts\n * const event = builder.buildScreenView({\n * name: 'home',\n * properties: {\n * title: 'Home Screen',\n * },\n * })\n * ```\n */\n buildScreenView(args: ScreenViewBuilderArgs): ScreenViewEvent {\n const { name, properties, ...universal } = ScreenViewBuilderArgs.parse(args)\n\n const {\n context: { page: _, ...universalContext },\n ...universalProperties\n } = this.buildUniversalEventProperties(universal)\n\n const context = ScreenEventContext.parse(universalContext)\n\n return {\n ...universalProperties,\n context,\n type: 'screen',\n name,\n properties,\n }\n }\n\n /**\n * Builds a track event payload for arbitrary user actions.\n *\n * @param args - {@link TrackBuilderArgs} arguments describing the tracked event.\n * @returns A {@link TrackEvent} payload.\n *\n * @public\n *\n * @example\n * ```ts\n * const event = builder.buildTrack({\n * event: 'button_clicked',\n * properties: { id: 'primary-cta', location: 'hero' },\n * })\n * ```\n */\n buildTrack(args: TrackBuilderArgs): TrackEvent {\n const { event, properties = {}, ...universal } = TrackBuilderArgs.parse(args)\n\n return {\n ...this.buildUniversalEventProperties(universal),\n type: 'track',\n event,\n properties,\n }\n }\n}\n\nexport default EventBuilder\n","function isDeepKey(key) {\n switch (typeof key) {\n case 'number':\n case 'symbol': {\n return false;\n }\n case 'string': {\n return key.includes('.') || key.includes('[') || key.includes(']');\n }\n }\n}\n\nexport { isDeepKey };\n","function toKey(value) {\n if (typeof value === 'string' || typeof value === 'symbol') {\n return value;\n }\n if (Object.is(value?.valueOf?.(), -0)) {\n return '-0';\n }\n return String(value);\n}\n\nexport { toKey };\n","function toPath(deepKey) {\n const result = [];\n const length = deepKey.length;\n if (length === 0) {\n return result;\n }\n let index = 0;\n let key = '';\n let quoteChar = '';\n let bracket = false;\n if (deepKey.charCodeAt(0) === 46) {\n result.push('');\n index++;\n }\n while (index < length) {\n const char = deepKey[index];\n if (quoteChar) {\n if (char === '\\\\' && index + 1 < length) {\n index++;\n key += deepKey[index];\n }\n else if (char === quoteChar) {\n quoteChar = '';\n }\n else {\n key += char;\n }\n }\n else if (bracket) {\n if (char === '\"' || char === \"'\") {\n quoteChar = char;\n }\n else if (char === ']') {\n bracket = false;\n result.push(key);\n key = '';\n }\n else {\n key += char;\n }\n }\n else {\n if (char === '[') {\n bracket = true;\n if (key) {\n result.push(key);\n key = '';\n }\n }\n else if (char === '.') {\n if (key) {\n result.push(key);\n key = '';\n }\n }\n else {\n key += char;\n }\n }\n index++;\n }\n if (key) {\n result.push(key);\n }\n return result;\n}\n\nexport { toPath };\n","import { isUnsafeProperty } from '../../_internal/isUnsafeProperty.mjs';\nimport { isDeepKey } from '../_internal/isDeepKey.mjs';\nimport { toKey } from '../_internal/toKey.mjs';\nimport { toPath } from '../util/toPath.mjs';\n\nfunction get(object, path, defaultValue) {\n if (object == null) {\n return defaultValue;\n }\n switch (typeof path) {\n case 'string': {\n if (isUnsafeProperty(path)) {\n return defaultValue;\n }\n const result = object[path];\n if (result === undefined) {\n if (isDeepKey(path)) {\n return get(object, toPath(path), defaultValue);\n }\n else {\n return defaultValue;\n }\n }\n return result;\n }\n case 'number':\n case 'symbol': {\n if (typeof path === 'number') {\n path = toKey(path);\n }\n const result = object[path];\n if (result === undefined) {\n return defaultValue;\n }\n return result;\n }\n default: {\n if (Array.isArray(path)) {\n return getWithPath(object, path, defaultValue);\n }\n if (Object.is(path?.valueOf(), -0)) {\n path = '-0';\n }\n else {\n path = String(path);\n }\n if (isUnsafeProperty(path)) {\n return defaultValue;\n }\n const result = object[path];\n if (result === undefined) {\n return defaultValue;\n }\n return result;\n }\n }\n}\nfunction getWithPath(object, path, defaultValue) {\n if (path.length === 0) {\n return defaultValue;\n }\n let current = object;\n for (let index = 0; index < path.length; index++) {\n if (current == null) {\n return defaultValue;\n }\n if (isUnsafeProperty(path[index])) {\n return defaultValue;\n }\n current = current[path[index]];\n }\n if (current === undefined) {\n return defaultValue;\n }\n return current;\n}\n\nexport { get };\n","import { MergeTagEntry, Profile } from '@contentful/optimization-api-client'\nimport { get } from 'es-toolkit/compat'\nimport { createScopedLogger } from 'logger'\n\nconst logger = createScopedLogger('Personalization')\n\n/** Base string for log messages when merge-tag resolution fails. */\nconst RESOLUTION_WARNING_BASE = 'Could not resolve Merge Tag value:'\n\n/**\n * Resolves merge tag values from a {@link Profile}.\n *\n * @public\n * @remarks\n * *Merge tags* are references to user profile data that may be embedded in content\n * and expanded at runtime. This resolver normalizes the merge-tag identifier into\n * a set of candidate selectors and searches the profile for a matching value.\n * Result values are returned as strings; numeric/boolean primitives are stringified.\n */\nconst MergeTagValueResolver = {\n /**\n * Type guard to ensure the input is a {@link MergeTagEntry}.\n *\n * @param embeddedEntryNodeTarget - Unknown value to validate.\n * @returns `true` if the input is a valid merge-tag entry.\n * @example\n * ```ts\n * if (MergeTagValueResolver.isMergeTagEntry(node)) {\n * // safe to read fields\n * }\n * ```\n */\n isMergeTagEntry(embeddedEntryNodeTarget: unknown): embeddedEntryNodeTarget is MergeTagEntry {\n return MergeTagEntry.safeParse(embeddedEntryNodeTarget).success\n },\n\n /**\n * Generate a list of candidate selectors for a merge-tag ID.\n *\n * @param id - Merge-tag identifier (segments separated by `_`).\n * @returns Array of dot-path selectors to try against a profile.\n * @example\n * ```ts\n * // \"profile_name_first\" -> [\n * // 'profile',\n * // 'profile.name',\n * // 'profile.name.first'\n * // ]\n * const selectors = MergeTagValueResolver.normalizeSelectors('profile_name_first')\n * ```\n */\n normalizeSelectors(id: string): string[] {\n return id.split('_').map((_path, index, paths) => {\n const dotPath = paths.slice(0, index).join('.')\n const underScorePath = paths.slice(index).join('_')\n\n return [dotPath, underScorePath].filter((path) => path !== '').join('.')\n })\n },\n\n /**\n * Look up a merge-tag value from a profile using normalized selectors.\n *\n * @param id - Merge-tag identifier.\n * @param profile - Profile from which to resolve the value.\n * @returns A stringified primitive if found; otherwise `undefined`.\n * @example\n * ```ts\n * const value = MergeTagValueResolver.getValueFromProfile('user_email', profile)\n * if (value) sendEmailTo(value)\n * ```\n * @remarks\n * Only string/number/boolean primitives are returned; objects/arrays are ignored.\n */\n getValueFromProfile(id: string, profile?: Profile): string | undefined {\n const selectors = MergeTagValueResolver.normalizeSelectors(id)\n const matchingSelector = selectors.find((selector) => get(profile, selector))\n\n if (!matchingSelector) return undefined\n\n const value: unknown = get(profile, matchingSelector)\n\n if (\n !value ||\n (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean')\n )\n return undefined\n\n return `${value}`\n },\n\n /**\n * Resolve the display value for a merge-tag entry using the provided profile,\n * falling back to the entry's configured `nt_fallback` when necessary.\n *\n * @param mergeTagEntry - The merge-tag entry to resolve.\n * @param profile - Optional profile used for lookup.\n * @returns The resolved string, or `undefined` if the entry is invalid and no\n * fallback is available.\n * @example\n * ```ts\n * const text = MergeTagValueResolver.resolve(entry, profile)\n * render(text ?? 'Guest')\n * ```\n */\n resolve(mergeTagEntry: MergeTagEntry | undefined, profile?: Profile): string | undefined {\n if (!MergeTagValueResolver.isMergeTagEntry(mergeTagEntry)) {\n logger.warn(`${RESOLUTION_WARNING_BASE} supplied entry is not a Merge Tag entry`)\n return\n }\n\n const {\n fields: { nt_fallback: fallback },\n } = mergeTagEntry\n\n if (!Profile.safeParse(profile).success) {\n logger.warn(`${RESOLUTION_WARNING_BASE} no valid profile`)\n return fallback\n }\n\n return (\n MergeTagValueResolver.getValueFromProfile(mergeTagEntry.fields.nt_mergetag_id, profile) ??\n fallback\n )\n },\n}\n\nexport default MergeTagValueResolver\n","import {\n type EntryReplacementComponent,\n type EntryReplacementVariant,\n isEntry,\n isEntryReplacementComponent,\n isEntryReplacementVariant,\n isPersonalizationEntry,\n isPersonalizedEntry,\n type PersonalizationEntry,\n type PersonalizedEntry,\n type SelectedPersonalization,\n type SelectedPersonalizationArray,\n} from '@contentful/optimization-api-client'\nimport type { ChainModifiers, Entry, EntrySkeletonType, LocaleCode } from 'contentful'\nimport { createScopedLogger } from 'logger'\n\nconst logger = createScopedLogger('Personalization')\n\n/**\n * Result returned by {@link PersonalizedEntryResolver.resolve}.\n *\n * @typeParam S - Entry skeleton type.\n * @typeParam M - Chain modifiers.\n * @typeParam L - Locale code.\n * @public\n */\nexport interface ResolvedData<\n S extends EntrySkeletonType,\n M extends ChainModifiers = ChainModifiers,\n L extends LocaleCode = LocaleCode,\n> {\n /** The baseline or resolved variant entry. */\n entry: Entry<S, M, L>\n /** The selected personalization metadata, if a non‑baseline variant was chosen. */\n personalization?: SelectedPersonalization\n}\n\n/** Base string for resolver warning messages. */\nconst RESOLUTION_WARNING_BASE = 'Could not resolve personalized entry variant:'\n\n/**\n * Resolve a personalized Contentful entry to the correct variant for the current\n * selections.\n *\n * @public\n * @remarks\n * Given a baseline {@link PersonalizedEntry} and a set of selected personalizations\n * (variants per experience), this resolver finds the matching replacement variant\n * for the component configured against the baseline entry.\n *\n * **Variant indexing**: `variantIndex` in {@link SelectedPersonalization} is treated as\n * 1‑based (index 1 = first variant). A value of `0` indicates baseline.\n */\nconst PersonalizedEntryResolver = {\n /**\n * Find the personalization entry corresponding to one of the selected experiences.\n *\n * @param params - Object containing the baseline personalized entry and the selections.\n * @param skipValidation - When `true`, skip type/shape validation for perf.\n * @returns The matching {@link PersonalizationEntry}, or `undefined` if not found/invalid.\n * @example\n * ```ts\n * const personalizationEntry = PersonalizedEntryResolver.getPersonalizationEntry({\n * personalizedEntry: entry,\n * selectedPersonalizations\n * })\n * ```\n * @remarks\n * A personalization entry is a personalization configuration object supplied in a\n * `PersonalizedEntry.nt_experiences` array. A personalized entry may relate to\n * multiple personalizations.\n */\n getPersonalizationEntry(\n {\n personalizedEntry,\n selectedPersonalizations,\n }: {\n personalizedEntry: PersonalizedEntry\n selectedPersonalizations: SelectedPersonalizationArray\n },\n skipValidation = false,\n ): PersonalizationEntry | undefined {\n if (\n !skipValidation &&\n (!selectedPersonalizations.length || !isPersonalizedEntry(personalizedEntry))\n )\n return\n\n const personalizationEntry = personalizedEntry.fields.nt_experiences\n .filter((maybePersonalization) => isPersonalizationEntry(maybePersonalization))\n .find((personalizationEntry) =>\n selectedPersonalizations.some(\n ({ experienceId }) => experienceId === personalizationEntry.fields.nt_experience_id,\n ),\n )\n\n return personalizationEntry\n },\n\n /**\n * Look up the selection metadata for a specific personalization entry.\n *\n * @param params - Object with the target personalization entry and selections.\n * @param skipValidation - When `true`, skip type checks.\n * @returns The matching {@link SelectedPersonalization}, if present.\n * @example\n * ```ts\n * const selectedPersonalization = PersonalizedEntryResolver.getSelectedPersonalization({\n * personalizationEntry,\n * selectedPersonalizations\n * })\n * ```\n * @remarks\n * Selected personalizations are supplied by the Experience API in the\n * `experiences` response data property.\n */\n getSelectedPersonalization(\n {\n personalizationEntry,\n selectedPersonalizations,\n }: {\n personalizationEntry: PersonalizationEntry\n selectedPersonalizations: SelectedPersonalizationArray\n },\n skipValidation = false,\n ): SelectedPersonalization | undefined {\n if (\n !skipValidation &&\n (!selectedPersonalizations.length || !isPersonalizationEntry(personalizationEntry))\n )\n return\n\n const selectedPersonalization = selectedPersonalizations.find(\n ({ experienceId }) => experienceId === personalizationEntry.fields.nt_experience_id,\n )\n\n return selectedPersonalization\n },\n\n /**\n * Get the replacement variant config for the given selection index.\n *\n * @param params - Baseline entry, personalization entry, and 1‑based variant index.\n * @param skipValidation - When `true`, skip type checks.\n * @returns The {@link EntryReplacementVariant} for the component, if any.\n * @example\n * ```ts\n * const selectedVariant = PersonalizedEntryResolver.getSelectedVariant({\n * personalizedEntry: entry,\n * personalizationEntry,\n * selectedVariantIndex: 2 // second variant (1‑based)\n * })\n * ```\n * @remarks\n * Entry replacement variants are variant configurations specified in a\n * personalization configuration component's `variants` array supplied by the\n * personalized entry via its `nt_config` field.\n */\n getSelectedVariant(\n {\n personalizedEntry,\n personalizationEntry,\n selectedVariantIndex,\n }: {\n personalizedEntry: PersonalizedEntry\n personalizationEntry: PersonalizationEntry\n selectedVariantIndex: number\n },\n skipValidation = false,\n ): EntryReplacementVariant | undefined {\n if (\n !skipValidation &&\n (!isPersonalizedEntry(personalizedEntry) || !isPersonalizationEntry(personalizationEntry))\n )\n return\n\n const relevantVariants = personalizationEntry.fields.nt_config?.components\n ?.filter(\n (component): component is EntryReplacementComponent =>\n isEntryReplacementComponent(component) && !component.baseline.hidden,\n )\n .find((component) => component.baseline.id === personalizedEntry.sys.id)?.variants\n\n if (!relevantVariants?.length) return\n\n return relevantVariants.at(selectedVariantIndex - 1)\n },\n\n /**\n * Resolve the concrete Contentful entry that corresponds to a selected variant.\n *\n * @typeParam S - Entry skeleton type.\n * @typeParam M - Chain modifiers.\n * @typeParam L - Locale code.\n * @param params - Personalization entry and selected variant.\n * @param skipValidation - When `true`, skip type checks.\n * @returns The resolved entry typed as {@link Entry} or `undefined`.\n * @example\n * ```ts\n * const selectedVariantEntry = PersonalizedEntryResolver.getSelectedVariantEntry<{ fields: unknown }>({\n * personalizationEntry,\n * selectedVariant\n * })\n * ```\n * @remarks\n * A personalized entry will resolve either to the baseline (the entry\n * supplied as `personalizedEntry`) or the selected variant.\n */\n getSelectedVariantEntry<\n S extends EntrySkeletonType,\n M extends ChainModifiers = ChainModifiers,\n L extends LocaleCode = LocaleCode,\n >(\n {\n personalizationEntry,\n selectedVariant,\n }: {\n personalizationEntry: PersonalizationEntry\n selectedVariant: EntryReplacementVariant\n },\n skipValidation = false,\n ): Entry<S, M, L> | undefined {\n if (\n !skipValidation &&\n (!isPersonalizationEntry(personalizationEntry) || !isEntryReplacementVariant(selectedVariant))\n )\n return\n\n const selectedVariantEntry = personalizationEntry.fields.nt_variants?.find(\n (variant) => variant.sys.id === selectedVariant.id,\n )\n\n return isEntry<S, M, L>(selectedVariantEntry) ? selectedVariantEntry : undefined\n },\n\n /**\n * Resolve the selected entry (baseline or variant) for a personalized entry\n * and optional selected personalizations, returning both the entry and the\n * personalization metadata.\n *\n * @typeParam S - Entry skeleton type.\n * @typeParam M - Chain modifiers.\n * @typeParam L - Locale code.\n * @param entry - The baseline personalized entry.\n * @param selectedPersonalizations - Optional selections for the current profile.\n * @returns An object containing the resolved entry and (if chosen) the selection.\n * @example\n * ```ts\n * const { entry: personalizedEntry, personalization } = PersonalizedEntryResolver.resolve(entry, selections)\n * if (personalization) console.log('Variant index', personalization.variantIndex)\n * ```\n */\n resolve<\n S extends EntrySkeletonType,\n M extends ChainModifiers = ChainModifiers,\n L extends LocaleCode = LocaleCode,\n >(\n entry: Entry<S, M, L>,\n selectedPersonalizations?: SelectedPersonalizationArray,\n ): ResolvedData<S, M, L> {\n logger.debug(`Resolving personalized entry for baseline entry ${entry.sys.id}`)\n\n if (!selectedPersonalizations?.length) {\n logger.warn(\n `${RESOLUTION_WARNING_BASE} no selectedPersonalizations exist for the current profile`,\n )\n return { entry }\n }\n\n if (!isPersonalizedEntry(entry)) {\n logger.warn(`${RESOLUTION_WARNING_BASE} entry ${entry.sys.id} is not personalized`)\n return { entry }\n }\n\n const personalizationEntry = PersonalizedEntryResolver.getPersonalizationEntry(\n {\n personalizedEntry: entry,\n selectedPersonalizations,\n },\n true,\n )\n\n if (!personalizationEntry) {\n logger.warn(\n `${RESOLUTION_WARNING_BASE} could not find a personalization entry for ${entry.sys.id}`,\n )\n return { entry }\n }\n\n const selectedPersonalization = PersonalizedEntryResolver.getSelectedPersonalization(\n {\n personalizationEntry,\n selectedPersonalizations,\n },\n true,\n )\n\n const selectedVariantIndex = selectedPersonalization?.variantIndex ?? 0\n\n if (selectedVariantIndex === 0) {\n logger.debug(`Resolved personalization entry for entry ${entry.sys.id} is baseline`)\n\n return { entry }\n }\n\n const selectedVariant = PersonalizedEntryResolver.getSelectedVariant(\n {\n personalizedEntry: entry,\n personalizationEntry,\n selectedVariantIndex,\n },\n true,\n )\n\n if (!selectedVariant) {\n logger.warn(\n `${RESOLUTION_WARNING_BASE} could not find a valid replacement variant entry for ${entry.sys.id}`,\n )\n return { entry }\n }\n\n const selectedVariantEntry = PersonalizedEntryResolver.getSelectedVariantEntry<S, M, L>(\n {\n personalizationEntry,\n selectedVariant,\n },\n true,\n )\n\n if (!selectedVariantEntry) {\n logger.warn(\n `${RESOLUTION_WARNING_BASE} could not find a valid replacement variant entry for ${entry.sys.id}`,\n )\n return { entry }\n } else {\n logger.debug(\n `Entry ${entry.sys.id} has been resolved to variant entry ${selectedVariantEntry.sys.id}`,\n )\n }\n\n return { entry: selectedVariantEntry, personalization: selectedPersonalization }\n },\n}\n\nexport default PersonalizedEntryResolver\n","import type {\n InsightsEvent as AnalyticsEvent,\n ChangeArray,\n Flags,\n ExperienceEvent as PersonalizationEvent,\n Profile,\n SelectedPersonalizationArray,\n} from '@contentful/optimization-api-client'\nimport { batch, computed, effect, signal, type Signal } from '@preact/signals-core'\nimport { FlagsResolver } from './personalization/resolvers'\n\nexport const changes: Signal<ChangeArray | undefined> = signal<ChangeArray | undefined>()\n\nexport const consent = signal<boolean | undefined>()\n\nexport const event: Signal<AnalyticsEvent | PersonalizationEvent | undefined> = signal<\n AnalyticsEvent | PersonalizationEvent | undefined\n>()\n\nexport const flags = computed<Flags | undefined>(() => FlagsResolver.resolve(changes.value ?? []))\n\nexport const online = signal<boolean | undefined>(true)\n\nexport const personalizations = signal<SelectedPersonalizationArray | undefined>()\n\nexport const profile: Signal<Profile | undefined> = signal<Profile | undefined>()\n\nexport interface Signals {\n changes: typeof changes\n consent: typeof consent\n event: typeof event\n flags: typeof flags\n online: typeof online\n personalizations: typeof personalizations\n profile: typeof profile\n}\n\nexport interface Subscription {\n unsubscribe: () => void\n}\n\nexport interface Observable<T> {\n subscribe: (next: (v: T) => void) => Subscription\n}\n\nexport function toObservable<T>(s: { value: T }): Observable<T> {\n return {\n subscribe(next) {\n const dispose = effect(() => {\n next(s.value)\n })\n\n return { unsubscribe: dispose }\n },\n }\n}\n\nexport const signals: Signals = {\n changes,\n consent,\n event,\n flags,\n online,\n personalizations,\n profile,\n}\n\nexport { batch, effect, type Signal }\n","/**\n * A callback invoked when a method call is blocked by {@link guardedBy}.\n *\n * @param methodName - The name of the method that was attempted.\n * @param args - The readonly array of arguments supplied to the blocked call.\n * @returns Nothing.\n *\n * @public\n */\ntype BlockHandler = (methodName: string, args: readonly unknown[]) => void\n\n/**\n * The original method implementation.\n *\n * @typeParam A - The parameter tuple of the original method.\n * @typeParam R - The return type of the original method.\n * @param value - The method being decorated.\n * @param context - The Stage-3 decorator context for a class method.\n * @returns Nothing.\n *\n * @remarks\n * Users do not call this directly; it's returned by {@link guardedBy}.\n */\ntype GuardedByFunction<T extends object> = <A extends readonly unknown[], R>(\n value: (...args: A) => R,\n context: ClassMethodDecoratorContext<T, (...args: A) => R>,\n) => void\n\n/**\n * Options that tweak the behavior of {@link guardedBy}.\n *\n * @typeParam T - The instance type on which the decorator is applied.\n *\n * @public\n */\nexport interface GuardedByOptions<T extends object> {\n /**\n * Inverts the predicate result.\n *\n * When `true`, a truthy predicate result **blocks** the method.\n * When `false` (default) or omitted, a truthy predicate result **allows** the method.\n *\n * @defaultValue `false`\n * @remarks\n * This option is useful when the predicate expresses a *forbid* condition\n * (e.g. \"isLocked\" or \"isDestroyed\") rather than an *allow* condition.\n */\n readonly invert?: boolean\n\n /**\n * Either a function to call when a method is blocked, or the name/symbol of\n * an instance method on `this` to call when blocked.\n *\n * Both forms are **synchronous** and receive `(methodName, argsArray)`.\n * If omitted, blocked calls fail silently (i.e., return `undefined` or\n * `Promise<undefined>` for async methods).\n *\n * @remarks\n * - If a property key is supplied and the instance does not have a callable at that key,\n * the hook is ignored.\n * - The hook **must not** be `async`; any async work should be scheduled manually.\n */\n readonly onBlocked?: BlockHandler | (keyof T & (string | symbol))\n}\n\n/**\n * Type guard for functions.\n *\n * @internal\n */\nconst isFunction = (v: unknown): v is (...args: readonly unknown[]) => unknown =>\n typeof v === 'function'\n\n/**\n * Converts a property key to a readable string for logs and messages.\n *\n * @param name - The property key to stringify.\n * @returns A human-friendly name.\n *\n * @internal\n */\nconst nameToString = (name: PropertyKey): string =>\n typeof name === 'string'\n ? name\n : typeof name === 'symbol'\n ? (name.description ?? String(name))\n : String(name)\n\n/**\n * True when the `onBlocked` option is a property key (string or symbol).\n *\n * @typeParam T - The instance type.\n * @param v - The `onBlocked` option value.\n * @returns Whether `v` is a property key.\n *\n * @internal\n */\nconst isOnBlockedKey = <T extends object>(\n v: GuardedByOptions<T>['onBlocked'],\n): v is keyof T & (string | symbol) => typeof v === 'string' || typeof v === 'symbol'\n\n/**\n * Detects declared `async` functions.\n *\n * @param fn - The candidate to test.\n * @returns `true` if `fn` is an async function, else `false`.\n *\n * @internal\n */\nconst isAsyncFunction = (fn: (...args: readonly unknown[]) => unknown): boolean =>\n Object.prototype.toString.call(fn) === '[object AsyncFunction]'\n\n/**\n * Decorator factory that **guards** class methods behind a synchronous predicate.\n *\n * When a decorated method is invoked:\n * - If the predicate returns a value that evaluates to **allowed** (see `invert`), the original\n * method is executed and its result is returned.\n * - If the call is **blocked**, the optional `onBlocked` hook is invoked (if configured) and:\n * - `undefined` is returned for sync methods; or\n * - `Promise<undefined>` is returned for async methods (to preserve `await` compatibility).\n *\n * @typeParam T - The instance type that owns both the predicate and the decorated method.\n *\n * @param predicateName - The name (string or symbol) of a **synchronous** instance method on `this`\n * that acts as the predicate. It is called as `this[predicateName](methodName, argsArray)`.\n * @param opts - Optional {@link GuardedByOptions | options} to configure inversion and `onBlocked`.\n *\n * @returns A methods-only class decorator compatible with Stage-3 decorators that wraps the method.\n *\n * @throws TypeError\n * Thrown at initialization time (first instance construction) if `predicateName` does not resolve\n * to a **synchronous function** on the instance.\n *\n * @remarks\n * - This is a **methods-only** decorator; applying it to accessors/fields is a no-op.\n * - The decorator preserves the original method's sync/async shape.\n * - The predicate is invoked with `(decoratedMethodName, argsArray)` to support context-aware checks.\n *\n * @example\n * Here, `canRun` allows the call when it returns truthy:\n * ```ts\n * class Runner {\n * canRun(method: string, _args: readonly unknown[]) { return method !== 'stop'; }\n *\n * @guardedBy<Runner>('canRun')\n * go() { console.log('running'); }\n * }\n * ```\n *\n * @example\n * Invert the predicate and call a handler on block:\n * ```ts\n * class Door {\n * isLocked() { return true } // truthy means \"locked\"\n * onBlocked(method: string) { console.warn(`${method} blocked`) }\n *\n * @guardedBy<Door>('isLocked', { invert: true, onBlocked: 'onBlocked' })\n * open() { /* ... *\\/ }\n * }\n * ```\n *\n * @public\n */\nexport function guardedBy<T extends object>(\n predicateName: keyof T & (string | symbol),\n opts?: GuardedByOptions<T>,\n): GuardedByFunction<T> {\n return function <A extends readonly unknown[], R>(\n _value: (...args: A) => R,\n context: ClassMethodDecoratorContext<T, (...args: A) => R>,\n ): void {\n const decoratedName = nameToString(context.name)\n\n context.addInitializer(function init(this: T): void {\n // Original method on the instance\n const originalUnknown: unknown = Reflect.get(this, context.name)\n if (!isFunction(originalUnknown)) {\n return // defensive: nothing to wrap\n }\n const original = originalUnknown\n const originalIsAsync = isAsyncFunction(original)\n\n const resolvePredicate = (self: T): ((...args: readonly unknown[]) => unknown) => {\n const { [predicateName]: cand } = self\n if (!isFunction(cand)) {\n throw new TypeError(\n `@guardedBy expects predicate \"${String(predicateName)}\" to be a synchronous function.`,\n )\n }\n return cand\n }\n\n const computeAllowed = (self: T, args: readonly unknown[]): boolean => {\n const pred = resolvePredicate(self)\n const ok = Boolean(pred.call(self, decoratedName, args))\n return opts?.invert === true ? !ok : ok\n }\n\n const runOnBlocked = (self: T, args: readonly unknown[]): void => {\n const { onBlocked } = opts ?? {}\n if (onBlocked === undefined) {\n return\n }\n if (isFunction(onBlocked)) {\n onBlocked.call(self, decoratedName, args)\n return\n }\n if (isOnBlockedKey<T>(onBlocked)) {\n const { [onBlocked]: handlerCandidate } = self\n if (isFunction(handlerCandidate)) {\n handlerCandidate.call(self, decoratedName, args)\n }\n }\n }\n\n const blockedReturn = (): unknown =>\n originalIsAsync ? Promise.resolve(undefined) : undefined\n\n const wrapped = function (this: T, ...args: readonly unknown[]): unknown {\n if (!computeAllowed(this, args)) {\n runOnBlocked(this, args)\n return blockedReturn()\n }\n return original.call(this, ...args)\n }\n\n // Replace the instance method with our wrapper\n Reflect.set(this, context.name, wrapped)\n })\n }\n}\n","/**\n * A scope identifier for grouping values.\n *\n * @remarks\n * Use a non-empty string for a named scope. Use `undefined` for the\n * \"global/default\" scope. An empty string (`\"\"`) passed to the constructor\n * initializer is normalized to `undefined`.\n *\n * @public\n */\ntype ValuePresenceScope = string | undefined\n\n/**\n * Tracks whether a given value is present within one or more logical scopes.\n *\n * @remarks\n * - Scope names are case-sensitive.\n * - Presence is based on `Set.has` reference equality for objects and\n * value equality for primitives.\n *\n * @example\n * ```ts\n * const presence = new ValuePresence({ default: ['a', 'b'] })\n * presence.isPresent('default', 'a') // true\n * presence.addValue('default', 'c')\n * presence.removeValue('default', 'b')\n * presence.reset('default')\n * ```\n *\n * @see {@link ValuePresenceScope}\n * @public\n */\nclass ValuePresence {\n /**\n * Internal map of scope -> set of values present in that scope.\n *\n * @internal\n */\n readonly #map: Map<ValuePresenceScope, Set<unknown>>\n\n /**\n * Create a new {@link ValuePresence}.\n *\n * @param defaultMap - Optional initial data. Keys are scope names; values are arrays of items to seed.\n * Empty-string keys are normalized to the default scope (`undefined`).\n *\n * @remarks\n * - If `defaultMap` contains duplicate items for a scope, duplicates are collapsed by the `Set`.\n */\n constructor(defaultMap?: Record<string, unknown[]>) {\n const map = new Map<ValuePresenceScope, Set<unknown>>()\n\n if (defaultMap)\n Object.entries(defaultMap).map(([scope, values]) =>\n map.set(scope.length ? scope : undefined, new Set(values)),\n )\n\n this.#map = map\n }\n\n /**\n * Check whether a value is present within a given scope.\n *\n * @param scope - The scope to check. Use `undefined` for the default scope.\n * @param value - The value to test for presence.\n * @returns `true` if the value is present in the specified scope; otherwise `false`.\n *\n * @remarks\n * Presence testing uses `Set.prototype.has` semantics.\n *\n * @example\n * ```ts\n * presence.isPresent(undefined, 42) // e.g., true or false\n * ```\n *\n * @public\n */\n isPresent(scope: ValuePresenceScope, value: unknown): boolean {\n return this.#map.get(scope)?.has(value) ?? false\n }\n\n /**\n * Add a value to a scope, creating the scope if it does not exist.\n *\n * @param scope - Scope to add the value to. Use `undefined` for the default scope.\n * @param value - The value to add.\n * @returns void\n *\n * @remarks\n * - No-op if the value is already present (due to `Set` semantics).\n *\n * @example\n * ```ts\n * presence.addValue('users', userId)\n * ```\n *\n * @public\n */\n addValue(scope: ValuePresenceScope, value: unknown): void {\n const values = this.#map.get(scope)\n\n if (!values) {\n this.#map.set(scope, new Set([value]))\n } else {\n values.add(value)\n }\n }\n\n /**\n * Remove a value from a scope.\n *\n * @param scope - Scope to remove from. Use `undefined` for the default scope.\n * @param value - The value to remove.\n * @returns void\n *\n * @remarks\n * If the scope does not exist or the value is not present, this is a no-op.\n *\n * @example\n * ```ts\n * presence.removeValue('users', userId)\n * ```\n *\n * @public\n */\n removeValue(scope: ValuePresenceScope, value: unknown): void {\n this.#map.get(scope)?.delete(value)\n }\n\n /**\n * Clear values from a single scope, or from all scopes.\n *\n * @param scope - If provided, clears only that scope. If omitted, clears all scopes.\n * @returns void\n *\n * @remarks\n * - When called with a specific scope that does not exist, this is a no-op.\n * - When called with no arguments, all scopes and values are removed.\n * - Clearing a non-existent scope will not create the scope.\n *\n * @example\n * ```ts\n * // Clear one scope\n * presence.reset('users')\n *\n * // Clear all scopes\n * presence.reset()\n * ```\n *\n * @public\n */\n reset(scope?: ValuePresenceScope): void {\n if (scope !== undefined) {\n this.#map.get(scope)?.clear()\n } else {\n this.#map.clear()\n }\n }\n}\n\nexport default ValuePresence\n","import type {\n InsightsEventType as AnalyticsEventType,\n ApiClient,\n EventBuilder,\n ExperienceEventType as PersonalizationEventType,\n} from '@contentful/optimization-api-client'\nimport type { LifecycleInterceptors } from './CoreBase'\nimport ValuePresence from './lib/value-presence/ValuePresence'\n\n/**\n * Union of all event {@link AnalyticsEventType | type keys} that this package may emit.\n *\n * @public\n */\nexport type EventType = AnalyticsEventType | PersonalizationEventType\n\n/**\n * Default allow‑list of event types that can be emitted without explicit consent.\n *\n * @internal\n * @privateRemarks These defaults are only applied when a consumer does not provide\n * {@link ProductConfig.allowedEventTypes}.\n */\nconst defaultAllowedEvents: EventType[] = ['page', 'identify']\n\n/**\n * Common configuration for all product implementations.\n *\n * @public\n */\nexport interface ProductConfig {\n /**\n * The set of event type strings that are allowed to be sent even if consent is\n * not granted.\n *\n * @defaultValue `['page', 'identify']`\n * @remarks These types are compared against the `type` property of events.\n */\n allowedEventTypes?: EventType[]\n\n /**\n * A map of duplication keys to a list of component IDs that should be\n * considered duplicates and therefore suppressed.\n *\n * @remarks\n * The actual duplication check is performed by {@link ValuePresence}. The\n * keys of this record are used as duplication scopes. An empty string `''`\n * is converted to an `indefined` scope when specific scopes are not required.\n */\n preventedComponentEvents?: Record<string, string[]>\n}\n\n/**\n * Options for configuring the common functionality of {@link ProductBase} descendents.\n *\n * @public\n */\nexport interface ProductBaseOptions {\n /** Optimization API client. */\n api: ApiClient\n /** Event builder for constructing events. */\n builder: EventBuilder\n /** Optional configuration for allow‑lists and duplication prevention. */\n config?: ProductConfig\n /** Lifecycle container for event and state interceptors. */\n interceptors: LifecycleInterceptors\n}\n\n/**\n * Shared base for all product implementations.\n *\n * @internal\n * @remarks\n * This abstract class is not exported as part of the public API surface.\n * Concrete implementations (e.g., analytics) should extend this class and\n * expose their own public methods.\n */\nabstract class ProductBase {\n /**\n * Allow‑list of event {@link AnalyticsEventType | type keys} permitted when consent is not present.\n */\n protected readonly allowedEventTypes?: string[]\n\n /** Event builder used to construct strongly‑typed events. */\n protected readonly builder: EventBuilder\n\n /** Optimization API client used to send events to the Experience and Insights APIs. */\n protected readonly api: ApiClient\n\n /**\n * Deduplication helper used to track previously seen values within optional\n * scopes\n */\n readonly duplicationDetector: ValuePresence\n\n /** Interceptors that can mutate/augment outgoing events or optimization state. */\n readonly interceptors: LifecycleInterceptors\n\n /**\n * Creates a new product base instance.\n *\n * @param options - Options for configuring the functionality common among products.\n */\n constructor(options: ProductBaseOptions) {\n const { api, builder, config, interceptors } = options\n this.allowedEventTypes = config?.allowedEventTypes ?? defaultAllowedEvents\n this.api = api\n this.builder = builder\n this.duplicationDetector = new ValuePresence(config?.preventedComponentEvents)\n this.interceptors = interceptors\n }\n}\n\nexport default ProductBase\n","import type { ComponentViewBuilderArgs } from '@contentful/optimization-api-client'\nimport ProductBase from '../ProductBase'\n\n/**\n * Base class for analytics implementations (internal).\n *\n * @internal\n * @remarks\n * Concrete analytics classes should implement the component/flag view tracking\n * methods below. This base is not part of the public API.\n */\nabstract class AnalyticsBase extends ProductBase {\n /**\n * Track a UI component view event.\n *\n * @param payload - Component view builder arguments.\n * @param duplicationScope - Optional string used to scope duplication used in Stateful\n * implementations.\n * @privateRemarks\n * Duplication prevention should be handled in Stateful implementations\n */\n abstract trackComponentView(\n payload: ComponentViewBuilderArgs,\n duplicationScope?: string,\n ): Promise<void> | void\n\n /**\n * Track a flag (feature) view event.\n *\n * @param payload - Flag view builder arguments.\n * @param duplicationScope - Optional string used to scope duplication used in Stateful\n * implementations.\n * @returns A promise that resolves when processing is complete (or `void`).\n * @privateRemarks\n * Duplication prevention should be handled in Stateful implementations\n */\n abstract trackFlagView(\n payload: ComponentViewBuilderArgs,\n duplicationScope?: string,\n ): Promise<void> | void\n}\n\nexport default AnalyticsBase\n","import {\n InsightsEvent as AnalyticsEvent,\n type BatchInsightsEventArray,\n type ComponentViewBuilderArgs,\n type InsightsEventArray,\n type ExperienceEvent as PersonalizationEvent,\n type Profile,\n} from '@contentful/optimization-api-client'\nimport { createScopedLogger } from 'logger'\nimport type { ConsentGuard } from '../Consent'\nimport { guardedBy } from '../lib/decorators'\nimport type { ProductBaseOptions, ProductConfig } from '../ProductBase'\nimport {\n batch,\n consent,\n effect,\n event as eventSignal,\n online as onlineSignal,\n profile as profileSignal,\n toObservable,\n type Observable,\n} from '../signals'\nimport AnalyticsBase from './AnalyticsBase'\n\nconst logger = createScopedLogger('Analytics')\n\n/**\n * Default analytics state values applied at construction time.\n *\n * @public\n */\nexport interface AnalyticsProductConfigDefaults {\n /** Whether analytics collection is allowed by default. */\n consent?: boolean\n /** Default profile to associate with events. */\n profile?: Profile\n}\n\n/**\n * Configuration for the stateful analytics implementation.\n *\n * @public\n */\nexport interface AnalyticsProductConfig extends ProductConfig {\n /**\n * Default signal values applied on initialization.\n */\n defaults?: AnalyticsProductConfigDefaults\n}\n\n/**\n * Observables exposed by the stateful analytics product.\n *\n * @public\n */\nexport interface AnalyticsStates {\n /** Observable stream of the latest {@link AnalyticsEvent} or {@link PersonalizationEvent} (or `undefined`). */\n eventStream: Observable<AnalyticsEvent | PersonalizationEvent | undefined>\n /** Observable stream of the active {@link Profile} (or `undefined`). */\n profile: Observable<Profile | undefined>\n}\n\n/**\n * Options for configuring {@link AnalyticsStateful} functionality.\n *\n * @public\n * @see {@link ProductBaseOptions}\n */\nexport type AnalyticsStatefulOptions = ProductBaseOptions & {\n /** Configuration specific to the Analytics product */\n config?: AnalyticsProductConfig\n}\n\n/**\n * Maximum number of queued events before an automatic flush is triggered.\n */\nconst MAX_QUEUED_EVENTS = 25\n\n/**\n * Analytics implementation that maintains local state (consent, profile) and\n * queues events until flushed or the queue reaches a maximum size.\n *\n * @public\n */\nclass AnalyticsStateful extends AnalyticsBase implements ConsentGuard {\n /** In‑memory queue keyed by profile. */\n private readonly queue = new Map<Profile, InsightsEventArray>()\n\n /** Exposed observable state references. */\n readonly states: AnalyticsStates = {\n eventStream: toObservable(eventSignal),\n profile: toObservable(profileSignal),\n }\n\n /**\n * Create a new stateful analytics instance.\n *\n * @param options - Options to configure the analytics product for stateful environments.\n */\n constructor(options: AnalyticsStatefulOptions) {\n const { api, builder, config, interceptors } = options\n\n super({ api, builder, config, interceptors })\n\n const { defaults } = config ?? {}\n\n if (defaults?.profile !== undefined) {\n const { profile: defaultProfile } = defaults\n profileSignal.value = defaultProfile\n }\n\n effect(() => {\n const id = profileSignal.value?.id\n\n logger.info(\n `Analytics ${consent.value ? 'will' : 'will not'} be collected due to consent (${consent.value})`,\n )\n\n logger.debug(`Profile ${id && `with ID ${id}`} has been ${id ? 'set' : 'cleared'}`)\n })\n\n effect(() => {\n if (onlineSignal.value) void this.flush()\n })\n }\n\n /**\n * Reset analytics‑related signals and the last emitted event.\n */\n reset(): void {\n batch(() => {\n eventSignal.value = undefined\n profileSignal.value = undefined\n })\n }\n\n /**\n * Determine whether the named operation is permitted based on consent and\n * allowed event type configuration.\n *\n * @param name - The method name; `'trackComponentView'` is normalized\n * to `'component'` for allow‑list checks.\n * @returns `true` if the operation is permitted; otherwise `false`.\n */\n hasConsent(name: string): boolean {\n return (\n !!consent.value ||\n (this.allowedEventTypes ?? []).includes(\n name === 'trackComponentView' || name === 'trackFlagView' ? 'component' : name,\n )\n )\n }\n\n /**\n * Hook invoked when an operation is blocked due to missing consent.\n *\n * @param name - The blocked operation name.\n * @param payload - The original arguments supplied to the operation.\n */\n onBlockedByConsent(name: string, payload: unknown[]): void {\n logger.warn(\n `Event \"${name}\" was blocked due to lack of consent; payload: ${JSON.stringify(payload)}`,\n )\n }\n\n /**\n * Guard used to suppress duplicate component/flag view events based on a\n * duplication key and the component identifier.\n *\n * @param _name - The operation name (unused).\n * @param payload - Tuple of [builderArgs, duplicationScope].\n * @returns `true` if the event is NOT a duplicate and should proceed.\n */\n isNotDuplicated(_name: string, payload: [ComponentViewBuilderArgs, string]): boolean {\n const [{ componentId: value }, duplicationScope] = payload\n\n const isDuplicated = this.duplicationDetector.isPresent(duplicationScope, value)\n\n if (!isDuplicated) this.duplicationDetector.addValue(duplicationScope, value)\n\n return !isDuplicated\n }\n\n /**\n * Hook invoked when an operation is blocked by the duplication guard.\n *\n * @param name - The blocked operation name.\n * @param payload - The original arguments supplied to the operation.\n */\n onBlockedByDuplication(name: string, payload: unknown[]): void {\n const componentType = name === 'trackFlagView' ? 'flag' : 'component'\n\n logger.debug(\n `Duplicate \"${componentType} view\" event detected, skipping; payload: ${JSON.stringify(payload)}`,\n )\n }\n\n /**\n * Queue a component view event for the active profile.\n *\n * @param payload - Component view builder arguments.\n * @param _duplicationScope - Optional string used to scope duplication (used\n * by guards); an empty string `''` is converted to the `undefined` scope\n */\n @guardedBy('isNotDuplicated', { onBlocked: 'onBlockedByDuplication' })\n @guardedBy('hasConsent', { onBlocked: 'onBlockedByConsent' })\n async trackComponentView(\n payload: ComponentViewBuilderArgs,\n _duplicationScope = '',\n ): Promise<void> {\n logger.info(`Processing \"component view\" event for ${payload.componentId}`)\n\n await this.enqueueEvent(this.builder.buildComponentView(payload))\n }\n\n /**\n * Queue a flag view event for the active profile.\n *\n * @param payload - Flag view builder arguments.\n * @param _duplicationScope - Optional string used to scope duplication (used\n * by guards); an empty string `''` is converted to the `undefined` scope\n */\n @guardedBy('isNotDuplicated', { onBlocked: 'onBlockedByDuplication' })\n @guardedBy('hasConsent', { onBlocked: 'onBlockedByConsent' })\n async trackFlagView(payload: ComponentViewBuilderArgs, _duplicationScope = ''): Promise<void> {\n logger.debug(`Processing \"flag view\" event for ${payload.componentId}`)\n\n await this.enqueueEvent(this.builder.buildFlagView(payload))\n }\n\n /**\n * Intercept, validate, and place an event into the profile‑scoped queue; then\n * trigger a size‑based flush if necessary.\n *\n * @param event - The event to enqueue.\n */\n private async enqueueEvent(event: AnalyticsEvent): Promise<void> {\n const { value: profile } = profileSignal\n\n if (!profile) {\n logger.warn('Attempting to emit an event without an Optimization profile')\n\n return\n }\n\n const intercepted = await this.interceptors.event.run(event)\n\n const validEvent = AnalyticsEvent.parse(intercepted)\n\n logger.debug(`Queueing ${validEvent.type} event for profile ${profile.id}`, validEvent)\n\n const profileEventQueue = this.queue.get(profile)\n\n eventSignal.value = validEvent\n\n if (profileEventQueue) {\n profileEventQueue.push(validEvent)\n } else {\n this.queue.set(profile, [validEvent])\n }\n\n await this.flushMaxEvents()\n }\n\n /**\n * Flush the queue automatically when the total number of queued events\n * reaches {@link MAX_QUEUED_EVENTS}.\n */\n private async flushMaxEvents(): Promise<void> {\n if (this.queue.values().toArray().flat().length >= MAX_QUEUED_EVENTS) await this.flush()\n }\n\n /**\n * Send all queued events grouped by profile and clear the queue.\n * @remarks Only under rare circumstances should there be more than one\n * profile in a stateful application.\n */\n async flush(): Promise<void> {\n logger.debug('Flushing event queue')\n\n const batches: BatchInsightsEventArray = []\n\n this.queue.forEach((events, profile) => batches.push({ profile, events }))\n\n if (!batches.length) return\n\n const sendSuccess = await this.api.insights.sendBatchEvents(batches)\n\n if (sendSuccess) this.queue.clear()\n }\n}\n\nexport default AnalyticsStateful\n","import {\n BatchInsightsEventArray,\n type ComponentViewBuilderArgs,\n ComponentViewEvent,\n type InsightsEvent,\n type PartialProfile,\n} from '@contentful/optimization-api-client'\nimport { createScopedLogger } from 'logger'\nimport AnalyticsBase from './AnalyticsBase'\n\nconst logger = createScopedLogger('Analytics')\n\n/**\n * Arguments for tracking a component/flag view in stateless mode.\n *\n * @public\n * @remarks\n * The `profile` is optional; when omitted, the APIs may infer identity via\n * other means.\n */\nexport type TrackViewArgs = ComponentViewBuilderArgs & { profile?: PartialProfile }\n\n/**\n * Stateless analytics implementation that sends each event immediately in a\n * single‑event batch.\n *\n * @public\n */\nclass AnalyticsStateless extends AnalyticsBase {\n /**\n * Build, intercept, validate, and send a component view event.\n *\n * @param args - {@link TrackViewArgs} used to build the event. Includes an\n * optional partial profile.\n * @returns A promise that resolves once the batch has been sent.\n */\n async trackComponentView(args: TrackViewArgs): Promise<void> {\n logger.info('Processing \"component view\" event')\n\n const { profile, ...builderArgs } = args\n\n const event = this.builder.buildComponentView(builderArgs)\n\n const intercepted = await this.interceptors.event.run(event)\n\n const parsed = ComponentViewEvent.parse(intercepted)\n\n await this.sendBatchEvent(parsed, profile)\n }\n\n /**\n * Build, intercept, validate, and send a flag view event.\n *\n * @param args - {@link TrackViewArgs} used to build the event. Includes an\n * optional partial profile.\n * @returns A promise that resolves once the batch has been sent.\n */\n async trackFlagView(args: TrackViewArgs): Promise<void> {\n logger.debug('Processing \"flag view\" event')\n\n const { profile, ...builderArgs } = args\n\n const event = this.builder.buildFlagView(builderArgs)\n\n const intercepted = await this.interceptors.event.run(event)\n\n const parsed = ComponentViewEvent.parse(intercepted)\n\n await this.sendBatchEvent(parsed, profile)\n }\n\n /**\n * Send a single {@link InsightsEvent} wrapped in a one‑item batch.\n *\n * @param event - The event to send.\n * @param profile - Optional partial profile to attach to the batch.\n * @returns A promise that resolves when the API call completes.\n * @internal\n */\n private async sendBatchEvent(event: InsightsEvent, profile?: PartialProfile): Promise<void> {\n const batchEvent: BatchInsightsEventArray = BatchInsightsEventArray.parse([\n {\n profile,\n events: [event],\n },\n ])\n\n await this.api.insights.sendBatchEvents(batchEvent)\n }\n}\n\nexport default AnalyticsStateless\n","// eslint-disable-next-line @typescript-eslint/naming-convention -- Replaced at build-time\ndeclare const __OPTIMIZATION_VERSION__: string | undefined\n\nexport const OPTIMIZATION_CORE_SDK_VERSION =\n typeof __OPTIMIZATION_VERSION__ === 'string' ? __OPTIMIZATION_VERSION__ : '0.0.0'\n\n/**\n * Anonymous-ID cookie name used by the Optimization Core.\n *\n * @public\n * @remarks\n * This constant represents the cookie key used by the Optimization Framework\n * to persist an anonymous identifier for tracking personalization and analytics\n * events when no explicit profile is known.\n *\n * @example\n * ```ts\n * import { ANONYMOUS_ID_COOKIE } from '@contentful/optimization-core'\n * const profileId = request.cookies[ANONYMOUS_ID_COOKIE]\n * ```\n */\nexport const ANONYMOUS_ID_COOKIE = 'ctfl-opt-aid'\n","/**\n * A utility type representing a value that may be synchronously available or\n * produced asynchronously.\n *\n * @typeParam T - The resolved value type.\n * @public\n */\ntype MaybePromise<T> = T | Promise<T>\n\n/**\n * A function that receives a value of type `T` and returns a (possibly async)\n * value of the same type `T`. The input is marked as `readonly` to discourage\n * mutation of the original object.\n *\n * @typeParam T - The value type intercepted and returned.\n * @param value - The current (readonly) value in the interception chain.\n * @returns The next value for the chain, either directly or via a promise.\n * @remarks Implementations SHOULD avoid mutating `value` and instead return a\n * new or safely-updated instance.\n * @see {@link InterceptorManager}\n * @public\n */\nexport type Interceptor<T> = (value: Readonly<T>) => MaybePromise<T>\n\n/**\n * Manages a list of interceptors and provides a way to run them in sequence.\n *\n * Interceptors are executed in insertion order. Each interceptor receives the\n * result of the previous interceptor (or the initial input for the first one)\n * and may return a new value synchronously or asynchronously.\n *\n * @typeParam T - The value type processed by the interceptors.\n * @remarks This class snapshots the current interceptor list at invocation time\n * so additions/removals during `run` do not affect the in-flight execution.\n * @example\n * ```ts\n * const mgr = new InterceptorManager<number>();\n * const id = mgr.add((n) => n + 1);\n * const final = await mgr.run(1); // 2\n * mgr.remove(id);\n * ```\n * @public\n */\nexport class InterceptorManager<T> {\n /**\n * The registry of interceptors keyed by their insertion id.\n *\n * @privateRemarks Internal storage; use {@link add}, {@link remove}, and\n * {@link clear} to manage contents.\n * @readonly\n * @defaultValue `new Map()`\n */\n private readonly interceptors = new Map<number, Interceptor<T>>()\n\n /**\n * The next numeric id to assign to an added interceptor.\n *\n * @privateRemarks Used only to generate unique, monotonically increasing ids.\n * @defaultValue `0`\n */\n private nextId = 0\n\n /**\n * Add an interceptor and return its identifier.\n *\n * @param interceptor - The interceptor function to register.\n * @returns The numeric id that can later be used with {@link remove}.\n * @remarks Interceptors are executed in the order they are added.\n * @example\n * ```ts\n * const id = manager.add(async (value) => transform(value));\n * ```\n * @public\n */\n add(interceptor: Interceptor<T>): number {\n const { nextId: id } = this\n this.nextId += 1\n this.interceptors.set(id, interceptor)\n return id\n }\n\n /**\n * Remove an interceptor by its identifier.\n *\n * @param id - The id previously returned by {@link add}.\n * @returns `true` if an interceptor was removed; otherwise `false`.\n * @example\n * ```ts\n * const removed = manager.remove(id);\n * ```\n * @public\n */\n remove(id: number): boolean {\n return this.interceptors.delete(id)\n }\n\n /**\n * Remove all registered interceptors.\n *\n * @returns Nothing.\n * @remarks After calling this, {@link count} will return `0`.\n * @example\n * ```ts\n * manager.clear();\n * ```\n * @public\n */\n clear(): void {\n this.interceptors.clear()\n }\n\n /**\n * Get the number of currently registered interceptors.\n *\n * @returns The count of interceptors.\n * @example\n * ```ts\n * if (manager.count() === 0) { /* ... *\\/ }\n * ```\n * @public\n */\n count(): number {\n return this.interceptors.size\n }\n\n /**\n * Run all interceptors in sequence on an input value and return the final result.\n *\n * Supports both sync and async interceptors; the return type is always `Promise<T>`\n * for consistency.\n *\n * @param input - The initial value to pass to the first interceptor.\n * @returns A promise resolving to the final value after all interceptors have run.\n * @throws May rethrow any error thrown by an interceptor. <!-- Intentionally vague: error type depends on interceptor implementation -->\n * @remarks The interceptor list is snapshotted at invocation time; changes to\n * the registry during execution do not affect the running sequence.\n * @example\n * ```ts\n * const result = await manager.run(initial);\n * ```\n * @public\n */\n async run(input: T): Promise<T> {\n // Snapshot to avoid issues if interceptors are added/removed during execution.\n const fns: ReadonlyArray<Interceptor<T>> = Array.from(this.interceptors.values())\n\n let acc: T = input\n\n for (const fn of fns) {\n // Pass a readonly view to discourage mutation of intermediate values.\n // Each interceptor must return a T (or Promise<T>).\n acc = await fn(acc as Readonly<T>)\n }\n\n return acc\n }\n}\n","import {\n ApiClient,\n EventBuilder,\n type InsightsEvent as AnalyticsEvent,\n type ApiClientConfig,\n type ChangeArray,\n type ComponentViewBuilderArgs,\n type EventBuilderConfig,\n type ExperienceApiClientConfig,\n type GlobalApiConfigProperties,\n type IdentifyBuilderArgs,\n type InsightsApiClientConfig,\n type Json,\n type MergeTagEntry,\n type OptimizationData,\n type PageViewBuilderArgs,\n type PartialProfile,\n type ExperienceEvent as PersonalizationEvent,\n type Profile,\n type ScreenViewBuilderArgs,\n type SelectedPersonalizationArray,\n type TrackBuilderArgs,\n} from '@contentful/optimization-api-client'\nimport type { ChainModifiers, Entry, EntrySkeletonType, LocaleCode } from 'contentful'\nimport type { LogLevels } from 'logger'\nimport { ConsoleLogSink, logger } from 'logger'\nimport type AnalyticsBase from './analytics/AnalyticsBase'\nimport { OPTIMIZATION_CORE_SDK_VERSION } from './global-constants'\nimport { InterceptorManager } from './lib/interceptor'\nimport type { ResolvedData } from './personalization'\nimport type PersonalizationBase from './personalization/PersonalizationBase'\n\n/**\n * Lifecycle container for event and state interceptors.\n *\n * @public\n */\nexport interface LifecycleInterceptors {\n /** Interceptors invoked for individual events prior to validation/sending. */\n event: InterceptorManager<AnalyticsEvent | PersonalizationEvent>\n /** Interceptors invoked before optimization state updates. */\n state: InterceptorManager<OptimizationData>\n}\n\n/**\n * Options for configuring the {@link CoreBase} runtime and underlying clients.\n *\n * @public\n */\nexport interface CoreConfig extends Pick<ApiClientConfig, GlobalApiConfigProperties> {\n /**\n * Configuration for the personalization (Experience) API client.\n */\n personalization?: Omit<ExperienceApiClientConfig, GlobalApiConfigProperties>\n\n /**\n * Configuration for the analytics (Insights) API client.\n */\n analytics?: Omit<InsightsApiClientConfig, GlobalApiConfigProperties>\n\n /**\n * Event builder configuration (channel/library metadata, etc.).\n */\n eventBuilder?: EventBuilderConfig\n\n /** Minimum log level for the default console sink. */\n logLevel?: LogLevels\n}\n\n/**\n * Internal base that wires the API client, event builder, and logging.\n *\n * @internal\n */\nabstract class CoreBase {\n /** Product implementation for analytics. */\n abstract readonly analytics: AnalyticsBase\n /** Product implementation for personalization. */\n abstract readonly personalization: PersonalizationBase\n\n /** Shared Optimization API client instance. */\n readonly api: ApiClient\n /** Shared event builder instance. */\n readonly eventBuilder: EventBuilder\n /** Resolved core configuration (minus any name metadata). */\n readonly config: Omit<CoreConfig, 'name'>\n\n readonly interceptors: LifecycleInterceptors = {\n event: new InterceptorManager<AnalyticsEvent | PersonalizationEvent>(),\n state: new InterceptorManager<OptimizationData>(),\n }\n\n /**\n * Create the core with API client and logging preconfigured.\n *\n * @param config - Core configuration including API and builder options.\n * @example\n * ```ts\n * const sdk = new CoreStateless({ clientId: 'abc123', environment: 'prod' })\n * ```\n */\n constructor(config: CoreConfig) {\n this.config = config\n\n const { analytics, personalization, eventBuilder, logLevel, environment, clientId } = config\n\n logger.addSink(new ConsoleLogSink(logLevel))\n\n const apiConfig = {\n ...analytics,\n ...personalization,\n clientId,\n environment,\n }\n\n this.api = new ApiClient(apiConfig)\n\n this.eventBuilder = new EventBuilder(\n eventBuilder ?? {\n channel: 'server',\n library: { name: 'Optimization Core', version: OPTIMIZATION_CORE_SDK_VERSION },\n },\n )\n }\n\n /**\n * Get the value of a custom flag derived from a set of optimization changes.\n *\n * @param name - The flag key to resolve.\n * @param changes - Optional change list to resolve from\n * @returns The resolved JSON value for the flag if available.\n * @remarks\n * This is a convenience wrapper around personalization’s flag resolution.\n */\n getCustomFlag(name: string, changes?: ChangeArray): Json {\n return this.personalization.getCustomFlag(name, changes)\n }\n\n /**\n * Resolve a Contentful entry to the appropriate personalized variant (or\n * return the baseline entry if no matching variant is selected).\n *\n * @typeParam S - Entry skeleton type.\n * @typeParam M - Chain modifiers.\n * @typeParam L - Locale code.\n * @param entry - The baseline entry to resolve.\n * @param personalizations - Optional selection array for the current profile.\n * @returns {@link ResolvedData} containing the resolved entry and\n * personalization metadata (if any).\n */\n personalizeEntry<\n S extends EntrySkeletonType,\n M extends ChainModifiers = ChainModifiers,\n L extends LocaleCode = LocaleCode,\n >(entry: Entry<S, M, L>, personalizations?: SelectedPersonalizationArray): ResolvedData<S, M, L> {\n return this.personalization.personalizeEntry<S, M, L>(entry, personalizations)\n }\n\n /**\n * Resolve a merge-tag value from the given entry node and profile.\n *\n * @param embeddedEntryNodeTarget - The merge-tag entry node to resolve.\n * @param profile - Optional profile used for value lookup.\n * @returns The resolved value (typically a string) or `undefined` if not found.\n */\n getMergeTagValue(embeddedEntryNodeTarget: MergeTagEntry, profile?: Profile): unknown {\n return this.personalization.getMergeTagValue(embeddedEntryNodeTarget, profile)\n }\n\n /**\n * Convenience wrapper for sending an `identify` event via personalization.\n *\n * @param payload - Identify builder arguments.\n * @returns The resulting {@link OptimizationData} for the identified user.\n */\n async identify(\n payload: IdentifyBuilderArgs & { profile?: PartialProfile },\n ): Promise<OptimizationData | undefined> {\n return await this.personalization.identify(payload)\n }\n\n /**\n * Convenience wrapper for sending a `page` event via personalization.\n *\n * @param payload - Page view builder arguments.\n * @returns The evaluated {@link OptimizationData} for this page view.\n */\n async page(\n payload: PageViewBuilderArgs & { profile?: PartialProfile },\n ): Promise<OptimizationData | undefined> {\n return await this.personalization.page(payload)\n }\n\n /**\n * Convenience wrapper for sending a `screen` event via personalization.\n *\n * @param payload - Screen view builder arguments.\n * @returns The evaluated {@link OptimizationData} for this screen view.\n */\n async screen(\n payload: ScreenViewBuilderArgs & { profile?: PartialProfile },\n ): Promise<OptimizationData | undefined> {\n return await this.personalization.screen(payload)\n }\n\n /**\n * Convenience wrapper for sending a custom `track` event via personalization.\n *\n * @param payload - Track builder arguments.\n * @returns The evaluated {@link OptimizationData} for this event.\n */\n async track(\n payload: TrackBuilderArgs & { profile?: PartialProfile },\n ): Promise<OptimizationData | undefined> {\n return await this.personalization.track(payload)\n }\n\n /**\n * Track a component view in both personalization and analytics.\n *\n * @param payload - Component view builder arguments. When `payload.sticky` is\n * `true`, the event will also be sent via personalization as a sticky\n * component view.\n * @param duplicationScope - Optional string used to scope duplication used in Stateful\n * implementations\n * @returns A promise that resolves when all delegated calls complete.\n * @remarks\n * The sticky behavior is delegated to personalization; analytics is always\n * invoked regardless of `sticky`.\n */\n async trackComponentView(\n payload: ComponentViewBuilderArgs & { profile?: PartialProfile },\n duplicationScope?: string,\n ): Promise<OptimizationData | undefined> {\n if (payload.sticky) {\n return await this.personalization.trackComponentView(payload, duplicationScope)\n }\n\n await this.analytics.trackComponentView(payload, duplicationScope)\n }\n\n /**\n * Track a feature flag view via analytics.\n *\n * @param payload - Component view builder arguments used to build the flag view event.\n * @param duplicationScope - Optional string used to scope duplication used in Stateful\n * implementations\n * @returns A promise that resolves when processing completes.\n */\n async trackFlagView(payload: ComponentViewBuilderArgs, duplicationScope?: string): Promise<void> {\n await this.analytics.trackFlagView(payload, duplicationScope)\n }\n}\n\nexport default CoreBase\n","import type {\n ChangeArray,\n ComponentViewBuilderArgs,\n IdentifyBuilderArgs,\n Json,\n MergeTagEntry,\n OptimizationData,\n PageViewBuilderArgs,\n Profile,\n ScreenViewBuilderArgs,\n SelectedPersonalizationArray,\n TrackBuilderArgs,\n} from '@contentful/optimization-api-client'\nimport type { ChainModifiers, Entry, EntrySkeletonType, LocaleCode } from 'contentful'\nimport ProductBase from '../ProductBase'\nimport {\n FlagsResolver,\n MergeTagValueResolver,\n PersonalizedEntryResolver,\n type ResolvedData,\n} from './resolvers'\n\n/**\n * These methods assist in resolving values via Resolvers\n *\n * @internal\n * @privateRemarks\n * This interface exists to document that the included methods should not be\n * considered static.\n */\ninterface ResolverMethods {\n /**\n * Get the specified Custom Flag's value from the supplied changes.\n * @param name - The name or key of the Custom Flag.\n * @param changes - Optional changes array.\n * @returns The current value of the Custom Flag if found.\n * @remarks\n * The changes array can be sourced from the data returned when emitting any\n * personalization event.\n * */\n getCustomFlag: (name: string, changes?: ChangeArray) => Json\n\n /**\n * Resolve a Contentful entry to a personalized variant using the current\n * or provided selected personalizations.\n *\n * @typeParam S - Entry skeleton type.\n * @typeParam M - Chain modifiers.\n * @typeParam L - Locale code.\n * @param entry - The entry to personalize.\n * @param personalizations - Optional selections.\n * @returns The resolved entry data.\n * @remarks\n * Selected personalizations can be sourced from the data returned when emitting any\n * personalization event.\n */\n personalizeEntry: <S extends EntrySkeletonType, M extends ChainModifiers, L extends LocaleCode>(\n entry: Entry<S, M, L>,\n personalizations?: SelectedPersonalizationArray,\n ) => ResolvedData<S, M, L>\n\n /**\n * Resolve a merge tag to a value based on the current (or provided) profile.\n *\n * @param embeddedEntryNodeTarget - The merge‑tag entry node to resolve.\n * @param profile - Optional profile.\n * @returns The resolved value (type depends on the tag).\n * @remarks\n * Merge tags are references to profile data that can be substituted into content. The\n * profile can be sourced from the data returned when emitting any personalization event.\n */\n getMergeTagValue: (embeddedEntryNodeTarget: MergeTagEntry, profile?: Profile) => unknown\n}\n\n/**\n * Internal base for personalization products.\n *\n * @internal\n * @remarks\n * Concrete implementations should extend this class to expose public methods for\n * identify, page, and track events. This base wires in shared singleton\n * resolvers used to fetch/resolve personalized data.\n */\nabstract class PersonalizationBase extends ProductBase implements ResolverMethods {\n /**\n * Static {@link FlagsResolver | resolver} for evaluating personalized\n * custom flags.\n */\n readonly flagsResolver = FlagsResolver\n\n /**\n * Static {@link MergeTagValueResolver | resolver} that returns values\n * sourced from a user profile based on a Contentful Merge Tag entry.\n */\n readonly mergeTagValueResolver = MergeTagValueResolver\n\n /**\n * Static {@link PersonalizedEntryResolver | resolver } for personalized\n * Contentful entries (e.g., entry variants targeted to a profile audience).\n *\n * @remarks\n * Used by higher-level personalization flows to materialize entry content\n * prior to event emission.\n */\n readonly personalizedEntryResolver = PersonalizedEntryResolver\n\n /**\n * Get the specified Custom Flag's value from the supplied changes.\n * @param name - The name/key of the Custom Flag.\n * @param changes - Optional changes array.\n * @returns The current value of the Custom Flag if found.\n * @remarks\n * The changes array can be sourced from the data returned when emitting any\n * personalization event.\n * */\n getCustomFlag(name: string, changes?: ChangeArray): Json {\n return FlagsResolver.resolve(changes)[name]\n }\n\n /**\n * Resolve a Contentful entry to a personalized variant using the current\n * or provided selected personalizations.\n *\n * @typeParam S - Entry skeleton type.\n * @typeParam M - Chain modifiers.\n * @typeParam L - Locale code.\n * @param entry - The entry to personalize.\n * @param personalizations - Optional selected personalizations.\n * @returns The resolved entry data.\n * @remarks\n * Selected personalizations can be sourced from the data returned when emitting any\n * personalization event.\n */\n personalizeEntry<\n S extends EntrySkeletonType,\n M extends ChainModifiers = ChainModifiers,\n L extends LocaleCode = LocaleCode,\n >(entry: Entry<S, M, L>, personalizations?: SelectedPersonalizationArray): ResolvedData<S, M, L> {\n return PersonalizedEntryResolver.resolve<S, M, L>(entry, personalizations)\n }\n\n /**\n * Resolve a merge tag to a value based on the current (or provided) profile.\n *\n * @param embeddedEntryNodeTarget - The merge tag entry node to resolve.\n * @param profile - Optional profile.\n * @returns The resolved value (type depends on the tag).\n * @remarks\n * Merge tags are references to profile data that can be substituted into content. The\n * profile can be sourced from the data returned when emitting any personalization event.\n */\n getMergeTagValue(embeddedEntryNodeTarget: MergeTagEntry, profile?: Profile): unknown {\n return MergeTagValueResolver.resolve(embeddedEntryNodeTarget, profile)\n }\n\n /**\n * Identify the current profile/visitor to associate traits with a profile.\n *\n * @param payload - Identify builder payload.\n * @returns The resulting {@link OptimizationData} for the identified user if the device is online.\n */\n abstract identify(payload: IdentifyBuilderArgs): Promise<OptimizationData | undefined>\n\n /**\n * Record a page view.\n *\n * @param payload - Page view builder payload.\n * @returns The evaluated {@link OptimizationData} for this page view if the device is online.\n */\n abstract page(payload: PageViewBuilderArgs): Promise<OptimizationData | undefined>\n\n /**\n * Record a screen view.\n *\n * @param payload - Screen view builder payload.\n * @returns The evaluated {@link OptimizationData} for this screen view if the device is online.\n */\n abstract screen(payload: ScreenViewBuilderArgs): Promise<OptimizationData | undefined>\n\n /**\n * Record a custom track event.\n *\n * @param payload - Track builder payload.\n * @returns The evaluated {@link OptimizationData} for this event if the device is online.\n */\n abstract track(payload: TrackBuilderArgs): Promise<OptimizationData | undefined>\n\n /**\n * Record a \"sticky\" component view.\n *\n * @param payload - \"Sticky\" component view builder payload.\n * @returns The evaluated {@link OptimizationData} for this component view if the device is online.\n * @remarks\n * This method is intended to be called only when a component is considered\n * \"sticky\".\n * @privateRemarks\n * Duplication prevention should be handled in Stateful implementations.\n */\n abstract trackComponentView(\n payload: ComponentViewBuilderArgs,\n duplicationScope?: string,\n ): Promise<OptimizationData | undefined>\n}\n\nexport default PersonalizationBase\n","import {\n type InsightsEvent as AnalyticsEvent,\n type ChangeArray,\n type ComponentViewBuilderArgs,\n type Flags,\n type IdentifyBuilderArgs,\n type Json,\n type MergeTagEntry,\n type OptimizationData,\n type PageViewBuilderArgs,\n ExperienceEvent as PersonalizationEvent,\n type ExperienceEventArray as PersonalizationEventArray,\n type Profile,\n type ScreenViewBuilderArgs,\n type SelectedPersonalizationArray,\n type TrackBuilderArgs,\n} from '@contentful/optimization-api-client'\nimport type { ChainModifiers, Entry, EntrySkeletonType, LocaleCode } from 'contentful'\nimport { isEqual } from 'es-toolkit'\nimport { createScopedLogger } from 'logger'\nimport type { ConsentGuard } from '../Consent'\nimport { guardedBy } from '../lib/decorators'\nimport type { ProductBaseOptions, ProductConfig } from '../ProductBase'\nimport {\n batch,\n changes as changesSignal,\n consent as consentSignal,\n effect,\n event as eventSignal,\n flags as flagsSignal,\n type Observable,\n online as onlineSignal,\n personalizations as personalizationsSignal,\n profile as profileSignal,\n toObservable,\n} from '../signals'\nimport PersonalizationBase from './PersonalizationBase'\nimport type { ResolvedData } from './resolvers'\n\nconst logger = createScopedLogger('Personalization')\n\n/**\n * Default state values for {@link PersonalizationStateful} applied at construction time.\n *\n * @public\n */\nexport interface PersonalizationProductConfigDefaults {\n /** Whether personalization is allowed by default. */\n consent?: boolean\n /** Initial diff of changes produced by the service. */\n changes?: ChangeArray\n /** Default active profile used for personalization. */\n profile?: Profile\n /** Preselected personalization variants (e.g., winning treatments). */\n personalizations?: SelectedPersonalizationArray\n}\n\n/**\n * Configuration for {@link PersonalizationStateful}.\n *\n * @public\n */\nexport interface PersonalizationProductConfig extends ProductConfig {\n /** Default signal values applied during initialization. */\n defaults?: PersonalizationProductConfigDefaults\n\n /**\n * Function used to obtain an anonymous user identifier.\n *\n * @remarks\n * If a `getAnonymousId` function has been provided, the returned value will\n * take precedence over the `id` property of the current {@link Profile}\n * signal value\n *\n * @returns A string identifier, or `undefined` if no anonymous ID is available.\n */\n getAnonymousId?: () => string | undefined\n}\n\n/**\n * Observables exposed by {@link PersonalizationStateful} that mirror internal signals.\n *\n * @public\n */\nexport interface PersonalizationStates {\n /** Observable stream of the latest {@link AnalyticsEvent} or {@link PersonalizationEvent} (or `undefined`). */\n eventStream: Observable<AnalyticsEvent | PersonalizationEvent | undefined>\n /** Live view of effective flags for the current profile (if available). */\n flags: Observable<Flags | undefined>\n /** Live view of the current profile. */\n profile: Observable<Profile | undefined>\n /** Live view of selected personalizations (variants). */\n personalizations: Observable<SelectedPersonalizationArray | undefined>\n}\n\n/**\n * Options for configuring {@link PersonalizationStateful} functionality.\n *\n * @public\n * @see {@link ProductBaseOptions}\n */\nexport type PersonalizationStatefulOptions = ProductBaseOptions & {\n /** Configuration specific to the Personalization product */\n config?: PersonalizationProductConfig\n}\n\n/**\n * Stateful personalization product that manages consent, profile, flags, and\n * selected variants while emitting Experience events and updating state.\n *\n * @public\n * @remarks\n * The class maintains reactive signals and exposes read‑only observables via\n * {@link PersonalizationStateful.states}. Events are validated via schema parsers and\n * run through interceptors before being submitted. Resulting state is merged\n * back into signals.\n */\nclass PersonalizationStateful extends PersonalizationBase implements ConsentGuard {\n /** In‑memory queue for offline events keyed by profile. */\n private readonly offlineQueue = new Set<PersonalizationEvent>()\n\n /** Exposed observable state references. */\n readonly states: PersonalizationStates = {\n eventStream: toObservable(eventSignal),\n flags: toObservable(flagsSignal),\n profile: toObservable(profileSignal),\n personalizations: toObservable(personalizationsSignal),\n }\n\n /**\n * Function that provides an anonymous ID when available.\n *\n * @internal\n */\n getAnonymousId: () => string | undefined\n\n /**\n * Create a new stateful personalization instance.\n *\n * @param options - Options to configure the personalization product for stateful environments.\n */\n constructor(options: PersonalizationStatefulOptions) {\n const { api, builder, config, interceptors } = options\n\n super({ api, builder, config, interceptors })\n\n const { defaults, getAnonymousId } = config ?? {}\n\n if (defaults) {\n const {\n changes: defaultChanges,\n personalizations: defaultPersonalizations,\n profile: defaultProfile,\n } = defaults\n\n batch(() => {\n changesSignal.value = defaultChanges\n personalizationsSignal.value = defaultPersonalizations\n profileSignal.value = defaultProfile\n })\n }\n\n if (defaults?.consent !== undefined) {\n const { consent: defaultConsent } = defaults\n consentSignal.value = defaultConsent\n }\n\n this.getAnonymousId = getAnonymousId ?? (() => undefined)\n\n // Log signal changes for observability\n effect(() => {\n logger.debug(\n `Profile ${profileSignal.value && `with ID ${profileSignal.value.id}`} has been ${profileSignal.value ? 'set' : 'cleared'}`,\n )\n })\n\n effect(() => {\n logger.debug(\n `Variants have been ${personalizationsSignal.value?.length ? 'populated' : 'cleared'}`,\n )\n })\n\n effect(() => {\n logger.info(\n `Personalization ${consentSignal.value ? 'will' : 'will not'} take effect due to consent (${consentSignal.value})`,\n )\n })\n\n effect(() => {\n if (onlineSignal.value) void this.flush()\n })\n }\n\n /**\n * Reset stateful signals managed by this product.\n *\n * @remarks\n * Clears `changes`, `profile`, and selected `personalizations`.\n */\n reset(): void {\n batch(() => {\n changesSignal.value = undefined\n eventSignal.value = undefined\n profileSignal.value = undefined\n personalizationsSignal.value = undefined\n })\n }\n\n /**\n * Get the specified Custom Flag's value (derived from the signal).\n * @param name - The name or key of the Custom Flag.\n * @returns The current value of the Custom Flag if found.\n * */\n getCustomFlag(name: string, changes: ChangeArray | undefined = changesSignal.value): Json {\n return super.getCustomFlag(name, changes)\n }\n\n /**\n * Resolve a Contentful entry to a personalized variant using the current\n * or provided selections.\n *\n * @typeParam S - Entry skeleton type.\n * @typeParam M - Chain modifiers.\n * @typeParam L - Locale code.\n * @param entry - The entry to personalize.\n * @param personalizations - Optional selections; defaults to the current signal value.\n * @returns The resolved entry data.\n */\n personalizeEntry<\n S extends EntrySkeletonType,\n M extends ChainModifiers = ChainModifiers,\n L extends LocaleCode = LocaleCode,\n >(\n entry: Entry<S, M, L>,\n personalizations: SelectedPersonalizationArray | undefined = personalizationsSignal.value,\n ): ResolvedData<S, M, L> {\n return super.personalizeEntry<S, M, L>(entry, personalizations)\n }\n\n /**\n * Resolve a merge tag to a value based on the current (or provided) profile.\n *\n * @param embeddedEntryNodeTarget - The merge‑tag entry node to resolve.\n * @param profile - Optional profile; defaults to the current signal value.\n * @returns The resolved value (type depends on the tag).\n * @remarks\n * Merge tags are references to profile data that can be substituted into content.\n */\n getMergeTagValue(\n embeddedEntryNodeTarget: MergeTagEntry,\n profile: Profile | undefined = profileSignal.value,\n ): unknown {\n return super.getMergeTagValue(embeddedEntryNodeTarget, profile)\n }\n\n /**\n * Determine whether the named operation is permitted based on consent and\n * allowed event type configuration.\n *\n * @param name - Method name; `trackComponentView` is normalized to\n * `'component'` for allow‑list checks.\n * @returns `true` if the operation is permitted; otherwise `false`.\n */\n hasConsent(name: string): boolean {\n return (\n !!consentSignal.value ||\n (this.allowedEventTypes ?? []).includes(\n name === 'trackComponentView' || name === 'trackFlagView' ? 'component' : name,\n )\n )\n }\n\n /**\n * Hook invoked when an operation is blocked due to missing consent.\n *\n * @param name - The blocked operation name.\n * @param payload - The original arguments supplied to the operation.\n */\n onBlockedByConsent(name: string, payload: unknown[]): void {\n logger.warn(\n `Event \"${name}\" was blocked due to lack of consent; payload: ${JSON.stringify(payload)}`,\n )\n }\n\n /**\n * Guard used to suppress duplicate component view events for the same\n * component based on a duplication key and the component identifier.\n *\n * @param _name - Operation name (unused).\n * @param payload - Tuple `[builderArgs, duplicationScope]`.\n * @returns `true` if the event is NOT a duplicate and should proceed.\n */\n isNotDuplicated(_name: string, payload: [ComponentViewBuilderArgs, string]): boolean {\n const [{ componentId: value }, duplicationScope] = payload\n\n const isDuplicated = this.duplicationDetector.isPresent(duplicationScope, value)\n\n if (!isDuplicated) this.duplicationDetector.addValue(duplicationScope, value)\n\n return !isDuplicated\n }\n\n /**\n * Hook invoked when an operation is blocked by the duplication guard.\n *\n * @param _name - The blocked operation name (unused).\n * @param payload - The original arguments supplied to the operation.\n */\n onBlockedByDuplication(_name: string, payload: unknown[]): void {\n logger.debug(\n `Duplicate \"component view\" event detected, skipping; payload: ${JSON.stringify(payload)}`,\n )\n }\n\n /**\n * Identify the current profile/visitor to associate traits with a profile\n * and update optimization state.\n *\n * @param payload - Identify builder payload.\n * @returns The resulting {@link OptimizationData} for the identified user.\n */\n @guardedBy('hasConsent', { onBlocked: 'onBlockedByConsent' })\n async identify(payload: IdentifyBuilderArgs): Promise<OptimizationData | undefined> {\n logger.info('Sending \"identify\" event')\n\n const event = this.builder.buildIdentify(payload)\n\n return await this.sendOrEnqueueEvent(event)\n }\n\n /**\n * Record a page view and update optimization state.\n *\n * @param payload - Page view builder payload.\n * @returns The evaluated {@link OptimizationData} for this page view.\n */\n @guardedBy('hasConsent', { onBlocked: 'onBlockedByConsent' })\n async page(payload: PageViewBuilderArgs): Promise<OptimizationData | undefined> {\n logger.info('Sending \"page\" event')\n\n const event = this.builder.buildPageView(payload)\n\n return await this.sendOrEnqueueEvent(event)\n }\n\n /**\n * Record a screen view and update optimization state.\n *\n * @param payload - Screen view builder payload.\n * @returns The evaluated {@link OptimizationData} for this screen view.\n */\n @guardedBy('hasConsent', { onBlocked: 'onBlockedByConsent' })\n async screen(payload: ScreenViewBuilderArgs): Promise<OptimizationData | undefined> {\n logger.info(`Sending \"screen\" event for \"${payload.name}\"`)\n\n const event = this.builder.buildScreenView(payload)\n\n return await this.sendOrEnqueueEvent(event)\n }\n\n /**\n * Record a custom track event and update optimization state.\n *\n * @param payload - Track builder payload.\n * @returns The evaluated {@link OptimizationData} for this event.\n */\n @guardedBy('hasConsent', { onBlocked: 'onBlockedByConsent' })\n async track(payload: TrackBuilderArgs): Promise<OptimizationData | undefined> {\n logger.info(`Sending \"track\" event \"${payload.event}\"`)\n\n const event = this.builder.buildTrack(payload)\n\n return await this.sendOrEnqueueEvent(event)\n }\n\n @guardedBy('isNotDuplicated', { onBlocked: 'onBlockedByDuplication' })\n @guardedBy('hasConsent', { onBlocked: 'onBlockedByConsent' })\n /**\n * Record a \"sticky\" component view and update optimization state.\n *\n * @param payload - Component view builder payload.\n * @param _duplicationScope - Optional duplication scope key used to suppress duplicates.\n * @returns The evaluated {@link OptimizationData} for this component view.\n */\n async trackComponentView(\n payload: ComponentViewBuilderArgs,\n _duplicationScope = '',\n ): Promise<OptimizationData | undefined> {\n logger.info(`Sending \"track personalization\" event for ${payload.componentId}`)\n\n const event = this.builder.buildComponentView(payload)\n\n return await this.sendOrEnqueueEvent(event)\n }\n\n /**\n * Intercept, validate, and place an event into the offline eventd queue; then\n * trigger a size‑based flush if necessary.\n *\n * @param event - The event to enqueue.\n */\n private async sendOrEnqueueEvent(\n event: PersonalizationEvent,\n ): Promise<OptimizationData | undefined> {\n const intercepted = await this.interceptors.event.run(event)\n\n const validEvent = PersonalizationEvent.parse(intercepted)\n\n eventSignal.value = validEvent\n\n if (onlineSignal.value) return await this.upsertProfile([validEvent])\n\n logger.debug(`Queueing ${validEvent.type} event`, validEvent)\n\n this.offlineQueue.add(validEvent)\n\n return undefined\n }\n\n /**\n * Flush the offline queue\n */\n async flush(): Promise<void> {\n if (this.offlineQueue.size === 0) return\n\n logger.debug('Flushing offline event queue')\n\n await this.upsertProfile(Array.from(this.offlineQueue))\n\n this.offlineQueue.clear()\n }\n\n /**\n * Submit events to the Experience API, updating output signals with the\n * returned state.\n *\n * @param events - The events to submit.\n * @returns The {@link OptimizationData} returned by the service.\n * @internal\n * @privateRemarks\n * If a `getAnonymousId` function has been provided, the returned value will\n * take precedence over the `id` property of the current {@link Profile}\n * signal value\n */\n private async upsertProfile(events: PersonalizationEventArray): Promise<OptimizationData> {\n const anonymousId = this.getAnonymousId()\n if (anonymousId) logger.debug(`Anonymous ID found: ${anonymousId}`)\n\n const data = await this.api.experience.upsertProfile({\n profileId: anonymousId ?? profileSignal.value?.id,\n events,\n })\n\n await this.updateOutputSignals(data)\n\n return data\n }\n\n /**\n * Apply returned optimization state to local signals after interceptor processing.\n *\n * @param data - Optimization state returned by the service.\n * @internal\n */\n private async updateOutputSignals(data: OptimizationData): Promise<void> {\n const intercepted = await this.interceptors.state.run(data)\n\n const { changes, personalizations, profile } = intercepted\n\n batch(() => {\n if (!isEqual(changesSignal.value, changes)) changesSignal.value = changes\n if (!isEqual(profileSignal.value, profile)) profileSignal.value = profile\n if (!isEqual(personalizationsSignal.value, personalizations))\n personalizationsSignal.value = personalizations\n })\n }\n}\n\nexport default PersonalizationStateful\n","import {\n type ComponentViewBuilderArgs,\n ComponentViewEvent,\n type IdentifyBuilderArgs,\n IdentifyEvent,\n type OptimizationData,\n type PageViewBuilderArgs,\n PageViewEvent,\n type PartialProfile,\n type ExperienceEvent as PersonalizationEvent,\n type ScreenViewBuilderArgs,\n ScreenViewEvent,\n type TrackBuilderArgs,\n TrackEvent,\n} from '@contentful/optimization-api-client'\nimport { createScopedLogger } from 'logger'\nimport PersonalizationBase from './PersonalizationBase'\n\nconst logger = createScopedLogger('Personalization')\n\n/**\n * Stateless personalization implementation that immediately validates and sends\n * a single event to the Experience API, upserting the profile as needed.\n *\n * @public\n * @remarks\n * Each public method constructs a strongly-typed event via the shared builder,\n * runs it through event interceptors, and performs a profile upsert using the\n * Experience API. If an anonymous ID is available from the builder, it will be\n * preferred as the `profileId` unless an explicit profile is provided.\n */\nclass PersonalizationStateless extends PersonalizationBase {\n /**\n * Identify the current profile/visitor to associate traits with a profile.\n *\n * @param payload - Identify builder arguments with an optional partial\n * profile to attach to the upsert request.\n * @returns The resulting {@link OptimizationData} for the identified user.\n */\n async identify(\n payload: IdentifyBuilderArgs & { profile?: PartialProfile },\n ): Promise<OptimizationData> {\n logger.info('Sending \"identify\" event')\n\n const { profile, ...builderArgs } = payload\n\n const event = IdentifyEvent.parse(this.builder.buildIdentify(builderArgs))\n\n return await this.upsertProfile(event, profile)\n }\n\n /**\n * Record a page view.\n *\n * @param payload - Page view builder arguments with an optional partial profile.\n * @returns The evaluated {@link OptimizationData} for this page view.\n */\n async page(\n payload: PageViewBuilderArgs & { profile?: PartialProfile },\n ): Promise<OptimizationData> {\n logger.info('Sending \"page\" event')\n\n const { profile, ...builderArgs } = payload\n\n const event = PageViewEvent.parse(this.builder.buildPageView(builderArgs))\n\n return await this.upsertProfile(event, profile)\n }\n\n /**\n * Record a screen view.\n *\n * @param payload - Screen view builder arguments with an optional partial profile.\n * @returns The evaluated {@link OptimizationData} for this screen view.\n */\n async screen(\n payload: ScreenViewBuilderArgs & { profile?: PartialProfile },\n ): Promise<OptimizationData> {\n logger.info(`Sending \"screen\" event for \"${payload.name}\"`)\n\n const { profile, ...builderArgs } = payload\n\n const event = ScreenViewEvent.parse(this.builder.buildScreenView(builderArgs))\n\n return await this.upsertProfile(event, profile)\n }\n\n /**\n * Record a custom track event.\n *\n * @param payload - Track builder arguments with an optional partial profile.\n * @returns The evaluated {@link OptimizationData} for this event.\n */\n async track(payload: TrackBuilderArgs & { profile?: PartialProfile }): Promise<OptimizationData> {\n logger.info(`Sending \"track\" event \"${payload.event}\"`)\n\n const { profile, ...builderArgs } = payload\n\n const event = TrackEvent.parse(this.builder.buildTrack(builderArgs))\n\n return await this.upsertProfile(event, profile)\n }\n\n /**\n * Record a \"sticky\" component view.\n *\n * @param payload - Component view builder arguments with an optional partial profile.\n * @returns The evaluated {@link OptimizationData} for this component view.\n */\n async trackComponentView(\n payload: ComponentViewBuilderArgs & { profile?: PartialProfile },\n ): Promise<OptimizationData> {\n logger.info('Sending \"track personalization\" event')\n\n const { profile, ...builderArgs } = payload\n\n const event = ComponentViewEvent.parse(this.builder.buildComponentView(builderArgs))\n\n return await this.upsertProfile(event, profile)\n }\n\n /**\n * Intercept, validate, and upsert the profile with a single personalization\n * event.\n *\n * @param event - The {@link PersonalizationEvent} to submit.\n * @param profile - Optional partial profile. If omitted, the anonymous ID from\n * the builder (when present) is used as the `profileId`.\n * @returns The {@link OptimizationData} returned by the Experience API.\n * @internal\n */\n private async upsertProfile(\n event: PersonalizationEvent,\n profile?: PartialProfile,\n ): Promise<OptimizationData> {\n const intercepted = await this.interceptors.event.run(event)\n\n const data = await this.api.experience.upsertProfile({\n profileId: profile?.id,\n events: [intercepted],\n })\n\n return data\n }\n}\n\nexport default PersonalizationStateless\n","import type {\n InsightsEvent as AnalyticsEvent,\n ChangeArray,\n ExperienceEvent as PersonalizationEvent,\n Profile,\n SelectedPersonalizationArray,\n} from '@contentful/optimization-api-client'\nimport { AnalyticsStateful, type AnalyticsStates } from './analytics'\nimport type { ConsentController } from './Consent'\nimport CoreBase, { type CoreConfig } from './CoreBase'\nimport {\n PersonalizationStateful,\n type PersonalizationProductConfig,\n type PersonalizationStates,\n} from './personalization'\nimport type { ProductConfig } from './ProductBase'\nimport {\n batch,\n changes,\n consent,\n event,\n flags,\n online,\n personalizations,\n profile,\n signals,\n toObservable,\n type Observable,\n type Signals,\n} from './signals'\n\n/**\n * Interface for objects that can be registered with the preview panel system.\n * When registered, the object receives direct access to SDK signals for state manipulation.\n *\n * @public\n */\nexport interface PreviewPanelSignalObject {\n /** Signals instance that will be populated by registerPreviewPanel */\n signals: Signals | null\n}\n\n/**\n * Combined observable state exposed by the stateful core.\n *\n * @public\n * @see {@link AnalyticsStates}\n * @see {@link PersonalizationStates}\n */\nexport interface CoreStates extends AnalyticsStates, PersonalizationStates {\n /** Current consent value (if any). */\n consent: Observable<boolean | undefined>\n /** Stream of the most recent event emitted (analytics or personalization). */\n eventStream: Observable<AnalyticsEvent | PersonalizationEvent | undefined>\n}\n\n/**\n * Default values used to preconfigure the stateful core and products.\n *\n * @public\n */\nexport interface CoreConfigDefaults {\n /** Global consent default applied at construction time. */\n consent?: boolean\n /** Default active profile used for personalization and analytics. */\n profile?: Profile\n /** Initial diff of changes produced by the service. */\n changes?: ChangeArray\n /** Preselected personalization variants (e.g., winning treatments). */\n personalizations?: SelectedPersonalizationArray\n}\n\n/**\n * Configuration for {@link CoreStateful}.\n *\n * @public\n * @see {@link CoreConfig}\n */\nexport interface CoreStatefulConfig extends CoreConfig {\n /**\n * Allow-listed event type strings permitted when consent is not set.\n *\n * @see {@link ProductConfig.allowedEventTypes}\n */\n allowedEventTypes?: ProductConfig['allowedEventTypes']\n\n /** Optional set of default values applied on initialization. */\n defaults?: CoreConfigDefaults\n\n /** Function used to obtain an anonymous user identifier. */\n getAnonymousId?: PersonalizationProductConfig['getAnonymousId']\n\n /**\n * Initial duplication prevention configuration for component events.\n *\n * @see {@link ProductConfig.preventedComponentEvents}\n */\n preventedComponentEvents?: ProductConfig['preventedComponentEvents']\n}\n\n/**\n * Core runtime that constructs stateful product instances and exposes shared\n * states, including consent and the event stream.\n *\n * @public\n * @remarks\n * @see {@link CoreBase}\n * @see {@link ConsentController}\n */\nclass CoreStateful extends CoreBase implements ConsentController {\n /** Stateful analytics product. */\n readonly analytics: AnalyticsStateful\n /** Stateful personalization product. */\n readonly personalization: PersonalizationStateful\n\n /**\n * Create a stateful core with optional default consent and product defaults.\n *\n * @param config - Core and defaults configuration.\n * @example\n * ```ts\n * const core = new CoreStateful({\n * clientId: 'app',\n * environment: 'prod',\n * defaults: { consent: true }\n * })\n * core.consent(true)\n * ```\n */\n constructor(config: CoreStatefulConfig) {\n super(config)\n\n const { allowedEventTypes, defaults, getAnonymousId, preventedComponentEvents } = config\n\n if (defaults?.consent !== undefined) {\n const { consent: defaultConsent } = defaults\n consent.value = defaultConsent\n }\n\n this.analytics = new AnalyticsStateful({\n api: this.api,\n builder: this.eventBuilder,\n config: {\n allowedEventTypes,\n preventedComponentEvents,\n defaults: {\n consent: defaults?.consent,\n profile: defaults?.profile,\n },\n },\n interceptors: this.interceptors,\n })\n\n this.personalization = new PersonalizationStateful({\n api: this.api,\n builder: this.eventBuilder,\n config: {\n allowedEventTypes,\n getAnonymousId,\n preventedComponentEvents,\n defaults: {\n consent: defaults?.consent,\n changes: defaults?.changes,\n profile: defaults?.profile,\n personalizations: defaults?.personalizations,\n },\n },\n interceptors: this.interceptors,\n })\n }\n\n /**\n * Expose merged observable state for consumers.\n */\n get states(): CoreStates {\n return {\n consent: toObservable(consent),\n eventStream: toObservable(event),\n flags: toObservable(flags),\n personalizations: toObservable(personalizations),\n profile: toObservable(profile),\n }\n }\n\n /**\n * Reset internal state. Consent is intentionally preserved.\n *\n * @remarks\n * Resetting personalization also resets analytics dependencies as a\n * consequence of the current shared-state design.\n */\n reset(): void {\n batch(() => {\n event.value = undefined\n changes.value = undefined\n profile.value = undefined\n personalizations.value = undefined\n })\n }\n\n /**\n * Flush the queues for both the analytics and personalization products.\n * @remarks\n * The personalization queue is only populated if events have been triggered\n * while a device is offline.\n */\n async flush(): Promise<void> {\n await this.analytics.flush()\n await this.personalization.flush()\n }\n\n /**\n * Update consent state\n *\n * @param accept - `true` if the user has granted consent; `false` otherwise.\n */\n consent(accept: boolean): void {\n consent.value = accept\n }\n\n /**\n * Update online state\n *\n * @param isOnline - `true` if the browser is online; `false` otherwise.\n */\n protected online(isOnline: boolean): void {\n online.value = isOnline\n }\n\n /**\n * Register a preview panel compatible object to receive direct signal access.\n * This enables the preview panel to modify SDK state for testing and simulation.\n *\n * @param previewPanel - An object implementing PreviewPanelSignalObject\n * @remarks\n * This method is intended for use by the Preview Panel component.\n * Direct signal access allows immediate state updates without API calls.\n */\n registerPreviewPanel(previewPanel: PreviewPanelSignalObject): void {\n previewPanel.signals = signals\n }\n}\n\nexport default CoreStateful\n","import type { EventBuilderConfig } from '@contentful/optimization-api-client'\nimport { AnalyticsStateless } from './analytics'\nimport CoreBase, { type CoreConfig } from './CoreBase'\nimport { PersonalizationStateless } from './personalization'\n\n/**\n * Configuration for the Node-specific Optimization SDK.\n *\n * @public\n * @remarks\n * This configuration extends {@link CoreConfig} but allows partial overrides\n * of the event-builder configuration. SDKs commonly inject their own library\n * metadata or channel definitions.\n */\nexport interface CoreStatelessConfig extends CoreConfig {\n /**\n * Override configuration for the analytics (Insights) API client. Omits\n * `beaconHandler`.\n */\n analytics?: Omit<CoreConfig['analytics'], 'beaconHandler'>\n\n /**\n * Overrides for the event builder configuration. Omits methods that are only\n * useful in stateful environments.\n */\n eventBuilder?: Omit<EventBuilderConfig, 'getLocale' | 'getPageProperties' | 'getUserAgent'>\n}\n\n/**\n * Core runtime that constructs product instances for stateless environments.\n *\n * @public\n * @see {@link CoreBase}\n */\nclass CoreStateless extends CoreBase {\n /** Stateless analytics product. */\n readonly analytics: AnalyticsStateless\n /** Stateless personalization product. */\n readonly personalization: PersonalizationStateless\n\n /**\n * Create a stateless core. Product instances share the same API client and\n * event builder configured in {@link CoreBase}.\n *\n * @param config - Stateless Core configuration.\n * @example\n * ```ts\n * const sdk = new CoreStateless({ clientId: 'app', environment: 'prod' })\n * core.analytics.trackFlagView({ componentId: 'hero' })\n * // or\n * core.trackFlagView({ componentId: 'hero' })\n * ```\n */\n constructor(config: CoreStatelessConfig) {\n super(config)\n\n this.analytics = new AnalyticsStateless({\n api: this.api,\n builder: this.eventBuilder,\n interceptors: this.interceptors,\n })\n\n this.personalization = new PersonalizationStateless({\n api: this.api,\n builder: this.eventBuilder,\n interceptors: this.interceptors,\n })\n }\n}\n\nexport default CoreStateless\n","/*! js-cookie v3.0.5 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n function set (name, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n name = encodeURIComponent(name)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n name + '=' + converter.write(value, name) + stringifiedAttributes)\n }\n\n function get (name) {\n if (typeof document === 'undefined' || (arguments.length && !name)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var found = decodeURIComponent(parts[0]);\n jar[found] = converter.read(value, found);\n\n if (name === found) {\n break\n }\n } catch (e) {}\n }\n\n return name ? jar[name] : jar\n }\n\n return Object.create(\n {\n set,\n get,\n remove: function (name, attributes) {\n set(\n name,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n/* eslint-enable no-var */\n\nexport { api as default };\n","import { type CoreStateful, createScopedLogger } from '@contentful/optimization-core'\nimport type {\n ElementExistenceObserverOptions,\n ElementViewCallbackInfo,\n ElementViewObserver,\n} from './observers'\n\nconst logger = createScopedLogger('Web:AutoTracking')\n\n/**\n * Data attributes used by the Web SDK to identify and configure tracked entries.\n */\nexport type CtflDataset = DOMStringMap & {\n /** Entry ID associated with the element. */\n ctflEntryId: string\n /** Optional duplication scope key for de-duplication across views. */\n ctflDuplicationScope?: string\n /** Optional personalization/experience ID associated with the entry. */\n ctflPersonalizationId?: string\n /** Whether this component view should be treated as sticky. */\n ctflSticky?: 'true' | 'false'\n /** Optional variant index for personalized variants (non-negative integer). */\n ctflVariantIndex?: string\n}\n\n/**\n * Element type representing a Contentful entry with required dataset attributes.\n *\n * @remarks\n * This does not support legacy browsers that do not expose `dataset` on `SVGElement`.\n */\nexport type EntryElement = (HTMLElement | SVGElement) & { dataset: CtflDataset }\n\n/**\n * Type guard that determines whether a given element is a tracked entry element.\n *\n * @param element - Candidate element.\n * @returns `true` if the element exposes a valid `ctflEntryId` dataset property.\n */\nexport function isEntryElement(element?: Element): element is EntryElement {\n const isWeb = typeof HTMLElement !== 'undefined' && typeof SVGElement !== 'undefined'\n\n if (!isWeb || !element || element.nodeType !== 1) return false\n\n if (!('dataset' in element)) return false\n\n if (!element.dataset || typeof element.dataset !== 'object') return false\n\n if (!('ctflEntryId' in element.dataset)) return false\n\n const {\n dataset: { ctflEntryId },\n } = element\n\n return typeof ctflEntryId === 'string' && ctflEntryId.trim().length > 0\n}\n\n/**\n * Normalized entry data resolved either from `dataset` or explicit callback data.\n */\nexport interface EntryData {\n /** Optional duplication scope used for de-duplication. */\n duplicationScope?: string\n /** ID of the Contentful entry. */\n entryId: string\n /** Optional personalization/experience ID. */\n personalizationId?: string\n /** Whether the view is sticky. */\n sticky?: boolean\n /** Optional variant index (non-negative integer). */\n variantIndex?: number\n}\n\n/**\n * Type guard that determines whether an arbitrary value is {@link EntryData}.\n *\n * @param data - Unknown value to validate.\n * @returns `true` if the object contains a non-empty entryId string.\n */\nexport function isEntryData(data?: unknown): data is EntryData {\n if (!data) return false\n if (typeof data !== 'object') return false\n return 'entryId' in data && typeof data.entryId === 'string' && !!data.entryId.trim().length\n}\n\n/**\n * Parse a string flag into a boolean indicating sticky behavior.\n *\n * @param sticky - Raw sticky string from dataset.\n * @returns `true` when the value equals `\"true\"` (case-insensitive); otherwise `false`.\n */\nfunction parseSticky(sticky: string | undefined): boolean {\n return (sticky?.trim().toLowerCase() ?? '') === 'true'\n}\n\n/**\n * Parse a non-negative integer variant index.\n *\n * @param variantIndex - Raw variantIndex string from dataset.\n * @returns Parsed number when valid and safe, otherwise `undefined`.\n */\nfunction parseVariantIndex(variantIndex: string | undefined): number | undefined {\n if (variantIndex === undefined || !/^\\d+$/.test(variantIndex)) return undefined\n const n = Number(variantIndex)\n return Number.isSafeInteger(n) ? n : undefined\n}\n\n/**\n * Create a callback that wires ElementViewObserver events into `trackComponentView`\n * on the {@link CoreStateful} instance.\n *\n * @param core - Stateful core instance used to send component view events.\n * @returns A callback suitable for use with {@link ElementViewObserver}.\n *\n * @example\n * ```ts\n * const callback = createAutoTrackingEntryViewCallback(core)\n * const observer = new ElementViewObserver(callback, { dwellTimeMs: 1000 })\n * observer.observe(element, { data: { entryId: 'xyz' } })\n * ```\n */\nexport const createAutoTrackingEntryViewCallback =\n (core: CoreStateful) =>\n async (element: Element, info: ElementViewCallbackInfo): Promise<void> => {\n if (!isEntryData(info.data) && !isEntryElement(element)) return\n\n let duplicationScope: string | undefined = undefined\n let entryId: string | undefined = undefined\n let personalizationId: string | undefined = undefined\n let sticky: boolean | undefined = undefined\n let variantIndex: number | undefined = undefined\n\n if (isEntryData(info.data)) {\n ;({\n data: { duplicationScope, entryId, personalizationId, sticky, variantIndex },\n } = info)\n } else if (isEntryElement(element)) {\n ;({\n dataset: {\n ctflDuplicationScope: duplicationScope,\n ctflEntryId: entryId,\n ctflPersonalizationId: personalizationId,\n },\n } = element)\n\n const {\n dataset: { ctflSticky, ctflVariantIndex },\n } = element\n\n sticky = parseSticky(ctflSticky)\n variantIndex = parseVariantIndex(ctflVariantIndex)\n }\n\n if (!entryId) {\n logger.warn(\n 'No entry data found in entry view observer callback; please add data attributes or observe with data info',\n )\n return\n }\n\n await core.trackComponentView(\n {\n componentId: entryId,\n experienceId: personalizationId,\n sticky,\n variantIndex,\n },\n duplicationScope,\n )\n }\n\n/**\n * Find a descendant or self element that qualifies as an {@link EntryElement}.\n *\n * @param element - Starting element.\n * @returns The matching entry element, if any.\n */\nfunction findEntryElement(element: Element): EntryElement | undefined {\n if (isEntryElement(element)) return element\n\n const maybeEntryElement = element.querySelector('[data-ctfl-entry-id]') ?? undefined\n\n return isEntryElement(maybeEntryElement) ? maybeEntryElement : undefined\n}\n\n/**\n * Create an {@link ElementExistenceObserverOptions} object that auto-observes\n * and/or unobserves entry elements for a given {@link ElementViewObserver}.\n *\n * @param entryViewObserver - ElementViewObserver instance to manage.\n * @param autoObserveEntryElements - When `true`, automatically start observing\n * newly-added entry elements.\n * @returns Options object suitable for constructing an ElementExistenceObserver.\n *\n * @example\n * ```ts\n * const viewObserver = new ElementViewObserver(callback, { dwellTimeMs: 1000 })\n * const existenceOpts = createAutoTrackingEntryExistenceCallback(viewObserver, true)\n * const existenceObserver = new ElementExistenceObserver(existenceOpts)\n * ```\n */\nexport const createAutoTrackingEntryExistenceCallback = (\n entryViewObserver: ElementViewObserver,\n autoObserveEntryElements = false,\n): ElementExistenceObserverOptions => ({\n onRemoved: (elements: readonly Element[]): void => {\n elements.forEach((element) => {\n const ctflElement = findEntryElement(element)\n\n if (!ctflElement || !entryViewObserver.getStats(ctflElement)) return\n\n logger.info('Auto-unobserving element (remove):', ctflElement)\n entryViewObserver.unobserve(ctflElement)\n })\n },\n onAdded: autoObserveEntryElements\n ? (elements: readonly Element[]): void => {\n elements.forEach((element) => {\n const ctflElement = findEntryElement(element)\n\n if (!ctflElement) return\n\n logger.info('Auto-observing element (add):', ctflElement)\n entryViewObserver.observe(ctflElement)\n })\n }\n : undefined,\n})\n","import { createScopedLogger, type Dictionary, type Page } from '@contentful/optimization-core'\n\nconst logger = createScopedLogger('Web:EventBuilder')\n\n/**\n * Build a plain-object representation of the query string from a URL.\n *\n * @param url - A URL instance or string from which to extract query parameters.\n * @returns A dictionary of query parameter keys to values.\n *\n * @internal\n */\nfunction buildQuery(url: string | URL): Dictionary {\n return new URL(url).searchParams.entries().reduce((entries: Dictionary, [k, v]) => {\n entries[k] = v\n return entries\n }, {})\n}\n\n/**\n * Determine the preferred locale of the current browser.\n *\n * @returns The first language from `navigator.languages`, or `navigator.language`\n * if `languages` is not available.\n *\n * @public\n * @example\n * ```ts\n * const locale = getLocale()\n * ```\n */\nexport function getLocale(): string {\n const { languages, language } = navigator\n\n return languages[0] ?? language\n}\n\n/**\n * Collect page-related properties from the current browser context.\n *\n * @returns A {@link Page} object describing the current URL, dimensions and\n * metadata. If an error occurs while reading from `window` or `document`,\n * a minimal object with empty strings and no query parameters is returned.\n *\n * @public\n * @example\n * ```ts\n * const page = getPageProperties()\n * optimization.page({ name: page.title, properties: page })\n * ```\n */\nexport function getPageProperties(): Page {\n try {\n const url = new URL(window.location.href)\n const { referrer, title } = document\n\n return {\n hash: window.location.hash,\n height: window.innerHeight,\n path: url.pathname,\n query: buildQuery(url),\n referrer,\n search: url.search,\n title,\n url: url.toString(),\n width: window.innerWidth,\n }\n } catch (error) {\n if (error instanceof Error) logger.error('Failed to get page properties:', error)\n\n return {\n path: '',\n query: {},\n referrer: '',\n search: '',\n title: '',\n url: '',\n }\n }\n}\n\n/**\n * Get the user agent string reported by the current browser.\n *\n * @returns The value of `navigator.userAgent`.\n *\n * @public\n * @example\n * ```ts\n * const ua = getUserAgent()\n * ```\n */\nexport function getUserAgent(): string {\n return navigator.userAgent\n}\n","// eslint-disable-next-line @typescript-eslint/naming-convention -- Replaced at build-time\ndeclare const __OPTIMIZATION_VERSION__: string | undefined\n\nexport const OPTIMIZATION_WEB_SDK_VERSION =\n typeof __OPTIMIZATION_VERSION__ === 'string' ? __OPTIMIZATION_VERSION__ : '0.0.0'\n\n/**\n * Name of the cookie used by the Optimization Core to persist an anonymous ID.\n *\n * @public\n * @remarks\n * Re-exported here to provide a stable Web SDK import path. The value itself\n * is defined and maintained in `@contentful/optimization-core`.\n *\n * @example\n * ```ts\n * import { ANONYMOUS_ID_COOKIE } from '@contentful/optimization-web/global-constants'\n *\n * const anonId = Cookies.get(ANONYMOUS_ID_COOKIE)\n * ```\n */\nexport { ANONYMOUS_ID_COOKIE } from '@contentful/optimization-core'\n\n/**\n * Flag indicating whether the current environment can safely add DOM\n * event listeners.\n *\n * @public\n * @remarks\n * Many Web SDK utilities short-circuit to no-ops when this flag is `false`\n * (e.g., during server-side rendering).\n *\n * @example\n * ```ts\n * import { CAN_ADD_LISTENERS } from '@contentful/optimization-web/global-constants'\n *\n * if (CAN_ADD_LISTENERS) {\n * window.addEventListener('resize', onResize)\n * }\n * ```\n */\nexport const CAN_ADD_LISTENERS =\n typeof window !== 'undefined' &&\n typeof document !== 'undefined' &&\n typeof document.addEventListener === 'function'\n","import type { BatchInsightsEventArray } from '@contentful/optimization-core'\n\n/**\n * Send a batch of analytics events using `navigator.sendBeacon`.\n *\n * @param url - The endpoint URL to which the beacon request should be sent.\n * @param events - The batch of events to serialize and send.\n * @returns `true` if the user agent successfully queued the data for transfer,\n * otherwise `false`.\n *\n * @public\n * @remarks\n * This is intended for fire-and-forget flushing of analytics events during\n * lifecycle transitions (e.g., page unload or visibility change).\n *\n * @example\n * ```ts\n * const ok = beaconHandler('/analytics/batch', batchEvents)\n * if (!ok) {\n * // Optionally fall back to XHR/fetch\n * }\n * ```\n */\nexport function beaconHandler(url: string | URL, events: BatchInsightsEventArray): boolean {\n const blobData = new Blob([JSON.stringify(events)], {\n type: 'text/plain',\n })\n\n return window.navigator.sendBeacon(url, blobData)\n}\n","import { createScopedLogger } from '@contentful/optimization-core'\nimport { CAN_ADD_LISTENERS } from '../global-constants'\n\nconst logger = createScopedLogger('Web:Network')\n\n/**\n * Callback invoked when the browser's connectivity state changes.\n *\n * The callback receives `true` when the browser is online and `false` when it is offline.\n *\n * @internal\n */\ntype Callback = (isOnline: boolean) => Promise<void> | void\n\n/**\n * Create an online/offline listener that invokes a callback whenever the browser transitions\n * between connectivity states, and returns a cleanup function to remove all listeners.\n *\n * @param callback - Function invoked when the browser goes online (`true`) or offline (`false`).\n * May return a promise.\n * @returns A function that removes the registered event listeners when called.\n *\n * @public\n * @remarks\n * - If the environment cannot add listeners (e.g., SSR), a no-op cleanup function is returned.\n * - If `navigator.onLine` is available, the callback is invoked immediately with the initial state.\n *\n * @example\n * ```ts\n * const cleanup = createOnlineChangeListener(async (isOnline) => {\n * if (isOnline) await sdk.analytics.flush()\n * })\n *\n * // Later:\n * cleanup()\n * ```\n */\nexport function createOnlineChangeListener(callback: Callback): () => void {\n if (!CAN_ADD_LISTENERS) {\n return () => {\n void 0\n }\n }\n\n const emit = (isOnline: boolean): void => {\n void (async () => {\n try {\n await callback(isOnline)\n } catch (error) {\n logger.error('Error in online state callback:', error)\n }\n })()\n }\n\n const onOnline = (): void => {\n emit(true)\n }\n const onOffline = (): void => {\n emit(false)\n }\n\n window.addEventListener('online', onOnline)\n window.addEventListener('offline', onOffline)\n\n // Emit initial state (best-effort). If `navigator.onLine` is unavailable, default to `true`.\n emit(typeof navigator.onLine === 'boolean' ? navigator.onLine : true)\n\n return () => {\n window.removeEventListener('online', onOnline)\n window.removeEventListener('offline', onOffline)\n }\n}\n","import { createScopedLogger } from '@contentful/optimization-core'\nimport { CAN_ADD_LISTENERS } from '../global-constants'\n\nconst logger = createScopedLogger('Web:Visibility')\n\n/**\n * Event type for browser page-hide / visibility-change events.\n *\n * @internal\n */\ntype HideEvent = Event | PageTransitionEvent\n\n/**\n * Callback type invoked when the page is being hidden.\n *\n * @internal\n */\ntype Callback = (event: HideEvent) => Promise<void> | void\n\n/**\n * Create a visibility-change listener that invokes a callback when the page\n * is hidden, and returns a cleanup function to remove all listeners.\n *\n * @param callback - Function invoked once when the page is being hidden, or\n * when a pagehide event occurs. May return a promise.\n * @returns A function that removes all registered event listeners when called.\n *\n * @public\n * @remarks\n * The callback is guaranteed to be invoked at most once per hide cycle until\n * the next visibility or page show event resets the internal state. If the\n * environment does not permit adding listeners (e.g., server-side rendering),\n * a no-op cleanup function is returned.\n *\n * @example\n * ```ts\n * const cleanup = createVisibilityChangeListener(async () => {\n * await flushPendingEvents()\n * })\n *\n * // Later, when teardown is needed:\n * cleanup()\n * ```\n */\nexport function createVisibilityChangeListener(callback: Callback): () => void {\n if (!CAN_ADD_LISTENERS) {\n return () => {\n void 0\n }\n }\n\n let handled = false\n\n const handleHide = (event: HideEvent): void => {\n if (handled) return\n handled = true\n\n void (async () => {\n try {\n await callback(event)\n } catch (error) {\n logger.error('Error handling page visibility change:', error)\n }\n })()\n }\n\n const resetHandled = (): void => {\n handled = false\n }\n\n const onVisibilityChange = (event: Event): void => {\n if (document.visibilityState === 'hidden') {\n handleHide(event)\n } else {\n resetHandled()\n }\n }\n\n const onPageHide = (event: PageTransitionEvent): void => {\n handleHide(event)\n }\n\n const onPageShow = (): void => {\n resetHandled()\n }\n\n document.addEventListener('visibilitychange', onVisibilityChange)\n window.addEventListener('pagehide', onPageHide)\n window.addEventListener('pageshow', onPageShow)\n\n // Cleanup function\n return () => {\n document.removeEventListener('visibilitychange', onVisibilityChange)\n window.removeEventListener('pagehide', onPageHide)\n window.removeEventListener('pageshow', onPageShow)\n }\n}\n","/**\n * Shared types, tunables, environment helpers, and state utilities for ElementViewObserver.\n */\n\nimport { CAN_ADD_LISTENERS } from '../global-constants'\n\n/**\n * Timer handle type returned by `setTimeout`.\n */\nexport type Timer = ReturnType<typeof setTimeout>\n\n/**\n * Interval handle type returned by `setInterval`.\n */\nexport type Interval = ReturnType<typeof setInterval>\n\n/**\n * Get a high-resolution timestamp when available.\n *\n * @returns A timestamp in milliseconds since an arbitrary origin.\n */\nexport const NOW = (): number =>\n typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now()\n\n/**\n * Determine whether the current page is visible.\n *\n * @returns `true` if the page is visible or no document is available, otherwise `false`.\n */\nexport const isPageVisible = (): boolean =>\n !CAN_ADD_LISTENERS ? true : document.visibilityState === 'visible'\n\n/** ---- Tunables ---- */\n\n/**\n * Default tuning values for {@link ElementViewObserver}.\n */\nexport const DEFAULTS = {\n /** Default dwell time in ms before firing. */\n DWELL_MS: 1000,\n /** Default minimum intersection ratio considered visible. */\n RATIO: 0.1,\n /** Default maximum retry attempts. */\n MAX_RETRIES: 2,\n /** Default initial backoff delay for retries in ms. */\n BACKOFF_MS: 300,\n /** Default exponential backoff multiplier. */\n MULTIPLIER: 2,\n /** Divisor used to compute jitter magnitude. */\n JITTER_DIVISOR: 2,\n /** Interval for sweeping orphaned states in ms. */\n SWEEP_INTERVAL_MS: 30000,\n} as const\n\n/**\n * Add small random jitter to a base delay to reduce thundering herd effects.\n *\n * @param base - Base delay in ms.\n * @returns Jittered delay in ms.\n */\nexport const withJitter = (base: number): number =>\n base + Math.floor(Math.random() * Math.max(1, Math.floor(base / DEFAULTS.JITTER_DIVISOR)))\n\n/** ---- Public Types ---- */\n\n/**\n * Information passed to the element view callback.\n */\nexport interface ElementViewCallbackInfo {\n /** Total number of milliseconds the element has been visible. */\n readonly totalVisibleMs: number\n /** How many attempts have been made (including the current one). */\n readonly attempts: number\n /** Optional user data associated with the element. */\n readonly data?: unknown\n}\n\n/**\n * Callback invoked once per element after the dwell requirement is met,\n * with retries on failure.\n */\nexport type ElementViewCallback = (\n element: Element,\n info: ElementViewCallbackInfo,\n) => void | Promise<void>\n\n/**\n * Observer-level options that apply to all observed elements.\n */\nexport interface ElementViewObserverOptions {\n /** Required visible time (in ms) before the callback is fired. */\n readonly dwellTimeMs?: number\n /** Minimum intersection ratio (0-1) considered visible. */\n readonly minVisibleRatio?: number\n /** IntersectionObserver root. Default: null (viewport). */\n readonly root?: Element | Document | null\n /** IntersectionObserver rootMargin. Default: `\"0px\"`. */\n readonly rootMargin?: string\n /** Max callback retry attempts on failure. */\n readonly maxRetries?: number\n /** Initial backoff delay in ms for retries. */\n readonly retryBackoffMs?: number\n /** Exponential backoff multiplier. */\n readonly backoffMultiplier?: number\n}\n\n/**\n * Per-element overrides and data passed to the callback.\n */\nexport interface ElementViewElementOptions {\n /** Per-element dwell time override in ms. */\n readonly dwellTimeMs?: number\n /** Per-element optional max callback retry attempts on failures. */\n readonly maxRetries?: number\n /** Per-element optional initial backoff delay in ms for retrie. */\n readonly retryBackoffMs?: number\n /** Per-element optional exponential backoff multiplier. */\n readonly backoffMultiplier?: number\n /** Arbitrary data to pass through to the callback for this element. */\n readonly data?: unknown\n /**\n * NOTE: minVisibleRatio is intentionally NOT supported per-element because\n * IntersectionObserver thresholds are configured per observer instance.\n * Use a separate observer if you need different ratio thresholds.\n */\n}\n\n/** ---- Effective internal option shapes ---- */\n\n/**\n * Fully-resolved observer-level options used internally.\n */\nexport type EffectiveObserverOptions = Required<\n Pick<\n ElementViewObserverOptions,\n | 'dwellTimeMs'\n | 'minVisibleRatio'\n | 'root'\n | 'rootMargin'\n | 'maxRetries'\n | 'retryBackoffMs'\n | 'backoffMultiplier'\n >\n>\n\n/**\n * Fully-resolved per-element overrides used internally.\n */\nexport type PerElementEffectiveOptions = Required<\n Pick<\n EffectiveObserverOptions,\n 'dwellTimeMs' | 'maxRetries' | 'retryBackoffMs' | 'backoffMultiplier'\n >\n>\n\n/**\n * Internal per-element state tracked by the observer.\n */\nexport interface ElementState {\n /** WeakRef path (modern browsers). */\n ref: WeakRef<Element> | null\n /** Strong reference fallback if WeakRef is unavailable. */\n strongRef: Element | null\n /** Effective per-element options. */\n opts: PerElementEffectiveOptions\n /** User data associated with the element. */\n data?: unknown\n /** Accumulated visible time in ms. */\n accumulatedMs: number\n /** Timestamp when the element became visible, or null if not currently visible. */\n visibleSince: number | null\n /** Timer handle for firing the callback after dwell time. */\n fireTimer: Timer | null\n /** Timer handle for scheduled retry. */\n retryTimer: Timer | null\n /** Timestamp when retry was scheduled. */\n retryScheduledAt: number | null\n /** Delay used for the current retry. */\n retryDelayMs: number | null\n /** True if a retry is pending but not yet scheduled. */\n pendingRetry: boolean\n /** Number of attempts performed so far. */\n attempts: number\n /** True once the callback has succeeded or retries are exhausted. */\n done: boolean\n /** True while a callback attempt is in flight. */\n inFlight: boolean\n /** Last known visibility state for the element. */\n lastKnownVisible: boolean\n}\n\n/**\n * Small numeric sanitizers.\n */\nexport const Num = {\n /** Use the provided number or fall back when the value is not numeric. */\n n: (value: unknown, fallback: number): number => (typeof value === 'number' ? value : fallback),\n /** Clamp a value to the [0, 1] range. */\n clamp01: (value: number | undefined, fallback: number): number =>\n Math.min(1, Math.max(0, Num.n(value, fallback))),\n /** Ensure a non-negative value. */\n nonNeg: (value: number | undefined, fallback: number): number =>\n Math.max(0, Num.n(value, fallback)),\n /** Ensure a value of at least 1. */\n atLeast1: (value: number | undefined, fallback: number): number =>\n Math.max(1, Num.n(value, fallback)),\n}\n\n/**\n * Clear a scheduled fire timer, if present.\n *\n * @param state - Element state whose fire timer should be cleared.\n */\nexport const clearFireTimer = (state: ElementState): void => {\n if (state.fireTimer !== null) {\n clearTimeout(state.fireTimer)\n state.fireTimer = null\n }\n}\n\n/**\n * Cancel a scheduled retry timer, if present.\n *\n * @param state - Element state whose retry timer should be cleared.\n */\nexport const cancelRetry = (state: ElementState): void => {\n if (state.retryTimer !== null) {\n clearTimeout(state.retryTimer)\n state.retryTimer = null\n }\n state.retryScheduledAt = null\n}\n\n/**\n * Dereference the element, honoring WeakRef when available.\n *\n * @param state - Element state containing refs.\n * @returns The underlying element or `null` if no longer available.\n */\nexport const derefElement = (state: ElementState): Element | null => {\n if (state.ref && typeof state.ref.deref === 'function') {\n const element = state.ref.deref()\n if (element) return element\n }\n return state.strongRef ?? null\n}\n","/**\n * ElementExistenceObserver\n * - Observes childList + subtree\n * - Coalesces moves (reparent/reorder ignored)\n * - Filters to Element (for IntersectionObserver)\n * - Batches & chunks delivery in idle time\n * - Two optional per-kind callbacks + one aggregate callback\n */\n\nimport { CAN_ADD_LISTENERS } from '../global-constants'\n\n/**\n * Default idle timeout (in milliseconds) used when scheduling processing\n * of mutation records.\n */\nexport const DEFAULT_IDLE_TIMEOUT_MS = 100\n\n/**\n * Default maximum number of elements delivered in a single callback chunk.\n */\nexport const DEFAULT_MAX_CHUNK = 250\n\n/**\n * Lower bound for idle timeout to avoid ultra-tight loops (~1 animation frame).\n */\nexport const MIN_IDLE_TIMEOUT_MS = 16 // ~1 frame\n\n/**\n * Lower bound for maximum chunk size (must deliver at least one element).\n */\nexport const MIN_MAX_CHUNK = 1\n\n/**\n * True when the environment supports `MutationObserver` and can add listeners.\n */\nexport const HAS_MUTATION_OBSERVER = CAN_ADD_LISTENERS && typeof MutationObserver !== 'undefined'\n\n/**\n * True when the environment supports `window.requestIdleCallback`.\n */\nexport const HAS_IDLE_CALLBACK =\n CAN_ADD_LISTENERS && typeof window.requestIdleCallback === 'function'\n\n/**\n * True when the environment supports `window.cancelIdleCallback`.\n */\nexport const HAS_CANCEL_IDLE = CAN_ADD_LISTENERS && typeof window.cancelIdleCallback === 'function'\n\n/**\n * Aggregate description of changes observed in a batch of mutation records.\n */\nexport interface MutationChange {\n /** Set of elements that were added. */\n readonly added: ReadonlySet<Element>\n /** Set of elements that were removed. */\n readonly removed: ReadonlySet<Element>\n /** Raw mutation records that produced this change. */\n readonly records: readonly MutationRecord[]\n}\n\n/**\n * Callback invoked when elements have been added.\n */\nexport type AddedCallback = (elements: readonly Element[]) => unknown\n\n/**\n * Callback invoked when elements have been removed.\n */\nexport type RemovedCallback = (elements: readonly Element[]) => unknown\n\n/**\n * Callback invoked when a batch of mutation records has been coalesced.\n */\nexport type MutationChangeCallback = (change: MutationChange) => unknown\n\n/**\n * Options for configuring {@link ElementExistenceObserver}.\n */\nexport interface ElementExistenceObserverOptions {\n /**\n * Root node to observe for changes. Defaults to `document` where possible.\n */\n readonly root?: Node\n /**\n * Idle timeout in milliseconds used when scheduling processing of mutations.\n */\n readonly idleTimeoutMs?: number\n /**\n * Maximum number of elements delivered per callback chunk.\n */\n readonly maxChunk?: number\n /**\n * Callback invoked with the aggregate change payload (added/removed plus raw records).\n */\n readonly onChange?: MutationChangeCallback\n /**\n * Callback invoked with per-kind additions (batched/chunked).\n */\n readonly onAdded?: AddedCallback\n /**\n * Callback invoked with per-kind removals (batched/chunked).\n */\n readonly onRemoved?: RemovedCallback\n /**\n * Optional error handler for callback failures.\n */\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * Observe the existence of elements under a root node and deliver coalesced\n * add/remove notifications in idle time.\n *\n * @remarks\n * In non-DOM / SSR environments, the observer becomes a safe no-op, and\n * mutation handling is disabled.\n */\nclass ElementExistenceObserver {\n private readonly observer?: MutationObserver\n\n private readonly root: Node | null\n private readonly idleTimeoutMs: number\n private readonly maxChunk: number\n\n private readonly onChange?: MutationChangeCallback\n private readonly onAdded?: AddedCallback\n private readonly onRemoved?: RemovedCallback\n private readonly onError?: (error: unknown) => void\n\n private pendingRecords: MutationRecord[] = []\n private scheduled = false\n private idleHandle: number | null = null\n private disconnected = false\n\n /**\n * Create a new element existence observer.\n *\n * @param options - Optional configuration for root, callbacks, and batching.\n */\n public constructor(options: ElementExistenceObserverOptions = {}) {\n const {\n root,\n idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,\n maxChunk = DEFAULT_MAX_CHUNK,\n onChange,\n onAdded,\n onRemoved,\n onError,\n } = options\n\n this.root = ElementExistenceObserver.isNode(root) ? root : CAN_ADD_LISTENERS ? document : null\n\n this.idleTimeoutMs = ElementExistenceObserver.sanitizeInt(\n idleTimeoutMs,\n DEFAULT_IDLE_TIMEOUT_MS,\n MIN_IDLE_TIMEOUT_MS,\n )\n this.maxChunk = ElementExistenceObserver.sanitizeInt(maxChunk, DEFAULT_MAX_CHUNK, MIN_MAX_CHUNK)\n\n this.onChange = onChange\n this.onAdded = onAdded\n this.onRemoved = onRemoved\n this.onError = onError\n\n if (HAS_MUTATION_OBSERVER && this.root) {\n this.observer = new MutationObserver((records) => {\n for (const record of records) {\n if (record.addedNodes.length > 0 || record.removedNodes.length > 0) {\n this.pendingRecords.push(record)\n }\n }\n if (this.pendingRecords.length > 0) this.scheduleProcess()\n })\n\n this.observer.observe(this.root, {\n childList: true,\n subtree: true,\n })\n }\n // Else: SSR / non-DOM env — stay dormant; methods become safe no-ops.\n }\n\n /**\n * True if the watcher is actively observing (i.e., in a browser with MutationObserver).\n */\n public isActive(): boolean {\n return !!this.observer && !this.disconnected\n }\n\n /**\n * Stop observing and clear any pending work.\n */\n public disconnect(): void {\n if (this.disconnected) return\n this.disconnected = true\n\n this.observer?.disconnect()\n this.pendingRecords = []\n\n if (this.idleHandle !== null) {\n ElementExistenceObserver.cancelIdle(this.idleHandle)\n this.idleHandle = null\n }\n this.scheduled = false\n }\n\n /**\n * Synchronously process any pending mutation records.\n *\n * @remarks\n * Cancels any outstanding idle callbacks or timeouts and delivers changes immediately.\n */\n public flush(): void {\n if (!this.isActive()) return\n\n if (this.idleHandle !== null) {\n ElementExistenceObserver.cancelIdle(this.idleHandle)\n this.idleHandle = null\n }\n if (!this.scheduled && this.pendingRecords.length === 0) return\n\n this.scheduled = false\n this.processNow()\n }\n\n /**\n * Schedule processing of pending records using idle time or a timeout.\n */\n private scheduleProcess(): void {\n if (!this.isActive() || this.scheduled) return\n this.scheduled = true\n\n const run = (): void => {\n this.idleHandle = null\n this.scheduled = false\n this.processNow()\n }\n\n this.idleHandle = HAS_IDLE_CALLBACK\n ? window.requestIdleCallback(run, { timeout: this.idleTimeoutMs })\n : window.setTimeout(run, this.idleTimeoutMs)\n }\n\n /**\n * Process all currently pending mutation records immediately.\n */\n private processNow(): void {\n if (!this.isActive() || this.pendingRecords.length === 0) return\n\n const records = this.drainPending()\n const { addedNodes, removedNodes } = ElementExistenceObserver.coalesce(records)\n const { added, removed } = ElementExistenceObserver.toElementSets(addedNodes, removedNodes)\n\n if (added.size === 0 && removed.size === 0) return\n\n this.deliverAggregate(added, removed, records)\n this.deliverPerKind(removed, added) // removals first, then additions\n }\n\n /**\n * Narrow a value to `Node` when the DOM is available.\n */\n private static isNode(value: unknown): value is Node {\n return CAN_ADD_LISTENERS && typeof Node !== 'undefined' && value instanceof Node\n }\n\n /**\n * Normalize a numeric option to a finite integer and enforce a minimum.\n */\n private static sanitizeInt(value: unknown, fallback: number, min: number): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return fallback\n const truncated = Math.trunc(value)\n return truncated >= min ? truncated : min\n }\n\n /**\n * Coalesce a set of mutation records into net added and removed nodes,\n * ignoring transient moves.\n */\n private static coalesce(records: readonly MutationRecord[]): {\n addedNodes: Set<Node>\n removedNodes: Set<Node>\n } {\n const addedNodes = new Set<Node>()\n const removedNodes = new Set<Node>()\n\n for (const record of records) {\n for (const node of record.addedNodes) {\n if (removedNodes.delete(node)) continue // move\n addedNodes.add(node)\n }\n for (const node of record.removedNodes) {\n if (addedNodes.delete(node)) continue // move\n removedNodes.add(node)\n }\n }\n return { addedNodes, removedNodes }\n }\n\n /**\n * Convert node-level sets into element-only sets, including descendants.\n */\n private static toElementSets(\n addedNodes: ReadonlySet<Node>,\n removedNodes: ReadonlySet<Node>,\n ): { added: Set<Element>; removed: Set<Element> } {\n const added = ElementExistenceObserver.flattenElements(addedNodes, true)\n const removed = ElementExistenceObserver.flattenElements(removedNodes, false)\n return { added, removed }\n }\n\n /**\n * Collect all elements (and descendants) from a set of nodes, optionally\n * filtering out disconnected nodes.\n */\n private static flattenElements(\n nodes: ReadonlySet<Node>,\n requireConnected: boolean,\n ): Set<Element> {\n const out = new Set<Element>()\n\n for (const node of nodes) {\n // If the node itself is an Element, include it\n if (node instanceof Element) {\n if (!requireConnected || node.isConnected) out.add(node)\n // Include all descendant elements\n node.querySelectorAll('*').forEach((el) => {\n if (!requireConnected || el.isConnected) out.add(el)\n })\n continue\n }\n\n // If it's a DocumentFragment (e.g., from templating), include its descendants\n if (node instanceof DocumentFragment) {\n node.querySelectorAll('*').forEach((el) => {\n if (!requireConnected || el.isConnected) out.add(el)\n })\n }\n }\n\n return out\n }\n\n /**\n * Cancel a previously scheduled idle callback or fallback timeout.\n */\n private static cancelIdle(handle: number): void {\n if (HAS_CANCEL_IDLE) {\n window.cancelIdleCallback(handle)\n } else if (CAN_ADD_LISTENERS) {\n window.clearTimeout(handle)\n }\n }\n\n /**\n * Drain and return the current list of pending mutation records.\n */\n private drainPending(): MutationRecord[] {\n const { pendingRecords: out } = this\n this.pendingRecords = []\n return out\n }\n\n /**\n * Deliver the aggregate change payload (added, removed, records) to the\n * `onChange` callback if configured.\n */\n private deliverAggregate(\n added: ReadonlySet<Element>,\n removed: ReadonlySet<Element>,\n records: readonly MutationRecord[],\n ): void {\n if (!this.onChange) return\n const payload: MutationChange = { added, removed, records }\n this.safeCall(() => this.onChange?.(payload))\n }\n\n /**\n * Deliver per-kind added/removed elements to their respective callbacks in\n * chunks if necessary.\n */\n private deliverPerKind(removed: ReadonlySet<Element>, added: ReadonlySet<Element>): void {\n const removedArr = removed.size > 0 ? [...removed] : []\n const addedArr = added.size > 0 ? [...added] : []\n\n if (this.onRemoved && removedArr.length > 0) {\n this.dispatchChunked(removedArr, this.onRemoved)\n }\n if (this.onAdded && addedArr.length > 0) {\n this.dispatchChunked(addedArr, this.onAdded)\n }\n }\n\n /**\n * Dispatch element arrays in chunks to respect the configured `maxChunk`\n * and avoid blocking the main thread.\n */\n private dispatchChunked(\n items: readonly Element[],\n fn: (chunk: readonly Element[]) => unknown,\n ): void {\n if (!this.isActive() || items.length === 0) return\n\n if (items.length <= this.maxChunk) {\n this.safeCall(() => fn(items))\n return\n }\n\n let index = 0\n const run = (): void => {\n if (!this.isActive()) return\n const end = Math.min(items.length, index + this.maxChunk)\n const chunk = items.slice(index, end)\n index = end\n\n this.safeCall(() => fn(chunk))\n\n if (index < items.length) {\n if (HAS_IDLE_CALLBACK) {\n window.requestIdleCallback(run, { timeout: this.idleTimeoutMs })\n } else if (CAN_ADD_LISTENERS) {\n window.setTimeout(run, this.idleTimeoutMs)\n }\n }\n }\n\n run()\n }\n\n /**\n * Normalize sync/async callbacks and centralize error handling.\n */\n private safeCall(invoke: () => unknown): void {\n try {\n const result = invoke()\n Promise.resolve(result).catch((error: unknown) => {\n this.onError?.(error)\n })\n } catch (error) {\n this.onError?.(error)\n }\n }\n}\n\nexport default ElementExistenceObserver\n","/**\n * IntersectionObserver that:\n * - Tracks cumulative visible time per element\n * - Fires a sync/async callback exactly once per observed element\n * - Retries on failure with exponential backoff (retry scope is per \"visibility cycle\")\n * - Pauses when the page/tab is hidden; resumes cleanly\n * - Coalesces retries to avoid duplicate concurrent attempts\n * - Supports per-element overrides and optional data on observe()\n * - Periodically sweeps orphaned states to prevent memory growth\n *\n * Assumes DOM environment (browser).\n */\n\nimport { CAN_ADD_LISTENERS } from '../global-constants'\nimport {\n DEFAULTS,\n type EffectiveObserverOptions,\n type ElementState,\n type ElementViewCallback,\n type ElementViewElementOptions,\n type ElementViewObserverOptions,\n type Interval,\n NOW,\n Num,\n type PerElementEffectiveOptions,\n cancelRetry,\n clearFireTimer,\n derefElement,\n isPageVisible,\n withJitter,\n} from './ElementView'\n\n/**\n * Observes elements for dwell time and triggers the callback (with retries)\n * once per element.\n *\n * @remarks\n * Uses IntersectionObserver under the hood and maintains per-element state to\n * track visibility, accumulated dwell time, and retry scheduling.\n */\nclass ElementViewObserver {\n private readonly callback: ElementViewCallback\n private readonly opts: EffectiveObserverOptions\n private readonly io: IntersectionObserver\n private readonly states = new WeakMap<Element, ElementState>()\n private readonly activeStates = new Set<ElementState>()\n private boundVisibilityHandler: (() => void) | null = null\n private sweepInterval: Interval | null = null\n\n /**\n * Create a new element view observer.\n *\n * @param callback - Callback invoked once per element when dwell/visibility\n * requirements are met.\n * @param options - Optional observer-level tuning options.\n */\n public constructor(callback: ElementViewCallback, options?: ElementViewObserverOptions) {\n this.callback = callback\n this.opts = ElementViewObserver.initOptions(options)\n this.io = new IntersectionObserver(\n (entries) => {\n this.onIntersect(entries)\n },\n {\n root: this.opts.root ?? null,\n rootMargin: this.opts.rootMargin,\n threshold: this.opts.minVisibleRatio === 0 ? [0] : [0, this.opts.minVisibleRatio],\n },\n )\n if (CAN_ADD_LISTENERS) {\n this.boundVisibilityHandler = () => {\n this.onPageVisibilityChange()\n }\n document.addEventListener('visibilitychange', this.boundVisibilityHandler)\n }\n }\n\n /**\n * Observe an element with optional per-element overrides and data.\n *\n * @param element - Element to observe.\n * @param options - Optional per-element overrides and callback data.\n */\n public observe(element: Element, options?: ElementViewElementOptions): void {\n let state = this.states.get(element)\n if (!state) {\n state = this.createState(element, options)\n this.states.set(element, state)\n this.activeStates.add(state)\n this.ensureSweeper()\n }\n this.io.observe(element)\n }\n\n /**\n * Stop observing an element and release its state and timers.\n *\n * @param element - Element to stop observing.\n */\n public unobserve(element: Element): void {\n this.io.unobserve(element)\n const state = this.states.get(element)\n if (!state) return\n clearFireTimer(state)\n cancelRetry(state)\n state.done = true\n this.activeStates.delete(state)\n if (state.strongRef === element) state.strongRef = null\n this.states.delete(element)\n this.maybeStopSweeper()\n }\n\n /**\n * Disconnect the underlying IntersectionObserver and clear all state.\n */\n public disconnect(): void {\n this.io.disconnect()\n for (const s of this.activeStates) {\n clearFireTimer(s)\n cancelRetry(s)\n s.done = true\n s.strongRef = null\n }\n this.activeStates.clear()\n if (CAN_ADD_LISTENERS && this.boundVisibilityHandler) {\n document.removeEventListener('visibilitychange', this.boundVisibilityHandler)\n this.boundVisibilityHandler = null\n }\n this.stopSweeper()\n }\n\n /**\n * Lightweight, readonly stats snapshot for a given element.\n *\n * @param element - Element for which to retrieve stats.\n * @returns A subset of {@link ElementState} or `null` if no state is tracked.\n */\n public getStats(\n element: Element,\n ): Readonly<\n Pick<\n ElementState,\n | 'accumulatedMs'\n | 'visibleSince'\n | 'attempts'\n | 'done'\n | 'inFlight'\n | 'pendingRetry'\n | 'lastKnownVisible'\n >\n > | null {\n const state = this.states.get(element)\n return state\n ? {\n accumulatedMs: state.accumulatedMs,\n visibleSince: state.visibleSince,\n attempts: state.attempts,\n done: state.done,\n inFlight: state.inFlight,\n pendingRetry: state.pendingRetry,\n lastKnownVisible: state.lastKnownVisible,\n }\n : null\n }\n\n /**\n * Normalize high-level observer options into an effective configuration.\n */\n private static initOptions(options?: ElementViewObserverOptions): EffectiveObserverOptions {\n return {\n dwellTimeMs: Num.nonNeg(options?.dwellTimeMs, DEFAULTS.DWELL_MS),\n minVisibleRatio: Num.clamp01(options?.minVisibleRatio, DEFAULTS.RATIO),\n root: options?.root ?? null,\n rootMargin: options?.rootMargin ?? '0px',\n maxRetries: Num.nonNeg(options?.maxRetries, DEFAULTS.MAX_RETRIES),\n retryBackoffMs: Num.nonNeg(options?.retryBackoffMs, DEFAULTS.BACKOFF_MS),\n backoffMultiplier: Num.atLeast1(options?.backoffMultiplier, DEFAULTS.MULTIPLIER),\n }\n }\n\n /**\n * Create a new per-element state object using observer defaults and any\n * per-element overrides.\n */\n private createState(element: Element, options?: ElementViewElementOptions): ElementState {\n const opts: PerElementEffectiveOptions = {\n dwellTimeMs: Num.nonNeg(options?.dwellTimeMs, this.opts.dwellTimeMs),\n maxRetries: Num.nonNeg(options?.maxRetries, this.opts.maxRetries),\n retryBackoffMs: Num.nonNeg(options?.retryBackoffMs, this.opts.retryBackoffMs),\n backoffMultiplier: Num.atLeast1(options?.backoffMultiplier, this.opts.backoffMultiplier),\n }\n const hasWeakRef = typeof WeakRef === 'function'\n return {\n ref: hasWeakRef ? new WeakRef(element) : null,\n strongRef: hasWeakRef ? null : element,\n opts,\n data: options?.data,\n accumulatedMs: 0,\n visibleSince: null,\n fireTimer: null,\n retryTimer: null,\n retryScheduledAt: null,\n retryDelayMs: null,\n pendingRetry: false,\n attempts: 0,\n done: false,\n inFlight: false,\n lastKnownVisible: false,\n }\n }\n\n /**\n * Handle page visibility changes by pausing/resuming timers and retries.\n */\n private onPageVisibilityChange(): void {\n const now = NOW()\n const hidden = !isPageVisible()\n for (const state of this.activeStates) {\n if (hidden) {\n ElementViewObserver.onHidden(state, now)\n } else {\n this.onResume(state, now)\n }\n }\n this.sweepOrphans()\n }\n\n /**\n * Update a state in response to the page becoming hidden.\n *\n * @remarks\n * Freezes dwell time accumulation and converts any active retry into a\n * pending retry with remaining delay.\n */\n private static onHidden(state: ElementState, now: number): void {\n if (state.done) return\n if (state.visibleSince !== null) {\n state.accumulatedMs += now - state.visibleSince\n state.visibleSince = null\n }\n clearFireTimer(state)\n if (state.retryTimer !== null) {\n const elapsed = state.retryScheduledAt ? now - state.retryScheduledAt : 0\n const remaining =\n state.retryDelayMs !== null ? Math.max(0, state.retryDelayMs - elapsed) : null\n cancelRetry(state)\n if (remaining !== null) {\n state.pendingRetry = true\n state.retryDelayMs = remaining\n state.retryScheduledAt = null\n }\n }\n }\n\n /**\n * Update a state in response to the page becoming visible again.\n */\n private onResume(state: ElementState, now: number): void {\n if (state.done) return\n if (state.lastKnownVisible && state.visibleSince === null) {\n state.visibleSince = now\n this.scheduleFireIfDue(state, now)\n }\n if (\n state.pendingRetry &&\n !state.inFlight &&\n state.lastKnownVisible &&\n state.retryDelayMs !== null\n ) {\n this.scheduleRetry(state, state.retryDelayMs)\n }\n }\n\n /**\n * Handle IntersectionObserver notifications and update per-element\n * visibility state.\n */\n private onIntersect(entries: readonly IntersectionObserverEntry[]): void {\n const now = NOW()\n for (const entry of entries) {\n const state = this.states.get(entry.target)\n if (!state || state.done) continue\n const visible =\n entry.isIntersecting &&\n entry.intersectionRatio >= this.opts.minVisibleRatio &&\n isPageVisible()\n visible ? this.onVisible(state, now) : ElementViewObserver.onNotVisible(state, now)\n }\n this.sweepOrphans()\n }\n\n /**\n * Mark a state as visible and schedule the callback if dwell time is met.\n */\n private onVisible(state: ElementState, now: number): void {\n state.lastKnownVisible = true\n if (state.visibleSince === null) {\n state.visibleSince = now\n state.attempts = 0\n if (state.pendingRetry && !state.inFlight && state.retryDelayMs !== null) {\n this.scheduleRetry(state, state.retryDelayMs)\n } else {\n this.scheduleFireIfDue(state, now)\n }\n return\n }\n if (!state.pendingRetry && state.fireTimer === null && !state.inFlight) {\n this.scheduleFireIfDue(state, now)\n }\n }\n\n /**\n * Mark a state as not visible and cancel any scheduled callback or retry.\n */\n private static onNotVisible(state: ElementState, now: number): void {\n state.lastKnownVisible = false\n if (state.visibleSince !== null) {\n state.accumulatedMs += now - state.visibleSince\n state.visibleSince = null\n }\n clearFireTimer(state)\n if (state.pendingRetry || state.retryTimer !== null) {\n cancelRetry(state)\n state.pendingRetry = false\n state.attempts = 0\n }\n }\n\n /**\n * Schedule firing of the callback when the remaining dwell requirement is met,\n * if appropriate for the current state.\n */\n private scheduleFireIfDue(state: ElementState, now: number): void {\n if (state.done || state.inFlight || state.fireTimer !== null || state.pendingRetry) return\n const elapsed =\n state.accumulatedMs + (state.visibleSince !== null ? now - state.visibleSince : 0)\n const remaining = state.opts.dwellTimeMs - elapsed\n if (remaining <= 0) {\n this.trigger(state)\n return\n }\n state.fireTimer = setTimeout(() => {\n if (!state.done && state.lastKnownVisible && isPageVisible()) this.trigger(state)\n else clearFireTimer(state)\n }, Math.ceil(remaining))\n }\n\n /**\n * Schedule a retry attempt after a delay, if the element is currently visible.\n */\n private scheduleRetry(state: ElementState, delayMs: number): void {\n state.pendingRetry = true\n state.retryDelayMs = Math.max(0, Math.ceil(delayMs))\n if (!isPageVisible() || !state.lastKnownVisible || state.done || state.inFlight) return\n state.retryScheduledAt = NOW()\n state.retryTimer = setTimeout(() => {\n state.retryTimer = null\n state.retryScheduledAt = null\n void this.attemptCallback(state)\n }, state.retryDelayMs)\n }\n\n /**\n * Immediately attempt to fire the callback for a state and record the\n * total dwell time used for this attempt.\n */\n private trigger(state: ElementState): void {\n if (state.done || state.inFlight) return\n const now = NOW()\n const total = state.accumulatedMs + (state.visibleSince !== null ? now - state.visibleSince : 0)\n cancelRetry(state)\n state.pendingRetry = false\n clearFireTimer(state)\n void this.attemptCallback(state, total)\n }\n\n /**\n * Perform a single callback attempt for a state, handling success or failure.\n *\n * @param state - State to attempt the callback for.\n * @param preTotal - Optional precomputed dwell time in ms.\n */\n private async attemptCallback(state: ElementState, preTotal?: number): Promise<void> {\n if (state.done || state.inFlight) return\n const element = derefElement(state)\n if (!element) {\n this.finalizeDroppedState(state)\n return\n }\n const attempt = state.attempts + 1\n state.attempts = attempt\n state.inFlight = true\n const totalVisibleMs =\n preTotal ??\n state.accumulatedMs + (state.visibleSince !== null ? NOW() - state.visibleSince : 0)\n try {\n await this.callback(element, { totalVisibleMs, attempts: attempt, data: state.data })\n this.onAttemptSuccess(state, element)\n } catch {\n this.onAttemptFailure(state)\n }\n }\n\n /**\n * Handle a successful callback attempt by marking the state as done and\n * unobserving the element.\n */\n private onAttemptSuccess(state: ElementState, element: Element): void {\n state.inFlight = false\n state.done = true\n this.safeAutoUnobserve(element, state)\n }\n\n /**\n * Handle a failed callback attempt by either scheduling another retry or\n * marking the state as exhausted.\n */\n private onAttemptFailure(state: ElementState): void {\n state.inFlight = false\n if (state.attempts > state.opts.maxRetries) {\n this.onRetriesExceeded(state)\n return\n }\n const base =\n state.opts.retryBackoffMs * Math.pow(state.opts.backoffMultiplier, state.attempts - 1)\n const delay = withJitter(base)\n if (!state.lastKnownVisible || !isPageVisible()) {\n state.pendingRetry = true\n state.retryDelayMs = Math.ceil(delay)\n state.retryScheduledAt = null\n return\n }\n this.scheduleRetry(state, delay)\n }\n\n /**\n * Handle the case where the maximum number of retries has been exceeded.\n */\n private onRetriesExceeded(state: ElementState): void {\n cancelRetry(state)\n state.pendingRetry = false\n state.done = true\n const element = derefElement(state)\n if (element) this.safeAutoUnobserve(element, state)\n else this.finalizeDroppedState(state)\n }\n\n /**\n * Finalize a state for an element that has been garbage-collected or otherwise\n * lost, ensuring timers are cleared and state maps are cleaned up.\n */\n private finalizeDroppedState(state: ElementState): void {\n clearFireTimer(state)\n cancelRetry(state)\n state.done = true\n this.activeStates.delete(state)\n if (state.strongRef) {\n this.states.delete(state.strongRef)\n state.strongRef = null\n }\n this.maybeStopSweeper()\n }\n\n /**\n * Attempt to unobserve an element and fall back to manual cleanup if an\n * error occurs.\n */\n private safeAutoUnobserve(element: Element, state: ElementState): void {\n try {\n this.unobserve(element)\n } catch {\n this.activeStates.delete(state)\n if (state.strongRef === element) {\n this.states.delete(element)\n state.strongRef = null\n }\n state.done = true\n this.maybeStopSweeper()\n }\n }\n\n /**\n * Ensure there is an active sweeper interval to clean up orphaned states.\n */\n private ensureSweeper(): void {\n if (this.sweepInterval !== null) return\n this.sweepInterval = setInterval(() => {\n this.sweepOrphans()\n }, DEFAULTS.SWEEP_INTERVAL_MS)\n }\n\n /**\n * Stop the sweeper interval if running.\n */\n private stopSweeper(): void {\n if (this.sweepInterval === null) return\n clearInterval(this.sweepInterval)\n this.sweepInterval = null\n }\n\n /**\n * Stop the sweeper interval when there are no active states left.\n */\n private maybeStopSweeper(): void {\n if (this.activeStates.size === 0) this.stopSweeper()\n }\n\n /**\n * Remove state for elements that are no longer present in the document or\n * whose references have been lost.\n */\n private sweepOrphans(): void {\n if (!CAN_ADD_LISTENERS) return\n for (const state of Array.from(this.activeStates)) {\n const element = derefElement(state)\n if (!element) {\n this.finalizeDroppedState(state)\n continue\n }\n const isConnected =\n typeof (element as Element & { isConnected?: boolean }).isConnected === 'boolean'\n ? (element as Element & { isConnected?: boolean }).isConnected\n : document.contains(element)\n if (!isConnected) this.safeAutoUnobserve(element, state)\n }\n this.maybeStopSweeper()\n }\n}\n\nexport default ElementViewObserver\n","import { ChangeArray, Profile, SelectedPersonalizationArray } from '@contentful/optimization-core'\nimport type { z } from 'zod/mini'\n\n/**\n * LocalStorage key for the anonymous identifier used by the Web SDK.\n *\n * @internal\n */\nexport const ANONYMOUS_ID = '__ctfl_opt_anonymous_id__'\n\n/**\n * LocalStorage key for the persisted consent status.\n *\n * @internal\n */\nexport const CONSENT = '__ctfl_opt_consent__'\n\n/**\n * LocalStorage key for cached Custom Flags.\n *\n * @internal\n */\nexport const CHANGES_CACHE = '__ctfl_opt_changes__'\n\n/**\n * LocalStorage key for the debug flag toggle.\n *\n * @internal\n */\nexport const DEBUG_FLAG = '__ctfl_opt_debug__'\n\n/**\n * LocalStorage key for cached profile data.\n *\n * @internal\n */\nexport const PROFILE_CACHE = '__ctfl_opt_profile__'\n\n/**\n * LocalStorage key for cached selected personalizations.\n *\n * @internal\n */\nexport const PERSONALIZATIONS_CACHE = '__ctfl_opt_personalizations__'\n\n/**\n * Local storage abstraction used by the Web SDK to persist optimization state.\n *\n * @internal\n * @remarks\n * Wraps browser `localStorage` access and uses zod parsers to safely read and\n * write typed values. All getters return `undefined` when no valid data is\n * present.\n */\nconst LocalStore = {\n /**\n * Reset local caches used by the Web SDK.\n *\n * @param options - Optional flags controlling whether consent and debug keys\n * should also be removed.\n * @example\n * ```ts\n * LocalStore.reset({ resetConsent: true, resetDebug: true })\n * ```\n */\n reset(options = { resetConsent: false, resetDebug: false }) {\n if (options.resetConsent) localStorage.removeItem(CONSENT)\n if (options.resetDebug) localStorage.removeItem(DEBUG_FLAG)\n\n localStorage.removeItem(ANONYMOUS_ID)\n localStorage.removeItem(CHANGES_CACHE)\n localStorage.removeItem(PROFILE_CACHE)\n localStorage.removeItem(PERSONALIZATIONS_CACHE)\n },\n\n /**\n * Anonymous identifier currently stored in localStorage, if any.\n */\n get anonymousId(): string | undefined {\n return localStorage.getItem(ANONYMOUS_ID) ?? undefined\n },\n\n /**\n * Set or clear the anonymous identifier.\n *\n * @param id - The new identifier, or `undefined` to clear it.\n */\n set anonymousId(id: string | undefined) {\n LocalStore.setCache(ANONYMOUS_ID, id)\n },\n\n /**\n * Persisted consent status.\n *\n * @returns `true` if consent was stored as `accepted`, `false` if stored as\n * `denied`, or `undefined` when no value is stored.\n */\n get consent(): boolean | undefined {\n const consent = localStorage.getItem(CONSENT)\n\n switch (consent) {\n case 'accepted':\n return true\n case 'denied':\n return false\n default:\n }\n },\n\n /**\n * Set or clear the persisted consent status.\n *\n * @param consent - `true` for accepted, `false` for denied, or `undefined`\n * to remove the stored value.\n */\n set consent(consent: boolean | undefined) {\n const translated = consent ? 'accepted' : 'denied'\n\n LocalStore.setCache(CONSENT, consent === undefined ? undefined : translated)\n },\n\n /**\n * Persisted debug flag value.\n *\n * @returns `true` or `false` when stored, or `undefined` otherwise.\n */\n get debug(): boolean | undefined {\n const debug = localStorage.getItem(DEBUG_FLAG)\n\n return debug ? debug === 'true' : undefined\n },\n\n /**\n * Set or clear the debug flag value.\n *\n * @param debug - New flag value or `undefined` to remove.\n */\n set debug(debug: boolean | undefined) {\n LocalStore.setCache(DEBUG_FLAG, debug)\n },\n\n /**\n * Cached Custom Flags change array, if present.\n */\n get changes(): ChangeArray | undefined {\n return LocalStore.getCache(CHANGES_CACHE, ChangeArray)\n },\n\n /**\n * Cache a new change array or clear it.\n *\n * @param changes - New changes to store, or `undefined` to remove.\n */\n set changes(changes: ChangeArray | undefined) {\n LocalStore.setCache(CHANGES_CACHE, changes)\n },\n\n /**\n * Cached profile from the personalization service, if present.\n */\n get profile(): Profile | undefined {\n return LocalStore.getCache(PROFILE_CACHE, Profile)\n },\n\n /**\n * Cache a new profile or clear it.\n *\n * @param profile - New profile to store, or `undefined` to remove.\n */\n set profile(profile: Profile | undefined) {\n LocalStore.setCache(PROFILE_CACHE, profile)\n },\n\n /**\n * Cached selected personalizations, if present.\n */\n get personalizations(): SelectedPersonalizationArray | undefined {\n return LocalStore.getCache(PERSONALIZATIONS_CACHE, SelectedPersonalizationArray)\n },\n\n /**\n * Cache new selected personalizations or clear them.\n *\n * @param personalizations - New selections to store, or `undefined` to remove.\n */\n set personalizations(personalizations: SelectedPersonalizationArray | undefined) {\n LocalStore.setCache(PERSONALIZATIONS_CACHE, personalizations)\n },\n\n /**\n * Safely read and parse typed data from localStorage.\n *\n * @typeParam T - Zod mini type describing the stored shape.\n * @param key - LocalStorage key to read from.\n * @param parser - Zod parser used to validate and parse the stored JSON.\n * @returns Parsed data when present and valid, otherwise `undefined`.\n */\n getCache<T extends z.ZodMiniType>(key: string, parser: T): z.output<T> | undefined {\n const cacheString = localStorage.getItem(key)\n\n if (!cacheString) return\n\n const parsedCache = parser.safeParse(JSON.parse(cacheString))\n\n if (parsedCache.success) return parsedCache.data\n },\n\n /**\n * Write arbitrary data to localStorage or remove the key when `undefined`.\n *\n * @param key - LocalStorage key to write to.\n * @param data - Value to store. Strings are written as-is; other values\n * are JSON-stringified.\n */\n setCache(key: string, data: unknown): void {\n if (data === undefined) {\n localStorage.removeItem(key)\n } else {\n localStorage.setItem(key, typeof data === 'string' ? data : JSON.stringify(data))\n }\n },\n}\n\nexport default LocalStore\n","import {\n type App,\n CoreStateful,\n type CoreStatefulConfig,\n createScopedLogger,\n effect,\n signals,\n} from '@contentful/optimization-core'\nimport { merge } from 'es-toolkit'\nimport Cookies from 'js-cookie'\nimport {\n createAutoTrackingEntryExistenceCallback,\n createAutoTrackingEntryViewCallback,\n isEntryElement,\n} from './AutoEntryViewTracking'\nimport { getLocale, getPageProperties, getUserAgent } from './builders'\nimport { ANONYMOUS_ID_COOKIE, OPTIMIZATION_WEB_SDK_VERSION } from './global-constants'\nimport {\n beaconHandler,\n createOnlineChangeListener,\n createVisibilityChangeListener,\n} from './handlers'\nimport {\n ElementExistenceObserver,\n type ElementViewElementOptions,\n ElementViewObserver,\n type ElementViewObserverOptions,\n} from './observers'\nimport { LocalStore } from './storage'\n\nconst logger = createScopedLogger('Web:SDK')\n\ndeclare global {\n interface Window {\n /** Global Optimization class constructor attached by the Web SDK. */\n Optimization?: typeof Optimization\n /** Singleton instance created by the Web SDK initializer. */\n optimization?: Optimization\n }\n}\n\ninterface CookieAttributes {\n domain?: string\n /**\n * Determines the expiration date of the cookie as the number of days until the cookie expires.\n */\n expires?: number\n}\n\nconst EXPIRATION_DAYS_DEFAULT = 365\n\n/**\n * Configuration options for the Optimization Web SDK.\n *\n * @public\n * @remarks\n * Extends {@link CoreStatefulConfig} with Web-specific options such as the\n * application descriptor and automatic entry view tracking.\n */\nexport interface OptimizationWebConfig extends CoreStatefulConfig {\n /**\n * Application metadata used to identify the Web app in downstream events.\n */\n app?: App\n\n /**\n * Whether the SDK should automatically track entry views based on DOM\n * attributes and observers.\n *\n * @defaultValue `false`\n */\n autoTrackEntryViews?: boolean\n\n cookie?: CookieAttributes\n}\n\n/**\n * Merge user-supplied Web configuration with sensible defaults for the\n * stateful core and browser environment.\n *\n * @param config - Incoming Web SDK configuration.\n * @returns A fully composed {@link CoreStatefulConfig} object.\n *\n * @internal\n * @remarks\n * This helper wires together:\n * - consent/profile/personalizations from LocalStore,\n * - Web-specific eventBuilder functions (locale, page, user agent),\n * - beacon-based analytics flushing,\n * - and anonymous ID retrieval.\n */\nfunction mergeConfig({\n app,\n defaults,\n logLevel,\n ...config\n}: OptimizationWebConfig): CoreStatefulConfig {\n const {\n consent = LocalStore.consent,\n profile = LocalStore.profile,\n changes = LocalStore.changes,\n personalizations = LocalStore.personalizations,\n } = defaults ?? {}\n\n return merge(\n {\n analytics: { beaconHandler },\n defaults: {\n consent,\n changes,\n profile,\n personalizations,\n },\n eventBuilder: {\n app,\n channel: 'web',\n library: { name: 'Optimization Web API', version: OPTIMIZATION_WEB_SDK_VERSION },\n getLocale,\n getPageProperties,\n getUserAgent,\n },\n getAnonymousId: () => LocalStore.anonymousId,\n logLevel: LocalStore.debug ? 'debug' : logLevel,\n },\n config,\n )\n}\n\n/**\n * Stateful Web SDK built on top of {@link CoreStateful}.\n *\n * @public\n * @remarks\n * Provides browser-specific wiring:\n * - automatic persistence of consent, profile, and personalizations,\n * - cookie-based anonymous ID handling,\n * - automatic entry view tracking via IntersectionObserver and MutationObserver,\n * - online-change based flushing of events,\n * - and visibility-change based flushing of events.\n *\n * A singleton instance is attached to `window.optimization` when constructed\n * in a browser environment.\n */\nclass Optimization extends CoreStateful {\n private elementViewObserver?: ElementViewObserver = undefined\n private elementExistenceObserver?: ElementExistenceObserver = undefined\n private autoTrackEntryViews = false\n private readonly cookieAttributes?: CookieAttributes = undefined\n\n /**\n * Create a new Optimization Web SDK instance.\n *\n * @param config - Web SDK configuration.\n *\n * @throws If an `Optimization` instance has already been initialized on\n * `window.optimization`.\n *\n * @example\n * ```ts\n * import Optimization from '@contentful/optimization-web'\n *\n * const optimization = new Optimization({\n * clientId: 'abc-123',\n * environment: 'main',\n * autoTrackEntryViews: true,\n * })\n * ```\n */\n constructor(config: OptimizationWebConfig) {\n if (typeof window !== 'undefined' && window.optimization)\n throw new Error('Optimization is already initialized')\n\n const { autoTrackEntryViews, ...restConfig } = config\n\n const mergedConfig: OptimizationWebConfig = mergeConfig(restConfig)\n\n super(mergedConfig)\n\n const cookieValue = Cookies.get(ANONYMOUS_ID_COOKIE)\n\n this.cookieAttributes = {\n domain: mergedConfig.cookie?.domain,\n expires: mergedConfig.cookie?.expires ?? EXPIRATION_DAYS_DEFAULT,\n }\n\n this.autoTrackEntryViews = true\n\n createOnlineChangeListener((isOnline) => {\n this.online(isOnline)\n })\n\n createVisibilityChangeListener(async () => {\n await this.flush()\n })\n\n effect(() => {\n const {\n changes: { value },\n } = signals\n\n LocalStore.changes = value\n })\n\n effect(() => {\n const {\n consent: { value },\n } = signals\n\n if (this.autoTrackEntryViews) {\n value ? this.startAutoTrackingEntryViews() : this.stopAutoTrackingEntryViews()\n }\n\n LocalStore.consent = value\n })\n\n effect(() => {\n const {\n profile: { value },\n } = signals\n\n LocalStore.profile = value\n this.setAnonymousId(value?.id)\n })\n\n effect(() => {\n const {\n personalizations: { value },\n } = signals\n\n LocalStore.personalizations = value\n })\n\n if (cookieValue && cookieValue !== LocalStore.anonymousId) {\n this.reset()\n this.setAnonymousId(cookieValue)\n }\n\n if (typeof window !== 'undefined') window.optimization ??= this\n }\n\n private setAnonymousId(value?: string): void {\n if (!value) {\n Cookies.remove(ANONYMOUS_ID_COOKIE)\n LocalStore.anonymousId = undefined\n return\n }\n Cookies.set(ANONYMOUS_ID_COOKIE, value, this.cookieAttributes)\n LocalStore.anonymousId = value\n }\n\n /**\n * Enable automatic entry view tracking for elements with `data-ctfl-*`\n * attributes and start observing the document.\n *\n * @param options - Optional per-element observer defaults for dwell time,\n * retries, and backoff behavior.\n *\n * @example\n * ```ts\n * optimization.startAutoTrackingEntryViews({ dwellTimeMs: 1000 })\n * ```\n */\n startAutoTrackingEntryViews(options?: ElementViewObserverOptions): void {\n this.autoTrackEntryViews = true\n\n this.elementViewObserver = new ElementViewObserver(createAutoTrackingEntryViewCallback(this))\n\n this.elementExistenceObserver = new ElementExistenceObserver(\n createAutoTrackingEntryExistenceCallback(this.elementViewObserver, true),\n )\n\n // Fully-automated observation for elements with ctfl data attributes\n const entries = document.querySelectorAll('[data-ctfl-entry-id]')\n\n entries.forEach((element) => {\n if (!isEntryElement(element)) return\n\n logger.info('Auto-observing element (init):', element)\n\n this.elementViewObserver?.observe(element, {\n ...options,\n })\n })\n }\n\n /**\n * Disable automatic entry view tracking and disconnect underlying observers.\n *\n * @example\n * ```ts\n * optimization.stopAutoTrackingEntryViews()\n * ```\n */\n stopAutoTrackingEntryViews(): void {\n this.elementExistenceObserver?.disconnect()\n this.elementViewObserver?.disconnect()\n }\n\n /**\n * Begin tracking entry views for a specific element, using the Web SDK’s\n * dwell-time and retry logic.\n *\n * @param element - Element to observe.\n * @param options - Per-element observer options and callback data.\n *\n * @example\n * ```ts\n * const element = document.querySelector('#hero')!\n * optimization.trackEntryViewForElement(element, {\n * dwellTimeMs: 1500,\n * data: { entryId: 'xyz' },\n * })\n * ```\n */\n trackEntryViewForElement(element: Element, options: ElementViewElementOptions): void {\n logger.info('Manually observing element:', element)\n this.elementViewObserver?.observe(element, options)\n }\n\n /**\n * Stop tracking entry views for a specific element.\n *\n * @param element - Element to stop observing.\n *\n * @example\n * ```ts\n * optimization.untrackEntryViewForElement(element)\n * ```\n */\n untrackEntryViewForElement(element: Element): void {\n logger.info('Manually unobserving element:', element)\n this.elementViewObserver?.unobserve(element)\n }\n\n /**\n * Reset all Web SDK state:\n * - stops auto-tracking entry views,\n * - clears the anonymous ID cookie,\n * - clears LocalStore caches,\n * - and delegates to {@link CoreStateful.reset} for underlying state reset.\n *\n * @example\n * ```ts\n * optimization.reset()\n * ```\n */\n reset(): void {\n this.stopAutoTrackingEntryViews()\n Cookies.remove(ANONYMOUS_ID_COOKIE)\n LocalStore.reset()\n super.reset()\n }\n}\n\nif (typeof window !== 'undefined') window.Optimization ??= Optimization\n\nexport default Optimization\n"],"names":["i","t","s","h","r","f","o","c","n","v","e","u","E","d","a","l","y","w","_","b","g","p","FlagsResolver","changes","acc","key","value","actualValue","$constructor","name","initializer","params","init","inst","def","_a","k","Parent","Definition","fn","$ZodAsyncError","$ZodEncodeError","globalConfig","config","newConfig","getEnumValues","entries","numericValues","jsonStringifyReplacer","cached","getter","nullish","input","cleanRegex","source","start","end","EVALUATING","defineLazy","object","assignProp","target","prop","mergeDefs","defs","mergedDescriptors","descriptors","captureStackTrace","_args","isObject","data","isPlainObject","ctor","prot","shallowClone","propertyKeyTypes","escapeRegex","str","clone","cl","normalizeParams","_params","optionalKeys","shape","extend","schema","checks","_shape","partial","Class","mask","oldShape","aborted","x","startIndex","prefixIssues","path","issues","iss","unwrapMessage","message","finalizeIssue","ctx","full","getLengthableOrigin","issue","args","util.jsonStringifyReplacer","$ZodError","$ZodRealError","_parse","_Err","_ctx","result","core.$ZodAsyncError","util.finalizeIssue","core.config","util.captureStackTrace","parse","errors.$ZodRealError","_parseAsync","parseAsync","_safeParse","errors.$ZodError","safeParse","_safeParseAsync","safeParseAsync","dateSource","timeSource","hhmm","datetime","time","opts","timeRegex","string","regex","number","boolean","_null","$ZodCheck","core.$constructor","$ZodCheckMinLength","payload","val","util.nullish","curr","origin","util.getLengthableOrigin","$ZodCheckLengthEquals","bag","length","tooBig","$ZodCheckStringFormat","_b","version","$ZodType","ch","runChecks","isAborted","util.aborted","asyncResult","currLen","handleCanaryResult","canary","checkResult","$ZodString","regexes.string","$ZodStringFormat","checks.$ZodCheckStringFormat","$ZodISODateTime","regexes.datetime","$ZodNumber","regexes.number","received","$ZodBoolean","regexes.boolean","$ZodNull","regexes.null","$ZodAny","$ZodUnknown","handleArrayResult","final","index","util.prefixIssues","$ZodArray","proms","item","handlePropertyResult","normalizeDef","keys","okeys","util.optionalKeys","handleCatchall","unrecognized","keySet","_catchall","$ZodObject","_normalized","util.cached","util.defineLazy","propValues","field","util.isObject","catchall","handleUnionResults","results","nonaborted","$ZodUnion","option","patterns","util.cleanRegex","single","first","async","$ZodDiscriminatedUnion","_super","pv","disc","map","values","opt","$ZodRecord","util.isPlainObject","keyResult","$ZodEnum","util.getEnumValues","valuesSet","util.propertyKeyTypes","util.escapeRegex","$ZodLiteral","$ZodTransform","core.$ZodEncodeError","_out","output","handleOptionalResult","$ZodOptional","pattern","$ZodNullable","$ZodPrefault","$ZodPipe","right","handlePipeResult","left","next","$ZodLazy","$ZodCustom","checks.$ZodCheck","handleRefineResult","_iss","util.issue","_string","util.normalizeParams","_isoDateTime","_number","_boolean","_any","_unknown","_minLength","minimum","checks.$ZodCheckMinLength","_length","checks.$ZodCheckLengthEquals","_custom","norm","ZodMiniType","core.$ZodType","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","_def","core.clone","reg","meta","ZodMiniString","core.$ZodString","core._string","ZodMiniStringFormat","core.$ZodStringFormat","ZodMiniNumber","core.$ZodNumber","core._number","ZodMiniBoolean","core.$ZodBoolean","core._boolean","ZodMiniNull","core.$ZodNull","core._null","ZodMiniAny","core.$ZodAny","any","core._any","ZodMiniUnknown","core.$ZodUnknown","unknown","core._unknown","ZodMiniArray","core.$ZodArray","array","element","ZodMiniObject","core.$ZodObject","util.assignProp","util.extend","util.partial","ZodMiniOptional","ZodMiniUnion","core.$ZodUnion","union","options","ZodMiniDiscriminatedUnion","core.$ZodDiscriminatedUnion","discriminatedUnion","discriminator","ZodMiniRecord","core.$ZodRecord","record","keyType","valueType","ZodMiniEnum","core.$ZodEnum","_enum","ZodMiniLiteral","core.$ZodLiteral","literal","ZodMiniTransform","core.$ZodTransform","transform","core.$ZodOptional","optional","innerType","ZodMiniNullable","core.$ZodNullable","nullable","ZodMiniPrefault","core.$ZodPrefault","prefault","defaultValue","util.shallowClone","ZodMiniPipe","core.$ZodPipe","pipe","in_","out","ZodMiniLazy","core.$ZodLazy","_lazy","ZodMiniCustom","core.$ZodCustom","custom","core._custom","json","jsonSchema","ZodMiniISODateTime","core.$ZodISODateTime","schemas.ZodMiniStringFormat","core._isoDateTime","EntryFields","z.catchall","z.object","z.json","Link","z.literal","z.string","ContentTypeLink","EnvironmentLink","SpaceLink","TagLink","EntrySys","z.number","z.any","z.optional","CtflEntry","z.array","isEntry","entry","AudienceEntryFields","z.extend","AudienceEntry","MergeTagEntry","EntryReplacementVariant","z.prefault","z.boolean","isEntryReplacementVariant","variant","EntryReplacementComponent","isEntryReplacementComponent","component","InlineVariableVariant","z.union","z.null","z.record","InlineVariableComponentValueType","z.enum","InlineVariableComponent","isInlineVariableComponent","PersonalizationComponent","z.discriminatedUnion","PersonalizationComponentArray","PersonalizationConfig","PersonalizationType","PersonalizationFields","z.nullable","z.pipe","z.transform","z.custom","PersonalizationEntry","isPersonalizationEntry","PersonalizationEntryArray","PersonalizedEntry","isPersonalizedEntry","App","Campaign","Channel","Dictionary","COUNTRY_CODE_LENGTH","Coordinates","GeoLocation","z.length","Library","Page","Properties","Screen","Traits","SessionStatistics","Profile","PartialProfile","ResponseEnvelope","BatchExperienceData","BatchExperienceResponse","ChangeType","ChangeBase","VariableChangeValue","UnknownChange","z.unknown","VariableChange","Change","ChangeArray","UniversalEventContext","UniversalEventProperties","z.iso.datetime","AliasEvent","ComponentViewEvent","GroupEvent","IdentifyEvent","PageEventContext","PageViewEvent","ScreenEventContext","ScreenViewEvent","TrackEvent","Anon","BatchExperienceEvent","BatchExperienceEventArray","ExperienceEvent","ExperienceEventArray","ExperienceRequestOptions","ExperienceRequestData","z.minLength","SelectedPersonalization","SelectedPersonalizationArray","ExperienceData","ExperienceResponse","InsightsEvent","InsightsEventArray","BatchInsightsEvent","BatchInsightsEventArray","Logger","diary","enable","logLocation","sink","existingSink","event","logger","createScopedLogger","location","LogSink","consoleMap","COMPARISON_EQUALITY","ConsoleLogSink","verbosity","compare","RetryOperation","timeouts","retry_operation","err","currentTime","timeout","self","timeoutOps","counts","mainError","mainErrorCount","error","count","require$$0","exports","attempt","random","obj","methods","method","original","op","callback","retry","objectToString","isError","errorMessages","isNetworkError","AbortError","decorateErrorWithCounts","attemptNumber","retriesLeft","pRetry","resolve","reject","operation","abortHandler","cleanUp","finalError","DEFAULT_INTERVAL_TIMEOUT","DEFAULT_RETRY_COUNT","RETRY_RESPONSE_STATUS","HTTP_ERROR_RESPONSE_STATUS","HttpError","status","createRetryFetchCallback","apiName","controller","fetchMethod","url","response","httpError","createRetryFetchMethod","intervalTimeout","onFailedAttempt","retries","retryResponse","DEFAULT_REQUEST_TIMEOUT","createTimeoutFetchMethod","onRequestTimeout","requestTimeout","id","createProtectedFetchMethod","timeoutFetchMethod","Fetch","DEFAULT_ENVIRONMENT","ApiClientBase","fetchOptions","clientId","environment","requestName","EXPERIENCE_BASE_URL","ExperienceApiClient","baseUrl","enabledFeatures","ip","locale","plainText","preflight","experiences","profile","body","events","profileId","profiles","headers","bodyOptions","INSIGHTS_BASE_URL","InsightsApiClient","beaconHandler","batches","ApiClient","personalization","analytics","apiConfig","noop","getSymbols","symbol","getTag","regexpTag","stringTag","numberTag","booleanTag","argumentsTag","symbolTag","dateTag","mapTag","setTag","arrayTag","functionTag","arrayBufferTag","objectTag","errorTag","dataViewTag","uint8ArrayTag","uint8ClampedArrayTag","uint16ArrayTag","uint32ArrayTag","bigUint64ArrayTag","int8ArrayTag","int16ArrayTag","int32ArrayTag","bigInt64ArrayTag","float32ArrayTag","float64ArrayTag","proto","isUnsafeProperty","merge","sourceKeys","sourceValue","targetValue","eq","other","isEqualWith","areValuesEqual","isEqualWithImpl","property","aParent","bParent","stack","areObjectsEqual","aTag","bTag","aStack","bStack","aValues","bValues","aValue","bValue","aKeys","bKeys","propKey","aProp","bProp","isEqual","UniversalEventBuilderArgs","ComponentViewBuilderArgs","IdentifyBuilderArgs","PageViewBuilderArgs","z.partial","ScreenViewBuilderArgs","TrackBuilderArgs","DEFAULT_PAGE_PROPERTIES","EventBuilder","app","channel","library","getLocale","getPageProperties","getUserAgent","campaign","page","screen","userAgent","timestamp","componentId","experienceId","variantIndex","universal","traits","userId","properties","pageProperties","merged","universalContext","universalProperties","context","isDeepKey","toKey","toPath","deepKey","quoteChar","bracket","char","get","getWithPath","current","RESOLUTION_WARNING_BASE","MergeTagValueResolver","embeddedEntryNodeTarget","_path","paths","dotPath","underScorePath","matchingSelector","selector","mergeTagEntry","fallback","PersonalizedEntryResolver","personalizedEntry","selectedPersonalizations","skipValidation","maybePersonalization","personalizationEntry","selectedVariantIndex","relevantVariants","selectedVariant","selectedVariantEntry","selectedPersonalization","signal","consent","flags","computed","online","personalizations","toObservable","effect","signals","isFunction","nameToString","isOnBlockedKey","isAsyncFunction","guardedBy","predicateName","_value","decoratedName","originalUnknown","originalIsAsync","resolvePredicate","cand","computeAllowed","ok","runOnBlocked","onBlocked","handlerCandidate","blockedReturn","wrapped","ValuePresence","#map","defaultMap","scope","defaultAllowedEvents","ProductBase","api","builder","interceptors","AnalyticsBase","_trackFlagView_dec","_trackComponentView_dec","_init","MAX_QUEUED_EVENTS","AnalyticsStateful","__runInitializers","__publicField","eventSignal","profileSignal","defaults","defaultProfile","onlineSignal","batch","_name","duplicationScope","isDuplicated","componentType","_duplicationScope","intercepted","validEvent","AnalyticsEvent","profileEventQueue","__decoratorStart","__decorateElement","__decoratorMetadata","AnalyticsStateless","builderArgs","parsed","batchEvent","OPTIMIZATION_CORE_SDK_VERSION","ANONYMOUS_ID_COOKIE","InterceptorManager","interceptor","fns","CoreBase","eventBuilder","logLevel","PersonalizationBase","_track_dec","_screen_dec","_page_dec","_identify_dec","PersonalizationStateful","flagsSignal","personalizationsSignal","getAnonymousId","defaultChanges","defaultPersonalizations","changesSignal","defaultConsent","consentSignal","PersonalizationEvent","anonymousId","PersonalizationStateless","CoreStateful","allowedEventTypes","preventedComponentEvents","accept","isOnline","previewPanel","CoreStateless","assign","defaultConverter","converter","defaultAttributes","set","attributes","stringifiedAttributes","attributeName","cookies","jar","parts","found","isEntryElement","ctflEntryId","isEntryData","parseSticky","sticky","parseVariantIndex","createAutoTrackingEntryViewCallback","core","info","entryId","personalizationId","ctflSticky","ctflVariantIndex","findEntryElement","maybeEntryElement","createAutoTrackingEntryExistenceCallback","entryViewObserver","autoObserveEntryElements","elements","ctflElement","buildQuery","languages","language","referrer","title","OPTIMIZATION_WEB_SDK_VERSION","CAN_ADD_LISTENERS","blobData","createOnlineChangeListener","emit","onOnline","onOffline","createVisibilityChangeListener","handled","handleHide","resetHandled","onVisibilityChange","onPageHide","onPageShow","NOW","isPageVisible","DEFAULTS","withJitter","base","Num","clearFireTimer","state","cancelRetry","derefElement","DEFAULT_IDLE_TIMEOUT_MS","DEFAULT_MAX_CHUNK","MIN_IDLE_TIMEOUT_MS","MIN_MAX_CHUNK","HAS_MUTATION_OBSERVER","HAS_IDLE_CALLBACK","HAS_CANCEL_IDLE","ElementExistenceObserver","root","idleTimeoutMs","maxChunk","onChange","onAdded","onRemoved","onError","records","run","addedNodes","removedNodes","added","removed","min","truncated","node","nodes","requireConnected","el","handle","removedArr","addedArr","items","chunk","invoke","ElementViewObserver","hasWeakRef","now","hidden","elapsed","remaining","delayMs","total","preTotal","totalVisibleMs","delay","ANONYMOUS_ID","CONSENT","CHANGES_CACHE","DEBUG_FLAG","PROFILE_CACHE","PERSONALIZATIONS_CACHE","LocalStore","translated","debug","parser","cacheString","parsedCache","EXPIRATION_DAYS_DEFAULT","mergeConfig","Optimization","autoTrackEntryViews","restConfig","mergedConfig","cookieValue","Cookies"],"mappings":"AAAA,IAAIA,KAAE,OAAO,IAAI,gBAAgB;AAAE,SAASC,KAAG;AAAC,MAAKC,IAAE;AAA0LA,IAAAA;AAAAA,OAAvL;AAAY,aAAPF,GAAEC,IAAE,IAAkBE,OAAT,UAAW;AAAC,UAAIC,IAAED;AAAe,WAAbA,KAAE,QAAOE,MAAmBD,MAAT,UAAW;AAAC,YAAIE,IAAEF,EAAE;AAAqB,YAAnBA,EAAE,IAAE,QAAOA,EAAE,KAAG,IAAM,EAAE,IAAEA,EAAE,MAAIG,GAAEH,CAAC,EAAE,KAAG;AAAC,UAAAA,EAAE,EAAC;AAAA,QAAE,SAAOA,GAAE;AAAC,UAAIH,MAAGD,IAAEI,GAAEH,IAAE;AAAA,QAAG;AAAC,QAAAG,IAAEE;AAAA,MAAC;AAAA,IAAC;AAAS,QAARD,KAAE,GAAEH,KAAOD,EAAE,OAAMD;AAAA,EAAC;AAAS;AAAC,SAASI,GAAEJ,GAAE;AAAC,MAAGE,IAAE,EAAE,QAAOF,EAAC;AAAGE,EAAAA;AAAI,MAAG;AAAC,WAAOF,EAAC;AAAA,EAAE,UA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